repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
idea4bsd/idea4bsd
plugins/settings-repository/src/authForm.kt
16
3430
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.credentialStore.Credentials import com.intellij.credentialStore.OneTimeString import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeed import com.intellij.ui.DocumentAdapter import com.intellij.ui.components.dialog import com.intellij.ui.layout.* import com.intellij.util.PathUtilRt import com.intellij.util.text.nullize import com.intellij.util.text.trimMiddle import javax.swing.JPasswordField import javax.swing.JTextField import javax.swing.event.DocumentEvent fun showAuthenticationForm(credentials: Credentials?, uri: String, host: String?, path: String?, sshKeyFile: String?): Credentials? { if (ApplicationManager.getApplication()?.isUnitTestMode === true) { throw AssertionError("showAuthenticationForm called from tests") } val isGitHub = host == "github.com" val isBitbucket = host == "bitbucket.org" val note = if (sshKeyFile == null) icsMessage(if (isGitHub) "login.github.note" else if (isBitbucket) "login.bitbucket.note" else "login.other.git.provider.note") else null var username = credentials?.userName if (username == null && isGitHub && path != null && sshKeyFile == null) { val firstSlashIndex = path.indexOf('/', 1) username = path.substring(1, if (firstSlashIndex == -1) path.length else firstSlashIndex) } val message = if (sshKeyFile == null) icsMessage("log.in.to", uri.trimMiddle(50)) else "Enter your password for the SSH key \"${PathUtilRt.getFileName(sshKeyFile)}\":" return invokeAndWaitIfNeed { val userField = JTextField(username) val passwordField = JPasswordField(credentials?.password?.toString()) val centerPanel = panel { noteRow(message) if (sshKeyFile == null && !isGitHub) { row("Username:") { userField() } } row(if (sshKeyFile == null && isGitHub) "Token:" else "Password:") { passwordField() } note?.let { noteRow(it) } } val authenticationForm = dialog( title = "Settings Repository", panel = centerPanel, focusedComponent = if (userField.parent == null) passwordField else userField, okActionEnabled = false) passwordField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { authenticationForm.isOKActionEnabled = e.document.length != 0 } }) authenticationForm.isOKActionEnabled = false if (authenticationForm.showAndGet()) { username = sshKeyFile ?: userField.text.nullize(true) val passwordChars = passwordField.password.nullize() Credentials(username, if (passwordChars == null) (if (username == null) null else OneTimeString("x-oauth-basic")) else OneTimeString(passwordChars)) } else { null } } }
apache-2.0
27736dfa27a43183f67c805f2bd93700
39.364706
174
0.724781
4.330808
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddInlineModifierFix.kt
3
3285
// 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 org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class AddInlineModifierFix( parameter: KtParameter, modifier: KtModifierKeywordToken ) : AddModifierFixFE10(parameter, modifier) { override fun getText(): String { val element = this.element return when { element != null -> KotlinBundle.message("fix.add.modifier.inline.parameter.text", modifier.value, element.name.toString()) else -> null } ?: "" } override fun getFamilyName() = KotlinBundle.message("fix.add.modifier.inline.parameter.family", modifier.value) companion object { private fun KtElement.findParameterWithName(name: String): KtParameter? { val function = getStrictParentOfType<KtFunction>() ?: return null return function.valueParameters.firstOrNull { it.name == name } ?: function.findParameterWithName(name) } } object CrossInlineFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val casted = Errors.NON_LOCAL_RETURN_NOT_ALLOWED.cast(diagnostic) val reference = casted.a as? KtNameReferenceExpression ?: return null val parameter = reference.findParameterWithName(reference.getReferencedName()) ?: return null return AddInlineModifierFix(parameter, KtTokens.CROSSINLINE_KEYWORD) } } object NoInlineFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val casted = Errors.USAGE_IS_NOT_INLINABLE.cast(diagnostic) val reference = casted.a as? KtNameReferenceExpression ?: return null val parameter = reference.findParameterWithName(reference.getReferencedName()) ?: return null return AddInlineModifierFix(parameter, KtTokens.NOINLINE_KEYWORD) } } object NoInlineSuspendFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val parameter = diagnostic.psiElement as? KtParameter ?: return null return AddInlineModifierFix(parameter, KtTokens.NOINLINE_KEYWORD) } } object CrossInlineSuspendFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val parameter = diagnostic.psiElement as? KtParameter ?: return null return AddInlineModifierFix(parameter, KtTokens.CROSSINLINE_KEYWORD) } } }
apache-2.0
de0d2b9b4d5989d9c55e52d332aee6e1
45.28169
158
0.731507
5.165094
false
false
false
false
pengwei1024/sampleShare
kotlin-basic/src/Hello.kt
1
1923
import java.net.URL /** * Created by pengwei on 2017/6/24. */ fun main(args: Array<String>) { /*loop@ for(i in 1..100){ print(i) }*/ // val students: Array<String> = arrayOf("Clock", "D_clock", "技术视界") // for ((index, student) in students.withIndex()) { // println("the element at $index is $student") // } { x: Int, y: Int -> println("${x + y}") }(1, 3) fun get(x: Int, y: Int) { println("${x + y}") } get(1, 3) val fruits = listOf("apple", "banana", "kiwi") val forecastJsonStr = URL("http://www.baidu.com").readText() println(forecastJsonStr) fruits.forEach { x -> println(x) } println("************") fruits .filter { it.startsWith("a") } .sortedBy { it } .map { it.toUpperCase() } .forEach { println(it) } val r1 = 1..5 for (i in r1) { print(i) } println("hello world") loop(arrayOf("1", "3", "5")) for (i in 1..5) { print(i) } val language = if (args.size == 0) "EN" else args[0] println(when (language) { "EN" -> "Hello!" "FR" -> "Salut!" "IT" -> "Ciao!" else -> "Sorry, I can't greet you in $language yet" }) if (args.isEmpty()) { println("empty") return } println("first=${args[0]}") for (name in args) { println("hello $name") } fun max(a: Int, b: Int) = if (a > b) a else b } fun parseInteger(str: String): Int? { try { return str.toInt() } catch (e: NumberFormatException) { return null } } fun getLength(obj: Any): Int? { if (obj is String) { return obj.length } return null } fun loop(args: Array<String>) { for (i in args) { println(i) } for (i in args.indices) { println("index:$i, value:${args[i]}") } }
apache-2.0
e61f11aba613c47b42c2827b8877ba86
17.601942
71
0.484073
3.273504
false
false
false
false
CobaltVO/2048-Neural-network
src/main/java/ru/falseteam/neural2048/ga/GeneticAlgorithm.kt
1
5007
package ru.falseteam.neural2048.ga import java.util.* import java.util.concurrent.atomic.AtomicInteger class GeneticAlgorithm<C, T : Comparable<T>>( private val fitnessFunc: Fitness<C, T>, // Функция роста private val mutatorCrossover: MutatorCrossover<C>// Мутатор ) { // Слушатель итераций interface IterationListener<C, T : Comparable<T>> { fun update(environment: GeneticAlgorithm<C, T>) } private val iterationListeners = LinkedList<IterationListener<C, T>>() // Набор хромосом private var chromosomes: MutableList<Pair<C, T>> = ArrayList() private var terminate = false // Количество родительских хромосом, которые выживают и участвуют в размножении var parentChromosomesSurviveCount = Integer.MAX_VALUE // Количество прошедших итераций var iteration = 0 private set var threadCount = 4 private val random = Random() private fun evolve() { val parentPopulationSize = chromosomes.size val newChromosomes = ArrayList<Pair<C, T>>()//TODO убрать // Копируем лучшие хромосомы run { var i = 0 while (i < parentPopulationSize && i < parentChromosomesSurviveCount) newChromosomes.add(chromosomes[i++]) } val newPopulationSize = newChromosomes.size // Мутируем лучшие хромосомы for (i in 0 until newPopulationSize) { newChromosomes.add(Pair(mutatorCrossover.mutate(newChromosomes[i].chromosome))) } @Suppress("LoopToCallChain") for (i in 0 until newPopulationSize) { val crossover = mutatorCrossover.crossover( newChromosomes[i].chromosome, newChromosomes[random.nextInt(newPopulationSize)].chromosome) crossover.mapTo(newChromosomes) { Pair(it) } } while (newChromosomes.size < parentPopulationSize) { //TODO написать красиво val crossover = mutatorCrossover.crossover( newChromosomes[random.nextInt(newPopulationSize)].chromosome, newChromosomes[random.nextInt(newPopulationSize)].chromosome) crossover.mapTo(newChromosomes) { Pair(it) } } sortPopulationByFitness(newChromosomes) chromosomes = newChromosomes.subList(0, parentPopulationSize) } fun evolve(count: Int) { this.terminate = false for (i in 0 until count) { if (this.terminate) { break } this.evolve() this.iteration++ for (l in this.iterationListeners) { l.update(this) } } } /** * Сортирует особи при помощи компаратора */ private fun sortPopulationByFitness(chromosomes: MutableList<Pair<C, T>>) { updateFitness(chromosomes) chromosomes.sortWith(compareBy({ it.fitness })) } private fun updateFitness(chromosomes: List<Pair<C, T>>) { val counter = AtomicInteger(0) class MyThread constructor(private val threadNumber: Int) : Thread() { override fun run() { while (true) { val chromosomeNumber = counter.getAndAdd(1) if (chromosomeNumber >= chromosomes.size) return val pair = chromosomes[chromosomeNumber] if (pair.fitness != null) continue // избегает повторных игр pair.fitness = fitnessFunc.calculate(pair.chromosome, threadNumber) } } } val threads = ArrayList<MyThread>(threadCount - 1) for (i in 0 until threadCount - 1) { threads.add(MyThread(i)) threads[i].start() } MyThread(threadCount - 1).run() for (i in 0 until threadCount - 1) { try { threads[i].join() } catch (e: InterruptedException) { e.printStackTrace() } } } fun terminate() { terminate = true } fun addIterationListener(listener: IterationListener<C, T>) { iterationListeners.add(listener) } @Suppress("unused") fun removeIterationListener(listener: IterationListener<C, T>) { iterationListeners.remove(listener) } fun addChromosome(chromosome: C) { chromosomes.add(Pair(chromosome)) } fun getBest(): C = chromosomes[0].chromosome @Suppress("unused") fun getWorst(): C = chromosomes[chromosomes.size - 1].chromosome fun getBestFitness(): T = chromosomes[0].fitness!! private class Pair<out C, T : Comparable<T>> constructor(val chromosome: C) { var fitness: T? = null } }
gpl-3.0
39df351b7a4f8bd91ff320216d6566e1
30.410596
91
0.603205
3.9525
false
false
false
false
androidx/androidx
wear/watchface/watchface/src/main/java/androidx/wear/watchface/TapEvent.kt
3
3374
/* * 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.wear.watchface import androidx.annotation.IntDef import androidx.annotation.Px import androidx.wear.watchface.control.IInteractiveWatchFace import java.time.Instant /** @hide */ @IntDef( value = [ TapType.DOWN, TapType.UP, TapType.CANCEL ] ) public annotation class TapType { public companion object { /** * Used to indicate a "down" touch event on the watch face. * * The watch face will receive an [UP] or a [CANCEL] event to follow this event, to * indicate whether this down event corresponds to a tap gesture to be handled by the watch * face, or a different type of gesture that is handled by the system, respectively. */ public const val DOWN: Int = IInteractiveWatchFace.TAP_TYPE_DOWN /** * Used in to indicate that a previous [TapType.DOWN] touch event has been canceled. This * generally happens when the watch face is touched but then a move or long press occurs. * * The watch face should not trigger any action, as the system is already processing the * gesture. */ public const val CANCEL: Int = IInteractiveWatchFace.TAP_TYPE_CANCEL /** * Used to indicate that an "up" event on the watch face has occurred that has not been * consumed by the system. A [TapType.DOWN] will always occur first. This event will not * be sent if a [TapType.CANCEL] is sent. * * Therefore, a [TapType.DOWN] event and the successive [TapType.UP] event are guaranteed * to be close enough to be considered a tap according to the value returned by * [android.view.ViewConfiguration.getScaledTouchSlop]. */ public const val UP: Int = IInteractiveWatchFace.TAP_TYPE_UP } } /** * An input event received by the watch face. * * @param xPos X coordinate of the event * @param yPos Y coordinate of the event * @param tapTime The [Instant] at which the tap event occurred */ public class TapEvent( @Px public val xPos: Int, @Px public val yPos: Int, public val tapTime: Instant ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TapEvent if (xPos != other.xPos) return false if (yPos != other.yPos) return false if (tapTime != other.tapTime) return false return true } override fun hashCode(): Int { var result = xPos result = 31 * result + yPos result = 31 * result + tapTime.hashCode() return result } override fun toString(): String = "[$xPos, $yPos @$tapTime]" }
apache-2.0
c4d8ab435cc4556259e12c2b8f13710d
33.428571
99
0.657676
4.303571
false
false
false
false
GunoH/intellij-community
platform/core-impl/src/com/intellij/ide/plugins/ModuleGraph.kt
3
10317
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet", "ReplaceNegatedIsEmptyWithIsNotEmpty") package com.intellij.ide.plugins import com.intellij.util.Java11Shim import com.intellij.util.graph.DFSTBuilder import com.intellij.util.graph.Graph import org.jetbrains.annotations.ApiStatus import java.util.* @ApiStatus.Internal interface ModuleGraph : Graph<IdeaPluginDescriptorImpl> { fun getDependencies(descriptor: IdeaPluginDescriptorImpl): Collection<IdeaPluginDescriptorImpl> fun getDependents(descriptor: IdeaPluginDescriptorImpl): Collection<IdeaPluginDescriptorImpl> } @ApiStatus.Internal open class ModuleGraphBase protected constructor( private val modules: Collection<IdeaPluginDescriptorImpl>, private val directDependencies: Map<IdeaPluginDescriptorImpl, Collection<IdeaPluginDescriptorImpl>>, private val directDependents: Map<IdeaPluginDescriptorImpl, Collection<IdeaPluginDescriptorImpl>>, ) : ModuleGraph { override fun getNodes(): Collection<IdeaPluginDescriptorImpl> = Collections.unmodifiableCollection(modules) override fun getDependencies(descriptor: IdeaPluginDescriptorImpl): Collection<IdeaPluginDescriptorImpl> { return getOrEmpty(directDependencies, descriptor) } override fun getIn(descriptor: IdeaPluginDescriptorImpl): Iterator<IdeaPluginDescriptorImpl> = getDependencies(descriptor).iterator() override fun getDependents(descriptor: IdeaPluginDescriptorImpl): Collection<IdeaPluginDescriptorImpl> { return getOrEmpty(directDependents, descriptor) } override fun getOut(descriptor: IdeaPluginDescriptorImpl): Iterator<IdeaPluginDescriptorImpl> = getDependents(descriptor).iterator() fun builder() = DFSTBuilder(this, null, true) internal fun sorted(builder: DFSTBuilder<IdeaPluginDescriptorImpl> = builder()): SortedModuleGraph { return SortedModuleGraph( topologicalComparator = toCoreAwareComparator(builder.comparator()), modules = modules, directDependencies = directDependencies, directDependents = directDependents, ) } } internal fun createModuleGraph(plugins: Collection<IdeaPluginDescriptorImpl>): ModuleGraphBase { val moduleMap = HashMap<String, IdeaPluginDescriptorImpl>(plugins.size * 2) val modules = ArrayList<IdeaPluginDescriptorImpl>(moduleMap.size) for (module in plugins) { moduleMap.put(module.pluginId.idString, module) for (v1Module in module.modules) { moduleMap.put(v1Module.idString, module) } modules.add(module) for (item in module.content.modules) { val subModule = item.requireDescriptor() modules.add(subModule) moduleMap.put(item.name, subModule) } } val hasAllModules = moduleMap.containsKey(PluginManagerCore.ALL_MODULES_MARKER.idString) val result = Collections.newSetFromMap<IdeaPluginDescriptorImpl>(IdentityHashMap()) val directDependencies = IdentityHashMap<IdeaPluginDescriptorImpl, List<IdeaPluginDescriptorImpl>>(modules.size) for (module in modules) { val implicitDep = if (hasAllModules) getImplicitDependency(module, moduleMap) else null if (implicitDep != null) { if (module === implicitDep) { PluginManagerCore.getLogger().error("Plugin $module depends on self") } else { result.add(implicitDep) } } collectDirectDependenciesInOldFormat(module, moduleMap, result) collectDirectDependenciesInNewFormat(module, moduleMap, result) if (module.moduleName != null && module.pluginId != PluginManagerCore.CORE_ID) { // add main as implicit dependency val main = moduleMap.get(module.pluginId.idString)!! assert(main !== module) result.add(main) } if (!result.isEmpty()) { directDependencies.put(module, Java11Shim.INSTANCE.copyOfCollection(result)) result.clear() } } val directDependents = IdentityHashMap<IdeaPluginDescriptorImpl, ArrayList<IdeaPluginDescriptorImpl>>(modules.size) val edges = Collections.newSetFromMap<Map.Entry<IdeaPluginDescriptorImpl, IdeaPluginDescriptorImpl>>(HashMap()) for (module in modules) { for (inNode in getOrEmpty(directDependencies, module)) { if (edges.add(AbstractMap.SimpleImmutableEntry(inNode, module))) { // not a duplicate edge directDependents.computeIfAbsent(inNode) { ArrayList() }.add(module) } } } return object : ModuleGraphBase( modules, directDependencies, directDependents, ) {} } private fun toCoreAwareComparator(comparator: Comparator<IdeaPluginDescriptorImpl>): Comparator<IdeaPluginDescriptorImpl> { // there is circular reference between core and implementation-detail plugin, as not all such plugins extracted from core, // so, ensure that core plugin is always first (otherwise not possible to register actions - parent group not defined) // don't use sortWith here - avoid loading kotlin stdlib return Comparator { o1, o2 -> when { o1.moduleName == null && o1.pluginId == PluginManagerCore.CORE_ID -> -1 o2.moduleName == null && o2.pluginId == PluginManagerCore.CORE_ID -> 1 else -> comparator.compare(o1, o2) } } } private fun getOrEmpty(map: Map<IdeaPluginDescriptorImpl, Collection<IdeaPluginDescriptorImpl>>, descriptor: IdeaPluginDescriptorImpl): Collection<IdeaPluginDescriptorImpl> { return map.getOrDefault(descriptor, Collections.emptyList()) } class SortedModuleGraph( val topologicalComparator: Comparator<IdeaPluginDescriptorImpl>, modules: Collection<IdeaPluginDescriptorImpl>, directDependencies: Map<IdeaPluginDescriptorImpl, Collection<IdeaPluginDescriptorImpl>>, directDependents: Map<IdeaPluginDescriptorImpl, Collection<IdeaPluginDescriptorImpl>>, ) : ModuleGraphBase( modules = modules.sortedWith(topologicalComparator), directDependencies = copySorted(directDependencies, topologicalComparator), directDependents = copySorted(directDependents, topologicalComparator) ) private fun copySorted( map: Map<IdeaPluginDescriptorImpl, Collection<IdeaPluginDescriptorImpl>>, comparator: Comparator<IdeaPluginDescriptorImpl>, ): Map<IdeaPluginDescriptorImpl, List<IdeaPluginDescriptorImpl>> { val result = IdentityHashMap<IdeaPluginDescriptorImpl, List<IdeaPluginDescriptorImpl>>(map.size) for (element in map.entries) { result.put(element.key, element.value.sortedWith(comparator)) } return result } /** * In 191.* and earlier builds Java plugin was part of the platform, so any plugin installed in IntelliJ IDEA might be able to use its * classes without declaring explicit dependency on the Java module. This method is intended to add implicit dependency on the Java plugin * for such plugins to avoid breaking compatibility with them. */ private fun getImplicitDependency(descriptor: IdeaPluginDescriptorImpl, idMap: Map<String, IdeaPluginDescriptorImpl>): IdeaPluginDescriptorImpl? { // skip our plugins as expected to be up-to-date whether bundled or not if (descriptor.isBundled || descriptor.packagePrefix != null || descriptor.implementationDetail) { return null } val pluginId = descriptor.pluginId if (PluginManagerCore.CORE_ID == pluginId || PluginManagerCore.JAVA_PLUGIN_ID == pluginId || hasModuleDependencies(descriptor)) { return null } // If a plugin does not include any module dependency tags in its plugin.xml, it's assumed to be a legacy plugin // and is loaded only in IntelliJ IDEA, so it may use classes from Java plugin. return idMap.get(PluginManagerCore.JAVA_MODULE_ID.idString) } val knownNotFullyMigratedPluginIds: Set<String> = hashSetOf( // Migration started with converting intellij.notebooks.visualization to a platform plugin, but adding a package prefix to Pythonid // or com.jetbrains.pycharm.ds.customization is a difficult task that can't be done by a single shot. "Pythonid", "com.jetbrains.pycharm.ds.customization", ) private fun collectDirectDependenciesInOldFormat(rootDescriptor: IdeaPluginDescriptorImpl, idMap: Map<String, IdeaPluginDescriptorImpl>, result: MutableSet<IdeaPluginDescriptorImpl>) { for (dependency in rootDescriptor.pluginDependencies) { // check for missing optional dependency val dep = idMap.get(dependency.pluginId.idString) ?: continue if (dep.pluginId != PluginManagerCore.CORE_ID) { // ultimate plugin it is combined plugin, where some included XML can define dependency on ultimate explicitly and for now not clear, // can be such requirements removed or not if (rootDescriptor === dep) { if (rootDescriptor.pluginId != PluginManagerCore.CORE_ID) { PluginManagerCore.getLogger().error("Plugin $rootDescriptor depends on self") } } else { // e.g. `.env` plugin in an old format and doesn't explicitly specify dependency on a new extracted modules dep.content.modules.mapTo(result) { it.requireDescriptor() } result.add(dep) } } if (knownNotFullyMigratedPluginIds.contains(rootDescriptor.pluginId.idString)) { idMap.get(PluginManagerCore.CORE_ID.idString)!!.content.modules.mapTo(result) { it.requireDescriptor() } } dependency.subDescriptor?.let { collectDirectDependenciesInOldFormat(it, idMap, result) } } for (moduleId in rootDescriptor.incompatibilities) { idMap.get(moduleId.idString)?.let { result.add(it) } } } private fun collectDirectDependenciesInNewFormat(module: IdeaPluginDescriptorImpl, idMap: Map<String, IdeaPluginDescriptorImpl>, result: MutableCollection<IdeaPluginDescriptorImpl>) { for (item in module.dependencies.modules) { val descriptor = idMap.get(item.name) if (descriptor != null) { result.add(descriptor) } } for (item in module.dependencies.plugins) { val descriptor = idMap.get(item.id.idString) // fake v1 module maybe located in a core plugin if (descriptor != null && descriptor.pluginId != PluginManagerCore.CORE_ID) { result.add(descriptor) } } }
apache-2.0
3e8f0efb8a8e91faa687ef7cc9f50a15
42.171548
139
0.741398
5.132836
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/descriptor/IndexDescriptor.kt
1
1117
package com.onyx.descriptor import com.onyx.extension.common.ClassMetadata import kotlin.jvm.internal.Intrinsics /** * Created by timothy.osborn on 12/11/14. * * General information regarding an index within an entity */ open class IndexDescriptor( override var name: String = "", open var type: Class<*> = ClassMetadata.ANY_CLASS ) : AbstractBaseDescriptor(), BaseDescriptor { open lateinit var entityDescriptor: EntityDescriptor override fun hashCode(): Int = (((this.entityDescriptor.entityClass.hashCode()) * 31) * 31 + this.name.hashCode()) * 31 + this.type.hashCode() override fun equals(other: Any?): Boolean { return if (this !== other) { if (other is IndexDescriptor) { val var2 = other as IndexDescriptor? if (Intrinsics.areEqual(this.entityDescriptor.partition, var2!!.entityDescriptor.partition) && Intrinsics.areEqual(this.name, var2.name) && Intrinsics.areEqual(this.type, var2.type)) { return true } } false } else { true } } }
agpl-3.0
a1efa5201d6518a5af14acc422cae557
31.852941
200
0.636526
4.380392
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToLabeledReturnFix.kt
4
4714
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors 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.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.findLabelAndCall import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.inline.InlineUtil import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf class ChangeToLabeledReturnFix( element: KtReturnExpression, val labeledReturn: String ) : KotlinQuickFixAction<KtReturnExpression>(element) { override fun getFamilyName() = KotlinBundle.message("fix.change.to.labeled.return.family") override fun getText() = KotlinBundle.message("fix.change.to.labeled.return.text", labeledReturn) override fun invoke(project: Project, editor: Editor?, file: KtFile) { val returnExpression = element ?: return val factory = KtPsiFactory(project) val returnedExpression = returnExpression.returnedExpression val newExpression = if (returnedExpression == null) factory.createExpression(labeledReturn) else factory.createExpressionByPattern("$0 $1", labeledReturn, returnedExpression) returnExpression.replace(newExpression) } companion object : KotlinIntentionActionsFactory() { private fun findAccessibleLabels(bindingContext: BindingContext, position: KtReturnExpression): List<Name> { val result = mutableListOf<Name>() for (parent in position.parentsWithSelf) { when (parent) { is KtClassOrObject -> break is KtFunctionLiteral -> { val (label, call) = parent.findLabelAndCall() if (label != null) { result.add(label) } // check if the current function literal is inlined and stop processing outer declarations if it's not val callee = call?.calleeExpression as? KtReferenceExpression ?: break if (!InlineUtil.isInline(bindingContext[BindingContext.REFERENCE_TARGET, callee])) break } else -> {} } } return result } override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val element = diagnostic.psiElement as? KtElement ?: return emptyList() val context by lazy { element.analyze() } val returnExpression = when (diagnostic.factory) { Errors.RETURN_NOT_ALLOWED -> diagnostic.psiElement as? KtReturnExpression Errors.TYPE_MISMATCH, Errors.TYPE_MISMATCH_WARNING, Errors.CONSTANT_EXPECTED_TYPE_MISMATCH, Errors.NULL_FOR_NONNULL_TYPE -> getLambdaReturnExpression(diagnostic.psiElement, context) else -> null } ?: return emptyList() val candidates = findAccessibleLabels(context, returnExpression) return candidates.map { ChangeToLabeledReturnFix(returnExpression, labeledReturn = "return@${it.render()}") } } private fun getLambdaReturnExpression(element: PsiElement, bindingContext: BindingContext): KtReturnExpression? { val returnExpression = element.getStrictParentOfType<KtReturnExpression>() ?: return null val lambda = returnExpression.getStrictParentOfType<KtLambdaExpression>() ?: return null val lambdaReturnType = bindingContext[BindingContext.FUNCTION, lambda.functionLiteral]?.returnType ?: return null val returnType = returnExpression.returnedExpression?.getType(bindingContext) ?: return null if (!returnType.isSubtypeOf(lambdaReturnType)) return null return returnExpression } } }
apache-2.0
3ccf123daba54672983b85460cfb6f84
49.698925
158
0.687527
5.462341
false
false
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt
2
7679
// 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.uast.kotlin import com.intellij.lang.Language import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.annotations.JVM_STATIC_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.uast.DEFAULT_TYPES_LIST import org.jetbrains.uast.UElement import org.jetbrains.uast.UExpression import org.jetbrains.uast.UastLanguagePlugin import org.jetbrains.uast.analysis.UastAnalysisPlugin import org.jetbrains.uast.kotlin.KotlinConverter.convertDeclaration import org.jetbrains.uast.kotlin.KotlinConverter.convertDeclarationOrElement import org.jetbrains.uast.kotlin.psi.UastFakeLightPrimaryConstructor import org.jetbrains.uast.util.ClassSet import org.jetbrains.uast.util.ClassSetsWrapper class KotlinUastLanguagePlugin : UastLanguagePlugin { override val priority = 10 override val language: Language get() = KotlinLanguage.INSTANCE override fun isFileSupported(fileName: String): Boolean { return fileName.endsWith(".kt", false) || fileName.endsWith(".kts", false) } private val PsiElement.isJvmElement: Boolean get() { val resolveProvider: KotlinUastResolveProviderService = project.getService(KotlinUastResolveProviderService::class.java)!! return resolveProvider.isJvmElement(this) } override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? { val requiredTypes = elementTypes(requiredType) return if (!canConvert(element, requiredTypes) || !element.isJvmElement) null else convertDeclarationOrElement(element, parent, requiredTypes) } override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? { val requiredTypes = elementTypes(requiredType) return when { !canConvert(element, requiredTypes) || !element.isJvmElement -> null element is PsiFile || element is KtLightClassForFacade -> convertDeclaration(element, null, requiredTypes) else -> convertDeclarationOrElement(element, null, requiredTypes) } } override fun getMethodCallExpression( element: PsiElement, containingClassFqName: String?, methodName: String ): UastLanguagePlugin.ResolvedMethod? { if (element !is KtCallExpression) return null val resolvedCall = element.getResolvedCall(element.analyze()) ?: return null val resultingDescriptor = resolvedCall.resultingDescriptor if (resultingDescriptor !is FunctionDescriptor || resultingDescriptor.name.asString() != methodName) return null val parent = element.parent val parentUElement = convertElementWithParent(parent, null) ?: return null val uExpression = KotlinUFunctionCallExpression(element, parentUElement) val method = uExpression.resolve() ?: return null if (method.name != methodName) return null return UastLanguagePlugin.ResolvedMethod(uExpression, method) } override fun getConstructorCallExpression( element: PsiElement, fqName: String ): UastLanguagePlugin.ResolvedConstructor? { if (element !is KtCallExpression) return null val resolvedCall = element.getResolvedCall(element.analyze()) ?: return null val resultingDescriptor = resolvedCall.resultingDescriptor if (resultingDescriptor !is ConstructorDescriptor || resultingDescriptor.returnType.constructor.declarationDescriptor?.name?.asString() != fqName ) { return null } val parent = KotlinConverter.unwrapElements(element.parent) ?: return null val parentUElement = convertElementWithParent(parent, null) ?: return null val uExpression = KotlinUFunctionCallExpression(element, parentUElement) val method = uExpression.resolve() ?: return null val containingClass = method.containingClass ?: return null return UastLanguagePlugin.ResolvedConstructor(uExpression, method, containingClass) } override fun isExpressionValueUsed(element: UExpression): Boolean { return when (element) { is KotlinUSimpleReferenceExpression.KotlinAccessorCallExpression -> element.setterValue != null is KotlinAbstractUExpression -> { val ktElement = element.sourcePsi as? KtElement ?: return false ktElement.analyze()[BindingContext.USED_AS_EXPRESSION, ktElement] ?: false } else -> false } } @Suppress("UNCHECKED_CAST") private fun <T : UElement> convertElement(element: PsiElement, parent: UElement?, expectedTypes: Array<out Class<out T>>): T? { val nonEmptyExpectedTypes = expectedTypes.nonEmptyOr(DEFAULT_TYPES_LIST) return if (!canConvert(element, nonEmptyExpectedTypes) || !element.isJvmElement) null else convertDeclarationOrElement(element, parent, nonEmptyExpectedTypes) as? T } override fun <T : UElement> convertElementWithParent(element: PsiElement, requiredTypes: Array<out Class<out T>>): T? { return convertElement(element, null, requiredTypes) } @Suppress("UNCHECKED_CAST") override fun <T : UElement> convertToAlternatives(element: PsiElement, requiredTypes: Array<out Class<out T>>): Sequence<T> = if (!element.isJvmElement) emptySequence() else when { element is KtFile -> KotlinConverter.convertKtFile(element, null, requiredTypes) as Sequence<T> (element is KtProperty && !element.isLocal) -> KotlinConverter.convertNonLocalProperty(element, null, requiredTypes) as Sequence<T> element is KtNamedFunction && element.isJvmStatic() -> KotlinConverter.convertJvmStaticMethod(element, null, requiredTypes) as Sequence<T> element is KtParameter -> KotlinConverter.convertParameter(element, null, requiredTypes) as Sequence<T> element is KtClassOrObject -> KotlinConverter.convertClassOrObject(element, null, requiredTypes) as Sequence<T> element is UastFakeLightPrimaryConstructor -> KotlinConverter.convertFakeLightConstructorAlternatives(element, null, requiredTypes) as Sequence<T> else -> sequenceOf(convertElementWithParent(element, requiredTypes.nonEmptyOr(DEFAULT_TYPES_LIST)) as? T).filterNotNull() } private fun KtNamedFunction.isJvmStatic() = annotationEntries.any { it.shortName?.asString() == JVM_STATIC_ANNOTATION_FQ_NAME.shortName().asString() && analyze()[BindingContext.ANNOTATION, it]?.fqName == JVM_STATIC_ANNOTATION_FQ_NAME } override fun getPossiblePsiSourceTypes(vararg uastTypes: Class<out UElement>): ClassSet<PsiElement> = when (uastTypes.size) { 0 -> getPossibleSourceTypes(UElement::class.java) 1 -> getPossibleSourceTypes(uastTypes.single()) else -> ClassSetsWrapper(Array(uastTypes.size) { getPossibleSourceTypes(uastTypes[it]) }) } override val analysisPlugin: UastAnalysisPlugin? get() = UastAnalysisPlugin.byLanguage(KotlinLanguage.INSTANCE) }
apache-2.0
5afbb1261d9f7921cf7dff75cbe77006
50.193333
134
0.727569
5.292212
false
false
false
false
siosio/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/constructors/customerBuilder.kt
3
970
package org.test.customer internal class Customer(first: String, last: String) { val firstName: String val lastName: String private fun doSmthBefore() {} private fun doSmthAfter() {} init { doSmthBefore() firstName = first lastName = last doSmthAfter() } } internal class CustomerBuilder { var _firstName = "Homer" var _lastName = "Simpson" fun WithFirstName(firstName: String): CustomerBuilder { _firstName = firstName return this } fun WithLastName(lastName: String): CustomerBuilder { _lastName = lastName return this } fun Build(): Customer { return Customer(_firstName, _lastName) } } object User { fun main() { val customer = CustomerBuilder() .WithFirstName("Homer") .WithLastName("Simpson") .Build() println(customer.firstName) println(customer.lastName) } }
apache-2.0
f35664cf12a3616ccdea4045d2619b3e
20.555556
59
0.598969
4.575472
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceIsEmptyWithIfEmptyInspection.kt
1
6575
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isElseIf import org.jetbrains.kotlin.idea.intentions.loopToCallChain.targetLoop import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.util.textRangeIn import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle import org.jetbrains.kotlin.psi.psiUtil.getPossiblyQualifiedCallExpression import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ReplaceIsEmptyWithIfEmptyInspection : AbstractKotlinInspection() { private data class Replacement( val conditionFunctionFqName: FqName, val replacementFunctionName: String, val negativeCondition: Boolean = false ) companion object { private val replacements = listOf( Replacement(FqName("kotlin.collections.Collection.isEmpty"), "ifEmpty"), Replacement(FqName("kotlin.collections.List.isEmpty"), "ifEmpty"), Replacement(FqName("kotlin.collections.Set.isEmpty"), "ifEmpty"), Replacement(FqName("kotlin.collections.Map.isEmpty"), "ifEmpty"), Replacement(FqName("kotlin.text.isEmpty"), "ifEmpty"), Replacement(FqName("kotlin.text.isBlank"), "ifBlank"), Replacement(FqName("kotlin.collections.isNotEmpty"), "ifEmpty", negativeCondition = true), Replacement(FqName("kotlin.text.isNotEmpty"), "ifEmpty", negativeCondition = true), Replacement(FqName("kotlin.text.isNotBlank"), "ifBlank", negativeCondition = true), ).associateBy { it.conditionFunctionFqName } private val conditionFunctionShortNames = replacements.keys.map { it.shortName().asString() }.toSet() } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = ifExpressionVisitor(fun(ifExpression: KtIfExpression) { if (ifExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_3) return if (ifExpression.isElseIf()) return val thenExpression = ifExpression.then ?: return val elseExpression = ifExpression.`else` ?: return if (elseExpression is KtIfExpression) return val condition = ifExpression.condition ?: return val conditionCallExpression = condition.getPossiblyQualifiedCallExpression() ?: return val conditionCalleeExpression = conditionCallExpression.calleeExpression ?: return if (conditionCalleeExpression.text !in conditionFunctionShortNames) return val context = ifExpression.analyze(BodyResolveMode.PARTIAL) val resultingDescriptor = conditionCallExpression.getResolvedCall(context)?.resultingDescriptor ?: return val receiverParameter = resultingDescriptor.dispatchReceiverParameter ?: resultingDescriptor.extensionReceiverParameter val receiverType = receiverParameter?.type ?: return if (KotlinBuiltIns.isArrayOrPrimitiveArray(receiverType)) return val conditionCallFqName = resultingDescriptor.fqNameOrNull() ?: return val replacement = replacements[conditionCallFqName] ?: return val selfBranch = if (replacement.negativeCondition) thenExpression else elseExpression val selfValueExpression = selfBranch.blockExpressionsOrSingle().singleOrNull() ?: return if (condition is KtDotQualifiedExpression) { if (selfValueExpression.text != condition.receiverExpression.text) return } else { if (selfValueExpression !is KtThisExpression) return } val loop = ifExpression.getStrictParentOfType<KtLoopExpression>() if (loop != null) { val defaultValueExpression = (if (replacement.negativeCondition) elseExpression else thenExpression) if (defaultValueExpression.anyDescendantOfType<KtExpression> { (it is KtContinueExpression || it is KtBreakExpression) && (it as KtExpressionWithLabel).targetLoop(context) == loop } ) return } holder.registerProblem( ifExpression, conditionCalleeExpression.textRangeIn(ifExpression), KotlinBundle.message("replace.with.0", "${replacement.replacementFunctionName} {...}"), ReplaceFix(replacement) ) }) private class ReplaceFix(private val replacement: Replacement) : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.with.0", "${replacement.replacementFunctionName} {...}") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val ifExpression = descriptor.psiElement as? KtIfExpression ?: return val condition = ifExpression.condition ?: return val thenExpression = ifExpression.then ?: return val elseExpression = ifExpression.`else` ?: return val defaultValueExpression = (if (replacement.negativeCondition) elseExpression else thenExpression) val psiFactory = KtPsiFactory(ifExpression) val receiverText = (condition as? KtDotQualifiedExpression)?.receiverExpression?.text?.let { "$it." } ?: "" val replacementFunctionName = replacement.replacementFunctionName val newExpression = if (defaultValueExpression is KtBlockExpression) { psiFactory.createExpression("${receiverText}$replacementFunctionName ${defaultValueExpression.text}") } else { psiFactory.createExpressionByPattern("${receiverText}$replacementFunctionName { $0 }", defaultValueExpression) } ifExpression.replace(newExpression) } } }
apache-2.0
c647358580e97b407694d2f2042c84c6
54.720339
158
0.732015
5.712424
false
false
false
false
jwren/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/lists/MarkdownListItemCreatingTypedHandlerDelegate.kt
2
2405
package org.intellij.plugins.markdown.editor.lists import com.intellij.codeInsight.editorActions.TypedHandlerDelegate import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.util.elementType import com.intellij.psi.util.parentOfType import com.intellij.refactoring.suggested.endOffset import com.intellij.util.text.CharArrayUtil import org.intellij.plugins.markdown.editor.lists.ListRenumberUtils.renumberInBulk import org.intellij.plugins.markdown.editor.lists.ListUtils.getLineIndentRange import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile import org.intellij.plugins.markdown.lang.psi.impl.MarkdownList import org.intellij.plugins.markdown.settings.MarkdownSettings /** * This handler renumbers the current list when you hit Enter after the number of some list item. */ internal class MarkdownListItemCreatingTypedHandlerDelegate : TypedHandlerDelegate() { override fun charTyped(c: Char, project: Project, editor: Editor, file: PsiFile): Result { if (file !is MarkdownFile || c != ' ' || !MarkdownSettings.getInstance(project).isEnhancedEditingEnabled) { return Result.CONTINUE } val document = editor.document PsiDocumentManager.getInstance(project).commitDocument(document) val caret = editor.caretModel.currentCaret val element = file.findElementAt(caret.offset - 1) if (element == null || element.elementType !in MarkdownTokenTypeSets.LIST_MARKERS) { return Result.CONTINUE } if (caret.offset <= document.getLineIndentRange(caret.logicalPosition.line).endOffset) { // so that entering a space before a list item won't renumber it return Result.CONTINUE } val markerEnd = element.endOffset - 1 if (CharArrayUtil.shiftBackward(document.charsSequence, markerEnd, " ") < markerEnd - 1) { // so that entering a space after a marker won't turn children-items into siblings return Result.CONTINUE } element.parentOfType<MarkdownList>()!!.renumberInBulk(document, recursive = false, restart = false) PsiDocumentManager.getInstance(project).commitDocument(document) caret.moveToOffset(file.findElementAt(caret.offset - 1)?.endOffset ?: caret.offset) return Result.STOP } }
apache-2.0
bafb4b06657a2900d328762e9819d997
41.946429
103
0.778378
4.52919
false
false
false
false
jwren/intellij-community
plugins/git4idea/src/git4idea/rebase/interactive/dialog/GitInteractiveRebaseDialog.kt
3
7546
// 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 git4idea.rebase.interactive.dialog import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.application.ModalityState import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.committed.CommittedChangesTreeBrowser import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.AnActionButton import com.intellij.ui.OnePixelSplitter import com.intellij.ui.PopupHandler import com.intellij.ui.ToolbarDecorator import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.labels.LinkListener import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.ui.details.FullCommitDetailsListPanel import git4idea.history.GitCommitRequirements import git4idea.history.GitLogUtil import git4idea.i18n.GitBundle import git4idea.rebase.GitRebaseEntryWithDetails import git4idea.rebase.interactive.GitRebaseTodoModel import org.jetbrains.annotations.ApiStatus import java.awt.BorderLayout import java.awt.Dimension import javax.swing.JComponent import javax.swing.JSeparator import javax.swing.SwingConstants @ApiStatus.Internal const val GIT_INTERACTIVE_REBASE_DIALOG_DIMENSION_KEY = "Git.Interactive.Rebase.Dialog" internal class GitInteractiveRebaseDialog<T : GitRebaseEntryWithDetails>( private val project: Project, root: VirtualFile, entries: List<T> ) : DialogWrapper(project, true) { companion object { private const val DETAILS_PROPORTION = "Git.Interactive.Rebase.Details.Proportion" internal const val PLACE = "Git.Interactive.Rebase.Dialog" private const val DIALOG_HEIGHT = 550 private const val DIALOG_WIDTH = 1000 } private val commitsTableModel = GitRebaseCommitsTableModel(entries) private val resetEntriesLabel = LinkLabel<Any?>(GitBundle.message("rebase.interactive.dialog.reset.link.text"), null).apply { isVisible = false setListener( LinkListener { _, _ -> commitsTable.removeEditor() commitsTableModel.resetEntries() isVisible = false }, null ) } private val commitsTable = object : GitRebaseCommitsTableView(project, commitsTableModel, disposable) { override fun onEditorCreate() { isOKActionEnabled = false } override fun onEditorRemove() { isOKActionEnabled = true } } private val modalityState = window?.let { ModalityState.stateForComponent(it) } ?: ModalityState.current() private val fullCommitDetailsListPanel = object : FullCommitDetailsListPanel(project, disposable, modalityState) { @RequiresBackgroundThread @Throws(VcsException::class) override fun loadChanges(commits: List<VcsCommitMetadata>): List<Change> { val changes = mutableListOf<Change>() GitLogUtil.readFullDetailsForHashes(project, root, commits.map { it.id.asString() }, GitCommitRequirements.DEFAULT) { gitCommit -> changes.addAll(gitCommit.changes) } return CommittedChangesTreeBrowser.zipChanges(changes) } } private val iconActions = listOf( PickAction(commitsTable), EditAction(commitsTable) ) private val rewordAction = RewordAction(commitsTable) private val fixupAction = FixupAction(commitsTable) private val squashAction = SquashAction(commitsTable) private val dropAction = DropAction(commitsTable) private val contextMenuOnlyActions = listOf<AnAction>(ShowGitRebaseCommandsDialog(project, commitsTable)) private var modified = false init { commitsTable.selectionModel.addListSelectionListener { _ -> fullCommitDetailsListPanel.commitsSelected(commitsTable.selectedRows.map { commitsTableModel.getEntry(it).commitDetails }) } commitsTableModel.addTableModelListener { resetEntriesLabel.isVisible = true } commitsTableModel.addTableModelListener { modified = true } PopupHandler.installRowSelectionTablePopup( commitsTable, DefaultActionGroup().apply { addAll(iconActions) add(rewordAction) add(squashAction) add(fixupAction) add(dropAction) addSeparator() addAll(contextMenuOnlyActions) }, PLACE ) title = GitBundle.message("rebase.interactive.dialog.title") setOKButtonText(GitBundle.message("rebase.interactive.dialog.start.rebase")) init() } override fun getDimensionServiceKey() = GIT_INTERACTIVE_REBASE_DIALOG_DIMENSION_KEY override fun createCenterPanel() = BorderLayoutPanel().apply { val decorator = ToolbarDecorator.createDecorator(commitsTable) .setToolbarPosition(ActionToolbarPosition.TOP) .setPanelBorder(JBUI.Borders.empty()) .setScrollPaneBorder(JBUI.Borders.empty()) .disableAddAction() .disableRemoveAction() .addExtraActions(*iconActions.toTypedArray()) .addExtraAction(AnActionButtonSeparator()) .addExtraAction(rewordAction) .addExtraAction(AnActionOptionButton(squashAction, listOf(fixupAction))) .addExtraAction(dropAction) val tablePanel = decorator.createPanel() val resetEntriesLabelPanel = BorderLayoutPanel().addToCenter(resetEntriesLabel).apply { border = JBUI.Borders.empty(0, 5, 0, 10) } decorator.actionsPanel.apply { add(BorderLayout.EAST, resetEntriesLabelPanel) } val detailsSplitter = OnePixelSplitter(DETAILS_PROPORTION, 0.5f).apply { firstComponent = tablePanel secondComponent = fullCommitDetailsListPanel } addToCenter(detailsSplitter) preferredSize = JBDimension(DIALOG_WIDTH, DIALOG_HEIGHT) } override fun getStyle() = DialogStyle.COMPACT fun getModel(): GitRebaseTodoModel<T> = commitsTableModel.rebaseTodoModel override fun getPreferredFocusedComponent(): JComponent = commitsTable override fun doCancelAction() { if (modified) { val result = Messages.showDialog( rootPane, GitBundle.message("rebase.interactive.dialog.discard.modifications.message"), GitBundle.message("rebase.interactive.dialog.discard.modifications.cancel"), arrayOf( GitBundle.message("rebase.interactive.dialog.discard.modifications.discard"), GitBundle.message("rebase.interactive.dialog.discard.modifications.continue") ), 0, Messages.getQuestionIcon() ) if (result != Messages.YES) { return } } super.doCancelAction() } override fun getHelpId(): String? { return "reference.VersionControl.Git.RebaseCommits" } private class AnActionButtonSeparator : AnActionButton(), CustomComponentAction, DumbAware { companion object { private val SEPARATOR_HEIGHT = JBUI.scale(20) } override fun actionPerformed(e: AnActionEvent) { throw UnsupportedOperationException() } override fun createCustomComponent(presentation: Presentation, place: String) = JSeparator(SwingConstants.VERTICAL).apply { preferredSize = Dimension(preferredSize.width, SEPARATOR_HEIGHT) } } }
apache-2.0
7994be6060ebd88cd36f187f50c26a45
36.924623
140
0.758415
4.69863
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/shit.kt
1
23590
package alraune import alraune.entity.* import pieces100.* import vgrechka.* import kotlin.reflect.KClass import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KVisibility import kotlin.reflect.full.declaredMemberFunctions class OoEntityTitleShit(val pagePath: String, val title: String, val shitIntoTopRight: () -> Unit = {}, val shitIntoHamburger: (MenuBuilder) -> Unit, val impersonationPillsUsage: EntityPageTemplate.ImpersonationPillsUsage?, val renderingStuff1: RenderingStuff1 = RenderingStuff1()): Dancer<Unit> { private var subTitle: Renderable? = null fun subTitle(x: String?) = this.also {subTitle = x?.let {span(it)}} fun subTitle(x: Renderable?) = this.also {subTitle = x} override fun dance() { oo(div().style("position: relative;").with { oo(h3().with { oo(div().style("display: flex; align-items: center;").with { oo(span(title)) renderingStuff1.debugTitleAddendum?.let { oo(div().style("font-size: 10pt; margin-left: 0.5em; background: #FFECB3; padding: 2px; border-radius: 4px; padding-left: 4px; padding-right: 4px;") .add(it)) } }) }) if (subTitle != null) oo(h4().add(subTitle)) oo(div().with { oo(div().style("position: absolute; right: 0px; top: 4px; display: flex;").with { shitIntoTopRight() ooHamburgerDropdown(shitIntoHamburger) // 465deb19-a764-42c3-ba30-2a0fbcd2542f .appendStyle("margin-left: 1em; margin-top: 3px;").appendClassName(AlCSS.grayHoverShit) }) }) }) } fun disabled_ooImpersonationPills() { ooImpersonationPills() // 965bea08-dfa8-4968-bedf-582187481d93 } fun ooImpersonationPills() { if (isAdmin()) { val ipu = impersonationPillsUsage if (ipu != null) { oo(ul().className("nav nav-pills ${AlCSS.topRightPills}").with { ipu.addTo(object : ImpersonationPillsSink { override fun add(who: AlUserKind) { oo(li().with { if (who == rctx0.al.pretending) currentTag().className("active") val href = makeUrlPart(pagePath, ipu.params().copy {p -> p.impersonate.set(who) }) oo(composeTagaProgressy(href).with { oo(span(who.title)) }) }) } }) }) } } } } class RenderingStuff1( val debugTitleAddendum: String? = null) class OoEntityTitleShit2( val title: String, val debugTitleAddendum: String? = null, val ooTopRight: () -> Unit = {}): Dancer<Unit> { private var subTitle: Renderable? = null fun subTitle(x: Renderable?) = this.also {subTitle = x} fun subTitle(x: String?) = this.also {subTitle = x?.let {span(it)}} override fun dance() { oo(div().style("position: relative;").with { oo(h3().with { oo(div().style("display: flex; align-items: center;").with { oo(span(title)) // 2f29a8fa-4057-41f3-a157-e2f6df724928 debugTitleAddendum?.let { oo(div().style("font-size: 10pt; margin-left: 0.5em; background: #FFECB3; padding: 2px; border-radius: 4px; padding-left: 4px; padding-right: 4px;") .add(it)) } }) }) if (subTitle != null) oo(h4().add(subTitle)) oo(div().with { oo(div().style("position: absolute; right: 0px; top: 4px; display: flex;").with { ooTopRight() }) }) }) } } class OoTabs(val activeTabId: String, val ooNearTabs: () -> Unit = {}, val build: (Boobs) -> Unit) : Dancer<Unit> { interface Boobs { fun tab(id: String, title: String, href: String) } override fun dance() { oo(div().style("position: relative;").with { oo(ul().className("nav nav-tabs").style("margin-bottom: 0.5rem;").with { build(object : Boobs { override fun tab(id: String, title: String, href: String) { oo(li().className((id == activeTabId).thenElseEmpty {"active"}) .add(composeTagaProgressy(href).text(title))) } }) }) ooNearTabs() }) } } abstract class Olivia<Fields : BunchOfFields>( val pageTitle: String, val makeFields: () -> Fields) { abstract fun checkAccess() abstract fun tamper() abstract fun composeFormBody(): Renderable abstract fun serveGivenNoFieldErrors(): String val contentDomid = simpleClassName(this) + "-content" var fields by notNullOnce<Fields>() fun spitPage() { btfReplaceShit() spitUsualPage_withNewContext1 {div().id(contentDomid)} } fun btfReplaceShit() { btfReplaceElement_withShitComposedInNewContext1(contentDomid) { div().id(contentDomid).with { oo(div().className("container").with { oo(composePageHeader(pageTitle)) oo(composeErrorBanner()) oo(composeFormBody()) oo(composeButtonBar.singleProceedButton(FreakingServant().also { it.oliviaClass = this::class.java.cast() })) }) } } } class FreakingServant : Servant { var oliviaClass by notNullOnce<Class<out Olivia<BunchOfFields>>>() override fun ignite() { val olivia = oliviaClass.newInstance() olivia.fields = useFields(olivia.makeFields(), FieldSource.Post()) if (anyFieldErrors(olivia.fields)) return olivia.btfReplaceShit() val nextHref = olivia.serveGivenNoFieldErrors() btfSetLocationHref(nextHref) } } fun spitDamnThing() { checkAccess() fields = useFields(makeFields(), FieldSource.Initial()) tamper() spitPage() } } fun useFunsOfAsTamperings(path: String, obj: Any) { val funs = obj::class.declaredMemberFunctions.filter {it.visibility == KVisibility.PUBLIC} useTamperings(path, funs.map {f-> makeTampering(f.name) {f.call(obj)}}) } class HrefThunk(val path: String, val shitIntoParams: (GetParams) -> Unit) { fun makeHref(shitIntoParamsAgain: (GetParams) -> Unit = {}): String { return makeUrlPart(path) { shitIntoParams(it) shitIntoParamsAgain(it) } } } abstract class Tabopezdal { abstract fun hrefThunk(): HrefThunk val tabs = mutableListOf<Tab>() class Tab(val id: String, val title: String, val ooNearTabs: () -> Unit = {}, val ooContent: () -> Unit) fun ooShit() { val tab = tabs.find {it.id == GetParams().tab.get()} ?: tabs.first() !OoTabs(activeTabId = tab.id, ooNearTabs = tab.ooNearTabs, build = {bunch-> for (tab in tabs) { bunch.tab(id = tab.id, title = tab.title, href = hrefThunk().makeHref { it.tab.set(tab.id) }) } }) tab.ooContent() } } interface Seriafuckable { fun serialize() = jsonize_withTyping(this) fun deserializerObject(): Deserializer = DejsonizeWithTypingDeserializer } abstract class PencilButton<Entity : Any>(val ctor: () -> PencilButton<Entity>) { abstract fun makeFields(): BunchOfFields abstract fun composeParamsModalBody(fields: BunchOfFields): Renderable abstract fun updateEntityParams(fields: BunchOfFields, forceOverwriteStale: Boolean) abstract fun hrefAfterParamsUpdated(): String abstract fun makeMidAirComparisonPageHref(ourFields: BunchOfFields): String var entity by notNullOnce<Entity>() var midAirComparisonPageHref: String? = null var hasErrors = false fun isMidAirCollision() = midAirComparisonPageHref != null fun addControl(trc: TopRightControls, entity: Entity) { this.entity = entity trc.addButton(FA.pencil, AlDebugTag.topRightButton).whenDomReady_addOnClick( jsBustOutModal(modalWithContext { composeParamsModalContent(useFields(makeFields(), fieldSource(entity)))}) ) } open fun fieldSource(entity: Entity): FieldSource = FieldSource.DB(entity) fun composeParamsModalContent(fields: BunchOfFields): Renderable { val rmc = ComposeModalContent() rmc.title = t("TOTE", "Параметры") rmc.blueLeftMargin() rmc.body = div().with { if (hasErrors) { oo(composeFixErrorsBelowBanner()) } val href = midAirComparisonPageHref if (href != null) { oo(composeMidAirCollisionBanner( toTheRightOfMessage = ComposeChevronLink(t("TOTE", "Сравнить"), href).WithLeftMargin().newTab())) } oo(composeParamsModalBody(fields)) } rmc.footer = dance(ButtonBarWithTicker() .tickerLocation(Rightness.Left) .addSubmitFormButton(MinimalButtonShit( title = when { isMidAirCollision() -> t("TOTE", "Затереть и сохранить мое") // d1530b37-a210-4ff1-866c-a996039c54bd else -> AlText.save }, style = when { isMidAirCollision() -> AlButtonStyle.Danger else -> AlButtonStyle.Primary }, servantHandle = freakingServant(bakeShit2(ctor, forceOverwriteStale = isMidAirCollision())))) .addCloseModalButton()) return rmc.dance() } fun serve(forceOverwriteStale: Boolean = false) { withNewContext1 { val fields = useFields(makeFields(), FieldSource.Post()) fun replaceShit() { btfReplaceElement(ComposeModalContent.defaultModalDialogDomid) { composeParamsModalContent(fields)} btfEval(jsScrollModalToTop()) } hasErrors = anyFieldErrors(fields) if (hasErrors) { replaceShit() } else { try { if (isMidAirCollision()) Context1.get().overwriteOptimisticShit = true updateEntityParams(fields, forceOverwriteStale = forceOverwriteStale) btfRemoveModalAndProgressyNavigate(hrefAfterParamsUpdated(), replaceState = true) } catch (mac: MidAirCollision) { midAirComparisonPageHref = makeMidAirComparisonPageHref(ourFields = fields) replaceShit() } } } } } fun <T : Any> bakeShit2(ctor: () -> PencilButton<T>, forceOverwriteStale: Boolean) = {ctor().serve(forceOverwriteStale)} abstract class ServantWithSerializedShit<Shit : Any>(private val shitClass: KClass<Shit>) : Servant { abstract fun ignitino(shit: Shit) var deserializerObjectClass by notNull<Class<out Deserializer>>() var serializedShit by notNullOnce<String>() override fun ignite() { val deser = deserializerObjectClass.kotlin.objectInstance!! val shit = deser.deserialize(serializedShit).cast(shitClass) ignitino(shit) } fun handle(seria: Seriafuckable): ServantHandle.JsonizedInstance { deserializerObjectClass = seria.deserializerObject()::class.java serializedShit = seria.serialize() return ServantHandle.JsonizedInstance.of(this) } } interface Deserializer { fun deserialize(s: String): Any } object DejsonizeWithTypingDeserializer : Deserializer { override fun deserialize(s: String) = dejsonize_withTyping(s)!! } open class Retupd<FieldValue> { open fun modelToField(modelValue: Any?): FieldValue = @Suppress("UNCHECKED_CAST") (modelValue as FieldValue) open fun fieldToModel(fieldValue: FieldValue, modelType: KClass<*>): Any? = fieldValue var retriever: ((Any) -> Any?)? = null var updater: ((Any, FieldValue) -> Unit)? = null var classField: ClassField<*, *>? = null var classFieldField: ClassFieldField<*, *, *>? = null var propChain: List<KMutableProperty1<Any, Any?>>? = null fun retrieve(x: Any): FieldValue { val modelValue = firstResult<Any?> {res-> classField?.let {res(it.getFromAny(x))} classFieldField?.let {res(it.getFromAny(x))} propChain?.let {res(it.fold<KMutableProperty1<Any, Any?>, Any?>(x) {obj, prop -> prop.get(obj!!)})} retriever?.let {res(it(x))} } return modelToField(modelValue) } fun update(entity: Any, fieldValue: FieldValue) { updater?.let {return it(entity, fieldValue)} val modelType = firstResult<KClass<*>> {res-> classField?.let {res(it.fieldType.kotlin)} classFieldField?.let {res(it.subFieldType.kotlin)} propChain?.let {res(it.last().returnType.classifier.cast())} } val value = fieldToModel(fieldValue, modelType) firstResult<Unit> {res-> classField?.let {res(it.setToAny(entity, value))} classFieldField?.let {res(it.setToAny(entity, value))} propChain?.let { val obj = it.dropLast(1).fold(entity) {obj, prop -> prop.get(obj)!!} res(it.last().set(obj, value)) } } } interface With { val retupd: Retupd<*> } @Suppress("UNCHECKED_CAST") interface Helpers<T> { fun prop(x: List<KMutableProperty1<*, *>>) = fluent {retupd.propChain = x.cast()} fun prop(vararg xs: KMutableProperty1<*, *>) = prop(xs.toList()) private val retupd get() = (this as With).retupd private fun fluent(block: () -> Unit): T = (this as T).also {block()} } } class ComposeUsualHistoryTabContent(val chloe: Chloe): Dancer<Renderable> { companion object { val comparisonBannerHeight_px = 51 } val comparisonBanner = makeComparisonBanner() val comparisonBannerHeight = "${comparisonBannerHeight_px}px" fun makeComparisonBanner(): AlTag? { // 3359319e-ec4f-4a97-a809-cf6c87930407 val compareOperationId1 = chloe.compareOperationId1 ?: return null val operation = dbSelectOperationOrBailOut(compareOperationId1) val offset = "0px" rctx0.shitToPlaceAtTheVeryTopOfThePage = div().style("height: $comparisonBannerHeight;") return div().className("container").style(""" position: fixed; z-index: ${BTFConst.ZIndex.fixedTopBannerBelowNavbar}; left: 0; right: 0; top: calc(${BTFConst.bodyMarginTopForNavbar_px}px + $offset); height: $comparisonBannerHeight;""").with { oo(div().style(""" position: relative; background: #f0f4c3; height: $comparisonBannerHeight; padding-left: 8px; padding-top: 4px; border: 1px solid #afb42b; border-top: none; border-bottom-left-radius: 8px; border-bottom-right-radius: 8px; box-shadow: 0px 0px 8px 0px #9e9e9e;"""").with { oo(divFlexCenter().with { oo(span().style("font-weight: bold; margin-right: 0.5em;") .add(t("TOTE", "Сравниваем запись:"))) oo(composeOperationTitle3(operation.data)) }) oo(div().add(t("TOTE", "Теперь выбери вторую..."))) val timesClass = nextJsIdent() ooStylesheet(""" .$timesClass {color: #A1887F;} .$timesClass:hover {color: #795548; cursor: pointer;}""") oo(div().style("position: absolute; right: 8px; top: 0;") .add(FA.times().appendClassName(timesClass).also { Context1.get().jsOnDomReady.onClickReplaceState(it.attrs.id, makeUrlBasedOnCurrent { it.compareOperationId1.discard() }) })) }) } } override fun dance(): Renderable { val paginatedShit = chloe.compose() return div().with { oo(comparisonBanner) oo(paginatedShit) } } } typealias AmendableUrlProvider = (amendParams: (GetParams) -> Unit) -> String class OrderFileComparison(val orderId: Long) { fun ooFileSection(separator: AlTag, filesBefore: List<Order.File>, filesAfter: List<Order.File>) { oo(separator) val filesCreated = filesAfter .filter {after -> !filesBefore.any {before -> before.id == after.id}} .map {Pair(null, it)} ooFileList(filesCreated, sectionTitle = t("TOTE", "Добавлены файлы:"), canOpenCurrent = true) val filesUpdated = filesAfter.mapNotNull {after-> val before = filesBefore.find {before-> before.id == after.id && before.updatedAt.time < after.updatedAt.time } before?.let {Pair(before, after)} } ooFileList(filesUpdated, sectionTitle = t("TOTE", "Насрано в файлы:"), canOpenCurrent = true) val filesDeleted = filesBefore .filter {before -> !filesAfter.any {after -> after.id == before.id}} .map {Pair(null, it)} ooFileList(filesDeleted, sectionTitle = t("TOTE", "Жестоко убиты файлы:"), tagaStyle = "text-decoration: line-through;", canOpenCurrent = false) if (filesCreated.isEmpty() && filesUpdated.isEmpty() && filesDeleted.isEmpty()) separator.displayNone() } fun ooFileList(files: List<Pair<Order.File?, Order.File>>, sectionTitle: String, tagaStyle: String = "", canOpenCurrent: Boolean) { if (files.isNotEmpty()) { oo(div(t("TOTE", sectionTitle)).style("font-weight: bold;")) for (file in files) { val domidTaga = nextDomid() Context1.get().jsOnDomReady.onClick(domidTaga, jsBustOutModal { it.blueLeftMargin() it.title = t("TOTE", "Файл ") + AlText.numString(file.second.id) if (canOpenCurrent) { it.nearTitle = ComposeChevronLink( title = t("TOTE", "Открыть текущий"), href = SpitOrderPage.href(orderId) { it.tab.set(OrderFilesTab_A2.filesTabID) it.search.set("${file.second.id}")}) .WithLeftMargin().newTab().appendStyle("margin-top: 2px;") } it.body = div().with {ooOrderFileComparison(file.first, file.second)} }) oo(div().style("margin-left: 1.5em;").with { oo(FA.file().style("margin-right: 0.5em; color: ${Color.Gray500};")) oo(taga().id(domidTaga).href("#").add(file.second.title).style(tagaStyle)) oo(span(AlText.fileId(file.second.id) + ", " + TimePile.kievTimeString(file.second.updatedAt)).style("margin-left: 1em; font-style: italic;")) }) } } } } class UserSeedingFarts { companion object { fun approveProfile(testUser: TestUser) { !object : UserSeedingFarts.ByAdmin(testUser) { override fun farts(fart: (() -> Unit) -> Unit) { fart { doApproveProfile(freshUser())} } } } fun createProfileAndSendForApproval(testUser: TestUser, fill: (WriterProfileFields) -> Unit) { !object : UserSeedingFarts.ByWriter(testUser) { override fun farts(fart: (() -> Unit) -> Unit) { fart { NewProfilePage().serveGivenNoFieldErrors( user = freshUser(), fields = useFields(WriterProfileFields(), FieldSource.Initial()).also {fill(it)})} fart { doSendProfileForApproval(freshUser())} } } } } abstract class ByActor(val testUser: TestUser) : Dancer<Unit> { abstract val site: AlSite abstract fun actor(): User abstract fun farts(fart: (() -> Unit) -> Unit) fun freshUser() = dbSelectMaybeUserByEmail(testUser.email)!! override fun dance() { fun fart(block: () -> Unit) { AlTestPile.pretendingSiteIs(site) {ctx -> ctx.imposedMaybeUser = Lin(actor()) block() } } farts(::fart) } } abstract class ByAdmin(testUser: TestUser) : ByActor(testUser) { override val site = AlSite.BoloneAdmin override fun actor() = dbSelectMaybeUserByEmail(TestUsers.dasja.email)!! } abstract class ByWriter(testUser: TestUser) : ByActor(testUser) { override val site = AlSite.BoloneWriter override fun actor() = freshUser() } } object Iconography { val customerIcon = FA.user!! val writerIcon = FA.pencil!! val adminIcon = FA.cog!! fun iconWithStyle(site: AlSite): FAIconWithStyle { val icon: FA.Icon; val style: String; val nonFirstItemClass: AlCSS.Pack; val amendTitleBar: (AlTag) -> Unit when (site) { AlSite.BoloneCustomer -> { icon = customerIcon style = "font-size: 125%; top: 4px;" nonFirstItemClass = AlCSS.fartus1.p1BlueGray amendTitleBar = {} } AlSite.BoloneWriter -> { icon = writerIcon style = "" nonFirstItemClass = AlCSS.fartus1.p1BlueGray amendTitleBar = {} } AlSite.BoloneAdmin -> { icon = adminIcon style = "color: ${Color.Brown400}" nonFirstItemClass = AlCSS.fartus1.p1LightGreen amendTitleBar = {it.appendStyle("background-color: ${Color.LightGreen100};")} } else -> bitchUnsupportedSite() } return FAIconWithStyle(icon = icon, style = style, nonFirstItemClass = nonFirstItemClass, amendTitleBar = amendTitleBar) } fun iconWithStyle(user: User) = iconWithStyle(when (user.kind) { AlUserKind.Customer -> AlSite.BoloneCustomer AlUserKind.Writer -> AlSite.BoloneWriter AlUserKind.Admin -> AlSite.BoloneAdmin }) }
apache-2.0
d52912db9dfe22e5806d047473bbc20e
35.479005
172
0.55683
4.296758
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/index/actions/GitStageAllAction.kt
6
1275
// 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 git4idea.index.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import git4idea.index.GitStageTracker import git4idea.index.isStagingAreaAvailable import git4idea.index.ui.NodeKind import git4idea.index.ui.fileStatusNodes import git4idea.index.ui.hasMatchingRoots abstract class GitStageAllActionBase(vararg val kinds: NodeKind) : DumbAwareAction() { override fun update(e: AnActionEvent) { val project = e.project if (project == null || !isStagingAreaAvailable(project)) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true e.presentation.isEnabled = GitStageTracker.getInstance(project).state.hasMatchingRoots(*kinds) } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! performStageOperation(project, GitStageTracker.getInstance(project).state.fileStatusNodes(*kinds), GitAddOperation) } } class GitStageAllAction : GitStageAllActionBase(NodeKind.UNTRACKED, NodeKind.UNSTAGED) class GitStageTrackedAction : GitStageAllActionBase(NodeKind.UNSTAGED)
apache-2.0
1c28a3d7f55aed8a8781e94b99600e7e
40.16129
140
0.797647
4.473684
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/PackageExistenceChecker.kt
1
1378
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir.low.level.api import com.intellij.openapi.project.Project import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.idea.caches.resolve.IdePackageOracleFactory import org.jetbrains.kotlin.name.FqName internal sealed class PackageExistenceChecker { abstract fun isPackageExists(packageFqName: FqName): Boolean } internal class PackageExistenceCheckerForSingleModule( project: Project, module: ModuleInfo ) : PackageExistenceChecker() { private val oracle = project.getService(IdePackageOracleFactory::class.java).createOracle(module) override fun isPackageExists(packageFqName: FqName): Boolean = oracle.packageExists(packageFqName) } internal class PackageExistenceCheckerForMultipleModules( project: Project, modules: List<ModuleInfo> ) : PackageExistenceChecker() { private val oracles = run { val factory = project.getService(IdePackageOracleFactory::class.java) modules.map { factory.createOracle(it) } } override fun isPackageExists(packageFqName: FqName): Boolean = oracles.any { oracle -> oracle.packageExists(packageFqName) } }
apache-2.0
3ef5af62fbe572b3369e909b39e983a6
36.27027
115
0.773585
4.388535
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/structureView/KotlinStructureViewModel.kt
6
3701
// 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.structureView import com.intellij.ide.structureView.StructureViewModel import com.intellij.ide.structureView.StructureViewModelBase import com.intellij.ide.structureView.StructureViewTreeElement import com.intellij.ide.structureView.impl.java.VisibilitySorter import com.intellij.ide.util.treeView.smartTree.* import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.util.PlatformIcons import org.jetbrains.kotlin.idea.KotlinIdeaAnalysisBundle import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.isPropertyParameter class KotlinStructureViewModel(ktFile: KtFile, editor: Editor?) : StructureViewModelBase(ktFile, editor, KotlinStructureViewElement(ktFile, false)), StructureViewModel.ElementInfoProvider { init { withSorters(KotlinVisibilitySorter, Sorter.ALPHA_SORTER) } override fun isSuitable(element: PsiElement?): Boolean = element is KtDeclaration && element !is KtPropertyAccessor && element !is KtFunctionLiteral && !(element is KtProperty && element.parent !is KtFile && element.containingClassOrObject !is KtNamedDeclaration) && !(element is KtFunction && element.parent !is KtFile && element.containingClassOrObject !is KtNamedDeclaration) override fun getNodeProviders() = NODE_PROVIDERS override fun getFilters() = FILTERS override fun isAlwaysShowsPlus(element: StructureViewTreeElement): Boolean { val value = element.value return (value is KtClassOrObject && value !is KtEnumEntry) || value is KtFile } override fun isAlwaysLeaf(element: StructureViewTreeElement): Boolean { // Local declarations can in any other declaration return false } companion object { private val NODE_PROVIDERS = listOf(KotlinInheritedMembersNodeProvider()) private val FILTERS = arrayOf(PropertiesFilter, PublicElementsFilter) } } object KotlinVisibilitySorter : VisibilitySorter() { override fun getComparator() = Comparator<Any> { a1, a2 -> a1.accessLevel() - a2.accessLevel() } private fun Any.accessLevel() = (this as? KotlinStructureViewElement)?.visibility?.accessLevel ?: Int.MAX_VALUE override fun getName() = ID const val ID = "KOTLIN_VISIBILITY_SORTER" } object PublicElementsFilter : Filter { override fun isVisible(treeNode: TreeElement): Boolean { return (treeNode as? KotlinStructureViewElement)?.visibility?.isPublic ?: true } override fun getPresentation(): ActionPresentation { return ActionPresentationData(KotlinIdeaAnalysisBundle.message("show.non.public"), null, PlatformIcons.PRIVATE_ICON) } override fun getName() = ID override fun isReverted() = true const val ID = "KOTLIN_SHOW_NON_PUBLIC" } object PropertiesFilter : Filter { override fun isVisible(treeNode: TreeElement): Boolean { val element = (treeNode as? KotlinStructureViewElement)?.element val isProperty = element is KtProperty && element.isMember || element is KtParameter && element.isPropertyParameter() return !isProperty } override fun getPresentation(): ActionPresentation { return ActionPresentationData(KotlinIdeaAnalysisBundle.message("show.properties"), null, PlatformIcons.PROPERTY_ICON) } override fun getName() = ID override fun isReverted() = true const val ID = "KOTLIN_SHOW_PROPERTIES" }
apache-2.0
51c7419166f1ce153c3a7b854f508f51
38.37234
158
0.746285
4.974462
false
false
false
false
egf2-guide/guide-android
app/src/main/kotlin/com/eigengraph/egf2/guide/ui/adapter/PostsAdapter.kt
1
1386
package com.eigengraph.egf2.guide.ui.adapter import android.support.v7.widget.RecyclerView import android.view.ViewGroup import com.eigengraph.egf2.guide.models.EGF2File import com.eigengraph.egf2.guide.models.EGF2Post import com.eigengraph.egf2.guide.models.EGF2User import com.eigengraph.egf2.guide.ui.adapter.holder.PostItemViewHolder import com.eigengraph.egf2.guide.ui.anko.PostItemUI import com.eigengraph.egf2.guide.util.RecyclerClickListener import java.util.* class PostsAdapter : RecyclerView.Adapter<PostItemViewHolder> { override fun getItemCount() = list.size val list: ArrayList<EGF2Post> val images: HashMap<String, EGF2File> val creators: HashMap<String, EGF2User> private val listener: RecyclerClickListener private var isAdmin = false constructor(li: ArrayList<EGF2Post>, mapImage: HashMap<String, EGF2File>, mapCreator: HashMap<String, EGF2User>, listener: RecyclerClickListener, admin: Boolean = false) { list = li images = mapImage creators = mapCreator this.listener = listener isAdmin = admin } override fun onBindViewHolder(holder: PostItemViewHolder?, position: Int) { val post = list[position] holder?.bind(post, images[post.image], creators[post.creator]) } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): PostItemViewHolder { return PostItemViewHolder(PostItemUI().bind(parent!!), listener, isAdmin) } }
mit
d4e677a6e5f1e4377af10242c939630c
34.564103
172
0.794372
3.647368
false
false
false
false
sg26565/hott-transmitter-config
HoTT-Serial/src/main/kotlin/de/treichels/hott/serial/TxInfo.kt
1
1690
/** * HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package de.treichels.hott.serial import de.treichels.hott.model.enums.LCDType import de.treichels.hott.model.enums.TransmitterType import java.io.Serializable /** * @author Oliver Treichel &lt;[email protected]&gt; */ data class TxInfo( val rfId: Long, val transmitterType: TransmitterType, val appVersion: Int, val memoryVersion: Int, val bootProductCode: Int, val bootVersion: Int, val lcdType: LCDType, val transmitterName: String, val vendorName: String, val ownerName: String, val customPhaseNames: List<String>) : Serializable { override fun toString(): String { return "TxInfo [transmitterType=$transmitterType, appVersion=$appVersion, memoryVersion=$memoryVersion, bootProductCode=$bootProductCode, bootVersion=$bootVersion, lcdType=$lcdType transmitterName=$transmitterName, vendorName=$vendorName, ownerName=$ownerName, customPhaseNames=$customPhaseNames]" } }
lgpl-3.0
9762c2436021fa26b7397abd503a9707
44.675676
305
0.735503
4.28934
false
false
false
false
sg26565/hott-transmitter-config
HoTT-Serial/src/main/kotlin/de/treichels/hott/serial/SerialPort.kt
1
3088
/** * HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package de.treichels.hott.serial import de.treichels.hott.model.HoTTException import de.treichels.hott.serial.spi.SerialPortProvider import de.treichels.hott.util.ByteOrder import de.treichels.hott.util.readInt import de.treichels.hott.util.readLong import de.treichels.hott.util.readShort import java.io.Closeable import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.util.* /** * @author Oliver Treichel &lt;[email protected]&gt; */ interface SerialPort : Closeable { val inputStream: InputStream val outputStream: OutputStream val portName: String var baudRate: Int val isOpen: Boolean var timeout: Int @Throws(HoTTException::class) override fun close() @Throws(HoTTException::class) fun open() @Throws(HoTTException::class) fun reset() fun readBytes(data: ByteArray, length: Long = data.size.toLong(), offset: Long = 0L): Int fun writeBytes(data: ByteArray, length: Long = data.size.toLong(), offset: Long = 0L): Int fun write(b: Int) = writeBytes(byteArrayOf(b.toByte())) fun read() = readIntoBuffer(1)[0].toInt() and 0xff fun readShort(byteOrder: ByteOrder = ByteOrder.LittleEndian) = readIntoBuffer(Short.SIZE_BYTES).readShort(byteOrder = byteOrder) fun readInt(byteOrder: ByteOrder = ByteOrder.LittleEndian) = readIntoBuffer(Int.SIZE_BYTES).readInt(byteOrder = byteOrder) fun readLong(byteOrder: ByteOrder = ByteOrder.LittleEndian) = readIntoBuffer(Long.SIZE_BYTES).readLong(byteOrder = byteOrder) private fun readIntoBuffer(size: Int): ByteArray { val buffer = ByteArray(size) val rc = readBytes(buffer) return if (rc == size) buffer else throw IOException() } fun expect(rc: Int) { val b = read() if (b != rc) throw IOException("Invalid response: expected $rc but got $b") } fun wait4Data() { for (i in 1..100) { if (inputStream.available() > 0) return Thread.sleep(10) } throw IOException("timeout") } companion object { private val provider: SerialPortProvider by lazy { ServiceLoader.load(SerialPortProvider::class.java).first() } fun getAvailablePorts(): List<String> = provider.getAvailablePorts() fun getPort(name: String): SerialPort = provider.getPort(name) } }
lgpl-3.0
73d7b260b932d7db73f0ef623021927a
34.906977
160
0.705959
4.172973
false
false
false
false
Commit451/Addendum
addendum/src/main/java/com/commit451/addendum/Activity.kt
1
1630
@file:Suppress("NOTHING_TO_INLINE", "unused") package com.commit451.addendum import android.app.Activity import android.graphics.Point import android.view.View import android.view.WindowManager import androidx.annotation.IdRes inline fun Activity.flagFullscreen() { window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE } inline fun Activity.screenHeight(): Int { val display = windowManager.defaultDisplay val size = Point() display.getSize(size) return size.y } inline fun Activity.screenWidth(): Int { val display = windowManager.defaultDisplay val size = Point() display.getSize(size) return size.x } /** * Sets the screen brightness. Call this before setContentView. * 0 is dimmest, 1 is brightest. Default value is 1 */ inline fun Activity.brightness(brightness: Float = 1f) { val params = window.attributes params.screenBrightness = brightness // range from 0 - 1 as per docs window.attributes = params window.addFlags(WindowManager.LayoutParams.FLAGS_CHANGED) } inline fun <T : View> Activity.bindView(@IdRes id: Int): Lazy<T> { @Suppress("UNCHECKED_CAST") return lazy(LazyThreadSafetyMode.NONE) { findViewById<T>(id) } } inline fun <T> Activity.extra(key: String): Lazy<T> { return lazy(LazyThreadSafetyMode.NONE) { @Suppress("UNCHECKED_CAST") intent.extras.get(key) as T } } inline fun <T> Activity.extraOrNull(key: String): Lazy<T?> { return lazy(LazyThreadSafetyMode.NONE) { @Suppress("UNCHECKED_CAST") intent.extras.get(key) as? T? } }
apache-2.0
65846bf12c67884652cca01da46c1d14
26.627119
116
0.71411
3.84434
false
false
false
false
aosp-mirror/platform_frameworks_support
lifecycle/compiler/src/main/kotlin/androidx/lifecycle/writer.kt
1
8379
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.lifecycle import androidx.lifecycle.model.AdapterClass import androidx.lifecycle.model.EventMethodCall import androidx.lifecycle.model.getAdapterName import com.squareup.javapoet.AnnotationSpec import com.squareup.javapoet.ClassName import com.squareup.javapoet.FieldSpec import com.squareup.javapoet.JavaFile import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterSpec import com.squareup.javapoet.TypeName import com.squareup.javapoet.TypeSpec import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Modifier import javax.lang.model.element.TypeElement import javax.tools.StandardLocation fun writeModels(infos: List<AdapterClass>, processingEnv: ProcessingEnvironment) { infos.forEach({ writeAdapter(it, processingEnv) }) } private val GENERATED_PACKAGE = "javax.annotation" private val GENERATED_NAME = "Generated" private val LIFECYCLE_EVENT = Lifecycle.Event::class.java private val T = "\$T" private val N = "\$N" private val L = "\$L" private val S = "\$S" private val OWNER_PARAM: ParameterSpec = ParameterSpec.builder( ClassName.get(LifecycleOwner::class.java), "owner").build() private val EVENT_PARAM: ParameterSpec = ParameterSpec.builder( ClassName.get(LIFECYCLE_EVENT), "event").build() private val ON_ANY_PARAM: ParameterSpec = ParameterSpec.builder(TypeName.BOOLEAN, "onAny").build() private val METHODS_LOGGER: ParameterSpec = ParameterSpec.builder( ClassName.get(MethodCallsLogger::class.java), "logger").build() private const val HAS_LOGGER_VAR = "hasLogger" private fun writeAdapter(adapter: AdapterClass, processingEnv: ProcessingEnvironment) { val receiverField: FieldSpec = FieldSpec.builder(ClassName.get(adapter.type), "mReceiver", Modifier.FINAL).build() val dispatchMethodBuilder = MethodSpec.methodBuilder("callMethods") .returns(TypeName.VOID) .addParameter(OWNER_PARAM) .addParameter(EVENT_PARAM) .addParameter(ON_ANY_PARAM) .addParameter(METHODS_LOGGER) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override::class.java) val dispatchMethod = dispatchMethodBuilder.apply { addStatement("boolean $L = $N != null", HAS_LOGGER_VAR, METHODS_LOGGER) val callsByEventType = adapter.calls.groupBy { it.method.onLifecycleEvent.value } beginControlFlow("if ($N)", ON_ANY_PARAM).apply { writeMethodCalls(callsByEventType[Lifecycle.Event.ON_ANY] ?: emptyList(), receiverField) }.endControlFlow() callsByEventType .filterKeys { key -> key != Lifecycle.Event.ON_ANY } .forEach { (event, calls) -> beginControlFlow("if ($N == $T.$L)", EVENT_PARAM, LIFECYCLE_EVENT, event) writeMethodCalls(calls, receiverField) endControlFlow() } }.build() val receiverParam = ParameterSpec.builder( ClassName.get(adapter.type), "receiver").build() val syntheticMethods = adapter.syntheticMethods.map { val method = MethodSpec.methodBuilder(syntheticName(it)) .returns(TypeName.VOID) .addModifiers(Modifier.PUBLIC) .addModifiers(Modifier.STATIC) .addParameter(receiverParam) if (it.parameters.size >= 1) { method.addParameter(OWNER_PARAM) } if (it.parameters.size == 2) { method.addParameter(EVENT_PARAM) } val count = it.parameters.size val paramString = generateParamString(count) method.addStatement("$N.$L($paramString)", receiverParam, it.name(), *takeParams(count, OWNER_PARAM, EVENT_PARAM)) method.build() } val constructor = MethodSpec.constructorBuilder() .addParameter(receiverParam) .addStatement("this.$N = $N", receiverField, receiverParam) .build() val adapterName = getAdapterName(adapter.type) val adapterTypeSpecBuilder = TypeSpec.classBuilder(adapterName) .addModifiers(Modifier.PUBLIC) .addSuperinterface(ClassName.get(GeneratedAdapter::class.java)) .addField(receiverField) .addMethod(constructor) .addMethod(dispatchMethod) .addMethods(syntheticMethods) addGeneratedAnnotationIfAvailable(adapterTypeSpecBuilder, processingEnv) JavaFile.builder(adapter.type.getPackageQName(), adapterTypeSpecBuilder.build()) .build().writeTo(processingEnv.filer) generateKeepRule(adapter.type, processingEnv) } private fun addGeneratedAnnotationIfAvailable(adapterTypeSpecBuilder: TypeSpec.Builder, processingEnv: ProcessingEnvironment) { val generatedAnnotationAvailable = processingEnv .elementUtils .getTypeElement(GENERATED_PACKAGE + "." + GENERATED_NAME) != null if (generatedAnnotationAvailable) { val generatedAnnotationSpec = AnnotationSpec.builder(ClassName.get(GENERATED_PACKAGE, GENERATED_NAME)).addMember( "value", S, LifecycleProcessor::class.java.canonicalName).build() adapterTypeSpecBuilder.addAnnotation(generatedAnnotationSpec) } } private fun generateKeepRule(type: TypeElement, processingEnv: ProcessingEnvironment) { val adapterClass = type.getPackageQName() + "." + getAdapterName(type) val observerClass = type.toString() val keepRule = """# Generated keep rule for Lifecycle observer adapter. |-if class $observerClass { | <init>(...); |} |-keep class $adapterClass { | <init>(...); |} |""".trimMargin() // Write the keep rule to the META-INF/proguard directory of the Jar file. The file name // contains the fully qualified observer name so that file names are unique. This will allow any // jar file merging to not overwrite keep rule files. val path = "META-INF/proguard/$observerClass.pro" val out = processingEnv.filer.createResource(StandardLocation.CLASS_OUTPUT, "", path) out.openWriter().use { it.write(keepRule) } } private fun MethodSpec.Builder.writeMethodCalls(calls: List<EventMethodCall>, receiverField: FieldSpec) { calls.forEach { (method, syntheticAccess) -> val count = method.method.parameters.size val callType = 1 shl count val methodName = method.method.name() beginControlFlow("if (!$L || $N.approveCall($S, $callType))", HAS_LOGGER_VAR, METHODS_LOGGER, methodName).apply { if (syntheticAccess == null) { val paramString = generateParamString(count) addStatement("$N.$L($paramString)", receiverField, methodName, *takeParams(count, OWNER_PARAM, EVENT_PARAM)) } else { val originalType = syntheticAccess val paramString = generateParamString(count + 1) val className = ClassName.get(originalType.getPackageQName(), getAdapterName(originalType)) addStatement("$T.$L($paramString)", className, syntheticName(method.method), *takeParams(count + 1, receiverField, OWNER_PARAM, EVENT_PARAM)) } }.endControlFlow() } addStatement("return") } private fun takeParams(count: Int, vararg params: Any) = params.take(count).toTypedArray() private fun generateParamString(count: Int) = (0 until count).joinToString(",") { N }
apache-2.0
d79d8ec62e800de07f46fae25bf71f2d
41.532995
100
0.663444
4.785266
false
false
false
false
kvnxiao/meirei
meirei-core/src/main/kotlin/com/github/kvnxiao/discord/meirei/Meirei.kt
1
2547
/* * Copyright (C) 2017-2018 Ze Hao Xiao * * 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.github.kvnxiao.discord.meirei import com.github.kvnxiao.discord.meirei.annotations.parser.AnnotationParser import com.github.kvnxiao.discord.meirei.annotations.parser.CommandRelations import com.github.kvnxiao.discord.meirei.command.CommandPackage import com.github.kvnxiao.discord.meirei.command.database.CommandRegistry import com.github.kvnxiao.discord.meirei.command.database.CommandRegistryImpl import mu.KotlinLogging abstract class Meirei( protected val registry: CommandRegistry = CommandRegistryImpl(), protected val commandParser: AnnotationParser ) { companion object { @JvmStatic val LOGGER = KotlinLogging.logger(Meirei::class.java.name) const val ENV_COMMAND_JAR_FOLDER = "ext_jar_folder" } open fun addCommands(vararg commandPackages: CommandPackage) { commandPackages.forEach { registry.addCommand(it.command, it.commandProperties, it.permissionProperties) } } open fun addSubCommands(parentId: String, vararg commandPackage: CommandPackage) { commandPackage.forEach { registry.addSubCommand(it.command, it.commandProperties, it.permissionProperties, parentId) } } open fun addAnnotatedCommands(vararg instances: Any) { instances.forEach { val relations = commandParser.parseAnnotations(it) relations.forEach { addCommands(it.pkg) addNestedSubCommands(it) } } } abstract fun registerEventListeners(client: Any) protected open fun addNestedSubCommands(relation: CommandRelations) { val subPkgs = relation.subPkgs if (subPkgs.isNotEmpty()) { subPkgs.forEach { subRelation -> addSubCommands(subRelation.pkg.commandProperties.parentId, subRelation.pkg) addNestedSubCommands(subRelation) } } } }
apache-2.0
477e5a93e2cf63177d8fbd9701e5df0e
35.913043
103
0.702395
4.398964
false
false
false
false
EMResearch/EvoMaster
e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/input/type/Flower.kt
1
204
package com.foo.graphql.input.type data class Flower ( var id: Int? = null, var name: String? = null, var type: String? = null, var color: String? = null, var price: Int? = null)
lgpl-3.0
1e8ea1bf60199a42708ea99b1a772e13
24.625
34
0.602941
3.344262
false
false
false
false
RSDT/Japp
app/src/main/java/nl/rsdt/japp/jotial/maps/NavigationLocationManager.kt
1
2846
package nl.rsdt.japp.jotial.maps import com.google.firebase.database.* import nl.rsdt.japp.application.Japp import nl.rsdt.japp.application.JappPreferences import nl.rsdt.japp.jotial.data.firebase.Location import nl.rsdt.japp.jotial.data.structures.area348.AutoInzittendeInfo import nl.rsdt.japp.jotial.net.apis.AutoApi import retrofit2.Call import retrofit2.Callback import retrofit2.Response /** * Created by mattijn on 30/09/17. */ class NavigationLocationManager : ChildEventListener, ValueEventListener { private var callback: OnNewLocation? = null private var oldLoc: Location? = null init { val reference = FirebaseDatabase.getInstance().reference.child(FDB_NAME) reference.addValueEventListener(this) } private fun update(snapshot: DataSnapshot, child: String?) { val id = JappPreferences.accountId if (id >= 0) { val api = Japp.getApi(AutoApi::class.java) api.getInfoById(JappPreferences.accountKey, id).enqueue(object : Callback<AutoInzittendeInfo> { override fun onResponse(call: Call<AutoInzittendeInfo>, response: Response<AutoInzittendeInfo>) { if (response.code() == 200) { val info = response.body() val loc = snapshot.child(info!!.autoEigenaar!!).getValue(Location::class.java) if (oldLoc != null && oldLoc != loc || oldLoc == null && loc != null) { oldLoc = loc if (loc != null) { callback?.onNewLocation(loc) } } } else if (response.code() == 404) { callback?.onNotInCar() } } override fun onFailure(call: Call<AutoInzittendeInfo>, t: Throwable) { throw RuntimeException(t) } }) } } override fun onChildAdded(dataSnapshot: DataSnapshot, s: String?) { update(dataSnapshot, s) } override fun onChildChanged(dataSnapshot: DataSnapshot, s: String?) { update(dataSnapshot, s) } override fun onChildRemoved(dataSnapshot: DataSnapshot) { } override fun onChildMoved(dataSnapshot: DataSnapshot, s: String?) { } override fun onDataChange(dataSnapshot: DataSnapshot) { update(dataSnapshot, dataSnapshot.key) } override fun onCancelled(databaseError: DatabaseError) { throw databaseError.toException() } fun setCallback(callback: OnNewLocation) { this.callback = callback } interface OnNewLocation { fun onNewLocation(location: Location) fun onNotInCar() } companion object { val FDB_NAME = "autos" } }
apache-2.0
fa3d98e0845fb2cec0e8f6b591355ecd
30.977528
113
0.601897
4.848382
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/libjamiclient/src/main/kotlin/net/jami/model/ContactEvent.kt
1
3221
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Adrien Béraud <[email protected]> * Rayan Osseiran <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package net.jami.model class ContactEvent : Interaction { var request: TrustRequest? = null @JvmField var event: Event constructor(interaction: Interaction) { id = interaction.id conversation = interaction.conversation author = interaction.author mType = InteractionType.CONTACT.toString() timestamp = interaction.timestamp mStatus = interaction.status.toString() mIsRead = 1 contact = interaction.contact event = getEventFromStatus(interaction.status) } constructor() { author = null event = Event.ADDED mType = InteractionType.CONTACT.toString() timestamp = System.currentTimeMillis() mStatus = InteractionStatus.SUCCESS.toString() mIsRead = 1 } constructor(contact: Contact) { this.contact = contact author = contact.uri.uri mType = InteractionType.CONTACT.toString() event = Event.ADDED mStatus = InteractionStatus.SUCCESS.toString() timestamp = contact.addedDate!!.time mIsRead = 1 } constructor(contact: Contact, request: TrustRequest) { this.request = request this.contact = contact author = contact.uri.uri timestamp = request.timestamp mType = InteractionType.CONTACT.toString() event = Event.INCOMING_REQUEST mStatus = InteractionStatus.UNKNOWN.toString() mIsRead = 1 } enum class Event { UNKNOWN, INCOMING_REQUEST, INVITED, ADDED, REMOVED, BANNED; companion object { fun fromConversationAction(action: String): Event { return when (action) { "add" -> INVITED "join" -> ADDED "remove" -> REMOVED "ban" -> BANNED else -> UNKNOWN } } } } fun setEvent(event: Event): ContactEvent { this.event = event return this } private fun getEventFromStatus(status: InteractionStatus): Event { // success for added contacts if (status === InteractionStatus.SUCCESS) return Event.ADDED else if (status === InteractionStatus.UNKNOWN) return Event.INCOMING_REQUEST return Event.UNKNOWN } }
gpl-3.0
6dee5a3bc28b81931e39da57a18b8a55
32.552083
145
0.635093
4.756278
false
false
false
false
fluidsonic/jetpack-kotlin
Sources/Measurement/Pressure.kt
1
1636
package com.github.fluidsonic.jetpack import com.github.fluidsonic.jetpack.Pressure.Unit import java.util.Locale public class Pressure : Measurement<Pressure, Unit> { private constructor(rawValue: Double) : super(rawValue) public constructor(pressure: Pressure) : super(pressure.rawValue) protected override val description: Description<Pressure, Unit> get() = Pressure.description public fun inchesOfMercury() = millibars() * inchesOfMercuryPerMillibar public fun millibars() = rawValue public override fun valueInUnit(unit: Unit) = when (unit) { Pressure.Unit.inchesOfMercury -> inchesOfMercury() Pressure.Unit.millibars -> millibars() } public enum class Unit private constructor(key: String) : _StandardUnitType<Unit, Pressure> { inchesOfMercury("inchOfMercury"), millibars("millibar"); public override val _descriptor = _StandardUnitType.Descriptor(key) public override fun toString() = pluralName(Locale.getDefault()) public override fun value(value: Double) = when (this) { inchesOfMercury -> inchesOfMercury(value) millibars -> millibars(value) } } public companion object { private val description = Measurement.Description("Pressure", Unit.millibars) private val inchesOfMercuryPerMillibar = 0.02953 private val millibarsPerInchOfMercury = 1 / inchesOfMercuryPerMillibar public fun inchesOfMercury(inchesOfMercury: Double) = millibars(Measurement.validatedValue(inchesOfMercury) * millibarsPerInchOfMercury) public fun millibars(millibars: Double) = Pressure(rawValue = Measurement.validatedValue(millibars)) } }
mit
0129a8deae413cef379dad9e7556796c
22.042254
94
0.752445
3.533477
false
false
false
false
shymmq/librus-client-kotlin
app/src/main/kotlin/com/wabadaba/dziennik/ui/announcements/AnnouncementsViewModel.kt
1
2129
package com.wabadaba.dziennik.ui.announcements import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import com.wabadaba.dziennik.api.EntityRepository import com.wabadaba.dziennik.ui.monthNameNominative import com.wabadaba.dziennik.ui.multiPut import com.wabadaba.dziennik.vo.Announcement import io.reactivex.android.schedulers.AndroidSchedulers import org.joda.time.LocalDate import org.joda.time.Months import java.util.* class AnnouncementsViewModel(entityRepo: EntityRepository) : ViewModel() { val announcementData = MutableLiveData<AnnouncementData>() init { entityRepo.announcements.observeOn(AndroidSchedulers.mainThread()) .subscribe { announcements -> val result = AnnouncementData() announcements.filter { it.addDate != null } .forEach { announcement -> val date = announcement.addDate!!.toLocalDate() val header = when (date) { LocalDate.now() -> AnnouncementHeader(0, "Dzisiaj") in LocalDate.now().minusDays(LocalDate.now().dayOfWeek - 1) .. LocalDate.now() -> AnnouncementHeader(1, "Ten tydzień") in LocalDate.now().minusDays(LocalDate.now().dayOfMonth - 1) .. LocalDate.now() -> AnnouncementHeader(2, "Ten miesiąc") else -> AnnouncementHeader(3 + Months.monthsBetween(date, LocalDate.now()).months, date.monthNameNominative().capitalize()) } result.multiPut(header, announcement) } announcementData.value = result } } } class AnnouncementData : TreeMap<AnnouncementHeader, List<Announcement>>({ (order1), (order2) -> order1.compareTo(order2) }) data class AnnouncementHeader(val order: Int, val title: String)
gpl-3.0
e64956ae3825caac5867469d3559baf8
47.363636
124
0.5811
5.251852
false
false
false
false
elect86/modern-jogl-examples
src/main/kotlin/glNext/tut06/rotations.kt
2
7602
package glNext.tut06 import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL.* import com.jogamp.opengl.GL3 import glNext.* import glm.* import glm.mat.Mat3 import glm.mat.Mat4 import glm.vec._3.Vec3 import glm.vec._4.Vec4 import main.framework.Framework import uno.buffer.* import uno.glsl.programOf /** * Created by elect on 23/02/17. */ fun main(args: Array<String>) { Rotations_Next().setup("Tutorial 06 - Rotations") } class Rotations_Next : Framework() { object Buffer { val VERTEX = 0 val INDEX = 1 val MAX = 2 } var theProgram = 0 var modelToCameraMatrixUnif = 0 var cameraToClipMatrixUnif = 0 val cameraToClipMatrix = Mat4(0.0f) val frustumScale = calcFrustumScale(45.0f) fun calcFrustumScale(fovDeg: Float) = 1.0f / glm.tan(fovDeg.rad / 2.0f) val bufferObject = intBufferBig(Buffer.MAX) val vao = intBufferBig(1) val numberOfVertices = 8 val GREEN_COLOR = floatArrayOf(0.0f, 1.0f, 0.0f, 1.0f) val BLUE_COLOR = floatArrayOf(0.0f, 0.0f, 1.0f, 1.0f) val RED_COLOR = floatArrayOf(1.0f, 0.0f, 0.0f, 1.0f) val BROWN_COLOR = floatArrayOf(0.5f, 0.5f, 0.0f, 1.0f) val vertexData = floatBufferOf( +1.0f, +1.0f, +1.0f, -1.0f, -1.0f, +1.0f, -1.0f, +1.0f, -1.0f, +1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, +1.0f, +1.0f, -1.0f, +1.0f, -1.0f, +1.0f, -1.0f, +1.0f, +1.0f, *GREEN_COLOR, *BLUE_COLOR, *RED_COLOR, *BROWN_COLOR, *GREEN_COLOR, *BLUE_COLOR, *RED_COLOR, *BROWN_COLOR) val indexData = shortBufferOf( 0, 1, 2, 1, 0, 3, 2, 3, 0, 3, 2, 1, 5, 4, 6, 4, 5, 7, 7, 6, 4, 6, 7, 5) private val instanceList = arrayOf( Instance(this::nullRotation, Vec3(0.0f, 0.0f, -25.0f)), Instance(this::rotateX, Vec3(-5.0f, -5.0f, -25.0f)), Instance(this::rotateY, Vec3(-5.0f, +5.0f, -25.0f)), Instance(this::rotateZ, Vec3(+5.0f, +5.0f, -25.0f)), Instance(this::rotateAxis, Vec3(5.0f, -5.0f, -25.0f))) var start = 0L override fun init(gl: GL3) = with(gl) { initializeProgram(gl) initializeVertexBuffers(gl) initVertexArray(vao) { val colorDataOffset = Vec3.SIZE * numberOfVertices array(bufferObject[Buffer.VERTEX], glf.pos3_col4, 0, colorDataOffset) element(bufferObject[Buffer.INDEX]) } cullFace { enable() cullFace = back frontFace = cw } depth { test = true mask = true func = lEqual range = 0.0 .. 1.0 } start = System.currentTimeMillis() } fun initializeProgram(gl: GL3) = with(gl) { theProgram = programOf(gl, javaClass, "tut06", "pos-color-local-transform.vert", "color-passthrough.frag") withProgram(theProgram) { modelToCameraMatrixUnif = "modelToCameraMatrix".location cameraToClipMatrixUnif = "cameraToClipMatrix".location val zNear = 1.0f val zFar = 61.0f cameraToClipMatrix[0].x = frustumScale cameraToClipMatrix[1].y = frustumScale cameraToClipMatrix[2].z = (zFar + zNear) / (zNear - zFar) cameraToClipMatrix[2].w = -1.0f cameraToClipMatrix[3].z = 2f * zFar * zNear / (zNear - zFar) use { cameraToClipMatrixUnif.mat4 = cameraToClipMatrix } } } fun initializeVertexBuffers(gl: GL3) = with(gl) { glGenBuffers(bufferObject) withArrayBuffer(bufferObject[Buffer.VERTEX]) { data(vertexData, GL_STATIC_DRAW) } withElementBuffer(bufferObject[Buffer.INDEX]) { data(indexData, GL_STATIC_DRAW) } } override fun display(gl: GL3) = with(gl) { clear { color(0) depth() } usingProgram(theProgram) { withVertexArray(vao) { val elapsedTime = (System.currentTimeMillis() - start) / 1_000f instanceList.forEach { val transformMatrix = it.constructMatrix(elapsedTime) modelToCameraMatrixUnif.mat4 = transformMatrix glDrawElements(indexData.size, GL_UNSIGNED_SHORT) } } } } override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { cameraToClipMatrix.a0 = frustumScale * (h / w.f) cameraToClipMatrix.b1 = frustumScale usingProgram(theProgram) { cameraToClipMatrixUnif.mat4 = cameraToClipMatrix } glViewport(w, h) } override fun end(gl: GL3) = with(gl) { glDeleteProgram(theProgram) glDeleteBuffers(bufferObject) glDeleteVertexArray(vao) destroyBuffers(vao, bufferObject, vertexData, indexData) } override fun keyPressed(keyEvent: KeyEvent) { when (keyEvent.keyCode) { KeyEvent.VK_ESCAPE -> quit() } } private class Instance(val calcRotation: (Float) -> Mat3, val offset: Vec3) { fun constructMatrix(elapsedTime: Float): Mat4 { val rotMatrix = calcRotation(elapsedTime) val theMat = Mat4(rotMatrix) theMat[3] = Vec4(offset, 1f) return theMat } } fun nullRotation(elapsedTime: Float) = Mat3(1f) fun rotateX(elapsedTime: Float): Mat3 { val angRad = computeAngleRad(elapsedTime, 3f) val cos = angRad.cos val sin = angRad.sin val theMat = Mat3(1f) theMat[1].y = cos; theMat[2].y = -sin theMat[1].z = sin; theMat[2].z = cos return theMat } fun rotateY(elapsedTime: Float): Mat3 { val angRad = computeAngleRad(elapsedTime, 2f) val cos = angRad.cos val sin = angRad.sin val theMat = Mat3(1f) theMat[0].x = cos; theMat[2].x = sin theMat[0].z = -sin; theMat[2].z = cos return theMat } fun rotateZ(elapsedTime: Float): Mat3 { val angRad = computeAngleRad(elapsedTime, 2f) val cos = angRad.cos val sin = angRad.sin val theMat = Mat3(1f) theMat[0].x = cos; theMat[1].x = -sin theMat[0].y = sin; theMat[1].y = cos return theMat } fun rotateAxis(elapsedTime: Float): Mat3 { val angRad = computeAngleRad(elapsedTime, 2f) val cos = angRad.cos val invCos = 1f - cos val sin = angRad.sin val axis = Vec3(1f).normalize_() val theMat = Mat3(1f) theMat[0].x = axis.x * axis.x + (1 - axis.x * axis.x) * cos theMat[1].x = axis.x * axis.y * invCos - axis.z * sin theMat[2].x = axis.x * axis.z * invCos + axis.y * sin theMat[0].y = axis.x * axis.y * invCos + axis.z * sin theMat[1].y = axis.y * axis.y + (1 - axis.y * axis.y) * cos theMat[2].y = axis.y * axis.z * invCos - axis.x * sin theMat[0].z = axis.x * axis.z * invCos - axis.y * sin theMat[1].z = axis.y * axis.z * invCos + axis.x * sin theMat[2].z = axis.z * axis.z + (1 - axis.z * axis.z) * cos return theMat } fun computeAngleRad(elapsedTime: Float, loopDuration: Float): Float { val scale = glm.PIf * 2.0f / loopDuration val currentTimeThroughLoop = elapsedTime % loopDuration return currentTimeThroughLoop * scale } }
mit
6b64b87c1254271da7eba592f6e9f3ee
25.767606
114
0.556827
3.574048
false
false
false
false
talent-bearers/Slimefusion
src/main/java/talent/bearers/slimefusion/common/block/BlockMark.kt
1
1748
package talent.bearers.slimefusion.common.block import com.teamwizardry.librarianlib.common.base.block.BlockMod import net.minecraft.block.material.Material import net.minecraft.block.properties.PropertyEnum import net.minecraft.block.state.BlockStateContainer import net.minecraft.block.state.IBlockState import net.minecraft.util.BlockRenderLayer import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.world.IBlockAccess import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.fml.relauncher.SideOnly import talent.bearers.slimefusion.common.core.EnumPolestone import talent.bearers.slimefusion.common.lib.LibNames /** * @author WireSegal * Created at 10:54 PM on 12/23/16. */ class BlockMark : BlockMod(LibNames.MARK, Material.GLASS, *EnumPolestone.getNamesFor(LibNames.MARK)) { companion object { val POLESTONE: PropertyEnum<EnumPolestone> = PropertyEnum.create("polestone", EnumPolestone::class.java) val AABB = AxisAlignedBB(6 / 16.0, 6 / 16.0, 6 / 16.0, 10 / 16.0, 10 / 16.0, 10 / 16.0) } override fun getBoundingBox(state: IBlockState?, source: IBlockAccess?, pos: BlockPos?) = AABB override fun isFullCube(state: IBlockState) = false override fun isOpaqueCube(state: IBlockState) = false override fun damageDropped(state: IBlockState) = getMetaFromState(state) override fun getMetaFromState(state: IBlockState) = state.getValue(POLESTONE).ordinal override fun getStateFromMeta(meta: Int) = defaultState.withProperty(POLESTONE, EnumPolestone[meta]) override fun createBlockState() = BlockStateContainer(this, POLESTONE) @SideOnly(Side.CLIENT) override fun getBlockLayer() = BlockRenderLayer.TRANSLUCENT }
mit
ded7c7673e003d04f8d807e0698fbaf2
45
112
0.784897
4.036952
false
false
false
false
LorittaBot/Loritta
web/dashboard/spicy-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/dashboard/frontend/utils/GlobalState.kt
1
4614
package net.perfectdreams.loritta.cinnamon.dashboard.frontend.utils import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import kotlinx.browser.window import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.i18nhelper.core.Language import net.perfectdreams.i18nhelper.core.keydata.StringI18nData import net.perfectdreams.loritta.cinnamon.dashboard.common.responses.GetSpicyInfoResponse import net.perfectdreams.loritta.cinnamon.dashboard.common.responses.GetUserIdentificationResponse import net.perfectdreams.loritta.cinnamon.dashboard.frontend.LorittaDashboardFrontend import net.perfectdreams.loritta.cinnamon.dashboard.frontend.components.CloseModalButton class GlobalState(val m: LorittaDashboardFrontend) { private var userInfoState = mutableStateOf<State<GetUserIdentificationResponse>>(State.Loading()) var userInfo by userInfoState var i18nContext by mutableStateOf<State<I18nContext>>(State.Loading()) private var spicyInfoState = mutableStateOf<State<GetSpicyInfoResponse>>(State.Loading()) var spicyInfo by spicyInfoState var isSidebarOpenState = mutableStateOf(false) var isSidebarOpen by isSidebarOpenState var activeModal by mutableStateOf<Modal?>(null) private val jobs = mutableListOf<Job>() suspend fun updateSelfUserInfo() { m.makeApiRequestAndUpdateState(userInfoState, HttpMethod.Get, "/api/v1/users/@me") } suspend fun updateSpicyInfo() { m.makeApiRequestAndUpdateState(spicyInfoState, HttpMethod.Get, "/api/v1/spicy") } suspend fun updateI18nContext() { val i18nContext = retrieveI18nContext() [email protected] = State.Success(i18nContext) } suspend fun retrieveI18nContext(): I18nContext { val languageId = window.location.pathname.split("/")[1] val result = m.http.get("${window.location.origin}/api/v1/languages/$languageId").bodyAsText() val language = Json.decodeFromString<Language>(result) return I18nContext( IntlMFFormatter(language.info.formattingLanguageId), Json.decodeFromString(result) ) } fun openModal( title: StringI18nData, body: @Composable () -> (Unit), vararg buttons: @Composable () -> (Unit) ) { launch { // I think it should always be "Success" here val state = i18nContext val i18nContext: I18nContext // Super hacky! Waits until the state is success and then opens the modal while (true) { val temp = (state as? State.Success)?.value if (temp != null) { i18nContext = temp break } delay(100) } activeModal = Modal( i18nContext.get(title), body, buttons.toMutableList() ) } } fun openCloseOnlyModal( title: StringI18nData, body: @Composable () -> (Unit) ) = openModal( title, body, { CloseModalButton(this) } ) fun openModal( title: String, body: @Composable () -> (Unit), vararg buttons: @Composable () -> (Unit) ) { activeModal = Modal( title, body, buttons.toMutableList() ) } fun openCloseOnlyModal( title: String, body: @Composable () -> (Unit) ) = openModal( title, body, { CloseModalButton(this) } ) fun launch(block: suspend CoroutineScope.() -> Unit): Job { val job = GlobalScope.launch(block = block) jobs.add(job) job.invokeOnCompletion { jobs.remove(job) } return job } fun <T> async(block: suspend CoroutineScope.() -> T): Deferred<T> { val job = GlobalScope.async(block = block) jobs.add(job) job.invokeOnCompletion { jobs.remove(job) } return job } }
agpl-3.0
e50126b4837a63adf42bddefc32ab789
30.827586
102
0.654746
4.536873
false
false
false
false
JustinMullin/drifter-kotlin
src/main/kotlin/xyz/jmullin/drifter/control/DropInControllerManager.kt
1
2144
package xyz.jmullin.drifter.control import com.badlogic.gdx.controllers.Controller import com.badlogic.gdx.controllers.ControllerAdapter import com.badlogic.gdx.controllers.Controllers import xyz.jmullin.drifter.debug.log abstract class DropInControllerManager { abstract fun playerJoined(id: Int, controller: Controller) abstract fun playerLeft(id: Int, controller: Controller) abstract fun playerRejoined(id: Int, controller: Controller) private var slots = Array<ControllerSlot>(8, { Empty }) private val firstAvailable: Int get() = slots.indexOfFirst { it == Empty || it == Inactive } val adapter = object : ControllerAdapter() { override fun connected(controller: Controller?) { controller?.let { val num = firstAvailable + 1 val existing = slots[firstAvailable] slots[firstAvailable] = Active(controller) when(existing) { is Inactive -> { log("Player $num reconnected (${controller.name}).") playerRejoined(num, controller) } is Empty -> { log("Player $num connected (${controller.name}).") playerJoined(num, controller) } } } super.connected(controller) } override fun disconnected(controller: Controller?) { controller?.let { val index = slots.indexOf(Active(controller)) val num = index + 1 slots[index] = Inactive log("Player $num disconnected (${controller.name}).") playerLeft(num, controller) } super.disconnected(controller) } } init { Controllers.addListener(adapter) Controllers.getControllers().forEach(adapter::connected) } private interface ControllerSlot private data class Active(val controller: Controller) : ControllerSlot private object Inactive : ControllerSlot private object Empty : ControllerSlot }
mit
06a946b8ea8474b5e46a503216e8e0f1
34.75
96
0.59375
5.280788
false
false
false
false
DataDozer/DataDozer
core/src/main/kotlin/org/datadozer/index/FieldCollection.kt
1
3934
package org.datadozer.index import org.datadozer.index.fields.FieldSchema /* * Licensed to DataDozer under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. DataDozer licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * A list and map combination designed for holding the fields schemas. This * will provide both fast iteration and lookup over the fields schema values. * NOTE: This is not a general purpose collection. */ class FieldCollection : Map<String, FieldSchema>, Collection<FieldSchema> { private val map = HashMap<String, FieldSchema>() private val arrayList = ArrayList<FieldSchema>() private var locked = false /** * Adds the specified element to the collection. * * @return `true` if the element has been added, `false` if the collection does not support duplicates * and the element is already contained in the collection. */ fun add(element: FieldSchema) { if (locked) { throw IllegalStateException("Elements cannot be added to collection after it is locked") } if (!map.containsKey(element.schemaName)) { map.put(element.schemaName, element) arrayList.add(element) } } /** * Locks the object and doesn't allow any further modification */ fun immutable() { locked = true } /** * Returns the size of the collection. */ override val size: Int get() = arrayList.size /** * Returns `true` if the collection is empty (contains no elements), `false` otherwise. */ override fun isEmpty(): Boolean { return arrayList.isEmpty() } /** * Returns a read-only [Set] of all key/value pairs in this map. */ override val entries: Set<Map.Entry<String, FieldSchema>> get() = map.entries /** * Returns a read-only [Set] of all keys in this map. */ override val keys: Set<String> get() = map.keys /** * Returns a read-only [Collection] of all values in this map. Note that this collection may contain duplicate values. */ override val values: Collection<FieldSchema> get() = arrayList /** * Returns `true` if the map contains the specified [key]. */ override fun containsKey(key: String): Boolean { return map.containsKey(key) } /** * Returns `true` if the map maps one or more keys to the specified [value]. */ override fun containsValue(value: FieldSchema): Boolean { return arrayList.contains(value) } /** * Returns the value corresponding to the given [key], or `null` if such a key is not present in the map. */ override fun get(key: String): FieldSchema? { return map[key] } fun get(index: Int): FieldSchema { if (index >= size) { throw IndexOutOfBoundsException("Index: $index, Size: $size") } return arrayList[index] } override fun contains(element: FieldSchema): Boolean { return arrayList.contains(element) } override fun containsAll(elements: Collection<FieldSchema>): Boolean { return arrayList.containsAll(elements) } override fun iterator(): Iterator<FieldSchema> { return arrayList.iterator() } }
apache-2.0
b339bd98659e54d57bb2af82cf38d126
29.742188
122
0.654296
4.480638
false
false
false
false
luoyuan800/NeverEnd
dataModel/src/cn/luo/yuan/maze/model/skill/swindler/SwindlerGame.kt
1
3331
package cn.luo.yuan.maze.model.skill.swindler import cn.luo.yuan.maze.model.Data import cn.luo.yuan.maze.model.HarmAble import cn.luo.yuan.maze.model.Hero import cn.luo.yuan.maze.model.NameObject import cn.luo.yuan.maze.model.skill.AtkSkill import cn.luo.yuan.maze.model.skill.SkillParameter import cn.luo.yuan.maze.model.skill.UpgradeAble import cn.luo.yuan.maze.model.skill.result.HarmResult import cn.luo.yuan.maze.model.skill.result.SkillResult import cn.luo.yuan.maze.service.BattleServiceBase import cn.luo.yuan.maze.utils.Random import cn.luo.yuan.maze.utils.StringUtils /** * Created by luoyuan on 2017/7/23. */ class SwindlerGame:AtkSkill(),UpgradeAble { private val model = SwindlerModel(this) private var level = 1L; override fun getName(): String { return "欺诈游戏 X $level" } override fun getDisplayName(): String { val builder = StringBuilder() builder.append("玩的就是心跳。<br>攻击时抛一次硬币,如果为正面,对敌人造成 $level 倍的攻击伤害。否则自己受到敌人攻击的 $level 倍伤害。") builder.append(StringUtils.formatPercentage(rate)).append("的概率释放。") builder.append("<br>已经使用:${StringUtils.formatNumber(useTime)}次") return builder.toString() } override fun canMount(parameter: SkillParameter?): Boolean { return model.canMount(parameter) } override fun upgrade(parameter: SkillParameter?): Boolean { level ++; if(rate + 0.5 < Data.RATE_MAX){ rate +=0.5f; } return true; } override fun invoke(parameter: SkillParameter): SkillResult { val hr = HarmResult() val hero: HarmAble = parameter[SkillParameter.ATKER] val target :HarmAble = parameter[SkillParameter.TARGET] val random:Random = parameter[SkillParameter.RANDOM] var side = random.nextBoolean() val min: Long = parameter[SkillParameter.MINHARM] hr.addMessage((hero as NameObject).displayName + "开启欺诈游戏, 抛了一次硬币,结果为:" + if(side) "正" else "反") if(!side){ if(model.isSkillEnable("Swindler", parameter[SkillParameter.CONTEXT])){ side = random.nextBoolean() hr.addMessage(hero.displayName + "不要脸的又抛了一次硬币,结果为:" + if(side) "正" else "反") } } var harm = min if(side) { harm = BattleServiceBase.getHarm(hero, target, min, random, parameter[SkillParameter.MESSAGE]) hr.isBack = false }else{ harm = BattleServiceBase.getHarm(target, hero, min, random, parameter[SkillParameter.MESSAGE]) hr.isBack = true } harm *= level hr.harm = harm; return hr } override fun getLevel(): Long { return level } override fun enable(parameter: SkillParameter?) { isEnable = true } override fun getSkillName(): String { return model.skillName } override fun canUpgrade(parameter: SkillParameter?): Boolean { return model.canUpgrade(parameter) && rate < Data.RATE_MAX/4 } override fun canEnable(parameter: SkillParameter?): Boolean { return model.canEnable(parameter) } }
bsd-3-clause
88069f99da7119196d3abf545478b859
33
106
0.654941
3.541336
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/transform/node/debug/PayloadVerificationPlugin.kt
1
1952
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.transform.node.debug import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.transform.node.Node import org.jitsi.nlj.transform.node.NodePlugin import org.jitsi.utils.logging2.createLogger import org.json.simple.JSONObject import java.util.concurrent.atomic.AtomicInteger /** * Verifies that the payload verification string of the packet hasn't changed. * * @author Boris Grozev */ class PayloadVerificationPlugin { companion object : NodePlugin { private val logger = createLogger() val numFailures = AtomicInteger() @JvmStatic fun getStatsJson() = JSONObject().apply { this["num_payload_verification_failures"] = numFailures.get() } override fun observe(after: Node, packetInfo: PacketInfo) { if (PacketInfo.ENABLE_PAYLOAD_VERIFICATION && packetInfo.payloadVerification != null ) { val expected = packetInfo.payloadVerification val actual = packetInfo.packet.payloadVerification if (expected != actual) { logger.warn("Payload unexpectedly modified by ${after.name}! Expected: $expected, actual: $actual") numFailures.incrementAndGet() packetInfo.resetPayloadVerification() } } } } }
apache-2.0
aeef2a12a75da581b62e85fd5068f9a0
34.490909
119
0.67623
4.571429
false
false
false
false
mozilla-mobile/focus-android
app/src/main/java/org/mozilla/focus/utils/MobileMetricsPingStorage.kt
1
1429
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.utils import android.content.Context import android.util.AtomicFile import org.json.JSONException import org.json.JSONObject import java.io.File import java.io.FileNotFoundException import java.io.IOException class MobileMetricsPingStorage( private val context: Context, private val file: File = File("${context.cacheDir}/$STORAGE_FOLDER/$FILE_NAME"), ) { private val atomicFile = AtomicFile(file) fun shouldStoreMetrics(): Boolean = !file.exists() fun clearStorage() { file.delete() } fun save(json: JSONObject) { val stream = atomicFile.startWrite() try { stream.writer().use { it.append(json.toString()) } atomicFile.finishWrite(stream) } catch (e: IOException) { atomicFile.failWrite(stream) } } fun load(): JSONObject? { return try { JSONObject(String(atomicFile.readFully())) } catch (e: FileNotFoundException) { null } catch (e: JSONException) { null } } companion object { const val STORAGE_FOLDER = "mobile-metrics" const val FILE_NAME = "metrics.json" } }
mpl-2.0
978bd1d60e2c35bee041add1a90f07c3
27.019608
84
0.63191
4.178363
false
false
false
false
sys1yagi/goat-reader-2-android-prototype
app/src/main/kotlin/com/sys1yagi/goatreader/models/Feed.kt
1
1041
package com.sys1yagi.goatreader.models import com.activeandroid.Model import com.activeandroid.annotation.Table import com.activeandroid.annotation.Column import java.util.Date Table(name = Feed.TABLE_NAME) public class Feed() : Model() { class object { val TABLE_NAME = "Feeds" val TITLE = "title" val URL = "url" val CATEGORY_ID = "category_id" val CREATED_AT = "created_at" val UPDATED_AT = "updated_at" fun create(title: String, url: String): Feed { val date = Date() val feed = Feed() feed.title = title feed.url = url feed.createdAt = date feed.updatedAt = date return feed } } Column(name = TITLE) var title: String? = null Column(name = URL) var url: String? = null Column(name = CATEGORY_ID) var categoryId: Long? = null Column(name = CREATED_AT) var createdAt: Date? = null Column(name = UPDATED_AT) var updatedAt: Date? = null }
apache-2.0
30bd39ea7dd16ec28ef1bec82732614d
25.025
54
0.590778
3.869888
false
false
false
false
facebook/litho
litho-widget-kotlin/src/main/kotlin/com/facebook/litho/widget/collection/CollectionChild.kt
1
1054
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho.widget.collection import com.facebook.litho.Component @Suppress("KtDataClass") data class CollectionChild( val id: Any, val component: Component? = null, val componentFunction: (() -> Component?)? = null, val isSticky: Boolean = false, val isFullSpan: Boolean = false, val spanSize: Int? = null, val deps: Array<Any?>? = null, val onNearViewport: OnNearCallback? = null, )
apache-2.0
715c55a3e2fceafd17a238dc44207e2d
33
75
0.71537
3.977358
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/preferences2/IdpPreference.kt
1
1671
package app.lawnchair.preferences2 import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import com.android.launcher3.InvariantDeviceProfile import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking class IdpPreference( val defaultSelector: InvariantDeviceProfile.GridOption.() -> Int, val key: Preferences.Key<Int>, private val preferencesDataStore: DataStore<Preferences>, val onSet: (Int) -> Unit = {}, ) { fun get(gridOption: InvariantDeviceProfile.GridOption) = preferencesDataStore.data.map { preferences -> val value = preferences[key] if (value == null || value == -1) { defaultSelector(gridOption) } else { value } } suspend fun set(value: Int, gridOption: InvariantDeviceProfile.GridOption) { preferencesDataStore.edit { mutablePreferences -> val defaultValue = defaultSelector(gridOption) if (value == defaultValue) { mutablePreferences.remove(key) } else { mutablePreferences[key] = value } } onSet(value) } } fun IdpPreference.firstBlocking(gridOption: InvariantDeviceProfile.GridOption) = runBlocking { get(gridOption = gridOption).first() } @Composable fun IdpPreference.state( gridOption: InvariantDeviceProfile.GridOption, initial: Int? = null, ) = get(gridOption = gridOption).collectAsState(initial = initial)
gpl-3.0
9d50ff01aa96aad78ec8c9fac8583547
33.102041
107
0.704967
4.420635
false
false
false
false
Ekito/koin
koin-projects/koin-core/src/main/kotlin/org/koin/java/KoinJavaComponent.kt
1
2775
/* * Copyright 2017-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.java import org.koin.core.Koin import org.koin.core.context.GlobalContext import org.koin.core.parameter.ParametersDefinition import org.koin.core.qualifier.Qualifier /** * Koin Java Helper - inject/get into Java code * * @author @fredy-mederos * @author Arnaud Giuliani */ object KoinJavaComponent { /** * Retrieve given dependency lazily * @param clazz - dependency class * @param qualifier - bean canonicalName / optional * @param scope - scope * @param parameters - dependency parameters / optional */ @JvmOverloads @JvmStatic fun <T : Any> inject( clazz: Class<T>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null ): Lazy<T> { return lazy(LazyThreadSafetyMode.NONE) { get(clazz, qualifier, parameters) } } /** * Retrieve given dependency * @param clazz - dependency class * @param qualifier - bean canonicalName / optional * @param scope - scope * @param parameters - dependency parameters / optional */ @JvmOverloads @JvmStatic fun <T : Any> get( clazz: Class<T>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null ): T { val kClass = clazz.kotlin return getKoin().get( kClass, qualifier, parameters ) ?: getKoin().get( kClass, qualifier, parameters ) } /** * Retrieve given dependency * @param clazz - dependency class * @param qualifier - bean canonicalName / optional * @param scope - scope * @param parameters - dependency parameters / optional */ @JvmOverloads @JvmStatic fun <P : Any, S : Any> bind( primary: Class<P>, secondary: Class<S>, parameters: ParametersDefinition? = null ): S { return getKoin() .bind(primary.kotlin, secondary.kotlin, parameters) } /** * inject lazily given property * @param key - key property */ @JvmStatic fun getKoin(): Koin = GlobalContext.get() }
apache-2.0
f62d363985d38512d1b32be7af878b15
27.326531
84
0.631351
4.534314
false
false
false
false
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/command/executors/fun/CommandColor.kt
1
2368
package me.mrkirby153.KirBot.command.executors.`fun` import me.mrkirby153.KirBot.command.CommandCategory import me.mrkirby153.KirBot.command.annotations.Command import me.mrkirby153.KirBot.command.annotations.CommandDescription import me.mrkirby153.KirBot.command.args.CommandContext import me.mrkirby153.KirBot.utils.Context import me.mrkirby153.KirBot.utils.getMember import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.Member import net.dv8tion.jda.api.entities.Role import java.awt.Color class CommandColor { @Command(name = "color", arguments = ["<color:string>"], category = CommandCategory.FUN, permissions = [Permission.MANAGE_ROLES]) @CommandDescription("Sets a user's color in the member list") fun execute(context: Context, cmdContext: CommandContext) { val colorString = cmdContext.get<String>("color") val member = context.author.getMember(context.guild) ?: return if (colorString.equals("reset", true)) { resetColor(member) context.send().success("Reset your color", true).queue() return } try { val color = Color.decode(colorString) setColorRole(context, member, color) context.send().success("Set your color to `$colorString`", true).queue() } catch (e: NumberFormatException) { context.send().error("That is not a valid hexadecimal color!").queue() } } private fun setColorRole(context: Context, member: Member, color: Color) { var role: Role? = null context.guild.roles.forEach { r -> if (r.name.equals("color-${member.user.id}", true)) { role = r return@forEach } } if (role != null) { if(role !in member.roles){ context.guild.addRoleToMember(member, role!!).queue() } role?.manager?.setColor(color)?.queue() } else { context.guild.createRole().setName("color-${member.user.id}").setColor(color).setPermissions(0).queue { r-> context.guild.addRoleToMember(member, r).queue() } } } private fun resetColor(member: Member) { member.guild.getRolesByName("color-${member.user.id}", true).forEach { r -> r.delete().queue() } } }
mit
e1ed5ebbe011a722c41be30de6e44a4d
36.015625
133
0.630068
4.183746
false
false
false
false
AllanWang/Frost-for-Facebook
app/src/main/kotlin/com/pitchedapps/frost/views/FrostContentView.kt
1
9234
/* * Copyright 2018 Allan Wang * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.pitchedapps.frost.views import android.content.Context import android.os.Build import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import android.widget.ProgressBar import ca.allanwang.kau.utils.bindView import ca.allanwang.kau.utils.circularReveal import ca.allanwang.kau.utils.fadeIn import ca.allanwang.kau.utils.fadeOut import ca.allanwang.kau.utils.invisibleIf import ca.allanwang.kau.utils.isVisible import ca.allanwang.kau.utils.launchMain import ca.allanwang.kau.utils.tint import ca.allanwang.kau.utils.withAlpha import com.pitchedapps.frost.R import com.pitchedapps.frost.contracts.FrostContentContainer import com.pitchedapps.frost.contracts.FrostContentCore import com.pitchedapps.frost.contracts.FrostContentParent import com.pitchedapps.frost.facebook.FbItem import com.pitchedapps.frost.facebook.WEB_LOAD_DELAY import com.pitchedapps.frost.injectors.ThemeProvider import com.pitchedapps.frost.prefs.Prefs import com.pitchedapps.frost.utils.L import com.pitchedapps.frost.web.FrostEmitter import com.pitchedapps.frost.web.asFrostEmitter import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.runningFold import kotlinx.coroutines.flow.transformWhile @ExperimentalCoroutinesApi class FrostContentWeb @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0 ) : FrostContentView<FrostWebView>(context, attrs, defStyleAttr, defStyleRes) { override val layoutRes: Int = R.layout.view_content_base_web } @ExperimentalCoroutinesApi class FrostContentRecycler @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0 ) : FrostContentView<FrostRecyclerView>(context, attrs, defStyleAttr, defStyleRes) { override val layoutRes: Int = R.layout.view_content_base_recycler } @ExperimentalCoroutinesApi abstract class FrostContentView<out T> @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0 ) : FrostContentViewBase(context, attrs, defStyleAttr, defStyleRes), FrostContentParent where T : View, T : FrostContentCore { val coreView: T by bindView(R.id.content_core) override val core: FrostContentCore get() = coreView } /** Subsection of [FrostContentView] that is [AndroidEntryPoint] friendly (no generics) */ @AndroidEntryPoint @ExperimentalCoroutinesApi abstract class FrostContentViewBase( context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int ) : FrameLayout(context, attrs, defStyleAttr, defStyleRes), FrostContentParent { // No JvmOverloads due to hilt constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor( context: Context, attrs: AttributeSet?, defStyleAttr: Int ) : this(context, attrs, defStyleAttr, 0) @Inject lateinit var prefs: Prefs @Inject lateinit var themeProvider: ThemeProvider private val refresh: SwipeRefreshLayout by bindView(R.id.content_refresh) private val progress: ProgressBar by bindView(R.id.content_progress) private val coreView: View by bindView(R.id.content_core) /** * While this can be conflated, there exist situations where we wish to watch refresh cycles. * Here, we'd need to make sure we don't skip events * * TODO ensure there is only one flow provider is this is still separated in login Use case for * shared flow is to avoid emitting before subscribing; buffer can probably be size 1 */ private val refreshMutableFlow = MutableSharedFlow<Boolean>( extraBufferCapacity = 10, onBufferOverflow = BufferOverflow.DROP_OLDEST ) override val refreshFlow: SharedFlow<Boolean> = refreshMutableFlow.asSharedFlow() override val refreshEmit: FrostEmitter<Boolean> = refreshMutableFlow.asFrostEmitter() private val progressMutableFlow = MutableStateFlow(0) override val progressFlow: SharedFlow<Int> = progressMutableFlow.asSharedFlow() override val progressEmit: FrostEmitter<Int> = progressMutableFlow.asFrostEmitter() private val titleMutableFlow = MutableStateFlow("") override val titleFlow: SharedFlow<String> = titleMutableFlow.asSharedFlow() override val titleEmit: FrostEmitter<String> = titleMutableFlow.asFrostEmitter() override lateinit var scope: CoroutineScope override lateinit var baseUrl: String override var baseEnum: FbItem? = null protected abstract val layoutRes: Int @Volatile override var swipeDisabledByAction = false set(value) { field = value updateSwipeEnabler() } @Volatile override var swipeAllowedByPage: Boolean = true set(value) { field = value updateSwipeEnabler() } private fun updateSwipeEnabler() { val swipeEnabled = swipeAllowedByPage && !swipeDisabledByAction if (refresh.isEnabled == swipeEnabled) return refresh.post { refresh.isEnabled = swipeEnabled } } /** Sets up everything Called by [bind] */ protected fun init() { inflate(context, layoutRes, this) reloadThemeSelf() } override fun bind(container: FrostContentContainer) { baseUrl = container.baseUrl baseEnum = container.baseEnum init() scope = container core.bind(this, container) refresh.setOnRefreshListener { core.reload(true) } refreshFlow .distinctUntilChanged() .onEach { r -> L.v { "Refreshing $r" } refresh.isRefreshing = r } .launchIn(scope) progressFlow .onEach { p -> progress.invisibleIf(p == 100) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progress.setProgress(p, true) else progress.progress = p } .launchIn(scope) } override fun reloadTheme() { reloadThemeSelf() core.reloadTheme() } override fun reloadTextSize() { core.reloadTextSize() } override fun reloadThemeSelf() { progress.tint(themeProvider.textColor.withAlpha(180)) refresh.setColorSchemeColors(themeProvider.iconColor) refresh.setProgressBackgroundColorSchemeColor(themeProvider.headerColor.withAlpha(255)) } override fun reloadTextSizeSelf() { // intentionally blank } override fun destroy() { core.destroy() } private var transitionStart: Long = -1 /** * Hook onto the refresh observable for one cycle Animate toggles between the fancy ripple and the * basic fade The cycle only starts on the first load since there may have been another process * when this is registered */ override fun registerTransition(urlChanged: Boolean, animate: Boolean): Boolean { if (!urlChanged && transitionStart != -1L) { L.v { "Consuming url load" } return false // still in progress; do not bother with load } coreView.transition(animate) return true } private fun View.transition(animate: Boolean) { L.v { "Registered transition" } transitionStart = 0L // Marker for pending transition scope.launchMain { refreshFlow .distinctUntilChanged() // Pseudo windowed mode .runningFold(false to false) { (_, prev), curr -> prev to curr } // Take until prev was loading and current is not loading // Unlike takeWhile, we include the last state (first non matching) .transformWhile { emit(it) it != (true to false) } .onEach { (prev, curr) -> if (curr) { transitionStart = System.currentTimeMillis() clearAnimation() if (isVisible) fadeOut(duration = 200L) } else if (prev) { // prev && !curr if (animate && prefs.animate) circularReveal(offset = WEB_LOAD_DELAY) else fadeIn(duration = 200L, offset = WEB_LOAD_DELAY) L.v { "Transition loaded in ${System.currentTimeMillis() - transitionStart} ms" } } } .collect() transitionStart = -1L } } }
gpl-3.0
319ffd39a275c3b4dcde22262c52a06b
30.841379
100
0.735759
4.357716
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/actions/styling/HeaderLevelDownAction.kt
1
2985
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.actions.styling import com.intellij.openapi.editor.Document import com.intellij.psi.PsiElement import com.vladsch.flexmark.util.misc.CharPredicate import com.vladsch.flexmark.util.sequence.BasedSequence import com.vladsch.flexmark.util.sequence.RepeatedSequence import com.vladsch.md.nav.actions.handlers.util.PsiEditAdjustment import com.vladsch.md.nav.psi.element.MdAtxHeader import com.vladsch.md.nav.psi.element.MdHeaderElement import com.vladsch.md.nav.psi.element.MdSetextHeader class HeaderLevelDownAction : HeaderAction() { companion object { val ATX_HEADING_HASH_SPACE_TAB: CharPredicate = CharPredicate.anyOf("# \t") } override fun canPerformAction(element: PsiElement): Boolean { return element is MdHeaderElement } override fun cannotPerformActionReason(element: PsiElement): String { return "Not heading element" } override fun headerAction(element: PsiElement, document: Document, caretOffset: Int, editContext: PsiEditAdjustment): Int? { if (element is MdHeaderElement) { if (element.canDecreaseLevel) { // disabled because it is not undoable without changing more of the context if (element is MdSetextHeader && element.headerLevel == 2) { val markerElement = element.headerMarkerNode ?: return null document.replaceString(markerElement.startOffset, markerElement.startOffset + markerElement.textLength, RepeatedSequence.repeatOf('=', element.headerText.length)) } else { element.setHeaderLevel(element.headerLevel - 1, editContext) } } else if (element is MdAtxHeader) { // remove # and following blanks val count = BasedSequence.of(element.text).countLeading(ATX_HEADING_HASH_SPACE_TAB) if (count > 0) { document.deleteString(element.node.startOffset, element.node.startOffset + count) } } else if (element is MdSetextHeader) { // remove marker and following EOL var offset: Int? = null val headerMarkerNode = element.headerMarkerNode ?: return null if (caretOffset >= headerMarkerNode.startOffset) { // caret needs to move up one line val caretLine = document.getLineNumber(caretOffset) offset = document.getLineStartOffset(caretLine - 1) + (caretOffset - document.getLineStartOffset(caretLine)) } document.deleteString(headerMarkerNode.startOffset, headerMarkerNode.startOffset + headerMarkerNode.textLength + 1) return offset } } return null } }
apache-2.0
afd2b0ade2789cbb04f3041bc9b095ea
50.465517
182
0.667002
4.885434
false
false
false
false
devunt/ika
annotation-processor/src/main/kotlin/org/ozinger/ika/annotation/processor/HandlerProcessor.kt
1
4850
package org.ozinger.ika.annotation.processor import com.google.devtools.ksp.getAnnotationsByType import com.google.devtools.ksp.processing.* import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.google.devtools.ksp.symbol.KSVisitorVoid import com.google.devtools.ksp.validate import com.squareup.kotlinpoet.* import com.squareup.kotlinpoet.ksp.writeTo import org.ozinger.ika.annotation.Handler class HandlerProcessor( private val codeGenerator: CodeGenerator, private val logger: KSPLogger, private val options: Map<String, String>, ) : SymbolProcessor { private val coreMap = mutableMapOf<Pair<String?, String>, MutableSet<String>>() private val elseMap = mutableMapOf<Pair<String?, String>, MutableSet<String>>() override fun process(resolver: Resolver): List<KSAnnotated> { val symbols = resolver .getSymbolsWithAnnotation(Handler::class.qualifiedName!!) .filterIsInstance<KSFunctionDeclaration>() if (!symbols.iterator().hasNext()) { return emptyList() } symbols.filter { it.validate() }.forEach { it.accept(Visitor(), Unit) } generateFile("GeneratedCoreHandlerInvoker", coreMap) generateFile("GeneratedHandlerInvoker", elseMap) return symbols.filterNot { it.validate() }.toList() } private fun generateFile(className: String, map: Map<Pair<String?, String>, MutableSet<String>>) { val whenBuilder = CodeBlock.builder() .beginControlFlow("when") map.forEach { (pair, handlers) -> val (sender, command) = pair if (sender == null) { whenBuilder.beginControlFlow("packet.sender == null && packet.command is %L -> {", command) for (handler in handlers) { whenBuilder.addStatement("%L(packet.command)", handler) } whenBuilder.endControlFlow() } else { whenBuilder.beginControlFlow("packet.sender is %L && packet.command is %L -> {", sender, command) for (handler in handlers) { whenBuilder.addStatement("%L(packet.sender, packet.command)", handler) } whenBuilder.endControlFlow() } } whenBuilder.endControlFlow() val fileSpec = FileSpec.builder("org.ozinger.ika.generated", className) .addType( TypeSpec.objectBuilder(className) .addFunction( FunSpec.builder("invoke") .addModifiers(KModifier.SUSPEND) .addParameter("packet", ClassName("org.ozinger.ika.definition", "Packet")) .addCode(whenBuilder.build()) .build() ) .build() ) .build() fileSpec.writeTo( codeGenerator = codeGenerator, dependencies = Dependencies(false), ) } inner class Visitor : KSVisitorVoid() { override fun visitFunctionDeclaration(function: KSFunctionDeclaration, data: Unit) { val annotation = function.getAnnotationsByType(Handler::class).first() val map = if (annotation.core) coreMap else elseMap val methodName = function.qualifiedName!!.asString() val paramTypeNames = function.parameters.map { it.type.resolve().declaration.qualifiedName!!.asString() } when (paramTypeNames.size) { 1 -> map.getOrPut(Pair(null, paramTypeNames[0]), ::mutableSetOf).add(methodName) 2 -> when (paramTypeNames[0]) { SERVER_ID, UNIVERSAL_USER_ID -> map.getOrPut(Pair(paramTypeNames[0], paramTypeNames[1]), ::mutableSetOf).add(methodName) IDENTIFIER -> { map.getOrPut(Pair(SERVER_ID, paramTypeNames[1]), ::mutableSetOf).add(methodName) map.getOrPut(Pair(UNIVERSAL_USER_ID, paramTypeNames[1]), ::mutableSetOf).add(methodName) } else -> throw ProcessingException("Handler sender parameter should be one of [$SERVER_ID, $UNIVERSAL_USER_ID, $IDENTIFIER], was ${paramTypeNames[0]}") } else -> throw ProcessingException("Handler parameter size should be 1 or 2") } } } companion object { private const val DEFINITION_PACKAGE = "org.ozinger.ika.definition" private const val SERVER_ID = "$DEFINITION_PACKAGE.ServerId" private const val UNIVERSAL_USER_ID = "$DEFINITION_PACKAGE.UniversalUserId" private const val IDENTIFIER = "$DEFINITION_PACKAGE.Identifier" } }
agpl-3.0
cc5c88b069004c67e9c91e5a334bb253
42.303571
170
0.605155
5.052083
false
false
false
false
Sjtek/sjtekcontrol-core
data/src/main/kotlin/nl/sjtek/control/data/amqp/SensorEvent.kt
1
1329
package nl.sjtek.control.data.amqp import java.util.* data class SensorEvent(val type: Type, val id: Int, val value1: Float, val value2: Float = 0f) : AMQPEvent() { override fun toMessage(): ByteArray = if (value2 == 0f) { TEMPLATE1.format(Locale.US, type.ordinal, id, value1).toByteArray() } else { TEMPLATE2.format(Locale.US, type.ordinal, id, value1, value2).toByteArray() } enum class Type { MOTION, LIGHT, TEMPERATURE } companion object { const val TEMPLATE1 = "%02d;%02d;%.2f" const val TEMPLATE2 = "%02d;%02d;%.2f;%.2f" fun fromMessage(message: String): SensorEvent? { val args = message.split(delimiters = ";") return if (args.size == 3 || args.size == 4) { try { val type = Type.values()[args[0].toInt()] val id = args[1].toInt() val value1 = args[2].toFloat() val value2 = if (args.size == 4) args[3].toFloat() else 0f SensorEvent(type, id, value1, value2) } catch (e: NumberFormatException) { null } catch (e: ArrayIndexOutOfBoundsException) { null } } else { null } } } }
gpl-3.0
c410d0171cdad29a3d85265a0864998e
34
110
0.51392
4.039514
false
false
false
false
laurencegw/jenjin
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/time/ClockControls.kt
1
2826
package com.binarymonks.jj.core.time import com.badlogic.gdx.Gdx import com.binarymonks.jj.core.api.ClockAPI class ClockControls : ClockAPI { companion object { private var fixedDelta = (1f / 60).toDouble() private var fixedDeltaFloat = 1f / 60 private var realToGameRatio = 1.0f private var DELTA = (1f / 60).toDouble() private var DELTA_FLOAT = 1f / 60 private var TIME = 0.0 private var timeFunction = TimeFunction.RATIO_TIME } val scheduler: Scheduler = Scheduler(this::timeFloat) override fun schedule(function: () -> Unit, delaySeconds: Float, repeat: Int, name: String?): Int { return scheduler.schedule(function, delaySeconds, repeat, name) } override fun schedule(function: () -> Unit, delayMinSeconds: Float, delayMaxSeconds: Float, repeat: Int, name: String?): Int { return scheduler.schedule(function, delayMinSeconds, delayMaxSeconds, repeat, name) } override fun cancel(id: Int) { scheduler.cancel(id) } override val delta: Double get() = DELTA override val deltaFloat: Float get() = DELTA_FLOAT override val time: Double get() = TIME override val timeFloat: Float get() = TIME.toFloat() fun update() { timeFunction.update(Gdx.graphics.deltaTime) TIME += DELTA scheduler.update() } fun setTimeFunction(function: TimeFunction) { timeFunction = function } fun getFixedDelta(): Double { return fixedDelta } val ratioFixedDelta: Double get() = fixedDelta * realToGameRatio fun setFixedDelta(fixedTime: Double) { ClockControls.fixedDelta = fixedTime ClockControls.fixedDeltaFloat = fixedTime.toFloat() } fun getRealToGameRatioDouble(): Double { return realToGameRatio.toDouble() } fun getRealToGameRatio(): Float { return realToGameRatio } fun setRealToGameRatio(realToGameRatio: Float) { ClockControls.realToGameRatio = realToGameRatio } fun getTimeFunction(): TimeFunction { return timeFunction } enum class TimeFunction { REAL_TIME { override fun update(realDelta: Float) { DELTA = realDelta.toDouble() DELTA_FLOAT = realDelta } }, FIXED_TIME { override fun update(realDelta: Float) { DELTA = fixedDelta DELTA_FLOAT = fixedDeltaFloat } }, RATIO_TIME { override fun update(realDelta: Float) { DELTA = (realToGameRatio * realDelta).toDouble() DELTA_FLOAT = realToGameRatio * realDelta } }; abstract fun update(realDelta: Float) } }
apache-2.0
77aafbf131e16c563875eee54225008a
25.660377
130
0.610757
4.321101
false
false
false
false
martinlschumann/mal
kotlin/src/mal/env.kt
4
1175
package mal import java.util.* class Env(val outer: Env?, binds: Sequence<MalSymbol>?, exprs: Sequence<MalType>?) { val data = HashMap<String, MalType>() init { if (binds != null && exprs != null) { val itb = binds.iterator() val ite = exprs.iterator() while (itb.hasNext()) { val b = itb.next() if (b.value != "&") { set(b, if (ite.hasNext()) ite.next() else NIL) } else { if (!itb.hasNext()) throw MalException("expected a symbol name for varargs") set(itb.next(), MalList(ite.asSequence().toCollection(LinkedList<MalType>()))) break } } } } constructor() : this(null, null, null) constructor(outer: Env?) : this(outer, null, null) fun set(key: MalSymbol, value: MalType): MalType { data.put(key.value, value) return value } fun find(key: MalSymbol): MalType? = data.getOrElse(key.value) { outer?.find(key) } fun get(key: MalSymbol): MalType = find(key) ?: throw MalException("'${key.value}' not found") }
mpl-2.0
d1e7e4fb9e6ecda4dd057f3dab032356
31.638889
98
0.526809
4.079861
false
false
false
false
xiaopansky/Sketch
sample/src/main/java/me/panpf/sketch/sample/bean/AppInfo.kt
1
652
package me.panpf.sketch.sample.bean import me.panpf.sketch.sample.util.FileScanner /** * App信息 */ class AppInfo(val isTempInstalled: Boolean) : FileScanner.FileItem { var name: String? = null var packageName: String? = null var id: String? = null var versionName: String? = null var formattedAppSize: String? = null var sortName: String? = null var apkFilePath: String? = null var versionCode: Int = 0 var appSize: Long = 0 var isTempXPK: Boolean = false override fun getFilePath(): String? { return apkFilePath } override fun getFileLength(): Long { return appSize } }
apache-2.0
8d4da50cf9e967e2cddb816833d4d2ed
23
68
0.660494
3.927273
false
false
false
false
Retronic/life-in-space
core/src/main/kotlin/com/retronicgames/utils/value/ObservableListWrapper.kt
1
1868
/** * Copyright (C) 2015 Oleg Dolya * Copyright (C) 2015 Eduardo Garcia * * This file is part of Life in Space, by Retronic Games * * Life in Space is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Life in Space 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 Life in Space. If not, see <http://www.gnu.org/licenses/>. */ package com.retronicgames.utils.value class ObservableListWrapper<T>(private val list: MutableList<T>) : Iterable<T> { private val listChangeListeners = com.badlogic.gdx.utils.Array<(ListChangeEvent<T>) -> Unit>(false, 4) val size: Int get() = list.size override fun iterator() = list.iterator() fun addListener(listener: (ListChangeEvent<T>) -> Unit) { listChangeListeners.add(listener) } fun add(value: T) { list.add(value) fireAdded(list.size - 1, 1) } fun remove(value: T) { list.remove(value) fireRemoved(value) } private fun fireAdded(position: Int, size: Int) { val ev = ListChangeEvent(list, true, position, position + size) for (listener in listChangeListeners) { listener(ev) } } private fun fireRemoved(vararg value: T) { val ev = ListChangeEvent(list, false, -1, -1, *value) for (listener in listChangeListeners) { listener(ev) } } } class ListChangeEvent<T>(val list: List<T>, private val added:Boolean, val from: Int, val to: Int, vararg val removed:T) { fun wasAdded() = added fun wasRemoved() = !added }
gpl-3.0
4d911e0eab74983e35820b3c60b3fc33
27.30303
122
0.710385
3.421245
false
false
false
false
runesong/scribbler
src/main/java/scribbler/content/DocumentRepository.kt
1
1718
package scribbler.content import org.springframework.stereotype.Repository import scribbler.LOG import java.io.* import java.nio.file.Files @Repository class DocumentRepository { private val repo: File = File("public").absoluteFile fun write(path: String, content: String) { val f = getFile(path) try { Files.createDirectories(f.parentFile.toPath()) FileWriter(f).use { out -> out.write(content) out.flush() } LOG.info("{} written", f) } catch (ex: FileNotFoundException) { throw DocumentNotFoundException(f.path, ex) } } fun read(path: String, output: OutputStream) { read(getFile(path), output) } private fun read(f: File, output: OutputStream) { try { FileInputStream(f).copyTo(output) output.flush() } catch (ex: FileNotFoundException) { throw DocumentNotFoundException(f.path, ex) } } private fun getFile(resourcePath: String): File { // Ascending the file structure is a security risk. Don't allow it. if (!resourcePath.contains("..")) { val candidate = File(repo, resourcePath).absoluteFile // Sanity check. Make sure the file is contained is in the container folder. var parent: File? = candidate.parentFile while (parent != null) { if (parent == repo) { return candidate } parent = parent.parentFile } } LOG.warn("Invalid file request: {}", resourcePath) throw DocumentNotFoundException(resourcePath) } }
apache-2.0
8c6f59c98601df73d11e2bb6bd690ac1
28.637931
88
0.576251
4.785515
false
false
false
false
gmillz/SlimFileManager
manager/src/main/java/com/slim/slimfilemanager/utils/SortUtils.kt
1
3458
package com.slim.slimfilemanager.utils import android.content.Context import android.text.TextUtils import com.slim.slimfilemanager.settings.SettingsProvider import com.slim.slimfilemanager.utils.file.BaseFile import java.util.ArrayList import java.util.Collections import java.util.Comparator object SortUtils { val SORT_MODE_NAME = "sort_mode_name" val SORT_MODE_SIZE = "sort_mode_size" val SORT_MODE_TYPE = "sort_mode_type" private val nameComparator: Comparator<BaseFile> get() = Comparator { lhs, rhs -> lhs.name.toLowerCase().compareTo(rhs.name.toLowerCase()) } private val sizeComparator: Comparator<BaseFile> get() = Comparator { lhs, rhs -> if (lhs.isDirectory && rhs.isDirectory) { var al = 0 var bl = 0 val aList = lhs.list() val bList = rhs.list() if (aList != null) { al = aList.size } if (bList != null) { bl = bList.size } if (al == bl) { return@Comparator lhs.name.toLowerCase().compareTo(rhs.name.toLowerCase()) } return@Comparator if (al < bl) { -1 } else 1 } if (rhs.isDirectory) { return@Comparator -1 } if (lhs.isDirectory) { return@Comparator 1 } val len_a = rhs.length() val len_b = lhs.length() if (len_a == len_b) { return@Comparator lhs.name.toLowerCase().compareTo(rhs.name.toLowerCase()) } if (len_a < len_b) { -1 } else 1 } private val typeComparator: Comparator<BaseFile> get() = Comparator { lhs, rhs -> if (lhs.isDirectory && rhs.isDirectory) { return@Comparator lhs.name.toLowerCase().compareTo(rhs.name.toLowerCase()) } if (lhs.isDirectory) { return@Comparator -1 } if (rhs.isDirectory) { return@Comparator 1 } val ext_a = lhs.extension val ext_b = rhs.extension if (TextUtils.isEmpty(ext_a) && TextUtils.isEmpty(ext_b)) { return@Comparator lhs.name.toLowerCase().compareTo(rhs.name.toLowerCase()) } if (TextUtils.isEmpty(ext_a)) { return@Comparator -1 } if (TextUtils.isEmpty(ext_b)) { return@Comparator 1 } val res = ext_a.compareTo(ext_b) if (res == 0) { lhs.name.toLowerCase().compareTo(rhs.name.toLowerCase()) } else res } fun sort(context: Context?, files: ArrayList<BaseFile>) { if (context != null) { val sortMode = SettingsProvider.getString(context, SettingsProvider.SORT_MODE, SORT_MODE_NAME) when (sortMode) { SORT_MODE_SIZE -> { Collections.sort(files, sizeComparator) return } SORT_MODE_TYPE -> { Collections.sort(files, typeComparator) return } } } Collections.sort(files, nameComparator) } }
gpl-3.0
c0384fbd1a8db3a4e9e054676dbb0812
28.067227
99
0.496819
4.586207
false
false
false
false
android/media-samples
VideoPlayer/videoplayerapp/src/main/java/com/example/android/videoplayersample/VideoActivity.kt
1
5137
/* * Copyright 2018 Google LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.videoplayersample import android.app.PictureInPictureParams import android.content.res.Configuration import android.media.AudioManager import android.os.Build import android.os.Bundle import android.support.v4.media.MediaDescriptionCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v7.app.AppCompatActivity import android.util.Rational import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector import com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator import kotlinx.android.synthetic.main.activity_video.* import org.jetbrains.anko.AnkoLogger /** * Allows playback of videos that are in a playlist, using [PlayerHolder] to load the and render * it to the [com.google.android.exoplayer2.ui.PlayerView] to render the video output. Supports * [MediaSessionCompat] and picture in picture as well. */ class VideoActivity : AppCompatActivity(), AnkoLogger { private val mediaSession: MediaSessionCompat by lazy { createMediaSession() } private val mediaSessionConnector: MediaSessionConnector by lazy { createMediaSessionConnector() } private val playerState by lazy { PlayerState() } private lateinit var playerHolder: PlayerHolder // Android lifecycle hooks. override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_video) // While the user is in the app, the volume controls should adjust the music volume. volumeControlStream = AudioManager.STREAM_MUSIC createMediaSession() createPlayer() } override fun onStart() { super.onStart() startPlayer() activateMediaSession() } override fun onStop() { super.onStop() stopPlayer() deactivateMediaSession() } override fun onDestroy() { super.onDestroy() releasePlayer() releaseMediaSession() } // MediaSession related functions. private fun createMediaSession(): MediaSessionCompat = MediaSessionCompat(this, packageName) private fun createMediaSessionConnector(): MediaSessionConnector = MediaSessionConnector(mediaSession).apply { // If QueueNavigator isn't set, then mediaSessionConnector will not handle following // MediaSession actions (and they won't show up in the minimized PIP activity): // [ACTION_SKIP_PREVIOUS], [ACTION_SKIP_NEXT], [ACTION_SKIP_TO_QUEUE_ITEM] setQueueNavigator(object : TimelineQueueNavigator(mediaSession) { override fun getMediaDescription(windowIndex: Int): MediaDescriptionCompat { return mediaCatalog[windowIndex] } }) } // MediaSession related functions. private fun activateMediaSession() { // Note: do not pass a null to the 3rd param below, it will cause a NullPointerException. // To pass Kotlin arguments to Java varargs, use the Kotlin spread operator `*`. mediaSessionConnector.setPlayer(playerHolder.audioFocusPlayer, null) mediaSession.isActive = true } private fun deactivateMediaSession() { mediaSessionConnector.setPlayer(null, null) mediaSession.isActive = false } private fun releaseMediaSession() { mediaSession.release() } // ExoPlayer related functions. private fun createPlayer() { playerHolder = PlayerHolder(this, playerState, exoplayerview_activity_video) } private fun startPlayer() { playerHolder.start() } private fun stopPlayer() { playerHolder.stop() } private fun releasePlayer() { playerHolder.release() } // Picture in Picture related functions. override fun onUserLeaveHint() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { enterPictureInPictureMode( with(PictureInPictureParams.Builder()) { val width = 16 val height = 9 setAspectRatio(Rational(width, height)) build() }) } } override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration?) { exoplayerview_activity_video.useController = !isInPictureInPictureMode } }
apache-2.0
6ec63367bee529077b4861a6b3b92b0f
34.93007
100
0.680164
5.106362
false
false
false
false
tschuchortdev/kotlin-compile-testing
core/src/main/kotlin/SynchronizedToolProvider.kt
1
2517
/* * Copyright 2018-present Facebook, 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.facebook.buck.jvm.java.javax import com.tschuchort.compiletesting.isJdk9OrLater import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import javax.tools.JavaCompiler import javax.tools.ToolProvider /** * ToolProvider has no synchronization internally, so if we don't synchronize from the outside we * could wind up loading the compiler classes multiple times from different class loaders. */ internal object SynchronizedToolProvider { private var getPlatformClassLoaderMethod: Method? = null val systemJavaCompiler: JavaCompiler get() { val compiler = synchronized(ToolProvider::class.java) { ToolProvider.getSystemJavaCompiler() } check(compiler != null) { "System java compiler is null! Are you running without JDK?" } return compiler } // The compiler classes are loaded using the platform class loader in Java 9+. val systemToolClassLoader: ClassLoader get() { if (isJdk9OrLater()) { try { return getPlatformClassLoaderMethod!!.invoke(null) as ClassLoader } catch (e: IllegalAccessException) { throw RuntimeException(e) } catch (e: InvocationTargetException) { throw RuntimeException(e) } } val classLoader: ClassLoader synchronized(ToolProvider::class.java) { classLoader = ToolProvider.getSystemToolClassLoader() } return classLoader } init { if (isJdk9OrLater()) { try { getPlatformClassLoaderMethod = ClassLoader::class.java.getMethod("getPlatformClassLoader") } catch (e: NoSuchMethodException) { throw RuntimeException(e) } } } }
mpl-2.0
263d89603c3474922ed9fc2fad5bc973
32.573333
106
0.649583
5.044088
false
false
false
false
WijayaPrinting/wp-javafx
openpss/src/com/hendraanggrian/openpss/schema/Customer.kt
1
1761
package com.hendraanggrian.openpss.schema import com.hendraanggrian.openpss.nosql.NamedDocument import com.hendraanggrian.openpss.nosql.NamedDocumentSchema import com.hendraanggrian.openpss.nosql.Schemed import com.hendraanggrian.openpss.nosql.StringId import kotlinx.nosql.ListColumn import kotlinx.nosql.boolean import kotlinx.nosql.date import kotlinx.nosql.integer import kotlinx.nosql.nullableString import kotlinx.nosql.string import org.joda.time.LocalDate object Customers : NamedDocumentSchema<Customer>("customers", Customer::class) { override val name = string("name") val isCompany = boolean("is_company") val since = date("since") val address = nullableString("address") val note = nullableString("note") val contacts = Contacts() class Contacts : ListColumn<Customer.Contact, Invoices>(schemaName, Customer.Contact::class) { val type = string("type") val value = integer("value") companion object : Schemed { override val schemaName: String = "contacts" } } } data class Customer( override var name: String, val isCompany: Boolean, val since: LocalDate, var address: String?, var note: String?, var contacts: List<Contact> ) : NamedDocument<Customers> { companion object { fun new( name: String, isCompany: Boolean, since: LocalDate ): Customer = Customer(name, isCompany, since, null, null, listOf()) } override lateinit var id: StringId<Customers> override fun toString(): String = name data class Contact( val type: String, val value: String ) { companion object; override fun toString(): String = value } }
apache-2.0
2fa078af2bb81d1bafa0cdab68cc12f5
26.092308
98
0.67916
4.458228
false
false
false
false
mkodekar/MaterialStatusBarCompat
library-kotlin/src/main/kotlin/moe/feng/material/statusbar/AppBarLayout.kt
6
3481
package moe.feng.material.statusbar import android.content.Context import android.graphics.Color import android.os.Build import android.util.AttributeSet import android.util.TypedValue import android.widget.LinearLayout import moe.feng.material.statusbar.R import moe.feng.material.statusbar.StatusBarHeaderView import moe.feng.material.statusbar.util.ViewHelper open public class AppBarLayout : LinearLayout { private var colorNormal : Int private var colorDark : Int private var enableMode : Int private var headerView: StatusBarHeaderView final var MODE_KITKAT = 1 ; final var MODE_LOLLIPOP = 2 ; final var MODE_ALL = 3 public constructor(context: Context) : this(context, null) { } public constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) { } public constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) { var a = context.obtainStyledAttributes(attrs, R.styleable.StatusBarHeaderView, defStyle, R.style.Widget_FengMoe_StatusBarHeaderView) colorNormal = a.getColor(R.styleable.StatusBarHeaderView_colorNormal, Color.TRANSPARENT) if (a.hasValue(R.styleable.StatusBarHeaderView_colorDark)) { colorDark = a.getColor(R.styleable.StatusBarHeaderView_colorDark, Color.TRANSPARENT) } else { colorDark = ViewHelper().getMiddleColor(colorNormal, Color.BLACK, 0.2f) } enableMode = a.getInt(R.styleable.StatusBarHeaderView_enableMode, MODE_KITKAT or MODE_LOLLIPOP) headerView = StatusBarHeaderView(context, colorNormal, colorDark, enableMode) this.setBackgroundColorWithoutAlpha(colorNormal) this.setOrientation(LinearLayout.VERTICAL) this.addView(headerView) a.recycle() if (Build.VERSION.SDK_INT >= 21) { this.setElevation(ViewHelper().dpToPx(context, 5f)) } } public fun setNormalColor(colorNormal: Int) { this.colorNormal = colorNormal this.setBackgroundColorWithoutAlpha(colorNormal) headerView.setNormalColor(colorNormal) headerView.init() } public fun setDarkColor(colorDark: Int) { this.colorDark = colorDark headerView.setDarkColor(colorDark) headerView.init() } public fun setColor(colorNormal: Int, colorDark: Int) { this.colorNormal = colorNormal this.colorDark = colorDark this.setBackgroundColorWithoutAlpha(colorNormal) headerView.setNormalColor(colorNormal) headerView.setDarkColor(colorDark) headerView.init() } public fun setColorResources(colorNormal: Int, colorDark: Int) { this.setColor( getResources().getColor(colorNormal), getResources().getColor(colorDark) ) } public fun getNormalColor(): Int { return this.colorNormal } public fun getDarkColor(): Int { return this.colorDark } public fun setMode(mode: Int) { this.enableMode = mode headerView.setMode(mode) headerView.init() } public fun getMode(): Int { return this.enableMode } private fun setBackgroundColorWithoutAlpha(color: Int) { this.setBackgroundColor(Color.argb(255, Color.red(color), Color.green(color), Color.blue(color))) } }
apache-2.0
15ba4b1ef720d3ec3cd77040aa8c7a08
32.81
113
0.669635
4.503234
false
false
false
false
songzhw/Hello-kotlin
AdvancedJ/src/main/kotlin/coroutine/Coroutine4.kt
1
868
package coroutine import kotlinx.coroutines.* fun getId4(): Int { println("getID4: ${Thread.currentThread().name}") Thread.sleep(500) return 44 } fun getUser4(id: Int): String { println("getUser4: ${Thread.currentThread().name}") Thread.sleep(900) return "getUser($id)" } fun getInfo4(user: String): String { println("getInfo4: ${Thread.currentThread().name}") Thread.sleep(600) return "getInfo($user)" } suspend fun foo4() { coroutineScope { val id = async { getId4() } val user = async { getUser4(id.await()) } val info = async { getInfo4(user.await()) } println("szw 4 info = ${info.await()}") } } suspend fun main() { foo4() } /* getID4: DefaultDispatcher-worker-1 getUser4: DefaultDispatcher-worker-1 getInfo4: DefaultDispatcher-worker-1 szw 4 info = getInfo(getUser(44)) */
apache-2.0
84e1958dba3f9d8fbd874ebace63e7f2
19.690476
55
0.638249
3.5
false
false
false
false
Kotlin/kotlinx.serialization
formats/cbor/commonTest/src/kotlinx/serialization/cbor/CborReaderTest.kt
1
29106
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.cbor import kotlinx.serialization.* import kotlinx.serialization.SimpleSealed.* import kotlinx.serialization.cbor.internal.* import kotlin.test.* class CborReaderTest { private val ignoreUnknownKeys = Cbor { ignoreUnknownKeys = true } private fun withDecoder(input: String, block: CborDecoder.() -> Unit) { val bytes = HexConverter.parseHexBinary(input.uppercase()) CborDecoder(ByteArrayInput(bytes)).block() } @Test fun testDecodeIntegers() { withDecoder("0C1903E8") { assertEquals(12L, nextNumber()) assertEquals(1000L, nextNumber()) } withDecoder("203903e7") { assertEquals(-1L, nextNumber()) assertEquals(-1000L, nextNumber()) } } @Test fun testDecodeStrings() { withDecoder("6568656C6C6F") { assertEquals("hello", nextString()) } withDecoder("7828737472696E672074686174206973206C6F6E676572207468616E2032332063686172616374657273") { assertEquals("string that is longer than 23 characters", nextString()) } } @Test fun testDecodeDoubles() { withDecoder("fb7e37e43c8800759c") { assertEquals(1e+300, nextDouble()) } withDecoder("fa47c35000") { assertEquals(100000.0f, nextFloat()) } } @Test fun testDecodeSimpleObject() { assertEquals(Simple("str"), Cbor.decodeFromHexString(Simple.serializer(), "bf616163737472ff")) } @Test fun testDecodeComplicatedObject() { val test = TypesUmbrella( "Hello, world!", 42, null, listOf("a", "b"), mapOf(1 to true, 2 to false), Simple("lol"), listOf(Simple("kek")), HexConverter.parseHexBinary("cafe"), HexConverter.parseHexBinary("cafe") ) // with maps, lists & strings of indefinite length assertEquals(test, Cbor.decodeFromHexString( TypesUmbrella.serializer(), "bf637374726d48656c6c6f2c20776f726c64216169182a686e756c6c61626c65f6646c6973749f61616162ff636d6170bf01f502f4ff65696e6e6572bf6161636c6f6cff6a696e6e6572734c6973749fbf6161636b656bffff6a62797465537472696e675f42cafeff696279746541727261799f383521ffff" ) ) // with maps, lists & strings of definite length assertEquals(test, Cbor.decodeFromHexString( TypesUmbrella.serializer(), "a9646c6973748261616162686e756c6c61626c65f6636d6170a202f401f56169182a6a696e6e6572734c69737481a16161636b656b637374726d48656c6c6f2c20776f726c642165696e6e6572a16161636c6f6c6a62797465537472696e6742cafe6962797465417272617982383521" ) ) } /** * Test using example shown on page 11 of [RFC 7049 2.2.2](https://tools.ietf.org/html/rfc7049#section-2.2.2): * * ``` * 0b010_11111 0b010_00100 0xaabbccdd 0b010_00011 0xeeff99 0b111_11111 * * 5F -- Start indefinite-length byte string * 44 -- Byte string of length 4 * aabbccdd -- Bytes content * 43 -- Byte string of length 3 * eeff99 -- Bytes content * FF -- "break" * * After decoding, this results in a single byte string with seven * bytes: 0xaabbccddeeff99. * ``` */ @Test fun testRfc7049IndefiniteByteStringExample() { withDecoder(input = "5F44aabbccdd43eeff99FF") { assertEquals( expected = "aabbccddeeff99", actual = HexConverter.printHexBinary(nextByteString(), lowerCase = true) ) } } @Test fun testReadByteStringWhenNullable() { /* A1 # map(1) * 6A # text(10) * 62797465537472696E67 # "byteString" * 44 # bytes(4) * 01020304 # "\x01\x02\x03\x04" */ assertEquals( expected = NullableByteString(byteArrayOf(1, 2, 3, 4)), actual = Cbor.decodeFromHexString( deserializer = NullableByteString.serializer(), hex = "a16a62797465537472696e674401020304" ) ) /* A1 # map(1) * 6A # text(10) * 62797465537472696E67 # "byteString" * F6 # primitive(22) */ assertEquals( expected = NullableByteString(byteString = null), actual = Cbor.decodeFromHexString( deserializer = NullableByteString.serializer(), hex = "a16a62797465537472696e67f6" ) ) } /** * CBOR hex data represents serialized versions of [TypesUmbrella] (which does **not** have a root property 'a') so * decoding to [Simple] (which has the field 'a') is expected to fail. */ @Test fun testIgnoreUnknownKeysFailsWhenCborDataIsMissingKeysThatArePresentInKotlinClass() { // with maps & lists of indefinite length assertFailsWithMessage<SerializationException>("Field 'a' is required") { ignoreUnknownKeys.decodeFromHexString( Simple.serializer(), "bf637374726d48656c6c6f2c20776f726c64216169182a686e756c6c61626c65f6646c6973749f61616162ff636d6170bf01f502f4ff65696e6e6572bf6161636c6f6cff6a696e6e6572734c6973749fbf6161636b656bffffff" ) } // with maps & lists of definite length assertFailsWithMessage<SerializationException>("Field 'a' is required") { ignoreUnknownKeys.decodeFromHexString( Simple.serializer(), "a7646c6973748261616162686e756c6c61626c65f6636d6170a202f401f56169182a6a696e6e6572734c69737481a16161636b656b637374726d48656c6c6f2c20776f726c642165696e6e6572a16161636c6f6c" ) } } @Test fun testIgnoreUnknownKeysFailsWhenDecodingIncompleteCbor() { /* A3 # map(3) * 63 # text(3) * 737472 # "str" * 66 # text(6) * 737472696E67 # "string" * 61 # text(1) * 69 # "i" * 00 # unsigned(0) * 66 # text(6) * 69676E6F7265 # "ignore" * (missing value associated with "ignore" key) */ assertFailsWithMessage<CborDecodingException>("Unexpected EOF while skipping element") { ignoreUnknownKeys.decodeFromHexString( TypesUmbrella.serializer(), "a36373747266737472696e676169006669676e6f7265" ) } /* A3 # map(3) * 63 # text(3) * 737472 # "str" * 66 # text(6) * 737472696E67 # "string" * 61 # text(1) * 69 # "i" * 00 # unsigned(0) * 66 # text(6) * 69676E6F7265 # "ignore" * A2 # map(2) * (missing map contents associated with "ignore" key) */ assertFailsWithMessage<CborDecodingException>("Unexpected EOF while skipping element") { ignoreUnknownKeys.decodeFromHexString( TypesUmbrella.serializer(), "a36373747266737472696e676169006669676e6f7265a2" ) } } @Test fun testIgnoreUnknownKeysFailsWhenEncounteringPreemptiveBreak() { /* A3 # map(3) * 63 # text(3) * 737472 # "str" * 66 # text(6) * 737472696E67 # "string" * 66 # text(6) * 69676E6F7265 # "ignore" * FF # primitive(*) */ assertFailsWithMessage<CborDecodingException>("Expected next data item, but found FF") { ignoreUnknownKeys.decodeFromHexString( TypesUmbrella.serializer(), "a36373747266737472696e676669676e6f7265ff" ) } } /** * Tests skipping unknown keys associated with values of the following CBOR types: * - Major type 0: an unsigned integer * - Major type 1: a negative integer * - Major type 2: a byte string * - Major type 3: a text string */ @Test fun testSkipPrimitives() { /* A4 # map(4) * 61 # text(1) * 61 # "a" * 1B FFFFFFFFFFFFFFFF # unsigned(18446744073709551615) * 61 # text(1) * 62 # "b" * 20 # negative(0) * 61 # text(1) * 63 # "c" * 42 # bytes(2) * CAFE # "\xCA\xFE" * 61 # text(1) * 64 # "d" * 6B # text(11) * 48656C6C6F20776F726C64 # "Hello world" */ withDecoder("a461611bffffffffffffffff616220616342cafe61646b48656c6c6f20776f726c64") { expectMap(size = 4) expect("a") skipElement() // unsigned(18446744073709551615) expect("b") skipElement() // negative(0) expect("c") skipElement() // "\xCA\xFE" expect("d") skipElement() // "Hello world" expectEof() } } /** * Tests skipping unknown keys associated with values (that are empty) of the following CBOR types: * - Major type 2: a byte string * - Major type 3: a text string */ @Test fun testSkipEmptyPrimitives() { /* A2 # map(2) * 61 # text(1) * 61 # "a" * 40 # bytes(0) * # "" * 61 # text(1) * 62 # "b" * 60 # text(0) * # "" */ withDecoder("a2616140616260") { expectMap(size = 2) expect("a") skipElement() // bytes(0) expect("b") skipElement() // text(0) expectEof() } } /** * Tests skipping unknown keys associated with values of the following CBOR types: * - Major type 4: an array of data items * - Major type 5: a map of pairs of data items */ @Test fun testSkipCollections() { /* A2 # map(2) * 61 # text(1) * 61 # "a" * 83 # array(3) * 01 # unsigned(1) * 18 FF # unsigned(255) * 1A 00010000 # unsigned(65536) * 61 # text(1) * 62 # "b" * A2 # map(2) * 61 # text(1) * 78 # "x" * 67 # text(7) * 6B6F746C696E78 # "kotlinx" * 61 # text(1) * 79 # "y" * 6D # text(13) * 73657269616C697A6174696F6E # "serialization" */ withDecoder("a26161830118ff1a000100006162a26178676b6f746c696e7861796d73657269616c697a6174696f6e") { expectMap(size = 2) expect("a") skipElement() // [1, 255, 65536] expect("b") skipElement() // {"x": "kotlinx", "y": "serialization"} expectEof() } } /** * Tests skipping unknown keys associated with values (empty collections) of the following CBOR types: * - Major type 4: an array of data items * - Major type 5: a map of pairs of data items */ @Test fun testSkipEmptyCollections() { /* A2 # map(2) * 61 # text(1) * 61 # "a" * 80 # array(0) * 61 # text(1) * 62 # "b" * A0 # map(0) */ withDecoder("a26161806162a0") { expectMap(size = 2) expect("a") skipElement() // [1, 255, 65536] expect("b") skipElement() // {"x": "kotlinx", "y": "serialization"} expectEof() } } /** * Tests skipping unknown keys associated with **indefinite length** values of the following CBOR types: * - Major type 2: a byte string * - Major type 3: a text string * - Major type 4: an array of data items * - Major type 5: a map of pairs of data items */ @Test fun testSkipIndefiniteLength() { /* A4 # map(4) * 61 # text(1) * 61 # "a" * 5F # bytes(*) * 42 # bytes(2) * CAFE # "\xCA\xFE" * 43 # bytes(3) * 010203 # "\x01\x02\x03" * FF # primitive(*) * 61 # text(1) * 62 # "b" * 7F # text(*) * 66 # text(6) * 48656C6C6F20 # "Hello " * 65 # text(5) * 776F726C64 # "world" * FF # primitive(*) * 61 # text(1) * 63 # "c" * 9F # array(*) * 67 # text(7) * 6B6F746C696E78 # "kotlinx" * 6D # text(13) * 73657269616C697A6174696F6E # "serialization" * FF # primitive(*) * 61 # text(1) * 64 # "d" * BF # map(*) * 61 # text(1) * 31 # "1" * 01 # unsigned(1) * 61 # text(1) * 32 # "2" * 02 # unsigned(2) * 61 # text(1) * 33 # "3" * 03 # unsigned(3) * FF # primitive(*) */ withDecoder("a461615f42cafe43010203ff61627f6648656c6c6f2065776f726c64ff61639f676b6f746c696e786d73657269616c697a6174696f6eff6164bf613101613202613303ff") { expectMap(size = 4) expect("a") skipElement() // "\xCA\xFE\x01\x02\x03" expect("b") skipElement() // "Hello world" expect("c") skipElement() // ["kotlinx", "serialization"] expect("d") skipElement() // {"1": 1, "2": 2, "3": 3} expectEof() } } /** * Tests that skipping unknown keys also skips over associated tags. * * Includes tags on the key, tags on the value, and tags on both key and value. */ @Test fun testSkipTags() { /* * A4 # map(4) * 61 # text(1) * 61 # "a" * CC # tag(12) * 1B FFFFFFFFFFFFFFFF # unsigned(18446744073709551615) * D8 22 # tag(34) * 61 # text(1) * 62 # "b" * 20 # negative(0) * D8 38 # tag(56) * 61 # text(1) * 63 # "c" * D8 4E # tag(78) * 42 # bytes(2) * CAFE # "\xCA\xFE" * 61 # text(1) * 64 # "d" * D8 5A # tag(90) * CC # tag(12) * 6B # text(11) * 48656C6C6F20776F726C64 # "Hello world" */ withDecoder("A46161CC1BFFFFFFFFFFFFFFFFD822616220D8386163D84E42CAFE6164D85ACC6B48656C6C6F20776F726C64") { expectMap(size = 4) expect("a") skipElement() // unsigned(18446744073709551615) expect("b") skipElement() // negative(0) expect("c") skipElement() // "\xCA\xFE" expect("d") skipElement() // "Hello world" expectEof() } } @Test fun testDecodeCborWithUnknownField() { assertEquals( expected = Simple("123"), actual = ignoreUnknownKeys.decodeFromHexString( deserializer = Simple.serializer(), /* BF # map(*) * 61 # text(1) * 61 # "a" * 63 # text(3) * 313233 # "123" * 61 # text(1) * 62 # "b" * 63 # text(3) * 393837 # "987" * FF # primitive(*) */ hex = "bf616163313233616263393837ff" ) ) } @Test fun testDecodeCborWithUnknownNestedIndefiniteFields() { assertEquals( expected = Simple("123"), actual = ignoreUnknownKeys.decodeFromHexString( deserializer = Simple.serializer(), /* BF # map(*) * 61 # text(1) * 61 # "a" * 63 # text(3) * 313233 # "123" * 61 # text(1) * 62 # "b" * BF # map(*) * 7F # text(*) * 61 # text(1) * 78 # "x" * FF # primitive(*) * A1 # map(1) * 61 # text(1) * 79 # "y" * 0A # unsigned(10) * FF # primitive(*) * 61 # text(1) * 63 # "c" * 9F # array(*) * 01 # unsigned(1) * 02 # unsigned(2) * 03 # unsigned(3) * FF # primitive(*) * FF # primitive(*) */ hex = "bf6161633132336162bf7f6178ffa161790aff61639f010203ffff" ) ) } /** * The following CBOR diagnostic output demonstrates the additional fields (prefixed with `+` in front of each line) * present in the encoded CBOR data that does not have associated fields in the Kotlin classes (they will be skipped * over with `ignoreUnknownKeys` is enabled). * * ```diff * { * + "extra": [ * + 9, * + 8, * + 7 * + ], * "boxed": [ * [ * "kotlinx.serialization.SimpleSealed.SubSealedA", * { * "s": "a", * + "newA": { * + "x": 1, * + "y": 2 * + } * } * ], * [ * "kotlinx.serialization.SimpleSealed.SubSealedB", * { * "i": 1 * } * ] * ] * } * ``` */ @Test fun testDecodeCborWithUnknownKeysInSealedClasses() { /* BF # map(*) * 65 # text(5) * 6578747261 # "extra" * 83 # array(3) * 09 # unsigned(9) * 08 # unsigned(8) * 07 # unsigned(7) * 65 # text(5) * 626F786564 # "boxed" * 9F # array(*) * 9F # array(*) * 78 2D # text(45) * 6B6F746C696E782E73657269616C697A6174696F6E2E53696D706C655365616C65642E5375625365616C656441 # "kotlinx.serialization.SimpleSealed.SubSealedA" * BF # map(*) * 61 # text(1) * 73 # "s" * 61 # text(1) * 61 # "a" * 64 # text(4) * 6E657741 # "newA" * BF # map(*) * 61 # text(1) * 78 # "x" * 01 # unsigned(1) * 61 # text(1) * 79 # "y" * 02 # unsigned(2) * FF # primitive(*) * FF # primitive(*) * FF # primitive(*) * 9F # array(*) * 78 2D # text(45) * 6B6F746C696E782E73657269616C697A6174696F6E2E53696D706C655365616C65642E5375625365616C656442 # "kotlinx.serialization.SimpleSealed.SubSealedB" * BF # map(*) * 61 # text(1) * 69 # "i" * 01 # unsigned(1) * FF # primitive(*) * FF # primitive(*) * FF # primitive(*) * FF # primitive(*) */ assertEquals( expected = SealedBox( listOf( SubSealedA("a"), SubSealedB(1) ) ), actual = ignoreUnknownKeys.decodeFromHexString( SealedBox.serializer(), "bf6565787472618309080765626f7865649f9f782d6b6f746c696e782e73657269616c697a6174696f6e2e53696d706c655365616c65642e5375625365616c656441bf61736161646e657741bf617801617902ffffff9f782d6b6f746c696e782e73657269616c697a6174696f6e2e53696d706c655365616c65642e5375625365616c656442bf616901ffffffff" ) ) } @Test fun testReadCustomByteString() { assertEquals( expected = TypeWithCustomByteString(CustomByteString(0x11, 0x22, 0x33)), actual = Cbor.decodeFromHexString("bf617843112233ff") ) } @Test fun testReadNullableCustomByteString() { assertEquals( expected = TypeWithNullableCustomByteString(CustomByteString(0x11, 0x22, 0x33)), actual = Cbor.decodeFromHexString("bf617843112233ff") ) } @Test fun testReadNullCustomByteString() { assertEquals( expected = TypeWithNullableCustomByteString(null), actual = Cbor.decodeFromHexString("bf6178f6ff") ) } @Test fun testIgnoresTagsOnStrings() { /* * 84 # array(4) * 68 # text(8) * 756E746167676564 # "untagged" * C0 # tag(0) * 68 # text(8) * 7461676765642D30 # "tagged-0" * D8 F5 # tag(245) * 6A # text(10) * 7461676765642D323435 # "tagged-244" * D9 3039 # tag(12345) * 6C # text(12) * 7461676765642D3132333435 # "tagged-12345" * */ withDecoder("8468756E746167676564C0687461676765642D30D8F56A7461676765642D323435D930396C7461676765642D3132333435") { assertEquals(4, startArray()) assertEquals("untagged", nextString()) assertEquals("tagged-0", nextString()) assertEquals("tagged-245", nextString()) assertEquals("tagged-12345", nextString()) } } @Test fun testIgnoresTagsOnNumbers() { /* * 86 # array(6) * 18 7B # unsigned(123) * C0 # tag(0) * 1A 0001E240 # unsigned(123456) * D8 F5 # tag(245) * 1A 000F423F # unsigned(999999) * D9 3039 # tag(12345) * 38 31 # negative(49) * D8 22 # tag(34) * FB 3FE161F9F01B866E # primitive(4603068020252444270) * D9 0237 # tag(567) * FB 401999999999999A # primitive(4618891777831180698) */ withDecoder("86187BC01A0001E240D8F51A000F423FD930393831D822FB3FE161F9F01B866ED90237FB401999999999999A") { assertEquals(6, startArray()) assertEquals(123, nextNumber()) assertEquals(123456, nextNumber()) assertEquals(999999, nextNumber()) assertEquals(-50, nextNumber()) assertEquals(0.54321, nextDouble(), 0.00001) assertEquals(6.4, nextDouble(), 0.00001) } } @Test fun testIgnoresTagsOnArraysAndMaps() { /* * A2 # map(2) * 63 # text(3) * 6D6170 # "map" * D8 7B # tag(123) * A1 # map(1) * 68 # text(8) * 74686973206D6170 # "this map" * 6D # text(13) * 69732074616767656420313233 # "is tagged 123" * 65 # text(5) * 6172726179 # "array" * DA 0012D687 # tag(1234567) * 83 # array(3) * 6A # text(10) * 74686973206172726179 # "this array" * 69 # text(9) * 697320746167676564 # "is tagged" * 67 # text(7) * 31323334353637 # "1234567" */ withDecoder("A2636D6170D87BA16874686973206D61706D69732074616767656420313233656172726179DA0012D687836A74686973206172726179696973207461676765646731323334353637") { assertEquals(2, startMap()) assertEquals("map", nextString()) assertEquals(1, startMap()) assertEquals("this map", nextString()) assertEquals("is tagged 123", nextString()) assertEquals("array", nextString()) assertEquals(3, startArray()) assertEquals("this array", nextString()) assertEquals("is tagged", nextString()) assertEquals("1234567", nextString()) } } } private fun CborDecoder.expect(expected: String) { assertEquals(expected, actual = nextString(), "string") } private fun CborDecoder.expectMap(size: Int) { assertEquals(size, actual = startMap(), "map size") } private fun CborDecoder.expectEof() { assertTrue(isEof(), "Expected EOF.") }
apache-2.0
b9361856cbeb8d1ccccdba76d2cdd7c0
38.492537
302
0.422215
4.147335
false
true
false
false
andrei-heidelbacher/algoventure-core
src/main/kotlin/com/aheidelbacher/algoventure/core/graphics2d/RenderOrderSystem.kt
1
2263
/* * Copyright 2016 Andrei Heidelbacher <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aheidelbacher.algoventure.core.graphics2d import com.aheidelbacher.algostorm.event.Event import com.aheidelbacher.algostorm.event.Publisher import com.aheidelbacher.algostorm.event.Subscribe import com.aheidelbacher.algostorm.event.Subscriber import com.aheidelbacher.algostorm.state.Layer.ObjectGroup import com.aheidelbacher.algostorm.state.Layer.ObjectGroup.DrawOrder import com.aheidelbacher.algostorm.state.Object import com.aheidelbacher.algostorm.systems.Update import java.util.Comparator class RenderOrderSystem( private val objectGroup: ObjectGroup, private val publisher: Publisher ) : Subscriber { companion object : Comparator<Object> { const val Z: String = "z" val Object.z: Int get() = getInt(Z) ?: -1 override fun compare(o1: Object, o2: Object): Int = if (o1.y != o2.y) o1.y - o2.y else o1.z - o2.z } object SortObjects : Event init { require(objectGroup.drawOrder == DrawOrder.INDEX) } private fun List<Object>.isSorted(): Boolean { for (i in 0..(size - 2)) { if (get(i).z > get(i + 1).z) { return false } } return true } @Subscribe fun onSortObjects(event: SortObjects) { if (!objectGroup.objectSet.isSorted()) { val objects = objectGroup.objectSet.toTypedArray() objectGroup.clear() objects.sortWith(Companion) objects.forEach { objectGroup.add(it) } } } @Subscribe fun onUpdate(event: Update) { publisher.post(SortObjects) } }
apache-2.0
03b5c91ab97e085646d3a9ca4ffbcdc4
30.873239
75
0.676536
4.137112
false
false
false
false
davidwhitman/changelogs
playstoreapi/src/main/kotlin/com/thunderclouddev/playstoreapi/legacyMarketApi/MarketApiConstantsInternal.kt
1
700
/* * Copyright (c) 2017. * Distributed under the GNU GPLv3 by David Whitman. * https://www.gnu.org/licenses/gpl-3.0.en.html * * This source code is made available to help others learn. Please don't clone my app. */ package com.thunderclouddev.playstoreapi.legacyMarketApi import okhttp3.MediaType internal object MarketApiConstantsInternal { val CONTENT_TYPE: MediaType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8") val PROTOCOL_VERSION = 2 val VERSION = 2009011 val OPERATOR_NAME_ID_PAIR = "T-Mobile" to "310260" val URL = "http://android.clients.google.com/market/api/ApiRequest" } object MarketApiConstants{ val REQUESTS_PER_GROUP = 10 }
gpl-3.0
773eff27550186760afee6275123b1a3
27.04
101
0.734286
3.517588
false
false
false
false
WindSekirun/RichUtilsKt
RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RInternal.kt
1
1329
@file:JvmName("RichUtils") @file:JvmMultifileClass @file:Suppress("UNCHECKED_CAST") package pyxis.uzuki.live.richutilskt.utils import android.util.Log import pyxis.uzuki.live.richutilskt.impl.F0 import java.io.File import java.math.BigDecimal import java.text.DecimalFormat inline fun <T, R> T.tryCatch(block: (T) -> R): R { try { return block(this) } catch (e: Exception) { Log.e("tag", "I/O Exception", e) throw e } } fun tryCatch(block: F0) { try { block.invoke() } catch (e: Exception) { println("catch exception :: ${e.message}") } } internal inline fun <R> getValue(block: () -> R, def: Any?): R = try { block() } catch (e: Exception) { def as R } internal inline fun <T, R> T.convert(block: (T) -> R, def: Any?): R = try { block(this) } catch (e: Exception) { def as R } internal inline fun <T, R> T.convertAcceptNull(block: (T) -> R, def: Any?): R? = try { block(this) } catch (e: Exception) { def as R } /** * formatting number like 1,000,000 */ @JvmOverloads fun toNumFormat(num: String, format: String = "#,###"): String { val df = DecimalFormat("#,###") return df.format(BigDecimal(num)) }
apache-2.0
55468875aa621d370d2d470a33d0c41a
21.166667
80
0.55681
3.416452
false
false
false
false
nathanjent/adventofcode-rust
kotlin/src/main/kotlin/2018/Lib02.kt
1
1912
package aoc.kt.y2018; /** * Day 2. */ /** Part 1 */ fun processBoxChecksum1(input: String): String { val (count2s, count3s) = input.lines() .filter { !it.isEmpty() } .map { val charCounts = mutableMapOf<Char, Int>() it.forEach { c -> val count = charCounts.getOrDefault(c, 0) charCounts.put(c, count + 1) } Pair(if (charCounts.containsValue(2)) 1 else 0, if (charCounts.containsValue(3)) 1 else 0) } .fold(Pair(0, 0), { (count2s, count3s), (two, three) -> Pair(count2s + two, count3s + three) }) return (count2s * count3s).toString() } /** Part 2 */ fun processBoxChecksum2(input: String): String { val lines = input.lines() .filter { !it.isEmpty() } val matchCounts = mutableMapOf<String, Pair<Int, Int>>() for (l1 in lines) { for (l2 in lines) { if (l1 == l2) continue // use combined lines as key val key = "$l1:$l2" l1.zip(l2).forEachIndexed({ index, (c1, c2) -> val (count, pIndex) = matchCounts.getOrDefault(key, Pair(0, -1)) if (c1 == c2) { // count matching characters matchCounts.put(key, Pair(count + 1, pIndex)) } else { // index of the non-matching character matchCounts.put(key, Pair(count, index)) } }) } } val maxEntry = matchCounts .maxBy { (_, p) -> p.first } val (_, index) = maxEntry?.component2()?:Pair(0, -1) val key = maxEntry?.component1()?:"" val word = key.substringBefore(':') val first = word.substring(0 until index) val last = word.substring(index+1..word.length-1) return "$first$last" }
mit
ac5660c558fed9c211a90fe03e5ced87
28.875
65
0.495816
3.756385
false
false
false
false
lightem90/Sismic
app/src/main/java/com/polito/sismic/Extensions/Extensions.kt
1
14873
package com.polito.sismic.Extensions import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.SharedPreferences import android.database.sqlite.SQLiteDatabase import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.widget.Toast import com.polito.sismic.Presenters.Adapters.ReportFragmentsAdapter import com.stepstone.stepper.adapter.StepAdapter import org.jetbrains.anko.db.MapRowParser import org.jetbrains.anko.db.SelectQueryBuilder import java.text.SimpleDateFormat import java.util.* import kotlin.reflect.KProperty import android.provider.OpenableColumns import android.view.* import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import com.github.mikephil.charting.data.Entry import com.polito.sismic.Domain.* import android.widget.EditText /** * Created by Matteo on 07/08/2017. */ //Context extensions fun Context.toast(resourceId: Int) = toast(getString(resourceId)) fun Context.toast(message: CharSequence) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show() inline fun SharedPreferences.edit(func: SharedPreferences.Editor.() -> Unit) { val editor = edit() editor.func() editor.apply() } object DelegatesExt { fun <T> notNullSingleValue() = NotNullSingleValueVar<T>() fun <T> preference(context: Context, name: String, default: T) = Preference(context, name, default) } fun <T : Any> SelectQueryBuilder.parseList(parser: (Map<String, Any?>) -> T): List<T> = parseList(object : MapRowParser<T> { override fun parseRow(columns: Map<String, Any?>): T = parser(columns) }) fun <T : Any> SelectQueryBuilder.parseOpt(parser: (Map<String, Any?>) -> T): T? = parseOpt(object : MapRowParser<T> { override fun parseRow(columns: Map<String, Any?>): T = parser(columns) }) fun SQLiteDatabase.clear(tableName: String) { execSQL("delete from $tableName") } fun SelectQueryBuilder.byId(id: String) = whereSimple("_id = ?", id) fun SelectQueryBuilder.byReportId(id: String) = whereSimple("report_id = ?", id) class NotNullSingleValueVar<T> { private var value: T? = null operator fun getValue(thisRef: Any?, property: KProperty<*>): T { return value ?: throw IllegalStateException("${property.name} not initialized") } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { this.value = if (this.value == null) value else throw IllegalStateException("${property.name} already initialized") } } class Preference<T>(val context: Context, val name: String, val default: T) { val prefs: SharedPreferences by lazy { context.getSharedPreferences("default", Context.MODE_PRIVATE) } operator fun getValue(thisRef: Any?, property: KProperty<*>): T { return findPreference(name, default) } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { putPreference(name, value) } @Suppress("UNCHECKED_CAST") private fun findPreference(name: String, default: T): T = with(prefs) { val res: Any = when (default) { is Long -> getLong(name, default) is String -> getString(name, default) is Int -> getInt(name, default) is Boolean -> getBoolean(name, default) is Float -> getFloat(name, default) else -> throw IllegalArgumentException("This type can be saved into Preferences") } res as T } @SuppressLint("CommitPrefEdits") private fun putPreference(name: String, value: T) = with(prefs.edit()) { when (value) { is Long -> putLong(name, value) is String -> putString(name, value) is Int -> putInt(name, value) is Boolean -> putBoolean(name, value) is Float -> putFloat(name, value) else -> throw IllegalArgumentException("This type can't be saved into Preferences") }.apply() } } fun String.toFormattedDate(): Date { return SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").parse(this) } fun Date.toFormattedString(): String { return SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(this) } fun <K, V : Any> Map<K, V?>.toVarargArray(): Array<out Pair<K, V>> = map({ Pair(it.key, it.value!!) }).toTypedArray() fun Bundle.putReport(state: Report) { putParcelable("report_state", state) } fun Bundle.getReport(): Report? { return getParcelable("report_state") } fun ViewGroup.inflate(layoutRes: Int): View { return LayoutInflater.from(context).inflate(layoutRes, this, false) } fun Double.getPowerOfTwoForSampleRatio(): Int { val k = Integer.highestOneBit(Math.floor(this).toInt()) if (k == 0) return 1 else return k } fun StepAdapter.getCustomAdapter(): ReportFragmentsAdapter { return this as ReportFragmentsAdapter } fun NeighboursNodeSquare.toList(): List<NeighboursNodeData> { return listOf(NE, NO, SO, SE) } fun Uri.getFileName(mContext: Context): String? { val returnCursor = mContext.contentResolver.query(this, null, null, null, null) val nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) returnCursor.moveToFirst() val filename = returnCursor.getString(nameIndex) returnCursor.close() return filename } fun Uri.getSizeInMb(mContext: Context): Double { val returnCursor = mContext.contentResolver.query(this, null, null, null, null) returnCursor.moveToFirst() val sizeIndex = returnCursor.getLong(returnCursor.getColumnIndex(OpenableColumns.SIZE)) returnCursor.close() val doubleSizeIndex = sizeIndex.toDouble() return doubleSizeIndex / 1024 / 1024 } fun Uri.getMediaPath(mContext: Context): String { val projection = arrayOf(MediaStore.Images.Media.DATA) val cursor = mContext.contentResolver.query(this, projection, null, null, null) val column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA) cursor.moveToFirst() val toReturn = cursor.getString(column_index) cursor.close() return toReturn } fun String.toUri(): Uri { return Uri.parse(this) } fun List<Entry>.toSpectrumPointList(): List<SpectrumPoint> { return map { SpectrumPoint(it.x.toDouble(), it.y.toDouble()) } } fun List<SpectrumPoint>.toEntryList(): List<Entry> { return map { Entry(it.x.toFloat(), it.y.toFloat()) } } fun PeriodData.interpolateWith(next: PeriodData, newYear: Int): PeriodData { val newAg = MathUti.periodDataInterpolation(ag, next.ag, years, next.years, newYear) val newF0 = MathUti.periodDataInterpolation(f0, next.f0, years, next.years, newYear) val newTcStar = MathUti.periodDataInterpolation(tcstar, next.tcstar, years, next.years, newYear) return PeriodData(newYear, newAg, newF0, newTcStar) } fun String.toDoubleOrZero(): Double { return if (isEmpty()) 0.0 else { var tmp = this tmp = tmp.replace(",", ".") return tmp.toDouble() } } fun String.toIntOrZero(): Int { return if (isEmpty()) 0 else toInt() } fun Double.toStringOrEmpty(): String { return if (this == 0.0) "" else toString() } fun Int.toStringOrEmpty(): String { return if (this == 0) "" else toString() } //better safe than sorry fun Activity.hideSoftKeyboard() { val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManager?.let { if (currentFocus != null && currentFocus.windowToken != null && window != null) it.hideSoftInputFromWindow(currentFocus.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) } } fun Activity.showSoftKeyboard() { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm?.let { if (currentFocus != null && window != null) it.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0) } } fun EditText.onConfirm(callback: () -> Unit) { setOnEditorActionListener { _, actionId, event -> if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_DONE || event?.action == KeyEvent.ACTION_DOWN && event?.keyCode == KeyEvent.KEYCODE_ENTER) { callback.invoke() true } else { false } } } fun String.toPlantPointList(): List<PlantPoint> { val pointList = split(" ") return pointList .filter { !it.isEmpty() } .map { it -> val pair = it.split(",") PlantPoint(pair[0].toDouble(), pair[1].toDouble()) } } fun List<PlantPoint>.toParsablePlantString(): String { val sb = StringBuilder() forEach { sb.append(it.x.toPrecisionString()) sb.append(",") sb.append(it.y.toPrecisionString()) sb.append(" ") } return sb.toString() } fun String.toPillarDomainPointList(): List<PillarDomainGraphPoint> { val pointList = split(" ") return pointList .filter { !it.isEmpty() } .map { it -> val pair = it.split(",") PillarDomainGraphPoint(pair[0].toDouble(), pair[1].toDouble()) } } fun List<PillarDomainGraphPoint>.toParsablePillarDomainPointString(): String { val sb = StringBuilder() forEach { sb.append(it.n.toString()) sb.append(",") sb.append(it.m.toString()) sb.append(" ") } return sb.toString() } fun String.toPillarDomainLimitStateList(): List<PillarDomainPoint> { val pointList = split(" ") return pointList .filter { !it.isEmpty() } .mapNotNull { it -> val values = it.split(",") if (values.size == 7) { PillarDomainPoint(values[0].toDoubleOrZero(), values[1].toDoubleOrZero(), values[2].toDoubleOrZero(), values[3].toDoubleOrZero(), values[4].toDoubleOrZero(), values[5], values[6].toIntOrZero()) } else null } } fun Double.toPrecisionString() : String { return "%.6f".format(this) } fun List<PillarDomainPoint>.toParsablePillarLimitStateString(): String { val sb = StringBuilder() forEach { sb.append(it.n.toString()) sb.append(",") sb.append(it.m.toString()) sb.append(",") sb.append(it.sd.toPrecisionString()) sb.append(",") sb.append(it.fh.toPrecisionString()) sb.append(",") sb.append(it.ty.toPrecisionString()) sb.append(",") sb.append(it.label) sb.append(",") sb.append(it.color.toString()) sb.append(" ") } return sb.toString() } fun String.toSpectrumDTOList(): List<SpectrumDTO> { val pointList = split(" ") return pointList .filter { !it.isEmpty() } .mapNotNull { it -> val values = it.split(",") if (values.size == 16) { SpectrumDTO(values[0], values[1].toIntOrZero(), values[2].toIntOrZero(), values[3].toDoubleOrZero(), values[4].toDoubleOrZero(), values[5].toDoubleOrZero(), values[6].toDoubleOrZero(), values[7].toDoubleOrZero(), values[8].toDoubleOrZero(), values[9].toDoubleOrZero(), values[10].toDoubleOrZero(), values[11].toDoubleOrZero(), values[12].toDoubleOrZero(), values[13].toDoubleOrZero(), values[14].toDoubleOrZero(), values[15].toSpectrumPointList()) } else null } } fun List<SpectrumDTO>.toParsableSpectrumDTOString(): String { val sb = StringBuilder() forEach { sb.append(it.name) sb.append(",") sb.append(it.year.toString()) sb.append(",") sb.append(it.color.toString()) sb.append(",") sb.append(it.ag.toPrecisionString()) sb.append(",") sb.append(it.f0.toPrecisionString()) sb.append(",") sb.append(it.tcStar.toPrecisionString()) sb.append(",") sb.append(it.ss.toPrecisionString()) sb.append(",") sb.append(it.cc.toPrecisionString()) sb.append(",") sb.append(it.st.toPrecisionString()) sb.append(",") sb.append(it.q.toPrecisionString()) sb.append(",") sb.append(it.s.toPrecisionString()) sb.append(",") sb.append(it.ni.toPrecisionString()) sb.append(",") sb.append(it.tb.toPrecisionString()) sb.append(",") sb.append(it.tc.toPrecisionString()) sb.append(",") sb.append(it.td.toPrecisionString()) sb.append(",") sb.append(it.pointList.toSpectrumPointString()) sb.append(" ") } return sb.toString() } fun String.toSpectrumPointList(): List<SpectrumPoint> { val pointList = split("&") return pointList .filter { !it.isEmpty() } .map { it -> val pair = it.split("-") SpectrumPoint(pair[0].toDouble(), pair[1].toDouble()) } } fun List<SpectrumPoint>.toSpectrumPointString(): String { val sb = StringBuilder() forEach { sb.append(it.x.toPrecisionString()) sb.append("-") sb.append(it.y.toPrecisionString()) sb.append("&") } return sb.toString() } fun List<PlantPoint>.indexOfNext(point: PlantPoint): Int { return indexOf(point) + 1 } fun PlantPoint.distanceFrom(other: PlantPoint): Double { return Math.sqrt((Math.pow((x - other.x), 2.0)) + (Math.pow((y - other.y), 2.0))) } fun SpectrumPoint.distanceFrom(other: SpectrumPoint): Double { return Math.sqrt((Math.pow((x - other.x), 2.0)) + (Math.pow((y - other.y), 2.0))) } fun SpectrumPoint.verticalMiddlePoint(other : SpectrumPoint) : Double { return (y + other.y) / 2 } class MathUti { companion object { fun periodDataInterpolation(p1: Double, p2: Double, tr1: Int, tr2: Int, tr: Int): Double { val first = Math.log(p1) val second = Math.log((p2 / p1)) val third = Math.log((tr.toDouble() / tr1.toDouble())) val fourth = Math.log((tr2.toDouble() / tr1.toDouble())) val lnp = first + (second * third * (1 / fourth)) return Math.pow(Math.E, lnp) } } }
mit
c7ca0b4f2f7763d1bff3f35038a2413c
31.262473
176
0.612452
4.096117
false
false
false
false
Mauin/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/empty/EmptyCodeTest.kt
1
3576
package io.gitlab.arturbosch.detekt.rules.empty import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.rules.Case import io.gitlab.arturbosch.detekt.test.TestConfig import io.gitlab.arturbosch.detekt.test.compileForTest import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import java.util.regex.PatternSyntaxException import kotlin.test.assertFailsWith /** * @author Artur Bosch */ class EmptyCodeTest { val file = compileForTest(Case.Empty.path()) private val regexTestingCode = """ fun f() { try { } catch (foo: MyException) { } }""" @Test fun findsEmptyCatch() { test { EmptyCatchBlock(Config.empty) } } @Test fun findsEmptyNestedCatch() { val code = """ fun f() { try { } catch (ignore: IOException) { try { } catch (e: IOException) { } } }""" assertThat(EmptyCatchBlock(Config.empty).lint(code)).hasSize(1) } @Test fun doesNotReportIgnoredOrExpectedException() { val code = """ fun f() { try { } catch (ignore: IOException) { } catch (expected: Exception) { } }""" assertThat(EmptyCatchBlock(Config.empty).lint(code)).isEmpty() } @Test fun doesNotReportEmptyCatchWithConfig() { val code = """ fun f() { try { } catch (foo: MyException) { } }""" val config = TestConfig(mapOf(EmptyCatchBlock.ALLOWED_EXCEPTION_NAME_REGEX to "foo")) assertThat(EmptyCatchBlock(config).lint(code)).isEmpty() } @Test fun findsEmptyFinally() { test { EmptyFinallyBlock(Config.empty) } } @Test fun findsEmptyIf() { test { EmptyIfBlock(Config.empty) } } @Test fun findsEmptyElse() { test { EmptyElseBlock(Config.empty) } } @Test fun findsEmptyFor() { test { EmptyForBlock(Config.empty) } } @Test fun findsEmptyWhile() { test { EmptyWhileBlock(Config.empty) } } @Test fun findsEmptyDoWhile() { test { EmptyDoWhileBlock(Config.empty) } } @Test fun findsEmptyFun() { test { EmptyFunctionBlock(Config.empty) } } @Test fun findsEmptyClass() { test { EmptyClassBlock(Config.empty) } } @Test fun findsEmptyWhen() { test { EmptyWhenBlock(Config.empty) } } @Test fun findsEmptyInit() { test { EmptyInitBlock(Config.empty) } } @Test fun findsOneEmptySecondaryConstructor() { test { EmptySecondaryConstructor(Config.empty) } } @Test fun findsEmptyDefaultConstructor() { val rule = EmptyDefaultConstructor(Config.empty) val text = compileForTest(Case.EmptyDefaultConstructorPositive.path()).text assertThat(rule.lint(text)).hasSize(2) } @Test fun doesNotFindEmptyDefaultConstructor() { val rule = EmptyDefaultConstructor(Config.empty) val text = compileForTest(Case.EmptyDefaultConstructorNegative.path()).text assertThat(rule.lint(text)).isEmpty() } @Test fun doesNotFailWithInvalidRegexWhenDisabled() { val configValues = mapOf("active" to "false", EmptyCatchBlock.ALLOWED_EXCEPTION_NAME_REGEX to "*foo") val config = TestConfig(configValues) assertThat(EmptyCatchBlock(config).lint(regexTestingCode)).isEmpty() } @Test fun doesFailWithInvalidRegex() { val configValues = mapOf(EmptyCatchBlock.ALLOWED_EXCEPTION_NAME_REGEX to "*foo") val config = TestConfig(configValues) assertFailsWith<PatternSyntaxException> { EmptyCatchBlock(config).lint(regexTestingCode) } } private fun test(block: () -> Rule) { val rule = block() rule.lint(file) assertThat(rule.findings).hasSize(1) } }
apache-2.0
63c64dfdfab718675d08132b419e9baf
21.074074
87
0.70274
3.295853
false
true
false
false
crunchersaspire/worshipsongs-android
app/src/main/java/org/worshipsongs/fragment/SettingsPreferenceFragment.kt
3
2515
package org.worshipsongs.fragment import android.content.Intent import android.os.Bundle import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import org.worshipsongs.CommonConstants.THEME_KEY import org.worshipsongs.R import org.worshipsongs.WorshipSongApplication import org.worshipsongs.activity.UserSettingActivity import org.worshipsongs.listener.ThemePreferenceListener import org.worshipsongs.preference.LanguagePreference import org.worshipsongs.preference.PreferenceListener import org.worshipsongs.preference.ThemeListPreference import org.worshipsongs.service.ResetDefaultSettingsService /** * @author Madasamy * @since 1.0.0 */ class SettingsPreferenceFragment : PreferenceFragmentCompat(), PreferenceListener { private var userSettingActivity = UserSettingActivity() override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.settings, rootKey) languagePreference() themePreference() resetPreferenceSettings() } private fun languagePreference() { val preference = findPreference<LanguagePreference>("languagePreference") if (preference is LanguagePreference) { preference.setPreferenceListener(this) } } private fun themePreference() { val themeListPreference = findPreference<ThemeListPreference>(THEME_KEY) themeListPreference!!.onPreferenceChangeListener = ThemePreferenceListener(userSettingActivity, this) } private fun resetPreferenceSettings() { val resetDialogPreference = findPreference<ResetDefaultSettingsService>("resetDialog") resetDialogPreference!!.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> val startIntent = Intent(WorshipSongApplication.context, UserSettingActivity::class.java) startIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) userSettingActivity.activityFinish() startActivity(startIntent) false } } fun setUserSettingActivity(userSettingActivity: UserSettingActivity) { this.userSettingActivity = userSettingActivity } override fun onSelect() { userSettingActivity.invalidateOptionsMenu() userSettingActivity.finish() val startIntent = Intent(WorshipSongApplication.context, UserSettingActivity::class.java) startActivity(startIntent) } }
gpl-3.0
d314f90ef5ac5a926cf7713abd190189
32.105263
115
0.752684
5.781609
false
false
false
false
danrien/projectBlueWater
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/service/broadcasters/GivenAPlayingFile/WhenBroadcastingTheFileProgress.kt
1
2610
package com.lasthopesoftware.bluewater.client.playback.service.broadcasters.GivenAPlayingFile import androidx.test.core.app.ApplicationProvider import com.lasthopesoftware.bluewater.client.playback.file.PlayableFile import com.lasthopesoftware.bluewater.client.playback.file.PlayedFile import com.lasthopesoftware.bluewater.client.playback.file.PlayingFile import com.lasthopesoftware.bluewater.client.playback.service.broadcasters.TrackPositionBroadcaster import com.lasthopesoftware.bluewater.shared.promises.extensions.ProgressedPromise import com.lasthopesoftware.bluewater.shared.promises.extensions.ProgressingPromise import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import com.lasthopesoftware.resources.FakeMessageBus import com.namehillsoftware.handoff.promises.Promise import io.mockk.mockk import org.assertj.core.api.AssertionsForClassTypes.assertThat import org.joda.time.Duration import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class WhenBroadcastingTheFileProgress { companion object { private val receivedIntent by lazy { val messageBus = FakeMessageBus(ApplicationProvider.getApplicationContext()) val trackPositionBroadcaster = TrackPositionBroadcaster(messageBus, mockk()) trackPositionBroadcaster.observeUpdates(object : PlayingFile { override fun promisePause(): Promise<PlayableFile> { return Promise.empty() } override fun promisePlayedFile(): ProgressedPromise<Duration, PlayedFile> { return object : ProgressingPromise<Duration, PlayedFile>() { override val progress: Promise<Duration> get() = Duration.ZERO.toPromise() } } override val duration: Promise<Duration> get() = Duration.standardMinutes(3).toPromise() override val progress: Promise<Duration> get() = promisePlayedFile().progress }).accept( Duration .standardSeconds(2) .plus(Duration.standardSeconds(30))) messageBus.recordedIntents.first() } private val duration by lazy { receivedIntent.getLongExtra(TrackPositionBroadcaster.TrackPositionChangedParameters.fileDuration, -1) } private val progress by lazy { receivedIntent.getLongExtra(TrackPositionBroadcaster.TrackPositionChangedParameters.filePosition, -1) } } @Test fun thenTheProgressIsCorrect() { assertThat(progress).isEqualTo(Duration .standardSeconds(2) .plus(Duration.standardSeconds(30)).millis) } @Test fun thenTheDurationIsCorrect() { assertThat(duration).isEqualTo(Duration.standardMinutes(3).millis) } }
lgpl-3.0
1a910878f44a7b76745919ce65c8a5d3
35.760563
104
0.803831
4.342762
false
true
false
false
GeoffreyMetais/vlc-android
application/television/src/main/java/org/videolan/television/ui/MediaTvItemAdapter.kt
1
13005
package org.videolan.television.ui import android.annotation.TargetApi import android.content.Context import android.graphics.drawable.BitmapDrawable import android.os.Build import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.annotation.RequiresApi import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment import androidx.paging.PagedList import androidx.paging.PagedListAdapter import androidx.recyclerview.widget.DiffUtil import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import org.videolan.libvlc.util.AndroidUtil import org.videolan.medialibrary.Tools import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.medialibrary.media.MediaLibraryItem import org.videolan.resources.UPDATE_PAYLOAD import org.videolan.resources.interfaces.FocusListener import org.videolan.television.databinding.MediaBrowserTvItemBinding import org.videolan.television.databinding.MediaBrowserTvItemListBinding import org.videolan.television.ui.browser.TvAdapterUtils import org.videolan.vlc.gui.helpers.SelectorViewHolder import org.videolan.vlc.gui.helpers.getMediaIconDrawable import org.videolan.vlc.gui.view.FastScroller import org.videolan.vlc.interfaces.IEventsHandler import org.videolan.vlc.util.generateResolutionClass @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi class MediaTvItemAdapter(type: Int, private val eventsHandler: IEventsHandler<MediaLibraryItem>, var itemSize: Int, private var inGrid: Boolean = true) : PagedListAdapter<MediaLibraryItem, MediaTvItemAdapter.AbstractMediaItemViewHolder<ViewDataBinding>>(DIFF_CALLBACK), FastScroller.SeparatedAdapter, TvItemAdapter { override var focusNext = -1 override fun displaySwitch(inGrid: Boolean) { this.inGrid = inGrid } private val defaultCover: BitmapDrawable? private var focusListener: FocusListener? = null init { val ctx: Context? = when (eventsHandler) { is Context -> eventsHandler is Fragment -> (eventsHandler as Fragment).context else -> null } defaultCover = ctx?.let { getMediaIconDrawable(it, type, true) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AbstractMediaItemViewHolder<ViewDataBinding> { val inflater = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater @Suppress("UNCHECKED_CAST") return if (inGrid) MediaItemTVViewHolder(MediaBrowserTvItemBinding.inflate(inflater, parent, false), eventsHandler) as AbstractMediaItemViewHolder<ViewDataBinding> else MediaItemTVListViewHolder(MediaBrowserTvItemListBinding.inflate(inflater, parent, false), eventsHandler) as AbstractMediaItemViewHolder<ViewDataBinding> } override fun getItemViewType(position: Int): Int { return if (inGrid) 0 else 1 } override fun onBindViewHolder(holder: AbstractMediaItemViewHolder<ViewDataBinding>, position: Int) { if (position >= itemCount) return val item = getItem(position) holder.setItem(item) holder.binding.executePendingBindings() if (position == focusNext) { holder.binding.root.requestFocus() focusNext = -1 } } override fun onBindViewHolder(holder: AbstractMediaItemViewHolder<ViewDataBinding>, position: Int, payloads: List<Any>) { if (payloads.isNullOrEmpty()) onBindViewHolder(holder, position) else { val payload = payloads[0] if (payload is MediaLibraryItem) { val isSelected = payload.hasStateFlags(MediaLibraryItem.FLAG_SELECTED) holder.setCoverlay(isSelected) holder.selectView(isSelected) } } } override fun onViewRecycled(holder: AbstractMediaItemViewHolder<ViewDataBinding>) { super.onViewRecycled(holder) holder.recycle() } override fun hasSections() = true override fun isEmpty() = currentList.isNullOrEmpty() override fun submitList(pagedList: Any?) { if (pagedList == null) { this.submitList(null) } if (pagedList is PagedList<*>) { @Suppress("UNCHECKED_CAST") this.submitList(pagedList as PagedList<MediaLibraryItem>) } } override fun setOnFocusChangeListener(focusListener: FocusListener?) { this.focusListener = focusListener } companion object { private const val TAG = "VLC/MediaTvItemAdapter" /** * Awful hack to workaround the [PagedListAdapter] not keeping track of notifyItemMoved operations */ private var preventNextAnim: Boolean = false private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<MediaLibraryItem>() { override fun areItemsTheSame( oldMedia: MediaLibraryItem, newMedia: MediaLibraryItem) = if (preventNextAnim) true else oldMedia === newMedia || oldMedia.itemType == newMedia.itemType && oldMedia.equals(newMedia) override fun areContentsTheSame(oldMedia: MediaLibraryItem, newMedia: MediaLibraryItem) = false override fun getChangePayload(oldItem: MediaLibraryItem, newItem: MediaLibraryItem): Any? { preventNextAnim = false return UPDATE_PAYLOAD } } } @TargetApi(Build.VERSION_CODES.M) abstract class AbstractMediaItemViewHolder<T : ViewDataBinding>(binding: T) : SelectorViewHolder<T>(binding) { fun onClick(v: View) { getItem(layoutPosition)?.let { eventsHandler.onClick(v, layoutPosition, it) } } fun onMoreClick(v: View) { getItem(layoutPosition)?.let { eventsHandler.onCtxClick(v, layoutPosition, it) } } fun onLongClick(view: View): Boolean { return getItem(layoutPosition)?.let { eventsHandler.onLongClick(view, layoutPosition, it) } ?: false } fun onImageClick(v: View) { getItem(layoutPosition)?.let { eventsHandler.onImageClick(v, layoutPosition, it) } } fun onMainActionClick(v: View) { getItem(layoutPosition)?.let { eventsHandler.onMainActionClick(v, layoutPosition, it) } } abstract fun getItem(layoutPosition: Int): MediaLibraryItem? abstract val eventsHandler: IEventsHandler<MediaLibraryItem> abstract fun setItem(item: MediaLibraryItem?) abstract fun recycle() abstract fun setCoverlay(selected: Boolean) } @RequiresApi(Build.VERSION_CODES.M) inner class MediaItemTVViewHolder( binding: MediaBrowserTvItemBinding, override val eventsHandler: IEventsHandler<MediaLibraryItem> ) : AbstractMediaItemViewHolder<MediaBrowserTvItemBinding>(binding) { override fun getItem(layoutPosition: Int) = [email protected](layoutPosition) init { binding.holder = this if (defaultCover != null) binding.cover = defaultCover if (AndroidUtil.isMarshMallowOrLater) itemView.setOnContextClickListener { v -> onMoreClick(v) true } binding.container.layoutParams.width = itemSize binding.container.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus -> TvAdapterUtils.itemFocusChange(hasFocus, itemSize, binding.container, false) { eventsHandler.onItemFocused(binding.root, getItem(layoutPosition)!!) if (focusListener != null) { focusListener!!.onFocusChanged(layoutPosition) } } } if (AndroidUtil.isLolliPopOrLater) binding.container.clipToOutline = true } override fun recycle() { if (defaultCover != null) binding.cover = defaultCover binding.title.text = "" binding.subtitle.text = "" binding.mediaCover.resetFade() } override fun setItem(item: MediaLibraryItem?) { binding.item = item var isSquare = true var progress = 0 var seen = 0L var description = item?.description var resolution = "" if (item is MediaWrapper) { if (item.type == MediaWrapper.TYPE_VIDEO) { resolution = generateResolutionClass(item.width, item.height) ?: "" isSquare = false description = if (item.time == 0L) Tools.millisToString(item.length) else Tools.getProgressText(item) binding.badge = resolution seen = item.seen var max = 0 if (item.length > 0) { val lastTime = item.displayTime if (lastTime > 0) { max = (item.length / 1000).toInt() progress = (lastTime / 1000).toInt() } } binding.max = max } } binding.progress = progress binding.isSquare = isSquare binding.seen = seen binding.description = description binding.scaleType = ImageView.ScaleType.CENTER_INSIDE if (seen == 0L) binding.mlItemSeen.visibility = View.GONE if (progress <= 0L) binding.progressBar.visibility = View.GONE binding.badgeTV.visibility = if (resolution.isBlank()) View.GONE else View.VISIBLE } @ObsoleteCoroutinesApi override fun setCoverlay(selected: Boolean) { } } @TargetApi(Build.VERSION_CODES.M) inner class MediaItemTVListViewHolder( binding: MediaBrowserTvItemListBinding, override val eventsHandler: IEventsHandler<MediaLibraryItem> ) : AbstractMediaItemViewHolder<MediaBrowserTvItemListBinding>(binding) { override fun getItem(layoutPosition: Int) = [email protected](layoutPosition) init { binding.holder = this if (defaultCover != null) binding.cover = defaultCover if (AndroidUtil.isMarshMallowOrLater) itemView.setOnContextClickListener { v -> onMoreClick(v) true } binding.container.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus -> TvAdapterUtils.itemFocusChange(hasFocus, itemSize, binding.container, true) { eventsHandler.onItemFocused(binding.root, getItem(layoutPosition)!!) if (focusListener != null) { focusListener!!.onFocusChanged(layoutPosition) } } } binding.container.clipToOutline = true } override fun recycle() { if (defaultCover != null) binding.cover = defaultCover binding.title.text = "" binding.subtitle.text = "" binding.mediaCover.resetFade() } override fun setItem(item: MediaLibraryItem?) { binding.item = item var isSquare = true var progress = 0 var seen = 0L var description = item?.description var resolution = "" if (item is MediaWrapper) { if (item.type == MediaWrapper.TYPE_VIDEO) { resolution = generateResolutionClass(item.width, item.height) ?: "" isSquare = false description = if (item.time == 0L) Tools.millisToString(item.length) else Tools.getProgressText(item) binding.badge = resolution seen = item.seen var max = 0 if (item.length > 0) { val lastTime = item.displayTime if (lastTime > 0) { max = (item.length / 1000).toInt() progress = (lastTime / 1000).toInt() } } binding.max = max } } binding.progress = progress binding.isSquare = isSquare binding.seen = seen binding.description = description binding.scaleType = ImageView.ScaleType.CENTER_INSIDE if (seen == 0L) binding.mlItemSeen.visibility = View.GONE if (progress <= 0L) binding.progressBar.visibility = View.GONE binding.badgeTV.visibility = if (resolution.isBlank()) View.GONE else View.VISIBLE } @ObsoleteCoroutinesApi override fun setCoverlay(selected: Boolean) {} } }
gpl-2.0
dfd9c0126fe6c3978797a9b7d00d42d5
39.640625
316
0.628143
5.269449
false
false
false
false
light-and-salt/kotloid
src/main/kotlin/kr/or/lightsalt/kotloid/view.kt
1
529
@file:Suppress("UNCHECKED_CAST") package kr.or.lightsalt.kotloid import android.app.Activity import android.view.View fun <T : Activity> View.activity() = context as T var View.isGone: Boolean get() = visibility == View.GONE set(value) { visibility = if (value) View.GONE else View.VISIBLE } var View.isInVisible: Boolean get() = visibility == View.INVISIBLE set(value) { visibility = if (value) View.INVISIBLE else View.VISIBLE } fun <T : View> T.postSelf(block: T.() -> Unit) { this.post { this.block() } }
apache-2.0
326684800f7ad115c8a73c4243e9610b
19.346154
58
0.695652
3.005682
false
false
false
false
kar/challenges
recruitment-r3pi/app/src/main/java/gs/kar/r3pi/Core.kt
1
1342
package gs.kar.r3pi import kotlinx.coroutines.experimental.channels.* import kotlinx.coroutines.experimental.launch /** * Core.kt provides a basic implementation of the Elm architecture reusable in other projects. * * Overview: * - State (S): Contains the explicit state of the app and propagates state changes, * - Message (M): Emitted as a result of user action, * - Update: Handles Messages and provides new State. * * State A -> Update(Message, State A) -> State B * * State is immutable and implementation is using Kotlin coroutines in order to provide concurrency * and take it off the main thread. */ class State<S>(init: S) { internal var container = init set(value) { field = value launch { broadcast.send(value) } } private val broadcast = BroadcastChannel<S>(Channel.CONFLATED) fun subscribe(): ReceiveChannel<S> { return broadcast.openSubscription() } } class Update<M, S>( state: State<S>, update: (M, S) -> S ) { private val channel = Channel<M>(Channel.CONFLATED) init { launch { channel.consumeEach { msg -> state.container = update(msg, state.container) } } } fun send(msg: M) = launch { channel.send(msg) } }
apache-2.0
685c891d4c725daa002642e4a2fae86f
22.964286
99
0.61699
4.167702
false
false
false
false
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/table/query/handlers/PlayerForceCheckedEventHandler.kt
1
2182
package com.flexpoker.table.query.handlers import com.flexpoker.chat.service.ChatService import com.flexpoker.framework.event.EventHandler import com.flexpoker.framework.pushnotifier.PushNotificationPublisher import com.flexpoker.login.repository.LoginRepository import com.flexpoker.pushnotifications.TableUpdatedPushNotification import com.flexpoker.table.command.events.PlayerForceCheckedEvent import com.flexpoker.table.query.repository.TableRepository import org.springframework.stereotype.Component import javax.inject.Inject @Component class PlayerForceCheckedEventHandler @Inject constructor( private val loginRepository: LoginRepository, private val tableRepository: TableRepository, private val pushNotificationPublisher: PushNotificationPublisher, private val chatService: ChatService ) : EventHandler<PlayerForceCheckedEvent> { override fun handle(event: PlayerForceCheckedEvent) { handleUpdatingTable(event) handlePushNotifications(event) handleChat(event) } private fun handleUpdatingTable(event: PlayerForceCheckedEvent) { val tableDTO = tableRepository.fetchById(event.aggregateId) val username = loginRepository.fetchUsernameByAggregateId(event.playerId) val updatedSeats = tableDTO.seats!! .map { if (it.name == username) { it.copy(raiseTo = 0, callAmount = 0, isActionOn = false) } else { it } } val updatedTable = tableDTO.copy(version = event.version, seats = updatedSeats) tableRepository.save(updatedTable) } private fun handlePushNotifications(event: PlayerForceCheckedEvent) { val pushNotification = TableUpdatedPushNotification(event.gameId, event.aggregateId) pushNotificationPublisher.publish(pushNotification) } private fun handleChat(event: PlayerForceCheckedEvent) { val username = loginRepository.fetchUsernameByAggregateId(event.playerId) val message = "Time expired - $username checks" chatService.saveAndPushSystemTableChatMessage(event.gameId, event.aggregateId, message) } }
gpl-2.0
496ec0a0eb55c495f9023f679dc27e54
40.188679
95
0.743813
5.468672
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/test/kotlin/platform/mixin/implements/DuplicateInterfaceInspectionTest.kt
1
3060
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.implements import com.demonwav.mcdev.framework.EdtInterceptor import com.demonwav.mcdev.platform.mixin.BaseMixinTest import com.demonwav.mcdev.platform.mixin.inspection.implements.DuplicateInterfaceInspection import org.intellij.lang.annotations.Language import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(EdtInterceptor::class) @DisplayName("Duplicate Interface Inspection Tests") class DuplicateInterfaceInspectionTest : BaseMixinTest() { @BeforeEach fun setupProject() { buildProject { dir("test") { java( "DummyFace.java", """ package test; interface DummyFace { } """, configure = false ) java( "DummyFace2.java", """ package test; interface DummyFace2 { } """, configure = false ) } } } private fun doTest(@Language("JAVA") mixinCode: String) { buildProject { dir("test") { java("DuplicateInterfaceMixin.java", mixinCode) } } fixture.enableInspections(DuplicateInterfaceInspection::class) fixture.checkHighlighting(true, false, false) } @Test @DisplayName("No Highlight On No Duplicate Interface Test") fun noHighlightOnNoDuplicateInterfaceTest() { doTest( """ package test; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; @Mixin @Implements({ @Interface(iface = DummyFace.class, prefix = "a$"), @Interface(iface = DummyFace2.class, prefix = "b$") }) class DuplicateInterfaceMixin { } """ ) } @Test @DisplayName("Highlight On Duplicate Interface Test") fun highlightOnDuplicateInterfaceTest() { doTest( """ package test; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; @Mixin @Implements({ @Interface(iface = DummyFace.class, prefix = "a$"), <warning descr="Interface is already implemented">@Interface(iface = DummyFace.class, prefix = "b$")</warning> }) class DuplicateInterfaceMixin { } """ ) } }
mit
750e6941646ac5ca181bef2df6aa434a
26.079646
126
0.54902
5.142857
false
true
false
false
ohmae/mmupnp
mmupnp/src/main/java/net/mm2d/upnp/util/NetworkUtils.kt
1
7537
/* * Copyright (c) 2017 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp.util import net.mm2d.upnp.Http import java.net.Inet4Address import java.net.Inet6Address import java.net.InetAddress import java.net.InetSocketAddress import java.net.InterfaceAddress import java.net.NetworkInterface import java.net.SocketException import java.nio.ByteBuffer /** * Provide network related utility methods. * * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ object NetworkUtils { /** * Return interfaces with address that can communicate with the network. */ @JvmStatic fun getAvailableInterfaces(): List<NetworkInterface> = getNetworkInterfaceList().filter { it.isAvailableInterface() } /** * Return interfaces with IPv4 address that can communicate with the network. */ @JvmStatic fun getAvailableInet4Interfaces(): List<NetworkInterface> = getNetworkInterfaceList().filter { it.isAvailableInet4Interface() } /** * Return interfaces with IPv6 address that can communicate with the network. */ @JvmStatic fun getAvailableInet6Interfaces(): List<NetworkInterface> = getNetworkInterfaceList().filter { it.isAvailableInet6Interface() } /** * Return a list of all network interfaces in the system. * * The return value of [java.net.NetworkInterface.getNetworkInterfaces] * is changed to [java.util.List] instead of [java.util.Enumeration]. * If there is no interface or if [java.net.SocketException] occurs, an empty List is returned. * * @return all network interfaces in the system. * @see java.net.NetworkInterface.getNetworkInterfaces */ @JvmStatic fun getNetworkInterfaceList(): List<NetworkInterface> = try { NetworkInterface.getNetworkInterfaces() } catch (ignored: Throwable) { // Some devices have bugs and occasionally cause RuntimeException null }.let { it?.toList() } ?: emptyList() } /** * Returns whether receiver has IPv4/IPv6 address that can communicate with the network. * * @receiver NetworkInterface to inspect * @return true: receiver has IPv4/IPv6 address that can communicate with the network. false: otherwise */ fun NetworkInterface.isAvailableInterface(): Boolean = isConnectedToNetwork() && (hasInet4Address() || hasInet6Address()) /** * Returns whether receiver has IPv4 address that can communicate with the network. * * @receiver NetworkInterface to inspect * @return true: receiver has IPv4 address that can communicate with the network. false: otherwise */ fun NetworkInterface.isAvailableInet4Interface(): Boolean = isConnectedToNetwork() && hasInet4Address() /** * Returns whether receiver has IPv6 address that can communicate with the network. * * @receiver NetworkInterface to inspect * @return true: receiver has IPv6 address that can communicate with the network. false: otherwise */ fun NetworkInterface.isAvailableInet6Interface(): Boolean = isConnectedToNetwork() && hasInet6Address() /** * Returns whether receiver has address that can communicate with the network. * * @receiver NetworkInterface to inspect * @return true: receiver has address that can communicate with the network. false: otherwise */ private fun NetworkInterface.isConnectedToNetwork(): Boolean = try { !isLoopback && isUp && supportsMulticast() } catch (ignored: SocketException) { false } /** * Returns whether receiver has IPv4 address. * * @receiver NetworkInterface to inspect * @return true: receiver has IPv4 address, false: otherwise */ private fun NetworkInterface.hasInet4Address(): Boolean = interfaceAddresses.any { it.address.isAvailableInet4Address() } /** * Determine if receiver is available Inet4addresses. * * @receiver InetAddress * @return true: receiver is available Inet4Address, false: otherwise */ internal fun InetAddress.isAvailableInet4Address() = this is Inet4Address /** * Returns whether receiver has IPv6 address. * * @receiver NetworkInterface to inspect * @return true: receiver has IPv6 address false: otherwise */ private fun NetworkInterface.hasInet6Address(): Boolean = interfaceAddresses.any { it.address.isAvailableInet6Address() } /** * Determine if receiver is available Inet6addresses. * * @receiver InetAddress * @return true: receiver is available Inet6Address, false: otherwise */ internal fun InetAddress.isAvailableInet6Address() = this is Inet6Address && this.isLinkLocalAddress /** * Extract IPv4 address from assigned to the interface. * * @receiver NetworkInterface * @return InterfaceAddress * @throws IllegalArgumentException receiver does not have IPv4 address */ // VisibleForTesting internal fun NetworkInterface.findInet4Address(): InterfaceAddress = interfaceAddresses.find { it.address.isAvailableInet4Address() } ?: throw IllegalArgumentException("$this does not have IPv4 address.") /** * Extract IPv6 address from assigned to the interface * * @receiver NetworkInterface * @return InterfaceAddress * @throws IllegalArgumentException receiver does not have IPv6 address */ // VisibleForTesting internal fun NetworkInterface.findInet6Address(): InterfaceAddress = interfaceAddresses.find { it.address.isAvailableInet6Address() } ?: throw IllegalArgumentException("$this does not have IPv6 address.") /** * Returns a combined string of address and port number. * * @receiver Address to convert * @return a combined string of address and port number */ @Throws(IllegalStateException::class) fun InetSocketAddress.toAddressString(): String = address.toAddressString(port) /** * Returns a combined string of address and port number. * * @receiver Address to convert * @param port port number * @return a combined string of address and port number */ @Throws(IllegalStateException::class) fun InetAddress.toAddressString(port: Int): String = toAddressString().let { if (port == Http.DEFAULT_PORT || port <= 0) it else "$it:$port" } private fun InetAddress.toAddressString(): String = if (this is Inet6Address) "[${toNormalizedString()}]" else hostAddress internal fun InetAddress.toSimpleString(): String = if (this is Inet6Address) toNormalizedString() else hostAddress // VisibleForTesting internal fun Inet6Address.toNormalizedString(): String { val buffer = ByteBuffer.wrap(address).asShortBuffer() val section = IntArray(8) { buffer.get().toInt() and 0xffff } val (start, end) = section.findSectionToOmission() return buildString { for (i in section.indices) { if (i < start || i >= end) { if (i != 0 && i != end) append(':') append(section[i].toString(16)) } else if (i == start) { append("::") } } } } private class Range( var start: Int = -1, var length: Int = 0 ) private fun IntArray.findSectionToOmission(): Pair<Int, Int> { var work = Range() var best = Range() for (i in indices) { if (this[i] == 0) { if (work.start < 0) work.start = i work.length++ } else if (work.start >= 0) { if (work.length > best.length) best = work work = Range() } } if (work.length > best.length) best = work return if (best.length < 2) -1 to -1 else best.start to best.start + best.length }
mit
a5971c2f35ce024952507c30364c1841
31.986842
103
0.707486
4.370134
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/view/filter/SwizzleColorFilter.kt
1
1687
package com.soywiz.korge.view.filter import com.soywiz.korag.shader.* import com.soywiz.korge.debug.* import com.soywiz.korge.render.* import com.soywiz.korge.view.* import com.soywiz.korim.color.* import com.soywiz.korma.geom.* import com.soywiz.korui.* /** * Allows to swizzle (interchange) color components via the [swizzle] property. * * - swizzle="rgba" would be the identity * - swizzle="bgra" would interchange red and blue channels * - swizzle="rrra" would show as greyscale the red component */ class SwizzleColorsFilter(initialSwizzle: String = "rgba") : Filter { private var proxy: ProxySwizzle = ProxySwizzle(initialSwizzle) class ProxySwizzle(val swizzle: String = "rgba") : ShaderFilter() { override val fragment: FragmentShader = Filter.DEFAULT_FRAGMENT.appending { out setTo out[swizzle] } } /** * The swizzling string * * - swizzle="rgba" would be the identity * - swizzle="bgra" would interchange red and blue channels * - swizzle="rrra" would show as greyscale the red component * */ var swizzle: String = initialSwizzle set(value) { field = value proxy = ProxySwizzle(value) } override fun render( ctx: RenderContext, matrix: Matrix, texture: Texture, texWidth: Int, texHeight: Int, renderColorAdd: ColorAdd, renderColorMul: RGBA, blendMode: BlendMode ) = proxy.render(ctx, matrix, texture, texWidth, texHeight, renderColorAdd, renderColorMul, blendMode) override fun buildDebugComponent(views: Views, container: UiContainer) { container.uiEditableValue(::swizzle) } }
apache-2.0
fa40633835433454654e575f4e60a1ff
31.442308
108
0.675756
4.114634
false
false
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/repository/git/prop/GitAttributesFactory.kt
1
6029
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.repository.git.prop import org.eclipse.jgit.attributes.Attribute import org.eclipse.jgit.attributes.Attributes import org.eclipse.jgit.attributes.AttributesNode import org.eclipse.jgit.attributes.AttributesRule import org.eclipse.jgit.errors.InvalidPatternException import org.slf4j.Logger import org.tmatesoft.svn.core.SVNProperty import org.tmatesoft.svn.core.internal.wc.SVNFileUtil import svnserver.Loggers import svnserver.repository.git.RepositoryFormat import svnserver.repository.git.path.Wildcard import java.io.IOException import java.io.InputStream import java.util.regex.PatternSyntaxException /** * Factory for properties, generated by .gitattributes. * * @author Artem V. Navrotskiy <[email protected]> */ class GitAttributesFactory : GitPropertyFactory { override val fileName: String get() { return ".gitattributes" } @Throws(IOException::class) override fun create(stream: InputStream, format: RepositoryFormat): Array<GitProperty> { val r = AttributesNode() r.parse(stream) val properties = ArrayList<GitProperty>() for (rule: AttributesRule in r.rules) { val wildcard: Wildcard try { wildcard = Wildcard(rule.pattern) } catch (e: InvalidPatternException) { log.warn("Found invalid git pattern: {}", rule.pattern) continue } catch (e: PatternSyntaxException) { log.warn("Found invalid git pattern: {}", rule.pattern) continue } val attrs = Attributes(*rule.attributes.map(::expandMacro).toTypedArray()) val eolType: EolType = if (format < RepositoryFormat.V5_REMOVE_IMPLICIT_NATIVE_EOL) getEolTypeV4(attrs) else getEolTypeV5(attrs) processProperty(properties, wildcard, SVNProperty.MIME_TYPE, eolType.mimeType) processProperty(properties, wildcard, SVNProperty.EOL_STYLE, eolType.eolStyle) processProperty(properties, wildcard, SVNProperty.NEEDS_LOCK, getNeedsLock(attrs)) val filter: String? = getFilter(attrs) if (filter != null) properties.add(GitFilterProperty(wildcard.matcher, filter)) } return properties.toTypedArray() } enum class EolType(val mimeType: String?, val eolStyle: String?) { Autodetect(null, null), Binary(SVNFileUtil.BINARY_MIME_TYPE, ""), Native("", SVNProperty.EOL_STYLE_NATIVE), LF("", SVNProperty.EOL_STYLE_LF), CRLF("", SVNProperty.EOL_STYLE_CRLF); } private fun getNeedsLock(attrs: Attributes): String? { if (attrs.isSet("lockable")) return "*" return null } companion object { /** * TODO: more fully-functional macro expansion * @see org.eclipse.jgit.attributes.AttributesHandler.expandMacro * @see org.eclipse.jgit.attributes.AttributesHandler.BINARY_RULE_ATTRIBUTES */ fun expandMacro(attr: Attribute): Attribute { return if (attr.key == "binary" && attr.state == Attribute.State.SET) { Attribute("text", Attribute.State.UNSET) } else { attr } } private val log: Logger = Loggers.git /** * @see org.eclipse.jgit.util.io.EolStreamTypeUtil.checkInStreamType * @see org.eclipse.jgit.util.io.EolStreamTypeUtil.checkOutStreamType */ fun getEolTypeV5(attrs: Attributes): EolType { // "binary" or "-text" (which is included in the binary expansion) if (attrs.isUnset("text")) return EolType.Binary // old git system if (attrs.isSet("crlf")) { return EolType.Native } else if (attrs.isUnset("crlf")) { return EolType.Binary } else if ("input" == attrs.getValue("crlf")) { return EolType.LF } // new git system if ("auto" == attrs.getValue("text")) { return EolType.Autodetect; } when (attrs.getValue("eol")) { "lf" -> return EolType.LF "crlf" -> return EolType.CRLF } if (attrs.isSet("text")) { return EolType.Native } return EolType.Autodetect } fun getEolTypeV4(attrs: Attributes): EolType { if (attrs.isUnset("text")) return EolType.Binary val eol: String? = attrs.getValue("eol") if (eol != null) { when (eol) { "lf" -> return EolType.LF "crlf" -> return EolType.CRLF } } if (attrs.isUnspecified("text")) return EolType.Autodetect return EolType.Native } private fun processProperty(properties: MutableList<GitProperty>, wildcard: Wildcard, property: String, value: String?) { if (value == null) { return } if (value.isNotEmpty()) { if (wildcard.isSvnCompatible) { properties.add(GitAutoProperty(wildcard.matcher, property, value)) } properties.add(GitFileProperty(wildcard.matcher, property, value)) } else { properties.add(GitFileProperty(wildcard.matcher, property, null)) } } private fun getFilter(attrs: Attributes): String? { return attrs.getValue("filter") } } }
gpl-2.0
4e4e0a30ae8cce2b3e3d882f01868ed1
35.539394
140
0.599104
4.616386
false
false
false
false
apixandru/intellij-community
platform/script-debugger/debugger-ui/src/RemoteVmConnection.kt
2
5608
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger.connection import com.intellij.execution.process.ProcessHandler import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.Condition import com.intellij.ui.ColoredListCellRenderer import com.intellij.ui.components.JBList import com.intellij.util.io.connectRetrying import com.intellij.util.io.socketConnection.ConnectionStatus import io.netty.bootstrap.Bootstrap import org.jetbrains.concurrency.* import org.jetbrains.debugger.Vm import org.jetbrains.io.NettyUtil import org.jetbrains.rpc.LOG import java.net.ConnectException import java.net.InetSocketAddress import java.util.concurrent.atomic.AtomicReference import java.util.function.Consumer import javax.swing.JList abstract class RemoteVmConnection : VmConnection<Vm>() { var address: InetSocketAddress? = null private val connectCancelHandler = AtomicReference<() -> Unit>() abstract fun createBootstrap(address: InetSocketAddress, vmResult: AsyncPromise<Vm>): Bootstrap @JvmOverloads fun open(address: InetSocketAddress, stopCondition: Condition<Void>? = null): Promise<Vm> { if (address.isUnresolved) { val error = "Host ${address.hostString} is unresolved" setState(ConnectionStatus.CONNECTION_FAILED, error) return rejectedPromise(error) } this.address = address setState(ConnectionStatus.WAITING_FOR_CONNECTION, "Connecting to ${address.hostString}:${address.port}") val result = AsyncPromise<Vm>() result .done { vm = it setState(ConnectionStatus.CONNECTED, "Connected to ${connectedAddressToPresentation(address, it)}") startProcessing() } .rejected { if (it !is ConnectException) { LOG.errorIfNotMessage(it) } setState(ConnectionStatus.CONNECTION_FAILED, it.message) } .processed { connectCancelHandler.set(null) } val future = ApplicationManager.getApplication().executeOnPooledThread { if (Thread.interrupted()) { return@executeOnPooledThread } connectCancelHandler.set { result.setError("Closed explicitly") } doOpen(result, address, stopCondition) } connectCancelHandler.set { try { future.cancel(true) } finally { result.setError("Cancelled") } } return result } protected open fun doOpen(result: AsyncPromise<Vm>, address: InetSocketAddress, stopCondition: Condition<Void>?) { val maxAttemptCount = if (stopCondition == null) NettyUtil.DEFAULT_CONNECT_ATTEMPT_COUNT else -1 val connectResult = createBootstrap(address, result).connectRetrying(address, maxAttemptCount, stopCondition) connectResult.handleError(Consumer { result.setError(it) }) connectResult.handleThrowable(Consumer { result.setError(it) }) val channel = connectResult.channel channel?.closeFuture()?.addListener { if (result.isFulfilled) { close("Process disconnected unexpectedly", ConnectionStatus.DISCONNECTED) } } if (channel != null) { stateChanged { if (it.status == ConnectionStatus.DISCONNECTED) { channel.close() } } } } protected open fun connectedAddressToPresentation(address: InetSocketAddress, vm: Vm): String = "${address.hostName}:${address.port}" override fun detachAndClose(): Promise<*> { try { connectCancelHandler.getAndSet(null)?.invoke() } finally { return super.detachAndClose() } } } fun RemoteVmConnection.open(address: InetSocketAddress, processHandler: ProcessHandler) = open(address, Condition<java.lang.Void> { processHandler.isProcessTerminating || processHandler.isProcessTerminated }) fun <T> chooseDebuggee(targets: Collection<T>, selectedIndex: Int, renderer: (T, ColoredListCellRenderer<*>) -> Unit): Promise<T> { if (targets.size == 1) { return resolvedPromise(targets.first()) } else if (targets.isEmpty()) { return rejectedPromise("No tabs to inspect") } val result = org.jetbrains.concurrency.AsyncPromise<T>() ApplicationManager.getApplication().invokeLater { val list = JBList(targets) list.cellRenderer = object : ColoredListCellRenderer<T>() { override fun customizeCellRenderer(list: JList<out T>, value: T, index: Int, selected: Boolean, hasFocus: Boolean) { renderer(value, this) } } if (selectedIndex != -1) { list.selectedIndex = selectedIndex } JBPopupFactory.getInstance() .createListPopupBuilder(list) .setTitle("Choose Page to Debug") .setCancelOnWindowDeactivation(false) .setItemChoosenCallback { @Suppress("UNCHECKED_CAST") val value = list.selectedValue if (value == null) { result.setError("No target to inspect") } else { result.setResult(value) } } .createPopup() .showInFocusCenter() } return result }
apache-2.0
008b163e821614f47c6c5126cc9cd676
33.20122
208
0.705956
4.608053
false
false
false
false
jitsi/jicofo
jicofo-selector/src/main/kotlin/org/jitsi/jicofo/bridge/colibri/Extensions.kt
1
5672
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2021 - present 8x8, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jicofo.bridge.colibri import org.jitsi.jicofo.TaskPools import org.jitsi.jicofo.conference.source.ConferenceSourceMap import org.jitsi.jicofo.conference.source.EndpointSourceSet import org.jitsi.jicofo.conference.source.Source import org.jitsi.jicofo.conference.source.SsrcGroup import org.jitsi.xmpp.extensions.colibri2.Capability import org.jitsi.xmpp.extensions.colibri2.Colibri2Endpoint import org.jitsi.xmpp.extensions.colibri2.ConferenceModifiedIQ import org.jitsi.xmpp.extensions.colibri2.MediaSource import org.jitsi.xmpp.extensions.colibri2.Sources import org.jitsi.xmpp.extensions.colibri2.Transport import org.jitsi.xmpp.extensions.jingle.IceUdpTransportPacketExtension import org.jivesoftware.smack.AbstractXMPPConnection import org.jivesoftware.smack.packet.IQ /** Read the [IceUdpTransportPacketExtension] for an endpoint with ID [endpointId] (or null if missing). */ fun ConferenceModifiedIQ.parseTransport(endpointId: String): Transport? { return endpoints.find { it.id == endpointId }?.transport } /** * Reads the feedback sources (at the "conference" level) and parses them into a [ConferenceSourceMap]. * Uses the special [SSRC_OWNER_JVB] JID as the "owner" and appends the msid, since this is how jitsi-meet clients * expect the bridge's sources to be signaled. */ fun ConferenceModifiedIQ.parseSources(): ConferenceSourceMap { val parsedSources = ConferenceSourceMap() sources?.mediaSources?.forEach { mediaSource -> mediaSource.sources.forEach { sourcePacketExtension -> val msid = "mixedmslabel mixedlabel${mediaSource.type}0" val source = Source(sourcePacketExtension.ssrc, mediaSource.type, sourcePacketExtension.name, msid) parsedSources.add(SSRC_OWNER_JVB, EndpointSourceSet(source)) } mediaSource.ssrcGroups.forEach { parsedSources.add(SSRC_OWNER_JVB, EndpointSourceSet(SsrcGroup.fromPacketExtension(it, mediaSource.type))) } } return parsedSources } fun EndpointSourceSet.toColibriMediaSources(endpointId: String): Sources { val mediaSources: MutableMap<String, MediaSource.Builder> = mutableMapOf() // We use the signaled "name" of the source at the colibri2 source ID. If a source name isn't signaled, we use a // default ID of "endpointId-v0". This allows backwards compat with clients that don't signal source names // (and only support a single source). sources.forEach { source -> val sourceId = source.name ?: Source.nameForIdAndMediaType(endpointId, source.mediaType, 0) val mediaSource = mediaSources.computeIfAbsent(sourceId) { MediaSource.getBuilder() .setType(source.mediaType) .setId(sourceId) } mediaSource.addSource(source.toPacketExtension(encodeMsid = false)) } ssrcGroups.forEach group@{ ssrcGroup -> if (ssrcGroup.ssrcs.isEmpty()) return@group val firstSource = sources.firstOrNull { ssrcGroup.ssrcs.contains(it.ssrc) } ?: throw IllegalStateException("An SsrcGroup in an EndpointSourceSet has an SSRC without a Source") val sourceId = firstSource.name ?: Source.nameForIdAndMediaType(endpointId, ssrcGroup.mediaType, 0) val mediaSource = mediaSources.computeIfAbsent(sourceId) { MediaSource.getBuilder() .setType(ssrcGroup.mediaType) .setId(sourceId) } mediaSource.addSsrcGroup(ssrcGroup.toPacketExtension()) } val sources = Sources.getBuilder() mediaSources.values.forEach { sources.addMediaSource(it.build()) } return sources.build() } /** Create a [Colibri2Endpoint] for a specific [ParticipantInfo]. */ internal fun ParticipantInfo.toEndpoint( /** Whether the request should have the "create" flag set. */ create: Boolean, /** Whether the request should have the "expire" flag set. */ expire: Boolean ): Colibri2Endpoint.Builder = Colibri2Endpoint.getBuilder().apply { setId(id) if (create) { setCreate(true) setStatsId(statsId) if (supportsSourceNames) { addCapability(Capability.CAP_SOURCE_NAME_SUPPORT) } if (useSsrcRewriting) { addCapability(Capability.CAP_SSRC_REWRITING_SUPPORT) } } // TODO: find a way to signal sources only when they change? Or is this already the case implicitly? if (!expire) { setSources(sources.toColibriMediaSources(id)) } if (expire) { setExpire(true) } } internal fun AbstractXMPPConnection.sendIqAndHandleResponseAsync(iq: IQ, block: (IQ?) -> Unit) { val stanzaCollector = createStanzaCollectorAndSend(iq) TaskPools.ioPool.submit { try { block(stanzaCollector.nextResult()) } finally { stanzaCollector.cancel() } } } /** * The constant value used as owner attribute value of * {@link SSRCInfoPacketExtension} for the SSRC which belongs to the JVB. */ const val SSRC_OWNER_JVB = "jvb"
apache-2.0
932085b46ae7cadee690bf145c1ab0f9
40.101449
117
0.715444
4.277526
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/dialog/wheel/AbstractWheelAdapter.kt
1
1444
package com.tamsiree.rxui.view.dialog.wheel import android.database.DataSetObserver import android.view.View import android.view.ViewGroup import java.util.* /** * @author tamsiree * @date 2018/6/11 11:36:40 整合修改 * Abstract Wheel adapter. */ abstract class AbstractWheelAdapter : WheelViewAdapter { // Observers private var datasetObservers: MutableList<DataSetObserver?>? = null override fun getEmptyItem(convertView: View?, parent: ViewGroup?): View? { return null } override fun registerDataSetObserver(observer: DataSetObserver?) { if (datasetObservers == null) { datasetObservers = LinkedList() } datasetObservers?.add(observer) } override fun unregisterDataSetObserver(observer: DataSetObserver?) { if (datasetObservers != null) { datasetObservers?.remove(observer) } } /** * Notifies observers about data changing */ protected fun notifyDataChangedEvent() { if (datasetObservers != null) { for (observer in datasetObservers!!) { observer?.onChanged() } } } /** * Notifies observers about invalidating data */ protected fun notifyDataInvalidatedEvent() { if (datasetObservers != null) { for (observer in datasetObservers!!) { observer?.onInvalidated() } } } }
apache-2.0
2b60c3ad5e454cbb72b097c9373aac3e
25.127273
78
0.624652
4.867797
false
false
false
false
slartus/4pdaClient-plus
app/src/main/java/org/softeg/slartus/forpdaplus/listfragments/TopicAttachmentListFragment.kt
1
2158
package org.softeg.slartus.forpdaplus.listfragments import android.os.Bundle import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import org.softeg.slartus.forpdaplus.App import org.softeg.slartus.forpdaplus.MainActivity import org.softeg.slartus.forpdaplus.R import org.softeg.slartus.forpdaplus.fragments.BaseBrickContainerFragment import org.softeg.slartus.forpdaplus.listtemplates.TopicAttachmentBrickInfo import org.softeg.slartus.forpdaplus.topic.impl.screens.attachments.TopicAttachmentsFragment class TopicAttachmentListFragment : BaseBrickContainerFragment() { private var topicId: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) topicId = savedInstanceState?.getString(TopicAttachmentsFragment.ARG_TOPIC_ID) ?: arguments?.getString(TopicAttachmentsFragment.ARG_TOPIC_ID) ?: topicId setBrickInfo(TopicAttachmentBrickInfo()) } override fun onResume() { super.onResume() setArrow() } override fun getListName(): String { return "TopicAttachmentListFragment_$topicId" } override fun getFragmentInstance(): Fragment { val args = arguments return TopicAttachmentsFragment().apply { this.arguments = args } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(TopicAttachmentsFragment.ARG_TOPIC_ID, topicId) } companion object { @JvmStatic fun showActivity(topicId: String) { val bundle = bundleOf( TopicAttachmentsFragment.ARG_TOPIC_ID to topicId ) val fragment = newInstance(bundle) MainActivity.addTab( App.getContext().getString(R.string.attachments), fragment.listName, newInstance(bundle) ) } @JvmStatic fun newInstance(args: Bundle?): TopicAttachmentListFragment = TopicAttachmentListFragment().apply { arguments = args } } }
apache-2.0
9eff9dafb9fd08220486b2cc67a0b5e8
32.215385
92
0.678869
5.113744
false
false
false
false
AndroidX/androidx
activity/activity-ktx/src/main/java/androidx/activity/PipHintTracker.kt
3
4497
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.activity import android.app.Activity import android.app.PictureInPictureParams import android.graphics.Rect import android.os.Build import android.view.View import android.view.ViewTreeObserver import androidx.annotation.RequiresApi import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow /** * Sets the [View] that will be used as reference to set the * [PictureInPictureParams.Builder.setSourceRectHint]. * * Anytime the view position changes, [Activity.setPictureInPictureParams] will be called with * the updated view's position in window coordinates as the * [PictureInPictureParams.Builder.setSourceRectHint]. * * @param view the view to use as the reference for the source rect hint */ @ExperimentalCoroutinesApi @RequiresApi(Build.VERSION_CODES.O) public suspend fun Activity.trackPipAnimationHintView(view: View) { // Returns a rect of the window coordinates of a view. fun View.positionInWindow(): Rect { val position = Rect() getGlobalVisibleRect(position) return position } // Create a cold flow that will emit the most updated position of the view in the form of a // rect as long as the view is attached to the window. @Suppress("DEPRECATION") val flow = callbackFlow<Rect> { // Emit a new hint rect any time the view moves. val layoutChangeListener = View.OnLayoutChangeListener { v, l, t, r, b, oldLeft, oldTop, oldRight, oldBottom -> if (l != oldLeft || r != oldRight || t != oldTop || b != oldBottom) { trySend(v.positionInWindow()) } } val scrollChangeListener = ViewTreeObserver.OnScrollChangedListener { trySend(view.positionInWindow()) } // When the view is attached, emit the current position and start listening for layout // changes to track movement. val attachStateChangeListener = object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) { trySend(view.positionInWindow()) view.viewTreeObserver.addOnScrollChangedListener(scrollChangeListener) view.addOnLayoutChangeListener(layoutChangeListener) } override fun onViewDetachedFromWindow(v: View) { v.viewTreeObserver.removeOnScrollChangedListener(scrollChangeListener) v.removeOnLayoutChangeListener(layoutChangeListener) } } // Check if the view is already attached to the window, if it is then emit the current // position and start listening for layout changes to track movement. if (Api19Impl.isAttachedToWindow(view)) { trySend(view.positionInWindow()) view.viewTreeObserver.addOnScrollChangedListener(scrollChangeListener) view.addOnLayoutChangeListener(layoutChangeListener) } view.addOnAttachStateChangeListener(attachStateChangeListener) awaitClose { view.viewTreeObserver.removeOnScrollChangedListener(scrollChangeListener) view.removeOnLayoutChangeListener(layoutChangeListener) view.removeOnAttachStateChangeListener(attachStateChangeListener) } } flow.collect { hint -> Api26Impl.setPipParamsSourceRectHint(this, hint) } } @RequiresApi(Build.VERSION_CODES.KITKAT) internal object Api19Impl { fun isAttachedToWindow(view: View): Boolean = view.isAttachedToWindow } @RequiresApi(Build.VERSION_CODES.O) internal object Api26Impl { fun setPipParamsSourceRectHint(activity: Activity, hint: Rect) { activity.setPictureInPictureParams( PictureInPictureParams.Builder() .setSourceRectHint(hint) .build() ) } }
apache-2.0
d71dc0d7dde62c297a2bac69ee41acd2
39.151786
96
0.70736
4.991121
false
false
false
false
exponent/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/gesturehandler/RotationGestureDetector.kt
2
4006
package versioned.host.exp.exponent.modules.api.components.gesturehandler import android.view.MotionEvent import kotlin.math.atan2 class RotationGestureDetector(private val gestureListener: OnRotationGestureListener?) { interface OnRotationGestureListener { fun onRotation(detector: RotationGestureDetector): Boolean fun onRotationBegin(detector: RotationGestureDetector): Boolean fun onRotationEnd(detector: RotationGestureDetector) } private var currentTime = 0L private var previousTime = 0L private var previousAngle = 0.0 /** * Returns rotation in radians since the previous rotation event. * * @return current rotation step in radians. */ var rotation = 0.0 private set /** * Returns X coordinate of the rotation anchor point relative to the view that the provided motion * event coordinates (usually relative to the view event was sent to). * * @return X coordinate of the rotation anchor point */ var anchorX = 0f private set /** * Returns Y coordinate of the rotation anchor point relative to the view that the provided motion * event coordinates (usually relative to the view event was sent to). * * @return Y coordinate of the rotation anchor point */ var anchorY = 0f private set /** * Return the time difference in milliseconds between the previous * accepted rotation event and the current rotation event. * * @return Time difference since the last rotation event in milliseconds. */ val timeDelta: Long get() = currentTime - previousTime private var isInProgress = false private val pointerIds = IntArray(2) private fun updateCurrent(event: MotionEvent) { previousTime = currentTime currentTime = event.eventTime val firstPointerIndex = event.findPointerIndex(pointerIds[0]) val secondPointerIndex = event.findPointerIndex(pointerIds[1]) val firstPtX = event.getX(firstPointerIndex) val firstPtY = event.getY(firstPointerIndex) val secondPtX = event.getX(secondPointerIndex) val secondPtY = event.getY(secondPointerIndex) val vectorX = secondPtX - firstPtX val vectorY = secondPtY - firstPtY anchorX = (firstPtX + secondPtX) * 0.5f anchorY = (firstPtY + secondPtY) * 0.5f // Angle diff should be positive when rotating in clockwise direction val angle = -atan2(vectorY.toDouble(), vectorX.toDouble()) rotation = if (previousAngle.isNaN()) { 0.0 } else previousAngle - angle previousAngle = angle if (rotation > Math.PI) { rotation -= Math.PI } else if (rotation < -Math.PI) { rotation += Math.PI } if (rotation > Math.PI / 2.0) { rotation -= Math.PI } else if (rotation < -Math.PI / 2.0) { rotation += Math.PI } } private fun finish() { if (isInProgress) { isInProgress = false gestureListener?.onRotationEnd(this) } } fun onTouchEvent(event: MotionEvent): Boolean { when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { isInProgress = false pointerIds[0] = event.getPointerId(event.actionIndex) pointerIds[1] = MotionEvent.INVALID_POINTER_ID } MotionEvent.ACTION_POINTER_DOWN -> if (!isInProgress) { pointerIds[1] = event.getPointerId(event.actionIndex) isInProgress = true previousTime = event.eventTime previousAngle = Double.NaN updateCurrent(event) gestureListener?.onRotationBegin(this) } MotionEvent.ACTION_MOVE -> if (isInProgress) { updateCurrent(event) gestureListener?.onRotation(this) } MotionEvent.ACTION_POINTER_UP -> if (isInProgress) { val pointerId = event.getPointerId(event.actionIndex) if (pointerId == pointerIds[0] || pointerId == pointerIds[1]) { // One of the key pointer has been lifted up, we have to end the gesture finish() } } MotionEvent.ACTION_UP -> finish() } return true } }
bsd-3-clause
f70c0c2685b65b876a1284c9cb9c4e3a
31.048
100
0.682227
4.378142
false
false
false
false
colesadam/hill-lists
app/src/main/java/uk/colessoft/android/hilllist/domain/entity/TypeLink.kt
1
713
package uk.colessoft.android.hilllist.domain.entity import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.PrimaryKey @Entity(tableName = "typeslink", foreignKeys = arrayOf(ForeignKey(entity = Hill::class, parentColumns = arrayOf("h_id"), childColumns = arrayOf("hill_id"), onDelete = ForeignKey.CASCADE), ForeignKey(entity = HillType::class, parentColumns = arrayOf("ht_id"), childColumns = arrayOf("type_Id")) )) data class TypeLink( @PrimaryKey(autoGenerate = true) val tl_id: Long, val hill_id: Long, val type_Id: Long )
mit
10cdef4073b41ed4f7378c8395447cd0
31.454545
62
0.593268
4.541401
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/lang/core/dfa/RsControlFlowGraphTest.kt
2
59210
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.dfa import org.intellij.lang.annotations.Language import org.rust.* import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.ext.block import org.rust.lang.core.psi.ext.descendantsOfType import org.rust.lang.core.types.regions.getRegionScopeTree // The graphs can be rendered right inside the IDE using the DOT Language plugin // https://plugins.jetbrains.com/plugin/10312-dot-language class RsControlFlowGraphTest : RsTestBase() { fun `test empty block`() = testCFG(""" fn main() {} """, """ digraph { "0: Entry" -> "3: BLOCK"; "3: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test straightforward`() = testCFG(""" fn main() { let x = (1 + 2) as i32; let x = (; let arr = [0, 5 * 7 + x]; let mut y = -arr[x + 10]; { y = 10; y += x; }; f(x, y); y += x; } """, """ digraph { "0: Entry" -> "3: 1"; "3: 1" -> "4: 2"; "4: 2" -> "5: 1 + 2"; "5: 1 + 2" -> "6: (1 + 2)"; "6: (1 + 2)" -> "7: (1 + 2) as i32"; "7: (1 + 2) as i32" -> "8: x"; "8: x" -> "9: x"; "9: x" -> "10: let x = (1 + 2) as i32;"; "10: let x = (1 + 2) as i32;" -> "11: ("; "11: (" -> "12: x"; "12: x" -> "13: x"; "13: x" -> "14: let x = (;"; "14: let x = (;" -> "15: 0"; "15: 0" -> "16: 5"; "16: 5" -> "17: 7"; "17: 7" -> "18: 5 * 7"; "18: 5 * 7" -> "19: x"; "19: x" -> "20: 5 * 7 + x"; "20: 5 * 7 + x" -> "21: [0, 5 * 7 + x]"; "21: [0, 5 * 7 + x]" -> "22: arr"; "22: arr" -> "23: arr"; "23: arr" -> "24: let arr = [0, 5 * 7 + x];"; "24: let arr = [0, 5 * 7 + x];" -> "25: arr"; "25: arr" -> "26: x"; "26: x" -> "27: 10"; "27: 10" -> "28: x + 10"; "28: x + 10" -> "29: arr[x + 10]"; "29: arr[x + 10]" -> "30: -arr[x + 10]"; "30: -arr[x + 10]" -> "31: mut y"; "31: mut y" -> "32: mut y"; "32: mut y" -> "33: let mut y = -arr[x + 10];"; "33: let mut y = -arr[x + 10];" -> "35: y"; "35: y" -> "36: 10"; "36: 10" -> "37: y = 10"; "37: y = 10" -> "38: y = 10;"; "38: y = 10;" -> "39: y"; "39: y" -> "40: x"; "40: x" -> "41: y += x"; "41: y += x" -> "42: y += x;"; "42: y += x;" -> "43: BLOCK"; "43: BLOCK" -> "34: BLOCK"; "34: BLOCK" -> "44: BLOCK;"; "44: BLOCK;" -> "45: f"; "45: f" -> "46: x"; "46: x" -> "47: y"; "47: y" -> "48: f(x, y)"; "48: f(x, y)" -> "49: f(x, y);"; "49: f(x, y);" -> "50: y"; "50: y" -> "51: x"; "51: x" -> "52: y += x"; "52: y += x" -> "53: y += x;"; "53: y += x;" -> "54: BLOCK"; "54: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test if`() = testCFG(""" fn foo() { if true { 1 }; } """, """ digraph { "0: Entry" -> "3: true"; "3: true" -> "4: 1"; "4: 1" -> "5: BLOCK"; "3: true" -> "6: IF"; "5: BLOCK" -> "6: IF"; "6: IF" -> "7: IF;"; "7: IF;" -> "8: BLOCK"; "8: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test if else`() = testCFG(""" fn foo() { if true { 1 } else if false { 2 } else { 3 }; } """, """ digraph { "0: Entry" -> "3: true"; "3: true" -> "4: 1"; "4: 1" -> "5: BLOCK"; "3: true" -> "6: false"; "6: false" -> "7: 2"; "7: 2" -> "8: BLOCK"; "6: false" -> "9: 3"; "9: 3" -> "10: BLOCK"; "8: BLOCK" -> "11: IF"; "10: BLOCK" -> "11: IF"; "5: BLOCK" -> "12: IF"; "11: IF" -> "12: IF"; "12: IF" -> "13: IF;"; "13: IF;" -> "14: BLOCK"; "14: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test if let`() = testCFG(""" fn foo() { if let Some(s) = x { 1 }; } """, """ digraph { "0: Entry" -> "3: x"; "3: x" -> "5: s"; "5: s" -> "6: s"; "6: s" -> "7: Some(s)"; "7: Some(s)" -> "4: Dummy"; "4: Dummy" -> "8: 1"; "8: 1" -> "9: BLOCK"; "3: x" -> "10: IF"; "9: BLOCK" -> "10: IF"; "10: IF" -> "11: IF;"; "11: IF;" -> "12: BLOCK"; "12: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test if let chain`() = testCFG(""" fn foo() { if let Some(s) = x && let Some(u) = y { 1 }; } """, """ digraph { "0: Entry" -> "3: x"; "3: x" -> "4: s"; "4: s" -> "5: s"; "5: s" -> "6: Some(s)"; "6: Some(s)" -> "7: let Some(s) = x"; "7: let Some(s) = x" -> "8: y"; "8: y" -> "9: u"; "9: u" -> "10: u"; "10: u" -> "11: Some(u)"; "11: Some(u)" -> "12: let Some(u) = y"; "7: let Some(s) = x" -> "13: let Some(s) = x && let Some(u) = y"; "12: let Some(u) = y" -> "13: let Some(s) = x && let Some(u) = y"; "13: let Some(s) = x && let Some(u) = y" -> "14: 1"; "14: 1" -> "15: BLOCK"; "13: let Some(s) = x && let Some(u) = y" -> "16: IF"; "15: BLOCK" -> "16: IF"; "16: IF" -> "17: IF;"; "17: IF;" -> "18: BLOCK"; "18: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test if let else`() = testCFG(""" fn foo() { if let Some(s) = x { 1 } else { 2 }; } """, """ digraph { "0: Entry" -> "3: x"; "3: x" -> "5: s"; "5: s" -> "6: s"; "6: s" -> "7: Some(s)"; "7: Some(s)" -> "4: Dummy"; "4: Dummy" -> "8: 1"; "8: 1" -> "9: BLOCK"; "3: x" -> "10: 2"; "10: 2" -> "11: BLOCK"; "9: BLOCK" -> "12: IF"; "11: BLOCK" -> "12: IF"; "12: IF" -> "13: IF;"; "13: IF;" -> "14: BLOCK"; "14: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test if let chain else`() = testCFG(""" fn foo() { if let Some(s) = x && let Some(u) = y { 1 } else { 2 }; } """, """ digraph { "0: Entry" -> "3: x"; "3: x" -> "4: s"; "4: s" -> "5: s"; "5: s" -> "6: Some(s)"; "6: Some(s)" -> "7: let Some(s) = x"; "7: let Some(s) = x" -> "8: y"; "8: y" -> "9: u"; "9: u" -> "10: u"; "10: u" -> "11: Some(u)"; "11: Some(u)" -> "12: let Some(u) = y"; "7: let Some(s) = x" -> "13: let Some(s) = x && let Some(u) = y"; "12: let Some(u) = y" -> "13: let Some(s) = x && let Some(u) = y"; "13: let Some(s) = x && let Some(u) = y" -> "14: 1"; "14: 1" -> "15: BLOCK"; "13: let Some(s) = x && let Some(u) = y" -> "16: 2"; "16: 2" -> "17: BLOCK"; "15: BLOCK" -> "18: IF"; "17: BLOCK" -> "18: IF"; "18: IF" -> "19: IF;"; "19: IF;" -> "20: BLOCK"; "20: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test if let or patterns`() = testCFG(""" fn foo() { if let A(s) | B(s) = x { 1 }; } """, """ digraph { "0: Entry" -> "3: x"; "3: x" -> "5: s"; "5: s" -> "6: s"; "6: s" -> "7: A(s)"; "7: A(s)" -> "4: Dummy"; "3: x" -> "8: s"; "8: s" -> "9: s"; "9: s" -> "10: B(s)"; "10: B(s)" -> "4: Dummy"; "4: Dummy" -> "11: 1"; "11: 1" -> "12: BLOCK"; "3: x" -> "13: IF"; "12: BLOCK" -> "13: IF"; "13: IF" -> "14: IF;"; "14: IF;" -> "15: BLOCK"; "15: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test if else with unreachable`() = testCFG(""" fn main() { let x = 1; if x > 0 && x < 10 { return; } else { return; } let y = 2; } """, """ digraph { "0: Entry" -> "3: 1"; "3: 1" -> "4: x"; "4: x" -> "5: x"; "5: x" -> "6: let x = 1;"; "6: let x = 1;" -> "7: x"; "7: x" -> "8: 0"; "8: 0" -> "9: x > 0"; "9: x > 0" -> "10: x"; "10: x" -> "11: 10"; "11: 10" -> "12: x < 10"; "9: x > 0" -> "13: x > 0 && x < 10"; "12: x < 10" -> "13: x > 0 && x < 10"; "13: x > 0 && x < 10" -> "14: return"; "14: return" -> "1: Exit"; "15: Unreachable" -> "16: return;"; "16: return;" -> "17: BLOCK"; "13: x > 0 && x < 10" -> "18: return"; "18: return" -> "1: Exit"; "19: Unreachable" -> "20: return;"; "20: return;" -> "21: BLOCK"; "17: BLOCK" -> "22: IF"; "21: BLOCK" -> "22: IF"; "22: IF" -> "23: IF;"; "23: IF;" -> "24: 2"; "24: 2" -> "25: y"; "25: y" -> "26: y"; "26: y" -> "27: let y = 2;"; "27: let y = 2;" -> "28: BLOCK"; "28: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test loop`() = testCFG(""" fn main() { loop { x += 1; } y; } """, """ digraph { "0: Entry" -> "3: Dummy"; "3: Dummy" -> "5: x"; "5: x" -> "6: 1"; "6: 1" -> "7: x += 1"; "7: x += 1" -> "8: x += 1;"; "8: x += 1;" -> "9: BLOCK"; "9: BLOCK" -> "3: Dummy"; "3: Dummy" -> "2: Termination"; "4: LOOP" -> "10: LOOP;"; "10: LOOP;" -> "11: y"; "11: y" -> "12: y;"; "12: y;" -> "13: BLOCK"; "13: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test while`() = testCFG(""" fn main() { let mut x = 1; while x < 5 { x += 1; if x > 3 { return; } } } """, """ digraph { "0: Entry" -> "3: 1"; "3: 1" -> "4: mut x"; "4: mut x" -> "5: mut x"; "5: mut x" -> "6: let mut x = 1;"; "6: let mut x = 1;" -> "7: Dummy"; "7: Dummy" -> "9: x"; "9: x" -> "10: 5"; "10: 5" -> "11: x < 5"; "11: x < 5" -> "8: WHILE"; "11: x < 5" -> "12: x"; "12: x" -> "13: 1"; "13: 1" -> "14: x += 1"; "14: x += 1" -> "15: x += 1;"; "15: x += 1;" -> "16: x"; "16: x" -> "17: 3"; "17: 3" -> "18: x > 3"; "18: x > 3" -> "19: return"; "19: return" -> "1: Exit"; "20: Unreachable" -> "21: return;"; "21: return;" -> "22: BLOCK"; "18: x > 3" -> "23: IF"; "22: BLOCK" -> "23: IF"; "23: IF" -> "24: BLOCK"; "24: BLOCK" -> "7: Dummy"; "8: WHILE" -> "25: BLOCK"; "25: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test while with break`() = testCFG(""" fn main() { while cond1 { op1; if cond2 { break; } op2; } } """, """ digraph { "0: Entry" -> "3: Dummy"; "3: Dummy" -> "5: cond1"; "5: cond1" -> "4: WHILE"; "5: cond1" -> "6: op1"; "6: op1" -> "7: op1;"; "7: op1;" -> "8: cond2"; "8: cond2" -> "9: break"; "9: break" -> "4: WHILE"; "9: break" -> "2: Termination"; "10: Unreachable" -> "11: break;"; "11: break;" -> "12: BLOCK"; "8: cond2" -> "13: IF"; "12: BLOCK" -> "13: IF"; "13: IF" -> "14: IF;"; "14: IF;" -> "15: op2"; "15: op2" -> "16: op2;"; "16: op2;" -> "17: BLOCK"; "17: BLOCK" -> "3: Dummy"; "4: WHILE" -> "18: BLOCK"; "18: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test while with labeled break`() = testCFG(""" fn main() { 'loop: while cond1 { op1; loop { if cond2 { break 'loop; } } op2; } } """, """ digraph { "0: Entry" -> "3: Dummy"; "3: Dummy" -> "5: cond1"; "5: cond1" -> "4: WHILE"; "5: cond1" -> "6: op1"; "6: op1" -> "7: op1;"; "7: op1;" -> "8: Dummy"; "8: Dummy" -> "10: cond2"; "10: cond2" -> "11: break 'loop"; "11: break 'loop" -> "4: WHILE"; "11: break 'loop" -> "2: Termination"; "12: Unreachable" -> "13: break 'loop;"; "13: break 'loop;" -> "14: BLOCK"; "10: cond2" -> "15: IF"; "14: BLOCK" -> "15: IF"; "15: IF" -> "16: BLOCK"; "16: BLOCK" -> "8: Dummy"; "8: Dummy" -> "2: Termination"; "9: LOOP" -> "17: LOOP;"; "17: LOOP;" -> "18: op2"; "18: op2" -> "19: op2;"; "19: op2;" -> "20: BLOCK"; "20: BLOCK" -> "3: Dummy"; "4: WHILE" -> "21: BLOCK"; "21: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test while with continue`() = testCFG(""" fn main() { while cond1 { op1; if cond2 { continue; } op2; } } """, """ digraph { "0: Entry" -> "3: Dummy"; "3: Dummy" -> "5: cond1"; "5: cond1" -> "4: WHILE"; "5: cond1" -> "6: op1"; "6: op1" -> "7: op1;"; "7: op1;" -> "8: cond2"; "8: cond2" -> "9: continue"; "9: continue" -> "3: Dummy"; "9: continue" -> "2: Termination"; "10: Unreachable" -> "11: continue;"; "11: continue;" -> "12: BLOCK"; "8: cond2" -> "13: IF"; "12: BLOCK" -> "13: IF"; "13: IF" -> "14: IF;"; "14: IF;" -> "15: op2"; "15: op2" -> "16: op2;"; "16: op2;" -> "17: BLOCK"; "17: BLOCK" -> "3: Dummy"; "4: WHILE" -> "18: BLOCK"; "18: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test while let`() = testCFG(""" fn main() { while let x = f() { 1; } } """, """ digraph { "0: Entry" -> "3: Dummy"; "3: Dummy" -> "5: f"; "5: f" -> "6: f()"; "6: f()" -> "4: WHILE"; "6: f()" -> "8: x"; "8: x" -> "9: x"; "9: x" -> "7: Dummy"; "7: Dummy" -> "10: 1"; "10: 1" -> "11: 1;"; "11: 1;" -> "12: BLOCK"; "12: BLOCK" -> "3: Dummy"; "4: WHILE" -> "13: BLOCK"; "13: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test while let or patterns`() = testCFG(""" fn main() { while let A(s) | B(s) = x { 1; } } """, """ digraph { "0: Entry" -> "3: Dummy"; "3: Dummy" -> "5: x"; "5: x" -> "4: WHILE"; "5: x" -> "7: s"; "7: s" -> "8: s"; "8: s" -> "9: A(s)"; "9: A(s)" -> "6: Dummy"; "5: x" -> "10: s"; "10: s" -> "11: s"; "11: s" -> "12: B(s)"; "12: B(s)" -> "6: Dummy"; "6: Dummy" -> "13: 1"; "13: 1" -> "14: 1;"; "14: 1;" -> "15: BLOCK"; "15: BLOCK" -> "3: Dummy"; "4: WHILE" -> "16: BLOCK"; "16: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test while with unreachable`() = testCFG(""" fn main() { let mut x = 1; while x < 5 { x += 1; if x > 3 { return; } else { x += 10; return; } let z = 42; } let y = 2; } """, """ digraph { "0: Entry" -> "3: 1"; "3: 1" -> "4: mut x"; "4: mut x" -> "5: mut x"; "5: mut x" -> "6: let mut x = 1;"; "6: let mut x = 1;" -> "7: Dummy"; "7: Dummy" -> "9: x"; "9: x" -> "10: 5"; "10: 5" -> "11: x < 5"; "11: x < 5" -> "8: WHILE"; "11: x < 5" -> "12: x"; "12: x" -> "13: 1"; "13: 1" -> "14: x += 1"; "14: x += 1" -> "15: x += 1;"; "15: x += 1;" -> "16: x"; "16: x" -> "17: 3"; "17: 3" -> "18: x > 3"; "18: x > 3" -> "19: return"; "19: return" -> "1: Exit"; "20: Unreachable" -> "21: return;"; "21: return;" -> "22: BLOCK"; "18: x > 3" -> "23: x"; "23: x" -> "24: 10"; "24: 10" -> "25: x += 10"; "25: x += 10" -> "26: x += 10;"; "26: x += 10;" -> "27: return"; "27: return" -> "1: Exit"; "28: Unreachable" -> "29: return;"; "29: return;" -> "30: BLOCK"; "22: BLOCK" -> "31: IF"; "30: BLOCK" -> "31: IF"; "31: IF" -> "32: IF;"; "32: IF;" -> "33: 42"; "33: 42" -> "34: z"; "34: z" -> "35: z"; "35: z" -> "36: let z = 42;"; "36: let z = 42;" -> "37: BLOCK"; "37: BLOCK" -> "7: Dummy"; "8: WHILE" -> "38: WHILE;"; "38: WHILE;" -> "39: 2"; "39: 2" -> "40: y"; "40: y" -> "41: y"; "41: y" -> "42: let y = 2;"; "42: let y = 2;" -> "43: BLOCK"; "43: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test for`() = testCFG(""" fn main() { for i in x.foo(42) { for j in 0..x.bar.foo { x += i; } } y; } """, """ digraph { "0: Entry" -> "4: x"; "4: x" -> "5: 42"; "5: 42" -> "6: x.foo(42)"; "6: x.foo(42)" -> "7: Dummy"; "7: Dummy" -> "3: FOR"; "7: Dummy" -> "8: i"; "8: i" -> "9: i"; "9: i" -> "11: 0"; "11: 0" -> "12: x"; "12: x" -> "13: x.bar"; "13: x.bar" -> "14: x.bar.foo"; "14: x.bar.foo" -> "15: 0..x.bar.foo"; "15: 0..x.bar.foo" -> "16: Dummy"; "16: Dummy" -> "10: FOR"; "16: Dummy" -> "17: j"; "17: j" -> "18: j"; "18: j" -> "19: x"; "19: x" -> "20: i"; "20: i" -> "21: x += i"; "21: x += i" -> "22: x += i;"; "22: x += i;" -> "23: BLOCK"; "23: BLOCK" -> "16: Dummy"; "10: FOR" -> "24: BLOCK"; "24: BLOCK" -> "7: Dummy"; "3: FOR" -> "25: FOR;"; "25: FOR;" -> "26: y"; "26: y" -> "27: y;"; "27: y;" -> "28: BLOCK"; "28: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test for with break and continue`() = testCFG(""" fn main() { for x in xs { op1; for y in ys { op2; if cond { continue; } break; op3; } } y; } """, """ digraph { "0: Entry" -> "4: xs"; "4: xs" -> "5: Dummy"; "5: Dummy" -> "3: FOR"; "5: Dummy" -> "6: x"; "6: x" -> "7: x"; "7: x" -> "8: op1"; "8: op1" -> "9: op1;"; "9: op1;" -> "11: ys"; "11: ys" -> "12: Dummy"; "12: Dummy" -> "10: FOR"; "12: Dummy" -> "13: y"; "13: y" -> "14: y"; "14: y" -> "15: op2"; "15: op2" -> "16: op2;"; "16: op2;" -> "17: cond"; "17: cond" -> "18: continue"; "18: continue" -> "12: Dummy"; "18: continue" -> "2: Termination"; "19: Unreachable" -> "20: continue;"; "20: continue;" -> "21: BLOCK"; "17: cond" -> "22: IF"; "21: BLOCK" -> "22: IF"; "22: IF" -> "23: IF;"; "23: IF;" -> "24: break"; "24: break" -> "10: FOR"; "24: break" -> "2: Termination"; "25: Unreachable" -> "26: break;"; "26: break;" -> "27: op3"; "27: op3" -> "28: op3;"; "28: op3;" -> "29: BLOCK"; "29: BLOCK" -> "12: Dummy"; "10: FOR" -> "30: BLOCK"; "30: BLOCK" -> "5: Dummy"; "3: FOR" -> "31: FOR;"; "31: FOR;" -> "32: y"; "32: y" -> "33: y;"; "33: y;" -> "34: BLOCK"; "34: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test match`() = testCFG(""" enum E { A, B(i32), C } fn main() { let x = E::A; match x { E::A => 1, E::B(x) => match x { 0...10 => 2, _ => 3 }, E::C => 4 }; let y = 0; } """, """ digraph { "0: Entry" -> "3: E::A"; "3: E::A" -> "4: x"; "4: x" -> "5: x"; "5: x" -> "6: let x = E::A;"; "6: let x = E::A;" -> "7: x"; "7: x" -> "10: E::A"; "10: E::A" -> "9: Dummy"; "9: Dummy" -> "11: 1"; "11: 1" -> "8: MATCH"; "7: x" -> "13: x"; "13: x" -> "14: x"; "14: x" -> "15: E::B(x)"; "15: E::B(x)" -> "12: Dummy"; "12: Dummy" -> "16: x"; "16: x" -> "19: 0...10"; "19: 0...10" -> "18: Dummy"; "18: Dummy" -> "20: 2"; "20: 2" -> "17: MATCH"; "16: x" -> "22: _"; "22: _" -> "21: Dummy"; "21: Dummy" -> "23: 3"; "23: 3" -> "17: MATCH"; "17: MATCH" -> "8: MATCH"; "7: x" -> "25: E::C"; "25: E::C" -> "24: Dummy"; "24: Dummy" -> "26: 4"; "26: 4" -> "8: MATCH"; "8: MATCH" -> "27: MATCH;"; "27: MATCH;" -> "28: 0"; "28: 0" -> "29: y"; "29: y" -> "30: y"; "30: y" -> "31: let y = 0;"; "31: let y = 0;" -> "32: BLOCK"; "32: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test match 1`() = testCFG(""" enum E { A(i32), B } fn main() { let x = E::A(1); match x { E::A(val) if val > 0 => val, E::B => return, }; let y = 0; } """, """ digraph { "0: Entry" -> "3: E::A"; "3: E::A" -> "4: 1"; "4: 1" -> "5: E::A(1)"; "5: E::A(1)" -> "6: x"; "6: x" -> "7: x"; "7: x" -> "8: let x = E::A(1);"; "8: let x = E::A(1);" -> "9: x"; "9: x" -> "12: val"; "12: val" -> "13: val"; "13: val" -> "14: E::A(val)"; "14: E::A(val)" -> "15: Dummy"; "15: Dummy" -> "16: val"; "16: val" -> "17: 0"; "17: 0" -> "18: val > 0"; "18: val > 0" -> "19: if val > 0"; "19: if val > 0" -> "11: Dummy"; "11: Dummy" -> "20: val"; "20: val" -> "10: MATCH"; "9: x" -> "22: E::B"; "22: E::B" -> "21: Dummy"; "21: Dummy" -> "23: return"; "23: return" -> "1: Exit"; "24: Unreachable" -> "10: MATCH"; "10: MATCH" -> "25: MATCH;"; "25: MATCH;" -> "26: 0"; "26: 0" -> "27: y"; "27: y" -> "28: y"; "28: y" -> "29: let y = 0;"; "29: let y = 0;" -> "30: BLOCK"; "30: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test match with missing arms`() = testCFG(""" enum E { A(i32), B } fn main() { if let [] = match f() { } { return; } else { main(); }; } fn f() -> E { E::A(1) } """, """ digraph { "0: Entry" -> "3: f"; "3: f" -> "4: f()"; "4: f()" -> "5: MATCH"; "5: MATCH" -> "7: []"; "7: []" -> "6: Dummy"; "6: Dummy" -> "8: return"; "8: return" -> "1: Exit"; "9: Unreachable" -> "10: return;"; "10: return;" -> "11: BLOCK"; "5: MATCH" -> "12: main"; "12: main" -> "13: main()"; "13: main()" -> "14: main();"; "14: main();" -> "15: BLOCK"; "11: BLOCK" -> "16: IF"; "15: BLOCK" -> "16: IF"; "16: IF" -> "17: IF;"; "17: IF;" -> "18: BLOCK"; "18: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test match on never type`() = testCFG(""" fn main() { g(true, match f() { }, 5u8); } fn f() -> ! { loop {} } fn g<A, B, C>(_ :A, _ :B, _ :C) {} """, """ digraph { "0: Entry" -> "3: g"; "3: g" -> "4: true"; "4: true" -> "5: f"; "5: f" -> "6: f()"; "6: f()" -> "2: Termination"; "7: Unreachable" -> "8: MATCH"; "8: MATCH" -> "9: 5u8"; "9: 5u8" -> "10: g(true, match f() { }, 5u8)"; "10: g(true, match f() { }, 5u8)" -> "11: g(true, match f() { }, 5u8);"; "11: g(true, match f() { }, 5u8);" -> "12: BLOCK"; "12: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test match on infinite loop`() = testCFG(""" fn main() { let x = match (loop {}) { }; let y = 0; } """, """ digraph { "0: Entry" -> "3: Dummy"; "3: Dummy" -> "5: BLOCK"; "5: BLOCK" -> "3: Dummy"; "3: Dummy" -> "2: Termination"; "4: LOOP" -> "6: (loop {})"; "6: (loop {})" -> "7: MATCH"; "7: MATCH" -> "8: x"; "8: x" -> "9: x"; "9: x" -> "10: let x = match (loop {}) { };"; "10: let x = match (loop {}) { };" -> "11: 0"; "11: 0" -> "12: y"; "12: y" -> "13: y"; "13: y" -> "14: let y = 0;"; "14: let y = 0;" -> "15: BLOCK"; "15: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test match on early exit`() = testCFG(""" fn main() { let x = match { return; } { }; let y = 0; } """, """ digraph { "0: Entry" -> "4: return"; "4: return" -> "1: Exit"; "5: Unreachable" -> "6: return;"; "6: return;" -> "7: BLOCK"; "7: BLOCK" -> "3: BLOCK"; "3: BLOCK" -> "8: MATCH"; "8: MATCH" -> "9: x"; "9: x" -> "10: x"; "10: x" -> "11: let x = match { return; } { };"; "11: let x = match { return; } { };" -> "12: 0"; "12: 0" -> "13: y"; "13: y" -> "14: y"; "14: y" -> "15: let y = 0;"; "15: let y = 0;" -> "16: BLOCK"; "16: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test match on break block`() = testCFG(""" fn main() { let x = 'b: { match break 'b true { } }; let y = 0; } """, """ digraph { "0: Entry" -> "4: true"; "4: true" -> "5: break 'b true"; "5: break 'b true" -> "3: BLOCK"; "5: break 'b true" -> "2: Termination"; "6: Unreachable" -> "7: MATCH"; "7: MATCH" -> "8: MATCH;"; "8: MATCH;" -> "9: true"; "9: true" -> "10: break 'b true"; "10: break 'b true" -> "3: BLOCK"; "10: break 'b true" -> "2: Termination"; "11: Unreachable" -> "12: MATCH"; "12: MATCH" -> "3: BLOCK"; "3: BLOCK" -> "13: x"; "13: x" -> "14: x"; "14: x" -> "15: let x = 'b: { match break 'b true { } };"; "15: let x = 'b: { match break 'b true { } };" -> "16: 0"; "16: 0" -> "17: y"; "17: y" -> "18: y"; "18: y" -> "19: let y = 0;"; "19: let y = 0;" -> "20: BLOCK"; "20: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test match on break loop`() = testCFG(""" fn main() { let x = loop { match break true { } }; let y = 0; } """, """ digraph { "0: Entry" -> "3: Dummy"; "3: Dummy" -> "5: true"; "5: true" -> "6: break true"; "6: break true" -> "4: LOOP"; "6: break true" -> "2: Termination"; "7: Unreachable" -> "8: MATCH"; "8: MATCH" -> "9: BLOCK"; "9: BLOCK" -> "3: Dummy"; "3: Dummy" -> "2: Termination"; "4: LOOP" -> "10: x"; "10: x" -> "11: x"; "11: x" -> "12: let x = loop { match break true { } };"; "12: let x = loop { match break true { } };" -> "13: 0"; "13: 0" -> "14: y"; "14: y" -> "15: y"; "15: y" -> "16: let y = 0;"; "16: let y = 0;" -> "17: BLOCK"; "17: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test try`() = testCFG(""" fn main() { x.foo(a, b)?; y; } """, """ digraph { "0: Entry" -> "4: x"; "4: x" -> "5: a"; "5: a" -> "6: b"; "6: b" -> "7: x.foo(a, b)"; "7: x.foo(a, b)" -> "8: Dummy"; "8: Dummy" -> "1: Exit"; "7: x.foo(a, b)" -> "3: x.foo(a, b)?"; "3: x.foo(a, b)?" -> "9: x.foo(a, b)?;"; "9: x.foo(a, b)?;" -> "10: y"; "10: y" -> "11: y;"; "11: y;" -> "12: BLOCK"; "12: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test patterns`() = testCFG(""" struct S { data1: i32, data2: i32 } fn main() { let x = S { data1: 42, data2: 24 }; let S { data1: a, data2: b } = s; let S { data1, data2 } = x; let (x, (y, z)) = (1, (2, 3)); [0, 1 + a]; } """, """ digraph { "0: Entry" -> "3: 42"; "3: 42" -> "4: data1: 42"; "4: data1: 42" -> "5: 24"; "5: 24" -> "6: data2: 24"; "6: data2: 24" -> "7: S { data1: 42, data2: 24 }"; "7: S { data1: 42, data2: 24 }" -> "8: x"; "8: x" -> "9: x"; "9: x" -> "10: let x = S { data1: 42, data2: 24 };"; "10: let x = S { data1: 42, data2: 24 };" -> "11: s"; "11: s" -> "12: a"; "12: a" -> "13: a"; "13: a" -> "14: data1: a"; "14: data1: a" -> "15: b"; "15: b" -> "16: b"; "16: b" -> "17: data2: b"; "17: data2: b" -> "18: S { data1: a, data2: b }"; "18: S { data1: a, data2: b }" -> "19: let S { data1: a, data2: b } = s;"; "19: let S { data1: a, data2: b } = s;" -> "20: x"; "20: x" -> "21: data1"; "21: data1" -> "22: data1"; "22: data1" -> "23: data2"; "23: data2" -> "24: data2"; "24: data2" -> "25: S { data1, data2 }"; "25: S { data1, data2 }" -> "26: let S { data1, data2 } = x;"; "26: let S { data1, data2 } = x;" -> "27: 1"; "27: 1" -> "28: 2"; "28: 2" -> "29: 3"; "29: 3" -> "30: (2, 3)"; "30: (2, 3)" -> "31: (1, (2, 3))"; "31: (1, (2, 3))" -> "32: x"; "32: x" -> "33: x"; "33: x" -> "34: y"; "34: y" -> "35: y"; "35: y" -> "36: z"; "36: z" -> "37: z"; "37: z" -> "38: (y, z)"; "38: (y, z)" -> "39: (x, (y, z))"; "39: (x, (y, z))" -> "40: let (x, (y, z)) = (1, (2, 3));"; "40: let (x, (y, z)) = (1, (2, 3));" -> "41: 0"; "41: 0" -> "42: 1"; "42: 1" -> "43: a"; "43: a" -> "44: 1 + a"; "44: 1 + a" -> "45: [0, 1 + a]"; "45: [0, 1 + a]" -> "46: [0, 1 + a];"; "46: [0, 1 + a];" -> "47: BLOCK"; "47: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test noreturn simple`() = testCFG(""" fn main() { if true { noreturn(); } 42; } fn noreturn() -> ! { panic!() } """, """ digraph { "0: Entry" -> "3: true"; "3: true" -> "4: noreturn"; "4: noreturn" -> "5: noreturn()"; "5: noreturn()" -> "2: Termination"; "6: Unreachable" -> "7: noreturn();"; "7: noreturn();" -> "8: BLOCK"; "3: true" -> "9: IF"; "8: BLOCK" -> "9: IF"; "9: IF" -> "10: IF;"; "10: IF;" -> "11: 42"; "11: 42" -> "12: 42;"; "12: 42;" -> "13: BLOCK"; "13: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test noreturn complex expr`() = testCFG(""" fn main() { if true { foo.bar(1, noreturn()); } 42; } fn noreturn() -> ! { panic!() } """, """ digraph { "0: Entry" -> "3: true"; "3: true" -> "4: foo"; "4: foo" -> "5: 1"; "5: 1" -> "6: noreturn"; "6: noreturn" -> "7: noreturn()"; "7: noreturn()" -> "2: Termination"; "8: Unreachable" -> "9: foo.bar(1, noreturn())"; "9: foo.bar(1, noreturn())" -> "10: foo.bar(1, noreturn());"; "10: foo.bar(1, noreturn());" -> "11: BLOCK"; "3: true" -> "12: IF"; "11: BLOCK" -> "12: IF"; "12: IF" -> "13: IF;"; "13: IF;" -> "14: 42"; "14: 42" -> "15: 42;"; "15: 42;" -> "16: BLOCK"; "16: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test panic macro call inside stmt`() = testCFG(""" fn main() { 1; if true { 2; } else { panic!(); } 42; } """, """ digraph { "0: Entry" -> "3: 1"; "3: 1" -> "4: 1;"; "4: 1;" -> "5: true"; "5: true" -> "6: 2"; "6: 2" -> "7: 2;"; "7: 2;" -> "8: BLOCK"; "5: true" -> "9: panic!()"; "9: panic!()" -> "2: Termination"; "10: Unreachable" -> "11: panic!();"; "11: panic!();" -> "12: BLOCK"; "8: BLOCK" -> "13: IF"; "12: BLOCK" -> "13: IF"; "13: IF" -> "14: IF;"; "14: IF;" -> "15: 42"; "15: 42" -> "16: 42;"; "16: 42;" -> "17: BLOCK"; "17: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test panic macro call outside stmt`() = testCFG(""" fn main() { match x { true => 2, false => panic!() }; } """, """ digraph { "0: Entry" -> "3: x"; "3: x" -> "6: true"; "6: true" -> "5: Dummy"; "5: Dummy" -> "7: 2"; "7: 2" -> "4: MATCH"; "3: x" -> "9: false"; "9: false" -> "8: Dummy"; "8: Dummy" -> "10: panic!()"; "10: panic!()" -> "2: Termination"; "11: Unreachable" -> "4: MATCH"; "4: MATCH" -> "12: MATCH;"; "12: MATCH;" -> "13: BLOCK"; "13: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test macro call outside stmt`() = testCFG(""" fn main() { match e { E::A => 2, E::B => some_macro!() }; } """, """ digraph { "0: Entry" -> "3: e"; "3: e" -> "6: E::A"; "6: E::A" -> "5: Dummy"; "5: Dummy" -> "7: 2"; "7: 2" -> "4: MATCH"; "3: e" -> "9: E::B"; "9: E::B" -> "8: Dummy"; "8: Dummy" -> "10: some_macro!()"; "10: some_macro!()" -> "4: MATCH"; "4: MATCH" -> "11: MATCH;"; "11: MATCH;" -> "12: BLOCK"; "12: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test shorthand struct literal`() = testCFG(""" struct S { x: i32 } fn foo(x: i32) { S { x }; } """, """ digraph { "0: Entry" -> "3: x"; "3: x" -> "4: S { x }"; "4: S { x }" -> "5: S { x };"; "5: S { x };" -> "6: BLOCK"; "6: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test struct literal dot dot syntax`() = testCFG(""" struct S { x: i32, y: i32 } fn main() { S { x, ..s }; } """, """ digraph { "0: Entry" -> "3: x"; "3: x" -> "4: s"; "4: s" -> "5: S { x, ..s }"; "5: S { x, ..s }" -> "6: S { x, ..s };"; "6: S { x, ..s };" -> "7: BLOCK"; "7: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test lambda expr`() = testCFG(""" fn foo() { let f = |x: i32| { x + 1 }; } """, """ digraph { "0: Entry" -> "4: x"; "4: x" -> "5: 1"; "5: 1" -> "6: x + 1"; "6: x + 1" -> "7: BLOCK"; "7: BLOCK" -> "3: BLOCK"; "3: BLOCK" -> "8: CLOSURE"; "0: Entry" -> "8: CLOSURE"; "8: CLOSURE" -> "9: f"; "9: f" -> "10: f"; "10: f" -> "11: let f = |x: i32| { x + 1 };"; "11: let f = |x: i32| { x + 1 };" -> "12: BLOCK"; "12: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test arbitrary macro call`() = testCFG(""" macro_rules! my_macro { ($ e1:expr, $ e2:expr) => ($ e1 + $ e2); } fn main() { my_macro!(x, y); } """, """ digraph { "0: Entry" -> "3: x"; "3: x" -> "4: y"; "4: y" -> "5: x + y"; "5: x + y" -> "6: x + y;"; "6: x + y;" -> "7: BLOCK"; "7: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test println! macro call`() = testCFG(""" fn main() { println!("{} {}", x, y); } """, """ digraph { "0: Entry" -> "3: \"{} {}\""; "3: \"{} {}\"" -> "4: x"; "4: x" -> "5: y"; "5: y" -> "6: println!(\"{} {}\", x, y)"; "6: println!(\"{} {}\", x, y)" -> "7: println!(\"{} {}\", x, y);"; "7: println!(\"{} {}\", x, y);" -> "8: BLOCK"; "8: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test vec! macro call`() = testCFG(""" fn main() { vec![ S { x }, s1 ]; } """, """ digraph { "0: Entry" -> "3: x"; "3: x" -> "4: S { x }"; "4: S { x }" -> "5: s1"; "5: s1" -> "6: vec![ S { x }, s1 ]"; "6: vec![ S { x }, s1 ]" -> "7: vec![ S { x }, s1 ];"; "7: vec![ S { x }, s1 ];" -> "8: BLOCK"; "8: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test assert_eq! macro call`() = testCFG(""" fn main() { assert_eq!(x, y); } """, """ digraph { "0: Entry" -> "3: x"; "3: x" -> "4: y"; "4: y" -> "5: assert_eq!(x, y)"; "5: assert_eq!(x, y)" -> "6: assert_eq!(x, y);"; "6: assert_eq!(x, y);" -> "7: BLOCK"; "7: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test panic in lambda expr`() = testCFG(""" fn foo() { let f = || { panic!() }; 1; } """, """ digraph { "0: Entry" -> "4: panic!()"; "4: panic!()" -> "2: Termination"; "5: Unreachable" -> "6: BLOCK"; "6: BLOCK" -> "3: BLOCK"; "3: BLOCK" -> "7: CLOSURE"; "0: Entry" -> "7: CLOSURE"; "7: CLOSURE" -> "8: f"; "8: f" -> "9: f"; "9: f" -> "10: let f = || { panic!() };"; "10: let f = || { panic!() };" -> "11: 1"; "11: 1" -> "12: 1;"; "12: 1;" -> "13: BLOCK"; "13: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test infinitely recursive macro call`() = testCFG(""" macro_rules! infinite_macro { () => { infinite_macro!() }; } fn foo() { 1; infinite_macro!(); 2; } """, """ digraph { "0: Entry" -> "3: 1"; "3: 1" -> "4: 1;"; "4: 1;" -> "5: infinite_macro ! ( )"; "5: infinite_macro ! ( )" -> "2: Termination"; "6: Unreachable" -> "7: infinite_macro ! ( )"; "7: infinite_macro ! ( )" -> "8: infinite_macro ! ( )"; "8: infinite_macro ! ( )" -> "9: infinite_macro ! ( )"; "9: infinite_macro ! ( )" -> "10: infinite_macro ! ( )"; "10: infinite_macro ! ( )" -> "11: infinite_macro ! ( )"; "11: infinite_macro ! ( )" -> "12: infinite_macro ! ( )"; "12: infinite_macro ! ( )" -> "13: infinite_macro ! ( )"; "13: infinite_macro ! ( )" -> "14: infinite_macro ! ( )"; "14: infinite_macro ! ( )" -> "15: infinite_macro ! ( )"; "15: infinite_macro ! ( )" -> "16: infinite_macro ! ( )"; "16: infinite_macro ! ( )" -> "17: infinite_macro ! ( )"; "17: infinite_macro ! ( )" -> "18: infinite_macro ! ( )"; "18: infinite_macro ! ( )" -> "19: infinite_macro ! ( )"; "19: infinite_macro ! ( )" -> "20: infinite_macro ! ( )"; "20: infinite_macro ! ( )" -> "21: infinite_macro ! ( )"; "21: infinite_macro ! ( )" -> "22: infinite_macro ! ( )"; "22: infinite_macro ! ( )" -> "23: infinite_macro ! ( )"; "23: infinite_macro ! ( )" -> "24: infinite_macro ! ( )"; "24: infinite_macro ! ( )" -> "25: infinite_macro ! ( )"; "25: infinite_macro ! ( )" -> "26: infinite_macro ! ( )"; "26: infinite_macro ! ( )" -> "27: infinite_macro ! ( )"; "27: infinite_macro ! ( )" -> "28: infinite_macro ! ( )"; "28: infinite_macro ! ( )" -> "29: infinite_macro ! ( )"; "29: infinite_macro ! ( )" -> "30: infinite_macro ! ( )"; "30: infinite_macro ! ( )" -> "31: infinite_macro ! ( )"; "31: infinite_macro ! ( )" -> "32: infinite_macro ! ( )"; "32: infinite_macro ! ( )" -> "33: infinite_macro ! ( )"; "33: infinite_macro ! ( )" -> "34: infinite_macro ! ( )"; "34: infinite_macro ! ( )" -> "35: infinite_macro ! ( )"; "35: infinite_macro ! ( )" -> "36: infinite_macro ! ( )"; "36: infinite_macro ! ( )" -> "37: infinite_macro ! ( )"; "37: infinite_macro ! ( )" -> "38: infinite_macro ! ( )"; "38: infinite_macro ! ( )" -> "39: infinite_macro ! ( )"; "39: infinite_macro ! ( )" -> "40: infinite_macro ! ( )"; "40: infinite_macro ! ( )" -> "41: infinite_macro ! ( )"; "41: infinite_macro ! ( )" -> "42: infinite_macro ! ( )"; "42: infinite_macro ! ( )" -> "43: infinite_macro ! ( )"; "43: infinite_macro ! ( )" -> "44: infinite_macro ! ( )"; "44: infinite_macro ! ( )" -> "45: infinite_macro ! ( )"; "45: infinite_macro ! ( )" -> "46: infinite_macro ! ( )"; "46: infinite_macro ! ( )" -> "47: infinite_macro ! ( )"; "47: infinite_macro ! ( )" -> "48: infinite_macro ! ( )"; "48: infinite_macro ! ( )" -> "49: infinite_macro ! ( )"; "49: infinite_macro ! ( )" -> "50: infinite_macro ! ( )"; "50: infinite_macro ! ( )" -> "51: infinite_macro ! ( )"; "51: infinite_macro ! ( )" -> "52: infinite_macro ! ( )"; "52: infinite_macro ! ( )" -> "53: infinite_macro ! ( )"; "53: infinite_macro ! ( )" -> "54: infinite_macro ! ( )"; "54: infinite_macro ! ( )" -> "55: infinite_macro ! ( )"; "55: infinite_macro ! ( )" -> "56: infinite_macro ! ( )"; "56: infinite_macro ! ( )" -> "57: infinite_macro ! ( )"; "57: infinite_macro ! ( )" -> "58: infinite_macro ! ( )"; "58: infinite_macro ! ( )" -> "59: infinite_macro ! ( )"; "59: infinite_macro ! ( )" -> "60: infinite_macro ! ( )"; "60: infinite_macro ! ( )" -> "61: infinite_macro ! ( )"; "61: infinite_macro ! ( )" -> "62: infinite_macro ! ( )"; "62: infinite_macro ! ( )" -> "63: infinite_macro ! ( )"; "63: infinite_macro ! ( )" -> "64: infinite_macro ! ( )"; "64: infinite_macro ! ( )" -> "65: infinite_macro ! ( )"; "65: infinite_macro ! ( )" -> "66: infinite_macro ! ( )"; "66: infinite_macro ! ( )" -> "67: infinite_macro ! ( )"; "67: infinite_macro ! ( )" -> "68: infinite_macro ! ( )"; "68: infinite_macro ! ( )" -> "69: infinite_macro ! ( )"; "69: infinite_macro ! ( )" -> "70: infinite_macro ! ( )"; "70: infinite_macro ! ( )" -> "71: infinite_macro ! ( )"; "71: infinite_macro ! ( )" -> "72: infinite_macro ! ( )"; "72: infinite_macro ! ( )" -> "73: infinite_macro ! ( )"; "73: infinite_macro ! ( )" -> "74: infinite_macro ! ( )"; "74: infinite_macro ! ( )" -> "75: infinite_macro ! ( )"; "75: infinite_macro ! ( )" -> "76: infinite_macro ! ( )"; "76: infinite_macro ! ( )" -> "77: infinite_macro ! ( )"; "77: infinite_macro ! ( )" -> "78: infinite_macro ! ( )"; "78: infinite_macro ! ( )" -> "79: infinite_macro ! ( )"; "79: infinite_macro ! ( )" -> "80: infinite_macro ! ( )"; "80: infinite_macro ! ( )" -> "81: infinite_macro ! ( )"; "81: infinite_macro ! ( )" -> "82: infinite_macro ! ( )"; "82: infinite_macro ! ( )" -> "83: infinite_macro ! ( )"; "83: infinite_macro ! ( )" -> "84: infinite_macro ! ( )"; "84: infinite_macro ! ( )" -> "85: infinite_macro ! ( )"; "85: infinite_macro ! ( )" -> "86: infinite_macro ! ( )"; "86: infinite_macro ! ( )" -> "87: infinite_macro ! ( )"; "87: infinite_macro ! ( )" -> "88: infinite_macro ! ( )"; "88: infinite_macro ! ( )" -> "89: infinite_macro ! ( )"; "89: infinite_macro ! ( )" -> "90: infinite_macro ! ( )"; "90: infinite_macro ! ( )" -> "91: infinite_macro ! ( )"; "91: infinite_macro ! ( )" -> "92: infinite_macro ! ( )"; "92: infinite_macro ! ( )" -> "93: infinite_macro ! ( )"; "93: infinite_macro ! ( )" -> "94: infinite_macro ! ( )"; "94: infinite_macro ! ( )" -> "95: infinite_macro ! ( )"; "95: infinite_macro ! ( )" -> "96: infinite_macro ! ( )"; "96: infinite_macro ! ( )" -> "97: infinite_macro ! ( )"; "97: infinite_macro ! ( )" -> "98: infinite_macro ! ( )"; "98: infinite_macro ! ( )" -> "99: infinite_macro ! ( )"; "99: infinite_macro ! ( )" -> "100: infinite_macro ! ( )"; "100: infinite_macro ! ( )" -> "101: infinite_macro ! ( )"; "101: infinite_macro ! ( )" -> "102: infinite_macro ! ( )"; "102: infinite_macro ! ( )" -> "103: infinite_macro ! ( )"; "103: infinite_macro ! ( )" -> "104: infinite_macro ! ( )"; "104: infinite_macro ! ( )" -> "105: infinite_macro ! ( )"; "105: infinite_macro ! ( )" -> "106: infinite_macro ! ( )"; "106: infinite_macro ! ( )" -> "107: infinite_macro ! ( )"; "107: infinite_macro ! ( )" -> "108: infinite_macro ! ( )"; "108: infinite_macro ! ( )" -> "109: infinite_macro ! ( )"; "109: infinite_macro ! ( )" -> "110: infinite_macro ! ( )"; "110: infinite_macro ! ( )" -> "111: infinite_macro ! ( )"; "111: infinite_macro ! ( )" -> "112: infinite_macro ! ( )"; "112: infinite_macro ! ( )" -> "113: infinite_macro ! ( )"; "113: infinite_macro ! ( )" -> "114: infinite_macro ! ( )"; "114: infinite_macro ! ( )" -> "115: infinite_macro ! ( )"; "115: infinite_macro ! ( )" -> "116: infinite_macro ! ( )"; "116: infinite_macro ! ( )" -> "117: infinite_macro ! ( )"; "117: infinite_macro ! ( )" -> "118: infinite_macro ! ( )"; "118: infinite_macro ! ( )" -> "119: infinite_macro ! ( )"; "119: infinite_macro ! ( )" -> "120: infinite_macro ! ( )"; "120: infinite_macro ! ( )" -> "121: infinite_macro ! ( )"; "121: infinite_macro ! ( )" -> "122: infinite_macro ! ( )"; "122: infinite_macro ! ( )" -> "123: infinite_macro ! ( )"; "123: infinite_macro ! ( )" -> "124: infinite_macro ! ( )"; "124: infinite_macro ! ( )" -> "125: infinite_macro ! ( )"; "125: infinite_macro ! ( )" -> "126: infinite_macro ! ( )"; "126: infinite_macro ! ( )" -> "127: infinite_macro ! ( )"; "127: infinite_macro ! ( )" -> "128: infinite_macro ! ( )"; "128: infinite_macro ! ( )" -> "129: infinite_macro ! ( )"; "129: infinite_macro ! ( )" -> "130: infinite_macro ! ( )"; "130: infinite_macro ! ( )" -> "131: infinite_macro ! ( )"; "131: infinite_macro ! ( )" -> "132: infinite_macro ! ( )"; "132: infinite_macro ! ( )" -> "133: infinite_macro ! ( )"; "133: infinite_macro ! ( )" -> "134: infinite_macro ! ( )"; "134: infinite_macro ! ( )" -> "135: infinite_macro ! ( )"; "135: infinite_macro ! ( )" -> "136: infinite_macro ! ( );"; "136: infinite_macro ! ( );" -> "137: 2"; "137: 2" -> "138: 2;"; "138: 2;" -> "139: BLOCK"; "139: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test async block with infinite loop`() = testCFG(""" fn foo() { 1; async { loop {} }; 2; } """, """ digraph { "0: Entry" -> "3: 1"; "3: 1" -> "4: 1;"; "4: 1;" -> "6: Dummy"; "6: Dummy" -> "8: BLOCK"; "8: BLOCK" -> "6: Dummy"; "6: Dummy" -> "2: Termination"; "7: LOOP" -> "9: BLOCK"; "9: BLOCK" -> "5: BLOCK"; "4: 1;" -> "5: BLOCK"; "5: BLOCK" -> "10: BLOCK;"; "10: BLOCK;" -> "11: 2"; "11: 2" -> "12: 2;"; "12: 2;" -> "13: BLOCK"; "13: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test loop with break inside block expr`() = testCFG(""" fn main() { loop { { break; } } 1; } """, """ digraph { "0: Entry" -> "3: Dummy"; "3: Dummy" -> "6: break"; "6: break" -> "4: LOOP"; "6: break" -> "2: Termination"; "7: Unreachable" -> "8: break;"; "8: break;" -> "9: BLOCK"; "9: BLOCK" -> "5: BLOCK"; "5: BLOCK" -> "10: BLOCK"; "10: BLOCK" -> "3: Dummy"; "3: Dummy" -> "2: Termination"; "4: LOOP" -> "11: LOOP;"; "11: LOOP;" -> "12: 1"; "12: 1" -> "13: 1;"; "13: 1;" -> "14: BLOCK"; "14: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) @MinRustcVersion("1.62.0") @ProjectDescriptor(WithStdlibRustProjectDescriptor::class) @MockAdditionalCfgOptions("intellij_rust") fun `test conditional code`() = testCFG(""" macro_rules! reachable { () => {}; } macro_rules! unreachable { () => { foo; }; } fn main() { 1; #[cfg(intellij_rust)] 2; #[cfg(not(intellij_rust))] unreachable; #[cfg(not(intellij_rust))] return; #[cfg(not(intellij_rust))] let x = unreachable(); let s = S { #[cfg(not(intellij_rust))] x: unreachable() }; foo(#[cfg(not(intellij_rust))] unreachable); #[cfg(intellij_rust)] reachable!(); #[cfg(not(intellij_rust))] unreachable!(); #[cfg(not(intellij_rust))] panic!(); 4; #[cfg(intellij_rust)] panic!(); 5; } """, """ digraph { "0: Entry" -> "3: 1"; "3: 1" -> "4: 1;"; "4: 1;" -> "5: 2"; "5: 2" -> "6: #[cfg(intellij_rust)] 2;"; "6: #[cfg(intellij_rust)] 2;" -> "7: S { #[cfg(not(intellij_rust))] x: unreachable() }"; "7: S { #[cfg(not(intellij_rust))] x: unreachable() }" -> "8: s"; "8: s" -> "9: s"; "9: s" -> "10: let s = S { #[cfg(not(intellij_rust))] x: unreachable() };"; "10: let s = S { #[cfg(not(intellij_rust))] x: unreachable() };" -> "11: foo"; "11: foo" -> "12: foo(#[cfg(not(intellij_rust))] unreachable)"; "12: foo(#[cfg(not(intellij_rust))] unreachable)" -> "13: foo(#[cfg(not(intellij_rust))] unreachable);"; "13: foo(#[cfg(not(intellij_rust))] unreachable);" -> "14: 4"; "14: 4" -> "15: 4;"; "15: 4;" -> "16: panic!()"; "16: panic!()" -> "2: Termination"; "17: Unreachable" -> "18: #[cfg(intellij_rust)] panic!();"; "18: #[cfg(intellij_rust)] panic!();" -> "19: 5"; "19: 5" -> "20: 5;"; "20: 5;" -> "21: BLOCK"; "21: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test break expanded from macro`() = testCFG(""" macro_rules! break_macro { () => { break }; } fn main() { 1; loop { break_macro!(); } 2; } """, """ digraph { "0: Entry" -> "3: 1"; "3: 1" -> "4: 1;"; "4: 1;" -> "5: Dummy"; "5: Dummy" -> "7: break"; "7: break" -> "6: LOOP"; "7: break" -> "2: Termination"; "8: Unreachable" -> "9: break;"; "9: break;" -> "10: BLOCK"; "10: BLOCK" -> "5: Dummy"; "5: Dummy" -> "2: Termination"; "6: LOOP" -> "11: LOOP;"; "11: LOOP;" -> "12: 2"; "12: 2" -> "13: 2;"; "13: 2;" -> "14: BLOCK"; "14: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) fun `test asm! macro call`() = testCFG(""" fn main() { 1; let x: u64; unsafe { asm!("mov {}, 5", out(reg) x); } 2; } """, """ digraph { "0: Entry" -> "3: 1"; "3: 1" -> "4: 1;"; "4: 1;" -> "5: x"; "5: x" -> "6: x"; "6: x" -> "7: let x: u64;"; "7: let x: u64;" -> "9: x"; "9: x" -> "10: asm!(\"mov {}, 5\", out(reg) x)"; "10: asm!(\"mov {}, 5\", out(reg) x)" -> "11: asm!(\"mov {}, 5\", out(reg) x);"; "11: asm!(\"mov {}, 5\", out(reg) x);" -> "12: BLOCK"; "12: BLOCK" -> "8: BLOCK"; "8: BLOCK" -> "13: BLOCK;"; "13: BLOCK;" -> "14: 2"; "14: 2" -> "15: 2;"; "15: 2;" -> "16: BLOCK"; "16: BLOCK" -> "1: Exit"; "1: Exit" -> "2: Termination"; } """) private fun testCFG(@Language("Rust") code: String, @Language("Dot") expectedIndented: String) { InlineFile(code) val function = myFixture.file.descendantsOfType<RsFunction>().firstOrNull() ?: return val cfg = ControlFlowGraph.buildFor(function.block!!, getRegionScopeTree(function)) val expected = expectedIndented.trimIndent() val actual = cfg.graph.createDotDescription().trimEnd() assertEquals(expected, actual) } }
mit
a67d56519ebd19912f847993d8b0b680
34.328162
116
0.322175
3.118121
false
true
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/docs/RsExternalDocUrlTest.kt
2
6733
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.docs import org.intellij.lang.annotations.Language import org.rust.CheckTestmarkHit import org.rust.ProjectDescriptor import org.rust.WithStdlibAndDependencyRustProjectDescriptor import org.rust.ide.docs.RsDocumentationProvider.Testmarks @ProjectDescriptor(WithStdlibAndDependencyRustProjectDescriptor::class) class RsExternalDocUrlTest : RsDocumentationProviderTest() { fun `test not stdlib item`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs pub struct Foo; //^ """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/struct.Foo.html") fun `test associated const`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs pub struct Foo; impl Foo { pub const BAR: i32 = 123; //^ } """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/struct.Foo.html#associatedconstant.BAR") fun `test enum variant field`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs pub enum Foo { Bar { baz: i32 } //^ } """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/enum.Foo.html#variant.Bar.field.baz") fun `test union`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs pub union Foo { x: i32, y: f32 } //^ """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/union.Foo.html") fun `test trait alias`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs pub trait Foo {} pub trait Bar {} pub trait FooBar = Foo + Bar; //^ """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/traitalias.FooBar.html") fun `test item with restricted visibility`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs pub(crate) enum Foo { V1, V2 } //^ """, null) fun `test private item`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs struct Foo; //^ """, null) fun `test pub item in private module`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs mod foo { pub struct Foo; //^ } """, null) fun `test method in private trait`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs trait Foo { fn foo(&self); //^ } """, null) fun `test private method`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs pub struct Foo; impl Foo { fn foo(&self) {} //^ } """, null) fun `test public method in private module`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs pub struct Foo; mod bar { impl crate::Foo { pub fn foo(&self) {} //^ } } """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/struct.Foo.html#method.foo") @CheckTestmarkHit(Testmarks.DocHidden::class) fun `test doc hidden`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs #[doc(hidden)] pub fn foo() {} //^ """, null) fun `test macro`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs #[macro_export] macro_rules! foo { //^ () => { unimplemented!() }; } """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/macro.foo.html") fun `test macro in module`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs pub mod bar { #[macro_export] macro_rules! foo { //^ () => { unimplemented!() }; } } """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/macro.foo.html") @CheckTestmarkHit(Testmarks.NotExportedMacro::class) fun `test not exported macro`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs macro_rules! foo { //^ () => { unimplemented!() }; } """, null) fun `test macro 2`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs pub macro bar() {} //^ """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/macro.bar.html") fun `test macro 2 in module`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs pub mod foo { pub macro bar() {} } //^ """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/foo/macro.bar.html") fun `test bang proc macro`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs #[proc_macro] fn foo(_input: TokenStream) -> TokenStream {} //^ """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/macro.foo.html") fun `test derive proc macro`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs #[proc_macro_derive(MyDerive)] //^ fn foo(_input: TokenStream) -> TokenStream {} """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/derive.MyDerive.html") fun `test attribute proc macro`() = doUrlTestByFileTree(""" //- dep-lib/lib.rs #[proc_macro_attribute] fn foo(_attr: TokenStream, _input: TokenStream) -> TokenStream {} //^ """, "https://docs.rs/dep-lib/0.0.1/dep_lib_target/attr.foo.html") @CheckTestmarkHit(Testmarks.NonDependency::class) fun `test not external url for workspace package`() = doUrlTestByFileTree(""" //- lib.rs pub enum Foo { FOO, BAR } //^ """, null) @CheckTestmarkHit(Testmarks.PkgWithoutSource::class) fun `test not external url for dependency package without source`() = doUrlTestByFileTree(""" //- no-source-lib/lib.rs pub enum Foo { FOO, BAR } //^ """, null) fun `test custom documentation URL`() = doCustomUrlTestByFileTree(""" //- dep-lib/lib.rs #[macro_export] macro_rules! foo { //^ () => { unimplemented!() }; } """, "file:///mydoc/", "file:///mydoc/dep-lib/0.0.1/dep_lib_target/macro.foo.html") fun `test custom documentation URL add slash`() = doCustomUrlTestByFileTree(""" //- dep-lib/lib.rs #[macro_export] macro_rules! foo { //^ () => { unimplemented!() }; } """, "file:///mydoc", "file:///mydoc/dep-lib/0.0.1/dep_lib_target/macro.foo.html") private fun doCustomUrlTestByFileTree(@Language("Rust") text: String, docBaseUrl: String, expectedUrl: String) { withExternalDocumentationBaseUrl(docBaseUrl) { doUrlTestByFileTree(text, expectedUrl) } } }
mit
a4dd1206c6ac0202562633f8b906acc7
30.759434
116
0.526066
3.887413
false
true
false
false
MeilCli/Twitter4HK
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/TwitterFactory.kt
1
4548
package com.twitter.meil_mitu.twitter4hk import com.twitter.meil_mitu.twitter4hk.oauth.Oauth import com.twitter.meil_mitu.twitter4hk.oauth.Oauth2 import com.twitter.meil_mitu.twitter4hk.oauth.OauthEcho import java.util.* class TwitterFactory private constructor() { private val map = HashMap<OauthItem, Twitter4HK>() fun <T : AbsOauth> getOauth(oauthClass: Class<T>, consumerKey: String, consumerSecret: String): AbsOauth? { return getOauth(oauthClass, consumerKey, consumerSecret, null, null) } fun <T : AbsOauth> getOauth( oauthClass: Class<T>, consumerKey: String, consumerSecret: String, accessToken: String?, accessTokenSecret: String?): AbsOauth? { val tw = getTwitter(oauthClass, consumerKey, consumerSecret, accessToken, accessTokenSecret) if (tw != null) { return tw.oauth } return null } fun <T : AbsOauth> getTwitter(oauthClass: Class<T>, consumerKey: String, consumerSecret: String): Twitter4HK? { return getTwitter(oauthClass, consumerKey, consumerSecret, null, null) } fun <T : AbsOauth> getTwitter( oauthClass: Class<T>, consumerKey: String, consumerSecret: String, accessToken: String?, accessTokenSecret: String?): Twitter4HK? { if (Oauth2::class.java == oauthClass == false && (accessToken == null || accessTokenSecret == null)) { throw IllegalArgumentException("accessToken or accessTokenSecret is null") } val item = OauthItem(oauthClass, consumerKey, consumerSecret, accessToken, accessTokenSecret) if (map.containsKey(item)) { val tw = map[item] if (tw != null) { return tw } } if (Oauth::class.java == oauthClass) { val tw = Twitter4HK(Oauth(null, consumerKey, consumerSecret, accessToken, accessTokenSecret)) map.put(item, tw) return tw } else if (Oauth2::class.java == oauthClass) { val tw = Twitter4HK(Oauth2(null, consumerKey, consumerSecret)) map.put(item, tw) return tw } else if (OauthEcho::class.java == oauthClass) { val tw = Twitter4HK(OauthEcho(null, null, consumerKey, consumerSecret, accessToken, accessTokenSecret)) map.put(item, tw) return tw } throw IllegalArgumentException("oauthClass is not default defined") } private inner class OauthItem internal constructor( private val oauthClass: Class<out AbsOauth>, private val consumerKey: String, private val consumerSecret: String, private val accessToken: String?, private val accessTokenSecret: String?) { override fun toString(): String { return "OauthItem{oauthClass=$oauthClass, consumerKey='$consumerKey', consumerSecret='$consumerSecret', accessToken='$accessToken', accessTokenSecret='$accessTokenSecret'}" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is OauthItem) return false if (oauthClass != other.oauthClass) return false if (consumerKey != other.consumerKey) return false if (consumerSecret != other.consumerSecret) return false if (if (accessToken != null) accessToken != other.accessToken else false) return false if (if (accessTokenSecret != null) accessTokenSecret != other.accessTokenSecret else false) return false return true } override fun hashCode(): Int { var result = oauthClass.hashCode() result = 31 * result + consumerKey.hashCode() result = 31 * result + consumerSecret.hashCode() result = 31 * result + (if (accessToken != null) accessToken.hashCode() else 0) result = 31 * result + (if (accessTokenSecret != null) accessTokenSecret.hashCode() else 0) return result } } companion object { private var _instance: TwitterFactory? = null fun getInstance(): TwitterFactory { if (_instance == null) { _instance = TwitterFactory() } return _instance!! } } }
mit
8cbb7e377460a946f721f752232c2a8e
37.542373
184
0.591689
4.986842
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/registration/VerifyAccountRepository.kt
1
6149
package org.thoughtcrime.securesms.registration import android.app.Application import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.schedulers.Schedulers import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.AppCapabilities import org.thoughtcrime.securesms.gcm.FcmUtil import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.pin.KbsRepository import org.thoughtcrime.securesms.pin.KeyBackupSystemWrongPinException import org.thoughtcrime.securesms.pin.TokenData import org.thoughtcrime.securesms.push.AccountManagerFactory import org.thoughtcrime.securesms.util.TextSecurePreferences import org.whispersystems.signalservice.api.KbsPinData import org.whispersystems.signalservice.api.KeyBackupSystemNoDataException import org.whispersystems.signalservice.api.SignalServiceAccountManager import org.whispersystems.signalservice.api.crypto.UnidentifiedAccess import org.whispersystems.signalservice.api.push.SignalServiceAddress import org.whispersystems.signalservice.internal.ServiceResponse import org.whispersystems.signalservice.internal.push.RequestVerificationCodeResponse import org.whispersystems.signalservice.internal.push.VerifyAccountResponse import java.io.IOException import java.util.Locale import java.util.Optional import java.util.concurrent.TimeUnit /** * Request SMS/Phone verification codes to help prove ownership of a phone number. */ class VerifyAccountRepository(private val context: Application) { fun requestVerificationCode( e164: String, password: String, mode: Mode, captchaToken: String? = null ): Single<ServiceResponse<RequestVerificationCodeResponse>> { Log.d(TAG, "SMS Verification requested") return Single.fromCallable { val fcmToken: Optional<String> = FcmUtil.getToken(context) val accountManager = AccountManagerFactory.createUnauthenticated(context, e164, SignalServiceAddress.DEFAULT_DEVICE_ID, password) val pushChallenge = PushChallengeRequest.getPushChallengeBlocking(accountManager, fcmToken, e164, PUSH_REQUEST_TIMEOUT) if (mode == Mode.PHONE_CALL) { accountManager.requestVoiceVerificationCode(Locale.getDefault(), Optional.ofNullable(captchaToken), pushChallenge, fcmToken) } else { accountManager.requestSmsVerificationCode(mode.isSmsRetrieverSupported, Optional.ofNullable(captchaToken), pushChallenge, fcmToken) } }.subscribeOn(Schedulers.io()) } fun verifyAccount(registrationData: RegistrationData): Single<ServiceResponse<VerifyAccountResponse>> { val universalUnidentifiedAccess: Boolean = TextSecurePreferences.isUniversalUnidentifiedAccess(context) val unidentifiedAccessKey: ByteArray = UnidentifiedAccess.deriveAccessKeyFrom(registrationData.profileKey) val accountManager: SignalServiceAccountManager = AccountManagerFactory.createUnauthenticated( context, registrationData.e164, SignalServiceAddress.DEFAULT_DEVICE_ID, registrationData.password ) return Single.fromCallable { accountManager.verifyAccount( registrationData.code, registrationData.registrationId, registrationData.isNotFcm, unidentifiedAccessKey, universalUnidentifiedAccess, AppCapabilities.getCapabilities(true), SignalStore.phoneNumberPrivacy().phoneNumberListingMode.isDiscoverable, registrationData.pniRegistrationId ) }.subscribeOn(Schedulers.io()) } fun verifyAccountWithPin(registrationData: RegistrationData, pin: String, tokenData: TokenData): Single<ServiceResponse<VerifyAccountWithRegistrationLockResponse>> { val universalUnidentifiedAccess: Boolean = TextSecurePreferences.isUniversalUnidentifiedAccess(context) val unidentifiedAccessKey: ByteArray = UnidentifiedAccess.deriveAccessKeyFrom(registrationData.profileKey) val accountManager: SignalServiceAccountManager = AccountManagerFactory.createUnauthenticated( context, registrationData.e164, SignalServiceAddress.DEFAULT_DEVICE_ID, registrationData.password ) return Single.fromCallable { try { val kbsData: KbsPinData = KbsRepository.restoreMasterKey(pin, tokenData.enclave, tokenData.basicAuth, tokenData.tokenResponse)!! val registrationLockV2: String = kbsData.masterKey.deriveRegistrationLock() val response: ServiceResponse<VerifyAccountResponse> = accountManager.verifyAccountWithRegistrationLockPin( registrationData.code, registrationData.registrationId, registrationData.isNotFcm, registrationLockV2, unidentifiedAccessKey, universalUnidentifiedAccess, AppCapabilities.getCapabilities(true), SignalStore.phoneNumberPrivacy().phoneNumberListingMode.isDiscoverable, registrationData.pniRegistrationId ) VerifyAccountWithRegistrationLockResponse.from(response, kbsData) } catch (e: KeyBackupSystemWrongPinException) { ServiceResponse.forExecutionError(e) } catch (e: KeyBackupSystemNoDataException) { ServiceResponse.forExecutionError(e) } catch (e: IOException) { ServiceResponse.forExecutionError(e) } }.subscribeOn(Schedulers.io()) } enum class Mode(val isSmsRetrieverSupported: Boolean) { SMS_WITH_LISTENER(true), SMS_WITHOUT_LISTENER(false), PHONE_CALL(false); } companion object { private val TAG = Log.tag(VerifyAccountRepository::class.java) private val PUSH_REQUEST_TIMEOUT = TimeUnit.SECONDS.toMillis(5) } data class VerifyAccountWithRegistrationLockResponse(val verifyAccountResponse: VerifyAccountResponse, val kbsData: KbsPinData) { companion object { fun from(response: ServiceResponse<VerifyAccountResponse>, kbsData: KbsPinData): ServiceResponse<VerifyAccountWithRegistrationLockResponse> { return if (response.result.isPresent) { ServiceResponse.forResult(VerifyAccountWithRegistrationLockResponse(response.result.get(), kbsData), 200, null) } else { ServiceResponse.coerceError(response) } } } } }
gpl-3.0
d87e04a0c5179e8b395273ebfda94956
43.23741
167
0.781428
4.748263
false
false
false
false
androidx/androidx
datastore/datastore-rxjava2/src/test-common/java/androidx/datastore/rxjava2/TestingSerializer.kt
3
1755
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.datastore.rxjava2 import androidx.datastore.core.CorruptionException import androidx.datastore.core.Serializer import java.io.IOException import java.io.InputStream import java.io.OutputStream class TestingSerializer( @Volatile var failReadWithCorruptionException: Boolean = false, @Volatile var failingRead: Boolean = false, @Volatile var failingWrite: Boolean = false ) : Serializer<Byte> { override suspend fun readFrom(input: InputStream): Byte { if (failReadWithCorruptionException) { throw CorruptionException( "CorruptionException", IOException() ) } if (failingRead) { throw IOException("I was asked to fail on reads") } val read = input.read() if (read == -1) { return 0 } return read.toByte() } override suspend fun writeTo(t: Byte, output: OutputStream) { if (failingWrite) { throw IOException("I was asked to fail on writes") } output.write(t.toInt()) } override val defaultValue: Byte = 0 }
apache-2.0
1c9e93e9587ad7e98553cd69af3593a0
29.807018
75
0.669516
4.582245
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/conversationlist/ConversationListFilterPullView.kt
1
1970
package org.thoughtcrime.securesms.conversationlist import android.content.Context import android.os.Build import android.provider.Settings import android.util.AttributeSet import android.view.HapticFeedbackConstants import android.widget.FrameLayout import androidx.core.content.ContextCompat import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.databinding.ConversationListFilterPullViewBinding /** * Encapsulates the push / pull latch for enabling and disabling * filters into a convenient view. */ class ConversationListFilterPullView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : FrameLayout(context, attrs) { private val colorPull = ContextCompat.getColor(context, R.color.signal_colorSurface1) private val colorRelease = ContextCompat.getColor(context, R.color.signal_colorSecondaryContainer) private var state: State = State.PULL init { inflate(context, R.layout.conversation_list_filter_pull_view, this) setBackgroundColor(colorPull) } private val binding = ConversationListFilterPullViewBinding.bind(this) fun setToPull() { if (state == State.PULL) { return } state = State.PULL setBackgroundColor(colorPull) binding.arrow.setImageResource(R.drawable.ic_arrow_down) binding.text.setText(R.string.ConversationListFilterPullView__pull_down_to_filter) } fun setToRelease() { if (state == State.RELEASE) { return } if (Settings.System.getInt(context.contentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) != 0) { performHapticFeedback(if (Build.VERSION.SDK_INT >= 30) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.KEYBOARD_TAP) } state = State.RELEASE setBackgroundColor(colorRelease) binding.arrow.setImageResource(R.drawable.ic_arrow_up_16) binding.text.setText(R.string.ConversationListFilterPullView__release_to_filter) } enum class State { RELEASE, PULL } }
gpl-3.0
7035fdb245ec46ed5d5d5076c2371577
30.269841
135
0.767513
4.200426
false
false
false
false
Soya93/Extract-Refactoring
plugins/settings-repository/src/git/JGitMergeProvider.kt
9
4510
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository.git import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.vcs.merge.MergeData import com.intellij.openapi.vcs.merge.MergeProvider2 import com.intellij.openapi.vcs.merge.MergeSession import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtil import com.intellij.util.ui.ColumnInfo import org.eclipse.jgit.lib.Repository import org.jetbrains.jgit.dirCache.deletePath import org.jetbrains.jgit.dirCache.writePath import org.jetbrains.settingsRepository.RepositoryVirtualFile import java.nio.CharBuffer import java.util.* internal fun conflictsToVirtualFiles(map: Map<String, Any>): MutableList<VirtualFile> { val result = ArrayList<VirtualFile>(map.size) for (path in map.keys) { result.add(RepositoryVirtualFile(path)) } return result } /** * If content null: * Ours or Theirs - deleted. * Base - missed (no base). */ class JGitMergeProvider<T>(private val repository: Repository, private val conflicts: Map<String, T>, private val pathToContent: Map<String, T>.(path: String, index: Int) -> ByteArray?) : MergeProvider2 { override fun createMergeSession(files: List<VirtualFile>): MergeSession = JGitMergeSession() override fun conflictResolvedForFile(file: VirtualFile) { // we can postpone dir cache update (on merge dialog close) to reduce number of flush, but it can leads to data loss (if app crashed during merge - nothing will be saved) // update dir cache val bytes = (file as RepositoryVirtualFile).content // not null if user accepts some revision (virtual file will be directly modified), otherwise document will be modified if (bytes == null) { val chars = FileDocumentManager.getInstance().getCachedDocument(file)!!.immutableCharSequence val byteBuffer = CharsetToolkit.UTF8_CHARSET.encode(CharBuffer.wrap(chars)) addFile(byteBuffer.array(), file, byteBuffer.remaining()) } else { addFile(bytes, file) } } private fun addFile(bytes: ByteArray, file: VirtualFile, size: Int = bytes.size) { repository.writePath(file.path, bytes, size) } override fun isBinary(file: VirtualFile) = file.fileType.isBinary override fun loadRevisions(file: VirtualFile): MergeData { val path = file.path val mergeData = MergeData() mergeData.ORIGINAL = getContentOrEmpty(path, 0) mergeData.CURRENT = getContentOrEmpty(path, 1) mergeData.LAST = getContentOrEmpty(path, 2) return mergeData } private fun getContentOrEmpty(path: String, index: Int) = conflicts.pathToContent(path, index) ?: ArrayUtil.EMPTY_BYTE_ARRAY private inner class JGitMergeSession : MergeSession { override fun getMergeInfoColumns(): Array<ColumnInfo<out Any?, out Any?>> { return arrayOf(StatusColumn(false), StatusColumn(true)) } override fun canMerge(file: VirtualFile) = conflicts.contains(file.path) override fun conflictResolvedForFile(file: VirtualFile, resolution: MergeSession.Resolution) { if (resolution == MergeSession.Resolution.Merged) { conflictResolvedForFile(file) } else { val content = getContent(file, resolution == MergeSession.Resolution.AcceptedTheirs) if (content == null) { repository.deletePath(file.path) } else { addFile(content, file) } } } private fun getContent(file: VirtualFile, isTheirs: Boolean) = conflicts.pathToContent(file.path, if (isTheirs) 2 else 1) inner class StatusColumn(private val isTheirs: Boolean) : ColumnInfo<VirtualFile, String>(if (isTheirs) "Theirs" else "Yours") { override fun valueOf(file: VirtualFile?) = if (getContent(file!!, isTheirs) == null) "Deleted" else "Modified" override fun getMaxStringValue() = "Modified" override fun getAdditionalWidth() = 10 } } }
apache-2.0
9f81b27de885e930af06cbc96ebb1d3e
38.920354
204
0.73459
4.283001
false
false
false
false
danwallach/CalWatch
app/src/main/kotlin/org/dwallach/calwatch2/PreferencesHelper.kt
1
2744
/* * CalWatch / CalWatch2 * Copyright © 2014-2022 by Dan S. Wallach * Home page: http://www.cs.rice.edu/~dwallach/calwatch/ * Licensing: http://www.cs.rice.edu/~dwallach/calwatch/licensing.html */ package org.dwallach.calwatch2 import android.content.Context import android.util.Log import androidx.core.content.edit private val TAG = "PreferencesHelper" /** * Support for saving and loading preferences to persistent storage. */ object PreferencesHelper { // @SuppressLint("CommitPrefEdits") fun savePreferences(context: Context) = context.getSharedPreferences(Constants.PREFS_KEY, Context.MODE_PRIVATE).edit { putInt("faceMode", ClockState.faceMode) putBoolean("showSeconds", ClockState.showSeconds) putBoolean("showDayDate", ClockState.showDayDate) putInt("preferencesVersion", 3) Log.v(TAG, "savePreferences: ${ClockState.faceMode}, showSeconds: ${ClockState.showSeconds}, showDayDate: ${ClockState.showDayDate}") if (!commit()) Log.e(TAG, "savePreferences commit failed ?!") } /** * Updates the preferences in ClockState, returns an integer version number. So far, * the choices are "0", meaning it didn't find a version number in placed, and "3", * which is the newest version. This will help with legacy migration. (If the version * is zero, then some of the values in ClockState will have been set from the defaults.) */ fun loadPreferences(context: Context): Int = with(context.getSharedPreferences(Constants.PREFS_KEY, Context.MODE_PRIVATE)) { val faceMode = getInt("faceMode", Constants.DEFAULT_WATCHFACE) val showSeconds = getBoolean("showSeconds", Constants.DEFAULT_SHOW_SECONDS) val showDayDate = getBoolean("showDayDate", Constants.DEFAULT_SHOW_DAY_DATE) val version = getInt("preferencesVersion", 0) Log.v(TAG, "loadPreferences: $faceMode, showSeconds: $showSeconds, showDayDate: $showDayDate, preferencesVersion: $version") ClockState.faceMode = faceMode ClockState.showSeconds = showSeconds ClockState.showDayDate = showDayDate Utilities.redrawEverything() return version // Kotlin engineering note: return inside of a lambda will return from the nearest enclosing `fun`, // so the above code has the desired effect. // https://www.reddit.com/r/Kotlin/comments/3yybyf/returning_from_lambda_functions/? // Curiously, this only really works because `with` is an inline function // https://kotlinlang.org/docs/reference/inline-functions.html#non-local-returns } }
gpl-3.0
0ca893426f585f96584db0b26eaa0fb5
41.859375
145
0.677725
4.312893
false
false
false
false
robohorse/RoboPOJOGenerator
generator/src/main/kotlin/com/robohorse/robopojogenerator/parser/JsonObjectParser.kt
1
2752
package com.robohorse.robopojogenerator.parser import com.robohorse.robopojogenerator.properties.ClassEnum import com.robohorse.robopojogenerator.properties.ClassField import com.robohorse.robopojogenerator.properties.ClassItem import com.robohorse.robopojogenerator.properties.JsonModel.JsonItem import com.robohorse.robopojogenerator.properties.JsonModel.JsonItemArray import com.robohorse.robopojogenerator.properties.templates.ImportsTemplate import com.robohorse.robopojogenerator.utils.ClassGenerateHelper import org.json.JSONArray import org.json.JSONObject internal class JsonObjectParser( private val classGenerateHelper: ClassGenerateHelper ) { fun parseJsonObject( jsonItem: JsonItem, classesMap: LinkedHashMap<String?, ClassItem>, classItem: ClassItem, jsonCallback: (innerJsonItem: JsonItem, classesMap: LinkedHashMap<String?, ClassItem>) -> Unit, arrayCallback: ( innerJsonItem: JsonItemArray, classField: ClassField, classesMap: LinkedHashMap<String?, ClassItem> ) -> Unit ) { for (jsonObjectKey in jsonItem.jsonObject.keySet()) { val itemObject = jsonItem.jsonObject[jsonObjectKey] val classFieldsParser = object : ClassFieldsParser() { override fun onPlainTypeRecognised(classEnum: ClassEnum?) { classItem.classFields[jsonObjectKey] = ClassField(classEnum) } override fun onJsonTypeRecognised() { val className = classGenerateHelper.formatClassName(jsonObjectKey) val classField = ClassField(null, className) val innerJsonItem = JsonItem(jsonObjectKey, (itemObject as JSONObject)) classItem.classFields[jsonObjectKey] = classField jsonCallback.invoke(innerJsonItem, classesMap) } override fun onJsonArrayTypeRecognised() { val jsonArray = itemObject as JSONArray classItem.classImports.add(ImportsTemplate.LIST) val classField = ClassField() if (jsonArray.length() == 0) { classField.classField = ClassField(ClassEnum.OBJECT) classItem.classFields[jsonObjectKey] = classField } else { val jsonItemArray = JsonItemArray(jsonObjectKey, itemObject) arrayCallback.invoke(jsonItemArray, classField, classesMap) classItem.classFields[jsonObjectKey] = classField } } } classFieldsParser.parseField(itemObject) } } }
mit
f39f6b0d0e28460b49ef048569b82b3d
44.114754
103
0.646439
5.28215
false
false
false
false
google/android-auto-companion-android
trustagent/src/com/google/android/libraries/car/trustagent/VersionResolver.kt
1
5746
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.trustagent import androidx.annotation.VisibleForTesting import com.google.android.companionprotos.VersionExchangeProto.VersionExchange import com.google.android.libraries.car.trustagent.blemessagestream.BluetoothConnectionManager import com.google.android.libraries.car.trustagent.util.loge import com.google.android.libraries.car.trustagent.util.logi import com.google.android.libraries.car.trustagent.util.logw import com.google.protobuf.InvalidProtocolBufferException import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine import kotlin.math.max import kotlin.math.min /** * Handles version exchange. * * @property manager provides the bluetooth connection with the remote device. */ internal class VersionResolver(private val manager: BluetoothConnectionManager) { /** * Exchanges supported version with [manager]. * * @return The received version; `null` if there was an error during exchange. */ suspend fun exchangeVersion(): VersionExchange? = suspendCoroutine<VersionExchange?> { continuation -> val messageCallback = object : BluetoothConnectionManager.MessageCallback { override fun onMessageReceived(data: ByteArray) { manager.unregisterMessageCallback(this) val remoteVersion = try { VersionExchange.parseFrom(data) } catch (e: InvalidProtocolBufferException) { loge(TAG, "Could not parse message from car as BLEVersionExchange.", e) null } logi(TAG, "Remote BleVersionExchange is ${remoteVersion?.asString()}") continuation.resume(remoteVersion) } } manager.registerMessageCallback(messageCallback) val versionExchange = makeVersionExchange().also { logi(TAG, "Sending version exchange: ${it.asString()}") } // After sending version exchange, gattMessageCallback will be triggered. if (!manager.sendMessage(versionExchange.toByteArray())) { logw(TAG, "Could not send message to init version exchange. Disconnecting.") manager.unregisterMessageCallback(messageCallback) manager.disconnect() continuation.resume(null) } } /** Returns the resolved version between local and [remoteVersion]; `null` if not compatible. */ fun resolveVersion(remoteVersion: VersionExchange): ResolvedVersion? { val maxSecurityVersion = min(remoteVersion.maxSupportedSecurityVersion, MAX_SECURITY_VERSION) val minSecurityVersion = max(remoteVersion.minSupportedSecurityVersion, MIN_SECURITY_VERSION) val maxMessageVersion = min(remoteVersion.maxSupportedMessagingVersion, MAX_MESSAGING_VERSION) val minMessageVersion = max(remoteVersion.minSupportedMessagingVersion, MIN_MESSAGING_VERSION) if (minSecurityVersion > maxSecurityVersion || minMessageVersion > maxMessageVersion) { loge( TAG, """ |Local version is ${makeVersionExchange().asString()}; |remote version is ${remoteVersion.asString()}. """.trimMargin() ) return null } logi(TAG, "Resolved message version $maxMessageVersion; security version $maxSecurityVersion.") return ResolvedVersion( maxMessageVersion, maxSecurityVersion, ) } companion object { private const val TAG = "VersionResolver" const val MIN_MESSAGING_VERSION = 2 const val MAX_MESSAGING_VERSION = 3 const val MIN_SECURITY_VERSION = 2 const val MAX_SECURITY_VERSION = 4 /** * Resolves version via [manager]. * * Returns [ResolvedVersion] based on the message version of IHU; `null` if local and remote * versions are incompatible or an error occurred. */ suspend fun resolve(manager: BluetoothConnectionManager): ResolvedVersion? { val resolver = VersionResolver(manager) val remoteVersion = resolver.exchangeVersion() return remoteVersion?.let { resolver.resolveVersion(it) } } /** Creates a proto that represents the locally supported version. */ @VisibleForTesting internal fun makeVersionExchange( minMessagingVersion: Int = MIN_MESSAGING_VERSION, maxMessagingVersion: Int = MAX_MESSAGING_VERSION, minSecurityVersion: Int = MIN_SECURITY_VERSION, maxSecurityVersion: Int = MAX_SECURITY_VERSION ) = VersionExchange.newBuilder() .setMinSupportedMessagingVersion(minMessagingVersion) .setMaxSupportedMessagingVersion(maxMessagingVersion) .setMinSupportedSecurityVersion(minSecurityVersion) .setMaxSupportedSecurityVersion(maxSecurityVersion) .build() } } // Proto toString() is not available in proto lite. private fun VersionExchange.asString() = """ |min security version: ${this.minSupportedSecurityVersion}; |max security version: ${this.maxSupportedSecurityVersion}; |min message version: ${this.minSupportedMessagingVersion}; |max message version: ${this.maxSupportedMessagingVersion}. """.trimMargin() internal data class ResolvedVersion( val messageVersion: Int, val securityVersion: Int, )
apache-2.0
1d762c4b9096ac8210923d1aaa89f2f7
38.902778
99
0.724504
4.721446
false
false
false
false
wealthfront/magellan
magellan-sample-advanced/src/main/java/com/wealthfront/magellan/sample/advanced/ToolbarHelper.kt
1
1134
package com.wealthfront.magellan.sample.advanced import android.view.View.GONE import android.view.View.VISIBLE import androidx.appcompat.app.ActionBar import androidx.appcompat.widget.Toolbar import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner class ToolbarHelper : LifecycleEventObserver { private var toolbar: Toolbar? = null private var actionBar: ActionBar? = null override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { if (event == Lifecycle.Event.ON_CREATE) { toolbar = (source as MainActivity).findViewById(R.id.toolbar) source.setSupportActionBar(toolbar) this.actionBar = source.supportActionBar actionBar!!.setDisplayHomeAsUpEnabled(true) actionBar!!.setDisplayShowTitleEnabled(true) } else if (event == Lifecycle.Event.ON_DESTROY) { toolbar = null actionBar = null } } fun setTitle(title: String) { actionBar!!.title = title } fun showToolbar() { toolbar!!.visibility = VISIBLE } fun hideToolbar() { toolbar!!.visibility = GONE } }
apache-2.0
3451eea9340cca046c023e758736d87e
27.35
79
0.739859
4.647541
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/reference/GotoReference.kt
2
2153
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.reference import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiReferenceBase import com.intellij.util.IncorrectOperationException import com.tang.intellij.lua.psi.LuaElementFactory import com.tang.intellij.lua.psi.LuaGotoStat import com.tang.intellij.lua.psi.LuaLabelStat import com.tang.intellij.lua.psi.LuaPsiTreeUtil class GotoReference(val goto: LuaGotoStat) : PsiReferenceBase<LuaGotoStat>(goto) { val id = goto.id!! override fun getVariants(): Array<Any> = arrayOf() @Throws(IncorrectOperationException::class) override fun handleElementRename(newElementName: String): PsiElement { val newId = LuaElementFactory.createIdentifier(myElement.project, newElementName) id.replace(newId) return newId } override fun getRangeInElement(): TextRange { val start = id.node.startOffset - myElement.node.startOffset return TextRange(start, start + id.textLength) } override fun isReferenceTo(element: PsiElement): Boolean { return myElement.manager.areElementsEquivalent(resolve(), element) } override fun resolve(): PsiElement? { val name = id.text var result: PsiElement? = null LuaPsiTreeUtil.walkUpLabel(goto) { if (it.name == name) { result = it return@walkUpLabel false } return@walkUpLabel true } return result } }
apache-2.0
b051947670d353f1e193d388eba581f1
32.65625
89
0.710636
4.3583
false
false
false
false
inorichi/tachiyomi-extensions
src/zh/dmzj/src/eu/kanade/tachiyomi/extension/zh/dmzj/Dmzj.kt
1
25780
package eu.kanade.tachiyomi.extension.zh.dmzj import android.app.Application import android.content.SharedPreferences import android.net.Uri import android.util.Base64 import androidx.preference.ListPreference import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.extension.zh.dmzj.protobuf.ComicDetailResponse import eu.kanade.tachiyomi.extension.zh.dmzj.utils.RSA import eu.kanade.tachiyomi.lib.ratelimit.SpecificHostRateLimitInterceptor import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.ConfigurableSource import eu.kanade.tachiyomi.source.model.Filter 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 kotlinx.serialization.decodeFromByteArray import kotlinx.serialization.protobuf.ProtoBuf import okhttp3.Headers import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.json.JSONArray import org.json.JSONObject import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.net.URLDecoder import java.net.URLEncoder /** * Dmzj source */ class Dmzj : ConfigurableSource, HttpSource() { override val lang = "zh" override val supportsLatest = true override val name = "动漫之家" override val baseUrl = "https://m.dmzj.com" private val v3apiUrl = "https://v3api.dmzj.com" private val v3ChapterApiUrl = "https://nnv3api.muwai.com" // v3api now shutdown the functionality to fetch manga detail and chapter list, so move these logic to v4api private val v4apiUrl = "https://nnv4api.muwai.com" // https://v4api.dmzj1.com private val apiUrl = "https://api.dmzj.com" private val oldPageListApiUrl = "https://api.m.dmzj.com" private val webviewPageListApiUrl = "https://m.dmzj.com/chapinfo" private val imageCDNUrl = "https://images.muwai.com" private fun cleanUrl(url: String) = if (url.startsWith("//")) "https:$url" else url private val preferences: SharedPreferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } private val v3apiRateLimitInterceptor = SpecificHostRateLimitInterceptor( v3apiUrl.toHttpUrlOrNull()!!, preferences.getString(API_RATELIMIT_PREF, "5")!!.toInt() ) private val v4apiRateLimitInterceptor = SpecificHostRateLimitInterceptor( v4apiUrl.toHttpUrlOrNull()!!, preferences.getString(API_RATELIMIT_PREF, "5")!!.toInt() ) private val apiRateLimitInterceptor = SpecificHostRateLimitInterceptor( apiUrl.toHttpUrlOrNull()!!, preferences.getString(API_RATELIMIT_PREF, "5")!!.toInt() ) private val imageCDNRateLimitInterceptor = SpecificHostRateLimitInterceptor( imageCDNUrl.toHttpUrlOrNull()!!, preferences.getString(IMAGE_CDN_RATELIMIT_PREF, "5")!!.toInt() ) override val client: OkHttpClient = network.client.newBuilder() .addNetworkInterceptor(apiRateLimitInterceptor) .addNetworkInterceptor(v3apiRateLimitInterceptor) .addNetworkInterceptor(v4apiRateLimitInterceptor) .addNetworkInterceptor(imageCDNRateLimitInterceptor) .build() override fun headersBuilder() = Headers.Builder().apply { set("Referer", "https://www.dmzj.com/") set( "User-Agent", "Mozilla/5.0 (Linux; Android 10) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/88.0.4324.93 " + "Mobile Safari/537.36 " + "Tachiyomi/1.0" ) } // for simple searches (query only, no filters) private fun simpleSearchJsonParse(json: String): MangasPage { val arr = JSONArray(json) val ret = ArrayList<SManga>(arr.length()) for (i in 0 until arr.length()) { val obj = arr.getJSONObject(i) val cid = obj.getString("id") ret.add( SManga.create().apply { title = obj.getString("comic_name") thumbnail_url = cleanUrl(obj.getString("comic_cover")) author = obj.optString("comic_author") url = "/comic/comic_$cid.json?version=2.7.019" } ) } return MangasPage(ret, false) } // for popular, latest, and filtered search private fun mangaFromJSON(json: String): MangasPage { val arr = JSONArray(json) val ret = ArrayList<SManga>(arr.length()) for (i in 0 until arr.length()) { val obj = arr.getJSONObject(i) val cid = obj.getString("id") ret.add( SManga.create().apply { title = obj.getString("title") thumbnail_url = obj.getString("cover") author = obj.optString("authors") status = when (obj.getString("status")) { "已完结" -> SManga.COMPLETED "连载中" -> SManga.ONGOING else -> SManga.UNKNOWN } url = "/comic/comic_$cid.json?version=2.7.019" } ) } return MangasPage(ret, arr.length() != 0) } private fun customUrlBuilder(baseUrl: String): HttpUrl.Builder { val rightNow = System.currentTimeMillis() / 1000 return baseUrl.toHttpUrlOrNull()!!.newBuilder() .addQueryParameter("channel", "android") .addQueryParameter("version", "3.0.0") .addQueryParameter("timestamp", rightNow.toInt().toString()) } private fun decryptProtobufData(rawData: String): ByteArray { return RSA.decrypt(Base64.decode(rawData, Base64.DEFAULT), privateKey) } override fun popularMangaRequest(page: Int) = GET("$v3apiUrl/classify/0/0/${page - 1}.json") override fun popularMangaParse(response: Response) = searchMangaParse(response) override fun latestUpdatesRequest(page: Int) = GET("$v3apiUrl/classify/0/1/${page - 1}.json") override fun latestUpdatesParse(response: Response): MangasPage = searchMangaParse(response) private fun searchMangaById(id: String): MangasPage { val comicNumberID = if (checkComicIdIsNumericalRegex.matches(id)) { id } else { // Chinese Pinyin ID val document = client.newCall(GET("$baseUrl/info/$id.html", headers)).execute().asJsoup() extractComicIdFromWebpageRegex.find( document.select("#Subscribe").attr("onclick") )!!.groups[1]!!.value // onclick="addSubscribe('{comicNumberID}')" } val sManga = try { val r = client.newCall(GET("$v4apiUrl/comic/detail/$comicNumberID.json", headers)).execute() mangaDetailsParse(r) } catch (_: Exception) { val r = client.newCall(GET("$apiUrl/dynamic/comicinfo/$comicNumberID.json", headers)).execute() mangaDetailsParse(r) } // Change url format to as same as mangaFromJSON, which used by popularMangaParse and latestUpdatesParse. // manga.url being used as key to identity a manga in tachiyomi, so if url format don't match popularMangaParse and latestUpdatesParse, // tachiyomi will mark them as unsubscribe in popularManga and latestUpdates page. sManga.url = "/comic/comic_$comicNumberID.json?version=2.7.019" return MangasPage(listOf(sManga), false) } override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { return if (query.startsWith(PREFIX_ID_SEARCH)) { // ID may be numbers or Chinese pinyin val id = query.removePrefix(PREFIX_ID_SEARCH).removeSuffix(".html") Observable.just(searchMangaById(id)) } else { client.newCall(searchMangaRequest(page, query, filters)) .asObservableSuccess() .map { response -> searchMangaParse(response) } } } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { if (query != "") { val uri = Uri.parse("http://s.acg.dmzj.com/comicsum/search.php").buildUpon() uri.appendQueryParameter("s", query) return GET(uri.toString()) } else { var params = filters.map { if (it !is SortFilter && it is UriPartFilter) { it.toUriPart() } else "" }.filter { it != "" }.joinToString("-") if (params == "") { params = "0" } val order = filters.filterIsInstance<SortFilter>().joinToString("") { (it as UriPartFilter).toUriPart() } return GET("$v3apiUrl/classify/$params/$order/${page - 1}.json") } } override fun searchMangaParse(response: Response): MangasPage { val body = response.body!!.string() return if (body.contains("g_search_data")) { simpleSearchJsonParse(body.substringAfter("=").trim().removeSuffix(";")) } else { mangaFromJSON(body) } } // Bypass mangaDetailsRequest, fetch api url directly override fun fetchMangaDetails(manga: SManga): Observable<SManga> { val cid = extractComicIdFromMangaUrlRegex.find(manga.url)!!.groups[1]!!.value return try { // Not using client.newCall().asObservableSuccess() to ensure we can catch exception here. val response = client.newCall( GET( customUrlBuilder("$v4apiUrl/comic/detail/$cid").build().toString(), headers ) ).execute() val sManga = mangaDetailsParse(response).apply { initialized = true } Observable.just(sManga) } catch (e: Exception) { val response = client.newCall(GET("$apiUrl/dynamic/comicinfo/$cid.json", headers)).execute() val sManga = mangaDetailsParse(response).apply { initialized = true } Observable.just(sManga) } catch (e: Exception) { Observable.error(e) } } // Workaround to allow "Open in browser" use human readable webpage url. override fun mangaDetailsRequest(manga: SManga): Request { val cid = extractComicIdFromMangaUrlRegex.find(manga.url)!!.groups[1]!!.value return GET("$baseUrl/info/$cid.html") } override fun mangaDetailsParse(response: Response) = SManga.create().apply { val responseBody = response.body!!.string() if (response.request.url.toString().startsWith(v4apiUrl)) { val pb = ProtoBuf.decodeFromByteArray<ComicDetailResponse>(decryptProtobufData(responseBody)) val pbData = pb.Data title = pbData.Title thumbnail_url = pbData.Cover author = pbData.Authors.joinToString(separator = ", ") { it.TagName } genre = pbData.TypesTypes.joinToString(separator = ", ") { it.TagName } status = when (pbData.Status[0].TagName) { "已完结" -> SManga.COMPLETED "连载中" -> SManga.ONGOING else -> SManga.UNKNOWN } description = pbData.Description } else { val obj = JSONObject(responseBody) val data = obj.getJSONObject("data").getJSONObject("info") title = data.getString("title") thumbnail_url = data.getString("cover") author = data.getString("authors") genre = data.getString("types").replace("/", ", ") status = when (data.getString("status")) { "连载中" -> SManga.ONGOING "已完结" -> SManga.COMPLETED else -> SManga.UNKNOWN } description = data.getString("description") } } override fun chapterListRequest(manga: SManga): Request = throw UnsupportedOperationException("Not used.") override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> { val cid = extractComicIdFromMangaUrlRegex.find(manga.url)!!.groups[1]!!.value return if (manga.status != SManga.LICENSED) { try { val response = client.newCall( GET( customUrlBuilder("$v4apiUrl/comic/detail/$cid").build().toString(), headers ) ).execute() Observable.just(chapterListParse(response)) } catch (e: Exception) { val response = client.newCall(GET("$apiUrl/dynamic/comicinfo/$cid.json", headers)).execute() Observable.just(chapterListParse(response)) } catch (e: Exception) { Observable.error(e) } } else { Observable.error(Exception("Licensed - No chapters to show")) } } override fun chapterListParse(response: Response): List<SChapter> { val ret = ArrayList<SChapter>() val responseBody = response.body!!.string() if (response.request.url.toString().startsWith(v4apiUrl)) { val pb = ProtoBuf.decodeFromByteArray<ComicDetailResponse>(decryptProtobufData(responseBody)) val mangaPBData = pb.Data // v4api can contain multiple series of chapters. if (mangaPBData.Chapters.isEmpty()) { throw Exception("empty chapter list") } mangaPBData.Chapters.forEach { chapterList -> for (i in chapterList.Data.indices) { val chapter = chapterList.Data[i] ret.add( SChapter.create().apply { name = "${chapterList.Title}: ${chapter.ChapterTitle}" date_upload = chapter.Updatetime * 1000 url = "${mangaPBData.Id}/${chapter.ChapterId}" } ) } } } else { // get chapter info from old api // Old api may only contain one series of chapters val obj = JSONObject(responseBody) val chaptersList = obj.getJSONObject("data").getJSONArray("list") for (i in 0 until chaptersList.length()) { val chapter = chaptersList.getJSONObject(i) ret.add( SChapter.create().apply { name = chapter.getString("chapter_name") date_upload = chapter.getString("updatetime").toLong() * 1000 url = "${chapter.getString("comic_id")}/${chapter.getString("id")}" } ) } } return ret } override fun pageListRequest(chapter: SChapter) = throw UnsupportedOperationException("Not used.") override fun fetchPageList(chapter: SChapter): Observable<List<Page>> { return try { // webpage api val response = client.newCall(GET("$webviewPageListApiUrl/${chapter.url}.html", headers)).execute() Observable.just(pageListParse(response)) } catch (e: Exception) { // api.m.dmzj.com val response = client.newCall(GET("$oldPageListApiUrl/comic/chapter/${chapter.url}.html", headers)).execute() Observable.just(pageListParse(response)) } catch (e: Exception) { // v3api val response = client.newCall( GET( customUrlBuilder("$v3ChapterApiUrl/chapter/${chapter.url}.json").build().toString(), headers ) ).execute() Observable.just(pageListParse(response)) } catch (e: Exception) { Observable.error(e) } } override fun pageListParse(response: Response): List<Page> { val requestUrl = response.request.url.toString() val responseBody = response.body!!.string() val arr = if ( requestUrl.startsWith(webviewPageListApiUrl) || requestUrl.startsWith(v3ChapterApiUrl) ) { // webpage api or v3api JSONObject(responseBody).getJSONArray("page_url") } else if (requestUrl.startsWith(oldPageListApiUrl)) { try { val obj = JSONObject(responseBody) obj.getJSONObject("chapter").getJSONArray("page_url") } catch (e: org.json.JSONException) { // JSON data from api.m.dmzj.com may be incomplete, extract page_url list using regex val extractPageList = extractPageListRegex.find(responseBody)!!.value JSONObject("{$extractPageList}").getJSONArray("page_url") } } else { throw Exception("can't parse response") } val ret = ArrayList<Page>(arr.length()) for (i in 0 until arr.length()) { // Seems image urls from webpage api and api.m.dmzj.com may be URL encoded multiple times val url = URLDecoder.decode(URLDecoder.decode(arr.getString(i), "UTF-8"), "UTF-8") .replace("http:", "https:") .replace("dmzj1.com", "dmzj.com") ret.add(Page(i, "", url)) } return ret } private fun String.encoded(): String { return this.chunked(1) .joinToString("") { if (it in setOf("%", " ", "+", "#")) URLEncoder.encode(it, "UTF-8") else it } .let { if (it.endsWith(".jp")) "${it}g" else it } } override fun imageRequest(page: Page): Request { return GET(page.imageUrl!!.encoded(), headers) } // Unused, we can get image urls directly from the chapter page override fun imageUrlParse(response: Response) = throw UnsupportedOperationException("This method should not be called!") override fun getFilterList() = FilterList( SortFilter(), GenreGroup(), StatusFilter(), TypeFilter(), ReaderFilter() ) private class GenreGroup : UriPartFilter( "分类", arrayOf( Pair("全部", ""), Pair("冒险", "4"), Pair("百合", "3243"), Pair("生活", "3242"), Pair("四格", "17"), Pair("伪娘", "3244"), Pair("悬疑", "3245"), Pair("后宫", "3249"), Pair("热血", "3248"), Pair("耽美", "3246"), Pair("其他", "16"), Pair("恐怖", "14"), Pair("科幻", "7"), Pair("格斗", "6"), Pair("欢乐向", "5"), Pair("爱情", "8"), Pair("侦探", "9"), Pair("校园", "13"), Pair("神鬼", "12"), Pair("魔法", "11"), Pair("竞技", "10"), Pair("历史", "3250"), Pair("战争", "3251"), Pair("魔幻", "5806"), Pair("扶她", "5345"), Pair("东方", "5077"), Pair("奇幻", "5848"), Pair("轻小说", "6316"), Pair("仙侠", "7900"), Pair("搞笑", "7568"), Pair("颜艺", "6437"), Pair("性转换", "4518"), Pair("高清单行", "4459"), Pair("治愈", "3254"), Pair("宅系", "3253"), Pair("萌系", "3252"), Pair("励志", "3255"), Pair("节操", "6219"), Pair("职场", "3328"), Pair("西方魔幻", "3365"), Pair("音乐舞蹈", "3326"), Pair("机战", "3325") ) ) private class StatusFilter : UriPartFilter( "连载状态", arrayOf( Pair("全部", ""), Pair("连载", "2309"), Pair("完结", "2310") ) ) private class TypeFilter : UriPartFilter( "地区", arrayOf( Pair("全部", ""), Pair("日本", "2304"), Pair("韩国", "2305"), Pair("欧美", "2306"), Pair("港台", "2307"), Pair("内地", "2308"), Pair("其他", "8453") ) ) private class SortFilter : UriPartFilter( "排序", arrayOf( Pair("人气", "0"), Pair("更新", "1") ) ) private class ReaderFilter : UriPartFilter( "读者", arrayOf( Pair("全部", ""), Pair("少年", "3262"), Pair("少女", "3263"), Pair("青年", "3264") ) ) private open class UriPartFilter( displayName: String, val vals: Array<Pair<String, String>>, defaultValue: Int = 0 ) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray(), defaultValue) { open fun toUriPart() = vals[state].second } override fun setupPreferenceScreen(screen: PreferenceScreen) { val apiRateLimitPreference = ListPreference(screen.context).apply { key = API_RATELIMIT_PREF title = API_RATELIMIT_PREF_TITLE summary = API_RATELIMIT_PREF_SUMMARY entries = ENTRIES_ARRAY entryValues = ENTRIES_ARRAY setDefaultValue("5") setOnPreferenceChangeListener { _, newValue -> try { val setting = preferences.edit().putString(API_RATELIMIT_PREF, newValue as String).commit() setting } catch (e: Exception) { e.printStackTrace() false } } } val imgCDNRateLimitPreference = ListPreference(screen.context).apply { key = IMAGE_CDN_RATELIMIT_PREF title = IMAGE_CDN_RATELIMIT_PREF_TITLE summary = IMAGE_CDN_RATELIMIT_PREF_SUMMARY entries = ENTRIES_ARRAY entryValues = ENTRIES_ARRAY setDefaultValue("5") setOnPreferenceChangeListener { _, newValue -> try { val setting = preferences.edit().putString(IMAGE_CDN_RATELIMIT_PREF, newValue as String).commit() setting } catch (e: Exception) { e.printStackTrace() false } } } screen.addPreference(apiRateLimitPreference) screen.addPreference(imgCDNRateLimitPreference) } companion object { private const val API_RATELIMIT_PREF = "apiRatelimitPreference" private const val API_RATELIMIT_PREF_TITLE = "主站每秒连接数限制" // "Ratelimit permits per second for main website" private const val API_RATELIMIT_PREF_SUMMARY = "此值影响向动漫之家网站发起连接请求的数量。调低此值可能减少发生HTTP 429(连接请求过多)错误的几率,但加载速度也会变慢。需要重启软件以生效。\n当前值:%s" // "This value affects network request amount to dmzj's url. Lower this value may reduce the chance to get HTTP 429 error, but loading speed will be slower too. Tachiyomi restart required. Current value: %s" private const val IMAGE_CDN_RATELIMIT_PREF = "imgCDNRatelimitPreference" private const val IMAGE_CDN_RATELIMIT_PREF_TITLE = "图片CDN每秒连接数限制" // "Ratelimit permits per second for image CDN" private const val IMAGE_CDN_RATELIMIT_PREF_SUMMARY = "此值影响加载图片时发起连接请求的数量。调低此值可能减小图片加载错误的几率,但加载速度也会变慢。需要重启软件以生效。\n当前值:%s" // "This value affects network request amount for loading image. Lower this value may reduce the chance to get error when loading image, but loading speed will be slower too. Tachiyomi restart required. Current value: %s" private val extractComicIdFromWebpageRegex = Regex("""addSubscribe\((\d+)\)""") private val checkComicIdIsNumericalRegex = Regex("""^\d+$""") private val extractComicIdFromMangaUrlRegex = Regex("""(\d+)\.(json|html)""") // Get comic ID from manga.url private val extractPageListRegex = Regex("""\"page_url\".+?\]""") private val ENTRIES_ARRAY = (1..10).map { i -> i.toString() }.toTypedArray() const val PREFIX_ID_SEARCH = "id:" private const val privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAK8nNR1lTnIfIes6oRWJNj3mB6OssDGx0uGMpgpbVCpf6+VwnuI2stmhZNoQcM417Iz7WqlPzbUmu9R4dEKmLGEEqOhOdVaeh9Xk2IPPjqIu5TbkLZRxkY3dJM1htbz57d/roesJLkZXqssfG5EJauNc+RcABTfLb4IiFjSMlTsnAgMBAAECgYEAiz/pi2hKOJKlvcTL4jpHJGjn8+lL3wZX+LeAHkXDoTjHa47g0knYYQteCbv+YwMeAGupBWiLy5RyyhXFoGNKbbnvftMYK56hH+iqxjtDLnjSDKWnhcB7089sNKaEM9Ilil6uxWMrMMBH9v2PLdYsqMBHqPutKu/SigeGPeiB7VECQQDizVlNv67go99QAIv2n/ga4e0wLizVuaNBXE88AdOnaZ0LOTeniVEqvPtgUk63zbjl0P/pzQzyjitwe6HoCAIpAkEAxbOtnCm1uKEp5HsNaXEJTwE7WQf7PrLD4+BpGtNKkgja6f6F4ld4QZ2TQ6qvsCizSGJrjOpNdjVGJ7bgYMcczwJBALvJWPLmDi7ToFfGTB0EsNHZVKE66kZ/8Stx+ezueke4S556XplqOflQBjbnj2PigwBN/0afT+QZUOBOjWzoDJkCQClzo+oDQMvGVs9GEajS/32mJ3hiWQZrWvEzgzYRqSf3XVcEe7PaXSd8z3y3lACeeACsShqQoc8wGlaHXIJOHTcCQQCZw5127ZGs8ZDTSrogrH73Kw/HvX55wGAeirKYcv28eauveCG7iyFR0PFB/P/EDZnyb+ifvyEFlucPUI0+Y87F" } }
apache-2.0
5cd7c36b6505766a141560c16f8d7e67
41.013356
862
0.591512
4.158982
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/groups/dto/GroupsAddress.kt
1
3293
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.groups.dto import com.google.gson.annotations.SerializedName import kotlin.Float import kotlin.Int import kotlin.String /** * @param id - Address id * @param additionalAddress - Additional address to the place (6 floor, left door) * @param address - String address to the place (Nevsky, 28) * @param cityId - City id of address * @param countryId - Country id of address * @param distance - Distance from the point * @param latitude - Address latitude * @param longitude - Address longitude * @param metroStationId - Metro id of address * @param phone - Address phone * @param timeOffset - Time offset int minutes from utc time * @param timetable - Week timetable for the address * @param title - Title of the place (Zinger, etc) * @param workInfoStatus - Status of information about timetable * @param placeId */ data class GroupsAddress( @SerializedName("id") val id: Int, @SerializedName("additional_address") val additionalAddress: String? = null, @SerializedName("address") val address: String? = null, @SerializedName("city_id") val cityId: Int? = null, @SerializedName("country_id") val countryId: Int? = null, @SerializedName("distance") val distance: Int? = null, @SerializedName("latitude") val latitude: Float? = null, @SerializedName("longitude") val longitude: Float? = null, @SerializedName("metro_station_id") val metroStationId: Int? = null, @SerializedName("phone") val phone: String? = null, @SerializedName("time_offset") val timeOffset: Int? = null, @SerializedName("timetable") val timetable: GroupsAddressTimetable? = null, @SerializedName("title") val title: String? = null, @SerializedName("work_info_status") val workInfoStatus: GroupsAddressWorkInfoStatus? = null, @SerializedName("place_id") val placeId: Int? = null )
mit
abdcdb877d0e8e75392d24497e12a26b
38.674699
82
0.687823
4.321522
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/transportation/MVVCardViewHolder.kt
1
1688
package de.tum.`in`.tumcampusapp.component.ui.transportation import android.view.View import de.tum.`in`.tumcampusapp.component.ui.overview.CardInteractionListener import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder import de.tum.`in`.tumcampusapp.component.ui.transportation.model.efa.Departure import de.tum.`in`.tumcampusapp.component.ui.transportation.model.efa.StationResult import kotlinx.android.synthetic.main.card_mvv.view.* import kotlin.math.min class MVVCardViewHolder( itemView: View, interactionListener: CardInteractionListener ) : CardViewHolder(itemView, interactionListener) { fun bind(station: StationResult, departures: List<Departure>) { with(itemView) { stationNameTextView.text = station.station val controller = TransportController(context) val items = min(departures.size, 5) if (contentContainerLayout.childCount == 0) { departures.asSequence() .take(items) .map { departure -> DepartureView(context, true).apply { val isFavorite = controller.isFavorite(departure.symbol) setSymbol(departure.symbol, isFavorite) setLine(departure.direction) setTime(departure.departureTime) } } .toList() .forEach { departureView -> contentContainerLayout.addView(departureView) } } } } }
gpl-3.0
98382b4c2e457626f7cae29e3c0fa4c0
40.195122
88
0.587678
5.341772
false
false
false
false
GKZX-HN/MyGithub
app/src/main/java/com/gkzxhn/mygithub/di/module/BaseModule.kt
1
2648
package com.gkzxhn.mygithub.di.module import android.content.Context import com.gkzxhn.mygithub.api.ExploreApi import com.gkzxhn.mygithub.api.TrendingApi import com.gkzxhn.mygithub.constant.GithubConstant import com.gkzxhn.mygithub.utils.rxbus.RxBus import com.google.gson.Gson import com.google.gson.GsonBuilder import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import dagger.Module import dagger.Provides import io.reactivex.schedulers.Schedulers import okhttp3.Cache import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.io.File import java.util.concurrent.TimeUnit import javax.inject.Named import javax.inject.Singleton /** * Created by 方 on 2017/10/19. */ @Module class BaseModule(private val context: Context) { @Singleton @Provides fun provideGson() = GsonBuilder().create() @Singleton @Provides @Named("cache_client") fun provideOkhttp(): OkHttpClient { val cacheSize = 1024 * 1024 * 10L val cacheDir = File(context.cacheDir, "http") val cache = Cache(cacheDir, cacheSize) return OkHttpClient.Builder() .cache(cache) .connectTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) // .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .build() } @Provides @Singleton @Named("trending") fun provideRetrofit(@Named("cache_client")client: OkHttpClient, gson: Gson) = Retrofit.Builder() .client(client) .baseUrl(GithubConstant.Trending_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) .build() @Provides @Singleton fun provideTrendingApi(@Named("trending") retrofit : Retrofit) = retrofit.create(TrendingApi::class.java) @Provides @Singleton fun provideRxbus() = RxBus.instance @Provides @Singleton @Named("explore") fun provideExploreRetrofit(@Named("cache_client")client: OkHttpClient) = Retrofit.Builder() .baseUrl(GithubConstant.EXPLORE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) .client(client) .build() @Provides @Singleton fun provideExploreApi(@Named("explore") retrofit : Retrofit) = retrofit.create(ExploreApi::class.java) }
gpl-3.0
61532c65a3446551e9007006a083160b
31.679012
109
0.683673
4.642105
false
false
false
false
GKZX-HN/MyGithub
app/src/main/java/com/gkzxhn/mygithub/ui/activity/RepoDetailActivity.kt
1
10092
package com.gkzxhn.mygithub.ui.activity import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.Toolbar import android.util.Log import android.view.View import android.widget.LinearLayout import com.gkzxhn.balabala.base.BaseActivity import com.gkzxhn.balabala.mvp.contract.BaseView import com.gkzxhn.mygithub.R import com.gkzxhn.mygithub.base.App import com.gkzxhn.mygithub.bean.info.Content import com.gkzxhn.mygithub.bean.info.Repo import com.gkzxhn.mygithub.constant.IntentConstant import com.gkzxhn.mygithub.di.module.OAuthModule import com.gkzxhn.mygithub.extension.base64Decode import com.gkzxhn.mygithub.extension.dp2px import com.gkzxhn.mygithub.extension.load import com.gkzxhn.mygithub.extension.toast import com.gkzxhn.mygithub.mvp.presenter.RepoDetailPresenter import com.ldoublem.loadingviewlib.view.LVNews import kotlinx.android.synthetic.main.activity_repo_detail.* import javax.inject.Inject /** * Created by 方 on 2017/10/25. */ class RepoDetailActivity:BaseActivity(),BaseView { val mTabs = listOf<String>("contributors", "forks", "issues") private lateinit var mFragments: ArrayList<Fragment> private var repo : Repo? = null private var isStarred = false private var isWatched = false private lateinit var loading: LVNews @Inject lateinit var presenter : RepoDetailPresenter override fun launchActivity(intent: Intent) { } override fun showLoading() { } override fun hideLoading() { } override fun showMessage() { } override fun killMyself() { } override fun setupComponent() { App.getInstance() .baseComponent .plus(OAuthModule(this)) .inject(this) } override fun initView(savedInstanceState: Bundle?) { setContentView(R.layout.activity_repo_detail) repo = intent.getParcelableExtra<Repo>(IntentConstant.REPO) setToolBarBack(true) toolbar.title = "" if (repo == null) { val fullName = intent.getStringExtra(IntentConstant.FULL_NAME) val list = fullName.split("/") if(list.size > 1) presenter.getRepoDetail(list[0], list[1]) else toast("请求错误,请重试") }else { initViewWithData() } } private fun initViewWithData() { stars_count = repo!!.stargazers_count watchers_count = repo!!.watchers_count appbar.addOnOffsetChangedListener { appBarLayout, verticalOffset -> Log.i(javaClass.simpleName, "verticalOffset -- : $verticalOffset total -- ${appBarLayout.totalScrollRange}") if (verticalOffset == 0) { //完全展开状态 rl_repo_head.visibility = View.VISIBLE iv_avatar_small.visibility = View.INVISIBLE toolbar_title.visibility = View.INVISIBLE } else if (Math.abs(verticalOffset) == appBarLayout.totalScrollRange) { //appBarLayout.getTotalScrollRange() == 100 //完全折叠 iv_avatar_small.visibility = View.VISIBLE toolbar_title.visibility = View.VISIBLE rl_repo_head.visibility = View.INVISIBLE } else { iv_avatar_small.visibility = View.INVISIBLE toolbar_title.visibility = View.INVISIBLE rl_repo_head.visibility = View.VISIBLE // val alpha = (1 - Math.abs(verticalOffset.toFloat()) / appBarLayout.totalScrollRange) * 255f // Log.i(javaClass.simpleName, "alpha : $alpha ~~") // rl_repo_head.background.alpha = alpha.toInt() } } setToolBar() setBaseData() presenter.getReadme(repo!!.owner.login, repo!!.name) presenter.checkIfStarred(repo!!.owner.login, repo!!.name) presenter.checkIfWatched(repo!!.owner.login, repo!!.name) setOnclick() } private var stars_count = 0 private var watchers_count = 0 private fun setBaseData() { tv_watch.setText(watchers_count.toString()) tv_stars.setText(stars_count.toString()) tv_forks.setText(repo!!.forks_count.toString()) repo_desc.text = repo!!.description tv_update_time.text = repo!!.updated_at.substring(0, repo!!.created_at.indexOf("T")) if (repo!!.fork) { iv_fork.setImageResource(R.drawable.fork_selected) }else { iv_fork.setImageResource(R.drawable.fork_normal) } } private fun setOnclick(){ ll_watch.setOnClickListener{ if (isWatched) { presenter.unwatchRepo(repo!!.owner.login, repo!!.name) }else { presenter.watchRepo(repo!!.owner.login, repo!!.name) } } ll_stars.setOnClickListener { if (isStarred) { presenter.unStarred(repo!!.owner.login, repo!!.name) }else { presenter.starRepo(repo!!.owner.login, repo!!.name) } } tv_view_issue.setOnClickListener { val intent = Intent(this, IssuesActivity::class.java) val mBundle = Bundle() mBundle.putParcelable(IntentConstant.REPO, repo) intent.putExtras(mBundle) startActivity(intent) } tv_view_project.setOnClickListener { val intent = Intent(this, ProjectListActivity::class.java) intent.putExtra(IntentConstant.OWNER, repo!!.owner.login) intent.putExtra(IntentConstant.REPO, repo!!.name) intent.putExtra(IntentConstant.TOOLBAR_TITLE, "${repo!!.name} Projects") startActivity(intent) } tv_reame_all.setOnClickListener { val layoutParams = md_view.layoutParams as LinearLayout.LayoutParams layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT md_view.layoutParams = layoutParams tv_reame_all.visibility = View.GONE } tv_view_code.setOnClickListener { // presenter.getCode(repo!!.owner.login, repo!!.name) val intent = Intent(this, FileTreeActivity::class.java) intent.putExtra(IntentConstant.NAME, repo!!.owner.login) intent.putExtra(IntentConstant.REPO, repo!!.name) startActivity(intent) } iv_avatar.setOnClickListener { gotoUser() } iv_avatar_small.setOnClickListener { gotoUser() } } /** * 跳转个人页 */ private fun gotoUser() { val owner = repo!!.owner val intent = Intent(this, UserActivity::class.java) val bundle = Bundle() bundle.putParcelable(IntentConstant.USER, owner) intent.putExtras(bundle) startActivity(intent) } @SuppressLint("ResourceAsColor") private fun setToolBar() { toolbar_title.text = repo!!.name tv_repo_name.text = repo!!.name tv_code.text = repo!!.language iv_avatar.load(this, repo!!.owner.avatar_url, R.drawable.default_avatar) iv_avatar_small.load(this, repo!!.owner.avatar_url, R.drawable.default_avatar) tv_username.text = repo!!.owner.login /*setToolbarMenuClickListener(object : Toolbar.OnMenuItemClickListener{ override fun onMenuItemClick(item: MenuItem?): Boolean { when(item!!.itemId) { R.id.toolbar_add_issue -> { val intent = Intent(this@RepoDetailActivity, EditIssueActivity::class.java) intent.putExtra(IntentConstant.NAME, repo!!.owner.login) intent.putExtra(IntentConstant.REPO, repo!!.name) startActivity(intent) } } return true } })*/ } override fun getToolbar(): Toolbar? { return toolbar } /* override fun getStatusBar(): View? { return status_view } */ /* override fun onCreateOptionsMenu(menu: Menu?): Boolean { getMenuInflater().inflate(R.menu.toolbar_menu, menu) return true }*/ fun starred(){ isStarred = true iv_stars.setImageResource(R.drawable.star_selected) } fun updateStars(add : Boolean) { tv_stars.text = (if (add) ++stars_count else --stars_count).toString() } fun unStarred(){ isStarred = false iv_stars.setImageResource(R.drawable.star_normal) } fun loadReadme(content: Content){ val layoutParams = md_view.layoutParams as LinearLayout.LayoutParams layoutParams.height = 180f.dp2px().toInt() md_view.layoutParams = layoutParams tv_reame_all.visibility = View.VISIBLE md_view.setMDText(content.content.base64Decode()) } fun showReadmeLoading() { pb_readme.visibility = View.VISIBLE } fun hideReadmeLoading() { pb_readme.visibility = View.GONE } fun showStarLoading() { pb_star.visibility = View.VISIBLE iv_stars.visibility = View.GONE } fun hideStarLoading() { pb_star.visibility = View.GONE iv_stars.visibility = View.VISIBLE } fun showWatchLoading() { pb_watch.visibility = View.VISIBLE iv_watch.visibility = View.GONE } fun hideWatchLoading() { pb_watch.visibility = View.GONE iv_watch.visibility = View.VISIBLE } fun watched() { isWatched = true iv_watch.setImageResource(R.drawable.watch_selected) } fun unwatched() { isWatched = false iv_watch.setImageResource(R.drawable.watch_normal) } fun updateWatch(add : Boolean) { tv_watch.text = (if (add) ++watchers_count else --watchers_count).toString() } fun initViewByData(repo: Repo) { this.repo = repo initViewWithData() } }
gpl-3.0
bdef3bb8b15c7090932a32fe83401b5e
30.996815
120
0.614175
4.431407
false
false
false
false
Heiner1/AndroidAPS
diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_MEAL_FAIL.kt
1
2260
package info.nightscout.androidaps.diaconn.pumplog import okhttp3.internal.and import java.nio.ByteBuffer import java.nio.ByteOrder /* * 식사주입 실패 */ class LOG_INJECT_MEAL_FAIL private constructor( val data: String, val dttm: String, typeAndKind: Byte, // 47.5=4750 private val setAmount: Short, // 47.5=4750 val injectAmount: Short, // 1분단위 주입시간(124=124분=2시간4분) private val injectTime: Byte, // 아침=1, 점심=2, 저녁=3 val time: Byte, // 1=주입막힘, 2=배터리잔량부족, 3=약물부족, 4=사용자중지, 5=시스템리셋, 6=기타, 7=긴급정지 val reason: Byte ) { val type: Byte = PumplogUtil.getType(typeAndKind) val kind: Byte = PumplogUtil.getKind(typeAndKind) fun getInjectTime(): Int { return injectTime and 0xff } override fun toString(): String { val sb = StringBuilder("LOG_INJECT_MEAL_FAIL{") sb.append("LOG_KIND=").append(LOG_KIND.toInt()) sb.append(", data='").append(data).append('\'') sb.append(", dttm='").append(dttm).append('\'') sb.append(", type=").append(type.toInt()) sb.append(", kind=").append(kind.toInt()) sb.append(", setAmount=").append(setAmount.toInt()) sb.append(", injectAmount=").append(injectAmount.toInt()) sb.append(", injectTime=").append(injectTime and 0xff) sb.append(", time=").append(time.toInt()) sb.append(", reason=").append(reason.toInt()) sb.append('}') return sb.toString() } companion object { const val LOG_KIND: Byte = 0x09 fun parse(data: String): LOG_INJECT_MEAL_FAIL { val bytes = PumplogUtil.hexStringToByteArray(data) val buffer = ByteBuffer.wrap(bytes) buffer.order(ByteOrder.LITTLE_ENDIAN) return LOG_INJECT_MEAL_FAIL( data, PumplogUtil.getDttm(buffer), PumplogUtil.getByte(buffer), PumplogUtil.getShort(buffer), PumplogUtil.getShort(buffer), PumplogUtil.getByte(buffer), PumplogUtil.getByte(buffer), PumplogUtil.getByte(buffer) ) } } }
agpl-3.0
40eda54d298ebfc61888498cd9f81d89
32.640625
84
0.592472
3.522095
false
false
false
false
k9mail/k-9
app/k9mail/src/main/java/com/fsck/k9/backends/Pop3BackendFactory.kt
2
1466
package com.fsck.k9.backends import com.fsck.k9.Account import com.fsck.k9.backend.BackendFactory import com.fsck.k9.backend.api.Backend import com.fsck.k9.backend.pop3.Pop3Backend import com.fsck.k9.mail.oauth.OAuth2TokenProvider import com.fsck.k9.mail.ssl.TrustedSocketFactory import com.fsck.k9.mail.store.pop3.Pop3Store import com.fsck.k9.mail.transport.smtp.SmtpTransport import com.fsck.k9.mailstore.K9BackendStorageFactory class Pop3BackendFactory( private val backendStorageFactory: K9BackendStorageFactory, private val trustedSocketFactory: TrustedSocketFactory ) : BackendFactory { override fun createBackend(account: Account): Backend { val accountName = account.displayName val backendStorage = backendStorageFactory.createBackendStorage(account) val pop3Store = createPop3Store(account) val smtpTransport = createSmtpTransport(account) return Pop3Backend(accountName, backendStorage, pop3Store, smtpTransport) } private fun createPop3Store(account: Account): Pop3Store { val serverSettings = account.incomingServerSettings return Pop3Store(serverSettings, trustedSocketFactory) } private fun createSmtpTransport(account: Account): SmtpTransport { val serverSettings = account.outgoingServerSettings val oauth2TokenProvider: OAuth2TokenProvider? = null return SmtpTransport(serverSettings, trustedSocketFactory, oauth2TokenProvider) } }
apache-2.0
0a63190fc71a7700eeef6a5e6210083a
40.885714
87
0.784447
4.28655
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/fir/test/org/jetbrains/kotlin/idea/fir/shortenRefs/AbstractFirShortenRefsTest.kt
2
1740
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.fir.shortenRefs import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.AbstractImportsTest import org.jetbrains.kotlin.executeOnPooledThreadInReadAction import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.utils.IgnoreTests abstract class AbstractFirShortenRefsTest : AbstractImportsTest() { override val captureExceptions: Boolean = false override fun doTest(file: KtFile): String? { val selectionModel = myFixture.editor.selectionModel if (!selectionModel.hasSelection()) error("No selection in input file") val selection = runReadAction { TextRange(selectionModel.selectionStart, selectionModel.selectionEnd) } val shortenings = executeOnPooledThreadInReadAction { analyze(file) { collectPossibleReferenceShortenings(file, selection) } } project.executeWriteCommand("") { shortenings.invokeShortening() } selectionModel.removeSelection() return null } override val runTestInWriteCommand: Boolean = false protected fun doTestWithMuting(unused: String) { IgnoreTests.runTestIfEnabledByFileDirective(dataFile().toPath(), IgnoreTests.DIRECTIVES.FIR_COMPARISON, ".after") { doTest(unused) } } override val nameCountToUseStarImportDefault: Int get() = Integer.MAX_VALUE }
apache-2.0
6a07c62cdd85d0a6f14aee3e09db982b
36.826087
123
0.736782
5.028902
false
true
false
false