repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
charroch/Kevice
src/main/kotlin/vertx/WithDevice.kt
1
2482
package vertx import java.io.File import org.vertx.java.core.http.HttpServerRequest import adb.Device import com.fasterxml.jackson.databind.JsonNode import json.JSON public trait WithDevice : WithADB, RESTx, RouteHelper { fun install(s: String, apk: File) { device(s).installPackage(apk.canonicalPath, true) } fun put(route: String, routeHandler: (HttpServerRequest, Device) -> Unit) { put(route) { req -> val serial = req?.params()?.get("serial") ?: "unknown" try { routeHandler(req!!, device(serial)) } catch(e: IllegalArgumentException) { req?.response()?.setStatusCode(404)?.setStatusMessage("device %s not found" format serial)?.end() } } } fun <T> get(route: String, routeHandler: (HttpServerRequest, Device) -> T) { get(route) { req -> val serial = req?.params()?.get("serial") ?: "unknown" try { val t = routeHandler(req!!, device(serial)) when (t) { is JSON -> req.response()?.headers()?.add("Content-Type", "application/json") } req.response()?.putHeader("Content-length", Integer.toString(t.toString().length)) req.response()?.write(t.toString())?.end() } catch(e: IllegalArgumentException) { req?.response()?.setStatusCode(404)?.setStatusMessage("device %s not found" format serial)?.end() } } } fun <T> delete(route: String, routeHandler: (HttpServerRequest, Device, String) -> T) { delete(route) { req -> val serial = req?.params()?.get("serial") ?: "unknown" val pkg = req?.params()?.get("package") try { routeHandler(req!!, device(serial), pkg!!) } catch(e: IllegalArgumentException) { req?.response()?.setStatusCode(404)?.setStatusMessage("device %s not found" format serial)?.end() } } } fun <T> post(route: String, routeHandler: (HttpServerRequest, Device) -> T) { post(route) { req -> val serial = req?.params()?.get("serial") ?: "unknown" try { routeHandler(req!!, device(serial)) } catch(e: IllegalArgumentException) { req?.response()?.setStatusCode(404)?.setStatusMessage("device %s not found" format serial)?.end() } } } }
apache-2.0
fba7d3e389b51bb648a800afc2896f08
36.621212
113
0.553989
4.369718
false
false
false
false
ktorio/ktor
ktor-io/jvm/src/io/ktor/utils/io/internal/CancellableReusableContinuation.kt
1
4318
package io.ktor.utils.io.internal import kotlinx.atomicfu.* import kotlinx.coroutines.* import kotlin.coroutines.* import kotlin.coroutines.intrinsics.* /** * Semi-cancellable reusable continuation. Unlike regular continuation this implementation has limitations: * - could be resumed only once per [completeSuspendBlock], undefined behaviour otherwise * - [T] should be neither [Throwable] nor [Continuation] * - value shouldn't be null */ internal class CancellableReusableContinuation<T : Any> : Continuation<T> { private val state = atomic<Any?>(null) private val jobCancellationHandler = atomic<JobRelation?>(null) public fun close(value: T) { resume(value) jobCancellationHandler.getAndSet(null)?.dispose() } public fun close(cause: Throwable) { resumeWithException(cause) jobCancellationHandler.getAndSet(null)?.dispose() } /** * Remember [actual] continuation or return resumed value * @return `COROUTINE_SUSPENDED` when remembered or return value if already resumed */ public fun completeSuspendBlock(actual: Continuation<T>): Any { loop@while (true) { val before = state.value when (before) { null -> { if (!state.compareAndSet(null, actual)) continue@loop parent(actual.context) return COROUTINE_SUSPENDED } else -> { if (!state.compareAndSet(before, null)) continue@loop if (before is Throwable) throw before @Suppress("UNCHECKED_CAST") return before as T } } } } private fun parent(context: CoroutineContext) { val newJob = context[Job] if (jobCancellationHandler.value?.job === newJob) return if (newJob == null) { jobCancellationHandler.getAndSet(null)?.dispose() } else { val newHandler = JobRelation(newJob) val oldJob = this.jobCancellationHandler.getAndUpdate { relation -> when { relation == null -> newHandler relation.job === newJob -> { newHandler.dispose() return } else -> newHandler } } oldJob?.dispose() } } private fun notParent(relation: JobRelation) { jobCancellationHandler.compareAndSet(relation, null) } override val context: CoroutineContext get() = (state.value as? Continuation<*>)?.context ?: EmptyCoroutineContext override fun resumeWith(result: Result<T>) { val before = state.getAndUpdate { before -> when (before) { null -> result.exceptionOrNull() ?: result.getOrThrow() is Continuation<*> -> null else -> return } } if (before is Continuation<*>) { @Suppress("UNCHECKED_CAST") val cont = before as Continuation<T> cont.resumeWith(result) } } private fun resumeWithExceptionContinuationOnly(job: Job, exception: Throwable) { @Suppress("UNCHECKED_CAST") val c = state.getAndUpdate { if (it !is Continuation<*>) return if (it.context[Job] !== job) return null } as Continuation<T> c.resumeWith(Result.failure(exception)) } private inner class JobRelation(val job: Job) : CompletionHandler { private var handler: DisposableHandle? = null // not volatile as double removal is safe init { @OptIn(InternalCoroutinesApi::class) val h = job.invokeOnCompletion(onCancelling = true, handler = this) if (job.isActive) { handler = h } } override fun invoke(cause: Throwable?) { notParent(this) dispose() if (cause != null) { resumeWithExceptionContinuationOnly(job, cause) } } public fun dispose() { handler?.let { this.handler = null it.dispose() } } } }
apache-2.0
7ca3421c5105976689327f7e042c6508
30.75
107
0.557897
5.165072
false
false
false
false
DarrenAtherton49/droid-community-app
app/src/main/kotlin/com/darrenatherton/droidcommunity/features/main/MainActivity.kt
1
6098
package com.darrenatherton.droidcommunity.features.main import android.os.Bundle import android.support.annotation.LayoutRes import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v4.view.ViewPager import android.support.v4.widget.DrawerLayout.LOCK_MODE_LOCKED_CLOSED import android.support.v4.widget.DrawerLayout.LOCK_MODE_UNLOCKED import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import com.darrenatherton.droidcommunity.R import com.darrenatherton.droidcommunity.base.presentation.BaseActivity import com.darrenatherton.droidcommunity.common.injection.component.DaggerMainViewComponent import com.darrenatherton.droidcommunity.common.injection.component.MainViewComponent import com.darrenatherton.droidcommunity.common.injection.module.MainViewModule import com.darrenatherton.droidcommunity.features.feed.FeedFragment import com.darrenatherton.droidcommunity.features.feed.SubscriptionFeedItem import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.content_main.* import kotlinx.android.synthetic.main.layout_appbar_tabs.* import javax.inject.Inject class MainActivity : BaseActivity<MainPresenter.View, MainPresenter>(), MainPresenter.View, MainNavigation, ViewPager.OnPageChangeListener, NavigationView.OnNavigationItemSelectedListener { private lateinit var mainViewComponent: MainViewComponent override val passiveView = this @Inject override lateinit var presenter: MainPresenter @LayoutRes override val layoutResId = R.layout.activity_main @Inject internal lateinit var viewPagerAdapter: MainViewPagerAdapter //=================================================================================== // Lifecycle functions and initialization //=================================================================================== override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) initTabs() // set initially selected tab presenter.onTabSelected(presenter.FEED_TAB) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId if (id == R.id.action_settings) { return true } return super.onOptionsItemSelected(item) } override fun onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.END)) { drawerLayout.closeDrawer(GravityCompat.END) } else { super.onBackPressed() } } private fun initTabs() { viewPagerAdapter.setFragments( getString(R.string.feed_title) to FeedFragment() //getString(R.string.chat_title) to FeedFragment(), //getString(R.string.events_title) to FeedFragment() ) viewPagerMain.adapter = viewPagerAdapter viewPagerMain.addOnPageChangeListener(this) tablayoutMain.setupWithViewPager(viewPagerMain) } //=================================================================================== // ViewPager callbacks //=================================================================================== override fun onPageScrollStateChanged(state: Int) {} override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { presenter.onTabSelected(position) } //=================================================================================== // DrawerLayout callbacks //=================================================================================== override fun onNavigationItemSelected(menuItem: MenuItem): Boolean { when (menuItem.itemId) { } menuItem.isChecked = true return true } //=================================================================================== // Dependency injection //=================================================================================== override fun initInjection() { mainViewComponent = DaggerMainViewComponent.builder() .appComponent(appComponent()) .activityModule(activityModule()) .mainViewModule(MainViewModule(this)) .build() mainViewComponent.inject(this) } //=================================================================================== // View functions //=================================================================================== override fun setTitleForFeed() { supportActionBar?.title = getString(R.string.feed_title) } override fun setTitleForChat() { supportActionBar?.title = getString(R.string.chat_title) } override fun setTitleForEvents() { supportActionBar?.title = getString(R.string.events_title) } override fun enableSubscriptionsMenuSwipe() { drawerLayout.setDrawerLockMode(LOCK_MODE_UNLOCKED) } override fun disableSubscriptionsMenuSwipe() { drawerLayout.setDrawerLockMode(LOCK_MODE_LOCKED_CLOSED) } //=================================================================================== // Navigation functions from fragments //=================================================================================== override fun showSubscription(subscriptionFeedItem: SubscriptionFeedItem) { //navigator.showSubscription(this, subscriptionFeedItem) } }
mit
8112253b49dbd7869bfd0c4237dbe4cd
37.847134
99
0.594293
6.06163
false
false
false
false
ktorio/ktor
buildSrc/src/main/kotlin/Publication.kt
1
6041
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ import org.gradle.api.* import org.gradle.api.publish.* import org.gradle.api.publish.maven.* import org.gradle.api.publish.maven.tasks.* import org.gradle.jvm.tasks.* import org.gradle.kotlin.dsl.* import org.gradle.plugins.signing.* import java.util.concurrent.locks.ReentrantLock fun isAvailableForPublication(publication: Publication): Boolean { val name = publication.name if (name == "maven") return true var result = false val jvmAndCommon = setOf( "jvm", "androidRelease", "androidDebug", "js", "jsLegacy", "metadata", "kotlinMultiplatform" ) result = result || name in jvmAndCommon result = result || (HOST_NAME == "linux" && name == "linuxX64") result = result || (HOST_NAME == "windows" && name == "mingwX64") val macPublications = setOf( "iosX64", "iosArm64", "iosArm32", "iosSimulatorArm64", "watchosX86", "watchosX64", "watchosArm32", "watchosArm64", "watchosSimulatorArm64", "tvosX64", "tvosArm64", "tvosSimulatorArm64", "macosX64", "macosArm64" ) result = result || (HOST_NAME == "macos" && name in macPublications) return result } fun Project.configurePublication() { if (COMMON_JVM_ONLY) return apply(plugin = "maven-publish") tasks.withType<AbstractPublishToMaven>().all { onlyIf { isAvailableForPublication(publication) } } val publishingUser: String? = System.getenv("PUBLISHING_USER") val publishingPassword: String? = System.getenv("PUBLISHING_PASSWORD") val repositoryId: String? = System.getenv("REPOSITORY_ID") val publishingUrl: String? = if (repositoryId?.isNotBlank() == true) { println("Set publishing to repository $repositoryId") "https://oss.sonatype.org/service/local/staging/deployByRepositoryId/$repositoryId" } else { System.getenv("PUBLISHING_URL") } val publishLocal: Boolean by rootProject.extra val globalM2: String by rootProject.extra val nonDefaultProjectStructure: List<String> by rootProject.extra val emptyJar = tasks.register<Jar>("emptyJar") { archiveAppendix.set("empty") } the<PublishingExtension>().apply { repositories { maven { if (publishLocal) { setUrl(globalM2) } else { publishingUrl?.let { setUrl(it) } credentials { username = publishingUser password = publishingPassword } } } maven { name = "testLocal" setUrl("$rootProject.buildDir/m2") } } publications.forEach { val publication = it as? MavenPublication ?: return@forEach publication.pom.withXml { val root = asNode() root.appendNode("name", project.name) root.appendNode( "description", "Ktor is a framework for quickly creating web applications in Kotlin with minimal effort." ) root.appendNode("url", "https://github.com/ktorio/ktor") root.appendNode("licenses").apply { appendNode("license").apply { appendNode("name", "The Apache Software License, Version 2.0") appendNode("url", "https://www.apache.org/licenses/LICENSE-2.0.txt") appendNode("distribution", "repo") } } root.appendNode("developers").apply { appendNode("developer").apply { appendNode("id", "JetBrains") appendNode("name", "JetBrains Team") appendNode("organization", "JetBrains") appendNode("organizationUrl", "https://www.jetbrains.com") } } root.appendNode("scm").apply { appendNode("url", "https://github.com/ktorio/ktor.git") } } } if (nonDefaultProjectStructure.contains(project.name)) return@apply kotlin.targets.forEach { target -> val publication = publications.findByName(target.name) as? MavenPublication ?: return@forEach if (target.platformType.name == "jvm") { publication.artifact(emptyJar) { classifier = "javadoc" } } else { publication.artifact(emptyJar) { classifier = "javadoc" } publication.artifact(emptyJar) { classifier = "kdoc" } } if (target.platformType.name == "native") { publication.artifact(emptyJar) } } } val publishToMavenLocal = tasks.getByName("publishToMavenLocal") tasks.getByName("publish").dependsOn(publishToMavenLocal) val signingKey = System.getenv("SIGN_KEY_ID") val signingKeyPassphrase = System.getenv("SIGN_KEY_PASSPHRASE") if (signingKey != null && signingKey != "") { extra["signing.gnupg.keyName"] = signingKey extra["signing.gnupg.passphrase"] = signingKeyPassphrase apply(plugin = "signing") the<SigningExtension>().apply { useGpgCmd() sign(the<PublishingExtension>().publications) } val gpgAgentLock: ReentrantLock by rootProject.extra { ReentrantLock() } tasks.withType<Sign> { doFirst { gpgAgentLock.lock() } doLast { gpgAgentLock.unlock() } } } }
apache-2.0
806ade56567b33eba41b33c19e2afc3a
30.628272
119
0.549743
4.719531
false
false
false
false
eyneill777/SpacePirates
core/src/rustyice/game/character/CharacterPhysics.kt
1
1775
package rustyice.game.character import com.badlogic.gdx.physics.box2d.FixtureDef import rustyice.game.Actor import rustyice.game.physics.SBPhysicsComponent import rustyice.physics.LARGE import rustyice.physics.WALL /** * @author gabek */ class CharacterPhysics: SBPhysicsComponent(){ private var characterRadius = 0f private var activatorRadius = 0f fun walk(maxX: Float, maxY: Float, acceleration: Float) { val body = body if(body != null) { var diffX = maxX - body.linearVelocity.x var diffY = maxY - body.linearVelocity.y if (Math.abs(diffX) > .1f || Math.abs(diffY) > .1f) { // cap on force generated. if (Math.abs(diffX) > acceleration) { diffX = if (diffX < 0) -acceleration else acceleration } if (Math.abs(diffY) > acceleration) { diffY = if (diffY < 0) -acceleration else acceleration } body.applyLinearImpulse(diffX, diffY, body.worldCenter.x, body.worldCenter.y, true) } } } override fun init() { super.init() val parent = parent!! val characterDef = FixtureDef() characterDef.density = 1f characterDef.filter.categoryBits = LARGE.toShort() characterDef.filter.maskBits = (LARGE or WALL).toShort() if(parent is Actor){ addCircle(parent.width/2, characterDef) } //FixtureDef activatorDef = new FixtureDef(); //activatorDef.density = 0; //characterDef.filter.categoryBits = FillterFlags.ACTIVATOR; //characterDef.filter.maskBits = FillterFlags.ACTIVATABLE; //addCircle(activatorRadius, activatorDef); } }
mit
663f8b261a9c34c2b3f56474311b525d
30.140351
99
0.606761
4.246411
false
false
false
false
seirion/code
facebook/2019/qualification/4/main.kt
1
1793
import java.util.* fun main(args: Array<String>) { val n = readLine()!!.toInt() repeat(n) { print("Case #${it + 1}: ") solve() } } data class T(val x: Int, val y:Int, val p: Int) fun solve() { fail = false val (n, M) = readLine()!!.split(" ").map { it.toInt() } val a = IntArray(n + 1) { 0 } val t = ArrayList<T>() val h = HashMap<Int, Int>() repeat(M) { val (x, y, p) = readLine()!!.split(" ").map { it.toInt() } t.add(T(x, y, p)) h[p] = h.getOrElse(p, { 0 }) + 1 } val v = h.toList().sortedBy { it.second }.map { it.first } v.forEach { while (true) { val index = find(it, t) if (index == -1) break put(t[index].x, t[index].p, a) put(t[index].y, t[index].p, a) t.removeAt(index) } } if (!fail && isValidTree(a)) { println(a.drop(1).joinToString(" ")) } else println("Impossible") } var fail = false // FIXME : bad codes fun find(i: Int, a: ArrayList<T>) = a.indexOfFirst { it.p == i } fun put(cc: Int, p: Int, a: IntArray) { var c = cc if (c == p) { // nothing to do } else if (a[c] == 0) { a[c] = p } else { var temp = 0 while (true) { temp++ if (temp > 100) { fail = true return } if (c == p) return if (a[c] == 0) break c = a[c] } a[c] = p } } fun isValidTree(a: IntArray) = a.indexOfFirst { cycle(it, a) } == -1 fun cycle(i: Int, a: IntArray): Boolean { val s = HashSet<Int>() var x = i while (x != 0) { if (s.contains(x)) return true s.add(x) x = a[x] } return false }
apache-2.0
2aed9efb4680cb78fe39cfb82c5c5a90
21.696203
66
0.440045
3.107452
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsGeneralController.kt
2
2168
package eu.kanade.tachiyomi.ui.setting import android.content.Intent import android.os.Build import android.provider.Settings import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.util.preference.bindTo import eu.kanade.tachiyomi.util.preference.defaultValue import eu.kanade.tachiyomi.util.preference.entriesRes import eu.kanade.tachiyomi.util.preference.intListPreference import eu.kanade.tachiyomi.util.preference.onClick import eu.kanade.tachiyomi.util.preference.preference import eu.kanade.tachiyomi.util.preference.switchPreference import eu.kanade.tachiyomi.util.preference.titleRes import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys class SettingsGeneralController : SettingsController() { override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply { titleRes = R.string.pref_category_general intListPreference { key = Keys.startScreen titleRes = R.string.pref_start_screen entriesRes = arrayOf( R.string.label_library, R.string.label_recent_updates, R.string.label_recent_manga, R.string.browse ) entryValues = arrayOf("1", "3", "2", "4") defaultValue = "1" summary = "%s" } switchPreference { bindTo(preferences.showUpdatesNavBadge()) titleRes = R.string.pref_library_update_show_tab_badge } switchPreference { key = Keys.confirmExit titleRes = R.string.pref_confirm_exit defaultValue = false } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { preference { key = "pref_manage_notifications" titleRes = R.string.pref_manage_notifications onClick { val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply { putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) } startActivity(intent) } } } } }
apache-2.0
3dfb82ed3cc67c3efe72f91e8148144a
36.37931
90
0.638376
4.662366
false
false
false
false
iSoron/uhabits
uhabits-android/src/main/java/org/isoron/uhabits/activities/AndroidThemeSwitcher.kt
1
2672
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker 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 org.isoron.uhabits.activities import android.app.Activity import android.content.Context import android.content.res.Configuration.UI_MODE_NIGHT_MASK import android.content.res.Configuration.UI_MODE_NIGHT_YES import android.os.Build.VERSION.SDK_INT import androidx.core.content.ContextCompat import org.isoron.uhabits.R import org.isoron.uhabits.core.preferences.Preferences import org.isoron.uhabits.core.ui.ThemeSwitcher import org.isoron.uhabits.core.ui.views.DarkTheme import org.isoron.uhabits.core.ui.views.LightTheme import org.isoron.uhabits.core.ui.views.PureBlackTheme import org.isoron.uhabits.core.ui.views.Theme import org.isoron.uhabits.inject.ActivityContext import org.isoron.uhabits.inject.ActivityScope @ActivityScope class AndroidThemeSwitcher constructor( @ActivityContext val context: Context, preferences: Preferences, ) : ThemeSwitcher(preferences) { override var currentTheme: Theme = LightTheme() override fun getSystemTheme(): Int { if (SDK_INT < 29) return THEME_LIGHT val uiMode = context.resources.configuration.uiMode return if ((uiMode and UI_MODE_NIGHT_MASK) == UI_MODE_NIGHT_YES) { THEME_DARK } else { THEME_LIGHT } } override fun applyDarkTheme() { currentTheme = DarkTheme() context.setTheme(R.style.AppBaseThemeDark) (context as Activity).window.navigationBarColor = ContextCompat.getColor(context, R.color.grey_900) } override fun applyLightTheme() { currentTheme = LightTheme() context.setTheme(R.style.AppBaseTheme) } override fun applyPureBlackTheme() { currentTheme = PureBlackTheme() context.setTheme(R.style.AppBaseThemeDark_PureBlack) (context as Activity).window.navigationBarColor = ContextCompat.getColor(context, R.color.black) } }
gpl-3.0
6ce550178ffae7c0b6904c217b1e787f
34.613333
78
0.733808
4.141085
false
false
false
false
mdanielwork/intellij-community
python/src/com/jetbrains/python/psi/impl/stubs/PyDataclassFieldStubImpl.kt
5
5010
/* * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.jetbrains.python.psi.impl.stubs import com.intellij.psi.stubs.StubInputStream import com.intellij.psi.stubs.StubOutputStream import com.intellij.psi.util.QualifiedName import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.stdlib.PyDataclassParameters import com.jetbrains.python.codeInsight.stdlib.resolvesToOmittedDefault import com.jetbrains.python.psi.PyCallExpression import com.jetbrains.python.psi.PyReferenceExpression import com.jetbrains.python.psi.PyTargetExpression import com.jetbrains.python.psi.impl.PyEvaluator import com.jetbrains.python.psi.resolve.PyResolveUtil import com.jetbrains.python.psi.stubs.PyDataclassFieldStub import java.io.IOException class PyDataclassFieldStubImpl private constructor(private val calleeName: QualifiedName, private val hasDefault: Boolean, private val hasDefaultFactory: Boolean, private val initValue: Boolean) : PyDataclassFieldStub { companion object { fun create(expression: PyTargetExpression): PyDataclassFieldStub? { val value = expression.findAssignedValue() as? PyCallExpression ?: return null val callee = value.callee as? PyReferenceExpression ?: return null val calleeNameAndType = calculateCalleeNameAndType(callee) ?: return null val arguments = analyzeArguments(value, calleeNameAndType.second) ?: return null return PyDataclassFieldStubImpl(calleeNameAndType.first, arguments.first, arguments.second, arguments.third) } @Throws(IOException::class) fun deserialize(stream: StubInputStream): PyDataclassFieldStub? { val calleeName = stream.readNameString() ?: return null val hasDefault = stream.readBoolean() val hasDefaultFactory = stream.readBoolean() val initValue = stream.readBoolean() return PyDataclassFieldStubImpl(QualifiedName.fromDottedString(calleeName), hasDefault, hasDefaultFactory, initValue) } private fun calculateCalleeNameAndType(callee: PyReferenceExpression): Pair<QualifiedName, PyDataclassParameters.Type>? { val qualifiedName = callee.asQualifiedName() ?: return null val dataclassesField = QualifiedName.fromComponents("dataclasses", "field") val attrIb = QualifiedName.fromComponents("attr", "ib") val attrAttr = QualifiedName.fromComponents("attr", "attr") val attrAttrib = QualifiedName.fromComponents("attr", "attrib") for (originalQName in PyResolveUtil.resolveImportedElementQNameLocally(callee)) { when (originalQName) { dataclassesField -> return qualifiedName to PyDataclassParameters.Type.STD attrIb, attrAttr, attrAttrib -> return qualifiedName to PyDataclassParameters.Type.ATTRS } } return null } private fun analyzeArguments(call: PyCallExpression, type: PyDataclassParameters.Type): Triple<Boolean, Boolean, Boolean>? { val initValue = PyEvaluator.evaluateAsBoolean(call.getKeywordArgument("init")) ?: true if (type == PyDataclassParameters.Type.STD) { val default = call.getKeywordArgument("default") val defaultFactory = call.getKeywordArgument("default_factory") return Triple(default != null && !resolvesToOmittedDefault(default, type), defaultFactory != null && !resolvesToOmittedDefault(defaultFactory, type), initValue) } else if (type == PyDataclassParameters.Type.ATTRS) { val default = call.getKeywordArgument("default") val hasFactory = call.getKeywordArgument("factory").let { it != null && it.text != PyNames.NONE } if (default != null && !resolvesToOmittedDefault(default, type)) { val callee = (default as? PyCallExpression)?.callee as? PyReferenceExpression val hasFactoryInDefault = callee != null && QualifiedName.fromComponents("attr", "Factory") in PyResolveUtil.resolveImportedElementQNameLocally(callee) return Triple(!hasFactoryInDefault, hasFactory || hasFactoryInDefault, initValue) } return Triple(false, hasFactory, initValue) } return null } } override fun getTypeClass(): Class<out CustomTargetExpressionStubType<out CustomTargetExpressionStub>> { return PyDataclassFieldStubType::class.java } override fun serialize(stream: StubOutputStream) { stream.writeName(calleeName.toString()) stream.writeBoolean(hasDefault) stream.writeBoolean(hasDefaultFactory) stream.writeBoolean(initValue) } override fun getCalleeName(): QualifiedName = calleeName override fun hasDefault(): Boolean = hasDefault override fun hasDefaultFactory(): Boolean = hasDefaultFactory override fun initValue(): Boolean = initValue }
apache-2.0
112ed9e0e49f25072c5eec7f8e31e7b8
44.972477
140
0.722555
5.307203
false
false
false
false
HomeMods/Relay
core/src/com/homemods/relay/Relay.kt
1
1597
package com.homemods.relay import com.homemods.relay.bluetooth.BluetoothConnection import com.homemods.relay.bluetooth.BluetoothServer import com.homemods.relay.pin.PinFactory import java.util.Random /** * @author sergeys */ class Relay(val pinFactory: PinFactory, val server: BluetoothServer) { fun run() { val connection = server.run { var conn: BluetoothConnection? = null beginDiscovery { connection -> conn = connection } while (conn == null) { Thread.sleep(1000) } conn!! } val outputStream = connection.openOutputStream() //val pins = Array<OutputPin>(8) { pinNum -> pinFactory.createOutputPin(pinNum) } //pins.forEach { pin -> // pin.setShutdownState(PinState.OFF) //} val rand = Random() //val bytes = ByteArray(1) //var num: Int for (i in 1..60) { //rand.nextBytes(bytes) //num = bytes[0].toInt() //Send over our random byte outputStream.write(rand.nextInt(Int.MAX_VALUE)) outputStream.flush() /* for (i in 0..7) { num = num ushr 1 pins[i].set(if (num and 0b0000_0001 != 0) { PinState.ON } else { PinState.OFF }) } */ Thread.sleep(1000) } outputStream.close() connection.close() } }
mit
dda26449b7b5a66cbd84525c2e067c6f
25.180328
89
0.49593
4.58908
false
false
false
false
dahlstrom-g/intellij-community
platform/external-system-api/src/com/intellij/openapi/externalSystem/autoimport/ExternalSystemProjectAware.kt
5
2485
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.autoimport import com.intellij.openapi.Disposable import com.intellij.openapi.externalSystem.autoimport.ExternalSystemSettingsFilesModificationContext.Event.CREATE import com.intellij.openapi.externalSystem.autoimport.ExternalSystemSettingsFilesModificationContext.ReloadStatus.JUST_FINISHED import org.jetbrains.annotations.ApiStatus interface ExternalSystemProjectAware { val projectId: ExternalSystemProjectId /** * Collects settings files which will be watched. * This property can be called from any thread context to reduce UI freezes and CPU usage. * Result will be cached, so settings files should be equals between reloads. */ val settingsFiles: Set<String> fun subscribe(listener: ExternalSystemProjectListener, parentDisposable: Disposable) fun reloadProject(context: ExternalSystemProjectReloadContext) /** * Experimental. Please see implementation limitations. * * This function allows ignoring settings files events. For example Idea can ignore external * changes during reload. * * Note: All ignored modifications cannot be reverted. So if we ignore only create events * then if settings file was created and removed then we mark project status as modified, * because we can restore only delete event by CRCs. * * Note: Now create event and register settings file (file appear in settings files list) event * is same (also for delete and unregister), because we cannot find settings file if it doesn't * exist in file system. Usually settings files list forms during file system scanning. * * Note: This function will be called on EDT. Please make only trivial checks like: * ```context.modificationType == EXTERNAL && path.endsWith(".my-ext")``` * * Note: [ReloadStatus.JUST_FINISHED] is used to ignore create events during reload. But we cannot * replace it by [ReloadStatus.IN_PROGRESS], because we should merge create and all next update * events into one create event and ignore all of them. So [ReloadStatus.JUST_FINISHED] true only * at the end of reload. */ @JvmDefault @ApiStatus.Experimental fun isIgnoredSettingsFileEvent(path: String, context: ExternalSystemSettingsFilesModificationContext): Boolean = context.reloadStatus == JUST_FINISHED && context.event == CREATE }
apache-2.0
dcd93ae5bfda81a12c033e0461495819
48.72
140
0.77505
4.930556
false
false
false
false
mikepenz/FastAdapter
app/src/main/java/com/mikepenz/fastadapter/app/items/IconItem.kt
1
2637
package com.mikepenz.fastadapter.app.items import android.view.View import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.mikepenz.fastadapter.IExpandable import com.mikepenz.fastadapter.IParentItem import com.mikepenz.fastadapter.ISubItem import com.mikepenz.fastadapter.app.R import com.mikepenz.fastadapter.app.utils.getThemeColor import com.mikepenz.fastadapter.items.AbstractItem import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.IIcon import com.mikepenz.iconics.utils.colorInt import com.mikepenz.iconics.view.IconicsImageView /** * Created by mikepenz on 28.12.15. */ class IconItem : AbstractItem<IconItem.ViewHolder>(), IExpandable<IconItem.ViewHolder> { var mIcon: IIcon? = null override var parent: IParentItem<*>? = null override var isExpanded: Boolean = false override var subItems: MutableList<ISubItem<*>> get() = mutableListOf() set(_) { } override val isAutoExpanding: Boolean get() = true /** * defines the type defining this item. must be unique. preferably an id * * @return the type */ override val type: Int get() = R.id.fastadapter_icon_item_id /** * defines the layout which will be used for this item in the list * * @return the layout for this item */ override val layoutRes: Int get() = R.layout.icon_item /** * setter method for the Icon * * @param icon the icon * @return this */ fun withIcon(icon: IIcon): IconItem { this.mIcon = icon return this } /** * binds the data of this item onto the viewHolder * * @param holder the viewHolder of this item */ override fun bindView(holder: ViewHolder, payloads: List<Any>) { super.bindView(holder, payloads) //define our data for the view mIcon?.let { holder.image.icon = IconicsDrawable(holder.image.context, it).apply { colorInt = holder.view.context.getThemeColor(R.attr.colorOnSurface) } } holder.name.text = mIcon?.name } override fun unbindView(holder: ViewHolder) { super.unbindView(holder) holder.image.setImageDrawable(null) } override fun getViewHolder(v: View): ViewHolder { return ViewHolder(v) } /** * our ViewHolder */ class ViewHolder(var view: View) : RecyclerView.ViewHolder(view) { var name: TextView = view.findViewById(R.id.name) var image: IconicsImageView = view.findViewById(R.id.icon) } }
apache-2.0
7335a475df51b7ef571ec2674e70699b
27.053191
88
0.661358
4.23955
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/maven/src/org/jetbrains/kotlin/idea/maven/KotlinMavenImporter.kt
1
24009
// 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.maven import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.util.PathUtil import org.jdom.Element import org.jdom.Text import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.idea.maven.execution.MavenRunner import org.jetbrains.idea.maven.importing.MavenImporter import org.jetbrains.idea.maven.importing.MavenRootModelAdapter import org.jetbrains.idea.maven.model.MavenPlugin import org.jetbrains.idea.maven.project.* import org.jetbrains.idea.maven.utils.resolved import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments import org.jetbrains.kotlin.compilerRunner.ArgumentUtils import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.extensions.ProjectExtensionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.platforms.detectLibraryKind import org.jetbrains.kotlin.idea.base.platforms.tooling.tooling import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.compiler.configuration.KotlinJpsPluginSettings import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.facet.* import org.jetbrains.kotlin.idea.framework.KotlinSdkType import org.jetbrains.kotlin.idea.maven.configuration.KotlinMavenConfigurator import org.jetbrains.kotlin.platform.IdePlatformKind import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.impl.CommonIdePlatformKind import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind import org.jetbrains.kotlin.platform.impl.isCommon import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addIfNotNull import java.io.File import java.util.* interface MavenProjectImportHandler { companion object : ProjectExtensionDescriptor<MavenProjectImportHandler>( "org.jetbrains.kotlin.mavenProjectImportHandler", MavenProjectImportHandler::class.java ) operator fun invoke(facet: KotlinFacet, mavenProject: MavenProject) } class KotlinMavenImporter : MavenImporter(KOTLIN_PLUGIN_GROUP_ID, KOTLIN_PLUGIN_ARTIFACT_ID) { companion object { const val KOTLIN_PLUGIN_GROUP_ID = "org.jetbrains.kotlin" const val KOTLIN_PLUGIN_ARTIFACT_ID = "kotlin-maven-plugin" const val KOTLIN_PLUGIN_SOURCE_DIRS_CONFIG = "sourceDirs" private val KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED = Key<Boolean>("KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED") private val KOTLIN_JPS_VERSION_ACCUMULATOR = Key<IdeKotlinVersion>("KOTLIN_JPS_VERSION_ACCUMULATOR") } override fun preProcess( module: Module, mavenProject: MavenProject, changes: MavenProjectChanges, modifiableModelsProvider: IdeModifiableModelsProvider ) { KotlinJpsPluginSettings.getInstance(module.project)?.dropExplicitVersion() module.project.putUserData(KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED, null) module.project.putUserData(KOTLIN_JPS_VERSION_ACCUMULATOR, null) } override fun process( modifiableModelsProvider: IdeModifiableModelsProvider, module: Module, rootModel: MavenRootModelAdapter, mavenModel: MavenProjectsTree, mavenProject: MavenProject, changes: MavenProjectChanges, mavenProjectToModuleName: MutableMap<MavenProject, String>, postTasks: MutableList<MavenProjectsProcessorTask> ) { if (changes.plugins) { contributeSourceDirectories(mavenProject, module, rootModel) } if (!KotlinJpsPluginSettings.isUnbundledJpsExperimentalFeatureEnabled(module.project)) { return } val mavenPlugin = mavenProject.findKotlinMavenPlugin() ?: return val currentVersion = mavenPlugin.compilerVersion val accumulatorVersion = module.project.getUserData(KOTLIN_JPS_VERSION_ACCUMULATOR) module.project.putUserData(KOTLIN_JPS_VERSION_ACCUMULATOR, maxOf(accumulatorVersion ?: currentVersion, currentVersion)) } override fun postProcess( module: Module, mavenProject: MavenProject, changes: MavenProjectChanges, modifiableModelsProvider: IdeModifiableModelsProvider ) { super.postProcess(module, mavenProject, changes, modifiableModelsProvider) module.project.getUserData(KOTLIN_JPS_VERSION_ACCUMULATOR)?.let { version -> KotlinJpsPluginSettings.importKotlinJpsVersionFromExternalBuildSystem( module.project, version.rawVersion, isDelegatedToExtBuild = MavenRunner.getInstance(module.project).settings.isDelegateBuildToMaven ) module.project.putUserData(KOTLIN_JPS_VERSION_ACCUMULATOR, null) } if (changes.dependencies) { scheduleDownloadStdlibSources(mavenProject, module) val targetLibraryKind = detectPlatformByExecutions(mavenProject)?.tooling?.libraryKind if (targetLibraryKind != null) { modifiableModelsProvider.getModifiableRootModel(module).orderEntries().forEachLibrary { library -> if ((library as LibraryEx).kind == null) { val model = modifiableModelsProvider.getModifiableLibraryModel(library) as LibraryEx.ModifiableModelEx detectLibraryKind(model.getFiles(OrderRootType.CLASSES))?.let { model.kind = it } } true } } } configureFacet(mavenProject, modifiableModelsProvider, module) } private fun scheduleDownloadStdlibSources(mavenProject: MavenProject, module: Module) { // TODO: here we have to process all kotlin libraries but for now we only handle standard libraries val artifacts = mavenProject.dependencyArtifactIndex.data[KOTLIN_PLUGIN_GROUP_ID]?.values?.flatMap { it.filter { it.resolved() } } ?: emptyList() val libraryNames = mutableSetOf<String?>() OrderEnumerator.orderEntries(module).forEachLibrary { library -> val model = library.modifiableModel try { if (model.getFiles(OrderRootType.SOURCES).isEmpty()) { libraryNames.add(library.name) } } finally { Disposer.dispose(model) } true } val toBeDownloaded = artifacts.filter { it.libraryName in libraryNames } if (toBeDownloaded.isNotEmpty()) { MavenProjectsManager.getInstance(module.project) .scheduleArtifactsDownloading(listOf(mavenProject), toBeDownloaded, true, false, AsyncPromise()) } } private fun configureJSOutputPaths( mavenProject: MavenProject, modifiableRootModel: ModifiableRootModel, facetSettings: KotlinFacetSettings, mavenPlugin: MavenPlugin ) { fun parentPath(path: String): String = File(path).absoluteFile.parentFile.absolutePath val sharedOutputFile = mavenPlugin.configurationElement?.getChild("outputFile")?.text val compilerModuleExtension = modifiableRootModel.getModuleExtension(CompilerModuleExtension::class.java) ?: return val buildDirectory = mavenProject.buildDirectory val executions = mavenPlugin.executions executions.forEach { val explicitOutputFile = it.configurationElement?.getChild("outputFile")?.text ?: sharedOutputFile if (PomFile.KotlinGoals.Js in it.goals) { // see org.jetbrains.kotlin.maven.K2JSCompilerMojo val outputFilePath = PathUtil.toSystemDependentName(explicitOutputFile ?: "$buildDirectory/js/${mavenProject.mavenId.artifactId}.js") compilerModuleExtension.setCompilerOutputPath(parentPath(outputFilePath)) facetSettings.productionOutputPath = outputFilePath } if (PomFile.KotlinGoals.TestJs in it.goals) { // see org.jetbrains.kotlin.maven.KotlinTestJSCompilerMojo val outputFilePath = PathUtil.toSystemDependentName( explicitOutputFile ?: "$buildDirectory/test-js/${mavenProject.mavenId.artifactId}-tests.js" ) compilerModuleExtension.setCompilerOutputPathForTests(parentPath(outputFilePath)) facetSettings.testOutputPath = outputFilePath } } } private data class ImportedArguments(val args: List<String>, val jvmTarget6IsUsed: Boolean) private fun getCompilerArgumentsByConfigurationElement( mavenProject: MavenProject, configuration: Element?, platform: TargetPlatform, project: Project ): ImportedArguments { val arguments = platform.createArguments() var jvmTarget6IsUsed = false arguments.apiVersion = configuration?.getChild("apiVersion")?.text ?: mavenProject.properties["kotlin.compiler.apiVersion"]?.toString() arguments.languageVersion = configuration?.getChild("languageVersion")?.text ?: mavenProject.properties["kotlin.compiler.languageVersion"]?.toString() arguments.multiPlatform = configuration?.getChild("multiPlatform")?.text?.trim()?.toBoolean() ?: false arguments.suppressWarnings = configuration?.getChild("nowarn")?.text?.trim()?.toBoolean() ?: false when (arguments) { is K2JVMCompilerArguments -> { arguments.classpath = configuration?.getChild("classpath")?.text arguments.jdkHome = configuration?.getChild("jdkHome")?.text arguments.javaParameters = configuration?.getChild("javaParameters")?.text?.toBoolean() ?: false val jvmTarget = configuration?.getChild("jvmTarget")?.text ?: mavenProject.properties["kotlin.compiler.jvmTarget"]?.toString() if (jvmTarget == JvmTarget.JVM_1_6.description && KotlinJpsPluginSettings.getInstance(project)?.settings?.version?.isBlank() != false ) { // Load JVM target 1.6 in Maven projects as 1.8, for IDEA platforms <= 222. // The reason is that JVM target 1.6 is no longer supported by the latest Kotlin compiler, yet we'd like JPS projects imported from // Maven to be compilable by IDEA, to avoid breaking local development. // (Since IDEA 222, JPS plugin is unbundled from the Kotlin IDEA plugin, so this change is not needed there in case // when explicit version is specified in kotlinc.xml) arguments.jvmTarget = JvmTarget.JVM_1_8.description jvmTarget6IsUsed = true } else { arguments.jvmTarget = jvmTarget } } is K2JSCompilerArguments -> { arguments.sourceMap = configuration?.getChild("sourceMap")?.text?.trim()?.toBoolean() ?: false arguments.sourceMapPrefix = configuration?.getChild("sourceMapPrefix")?.text?.trim() ?: "" arguments.sourceMapEmbedSources = configuration?.getChild("sourceMapEmbedSources")?.text?.trim() ?: "inlining" arguments.outputFile = configuration?.getChild("outputFile")?.text arguments.metaInfo = configuration?.getChild("metaInfo")?.text?.trim()?.toBoolean() ?: false arguments.moduleKind = configuration?.getChild("moduleKind")?.text arguments.main = configuration?.getChild("main")?.text } } val additionalArgs = SmartList<String>().apply { val argsElement = configuration?.getChild("args") argsElement?.content?.forEach { argElement -> when (argElement) { is Text -> { argElement.text?.let { addAll(splitArgumentString(it)) } } is Element -> { if (argElement.name == "arg") { addIfNotNull(argElement.text) } } } } } parseCommandLineArguments(additionalArgs, arguments) return ImportedArguments(ArgumentUtils.convertArgumentsToStringList(arguments), jvmTarget6IsUsed) } private fun displayJvmTarget6UsageNotification(project: Project) { NotificationGroupManager.getInstance() .getNotificationGroup("Kotlin Maven project import") .createNotification( KotlinBundle.message("configuration.maven.jvm.target.1.6.title"), KotlinBundle.message("configuration.maven.jvm.target.1.6.content"), NotificationType.WARNING, ) .setImportant(true) .notify(project) } private val compilationGoals = listOf( PomFile.KotlinGoals.Compile, PomFile.KotlinGoals.TestCompile, PomFile.KotlinGoals.Js, PomFile.KotlinGoals.TestJs, PomFile.KotlinGoals.MetaData ) private val MavenPlugin.compilerVersion: IdeKotlinVersion get() = version?.let(IdeKotlinVersion::opt) ?: KotlinPluginLayout.standaloneCompilerVersion private fun MavenProject.findKotlinMavenPlugin(): MavenPlugin? = findPlugin( KotlinMavenConfigurator.GROUP_ID, KotlinMavenConfigurator.MAVEN_PLUGIN_ID, ) private fun configureFacet(mavenProject: MavenProject, modifiableModelsProvider: IdeModifiableModelsProvider, module: Module) { val mavenPlugin = mavenProject.findKotlinMavenPlugin() ?: return val compilerVersion = mavenPlugin.compilerVersion val kotlinFacet = module.getOrCreateFacet( modifiableModelsProvider, false, ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID ) // TODO There should be a way to figure out the correct platform version val platform = detectPlatform(mavenProject)?.defaultPlatform kotlinFacet.configureFacet( compilerVersion, platform, modifiableModelsProvider, emptySet() ) val facetSettings = kotlinFacet.configuration.settings val configuredPlatform = kotlinFacet.configuration.settings.targetPlatform!! val configuration = mavenPlugin.configurationElement val sharedArguments = getCompilerArgumentsByConfigurationElement(mavenProject, configuration, configuredPlatform, module.project) val executionArguments = mavenPlugin.executions ?.firstOrNull { it.goals.any { s -> s in compilationGoals } } ?.configurationElement?.let { getCompilerArgumentsByConfigurationElement(mavenProject, it, configuredPlatform, module.project) } parseCompilerArgumentsToFacet(sharedArguments.args, emptyList(), kotlinFacet, modifiableModelsProvider) if (executionArguments != null) { parseCompilerArgumentsToFacet(executionArguments.args, emptyList(), kotlinFacet, modifiableModelsProvider) } if (facetSettings.compilerArguments is K2JSCompilerArguments) { configureJSOutputPaths(mavenProject, modifiableModelsProvider.getModifiableRootModel(module), facetSettings, mavenPlugin) } MavenProjectImportHandler.getInstances(module.project).forEach { it(kotlinFacet, mavenProject) } setImplementedModuleName(kotlinFacet, mavenProject, module) kotlinFacet.noVersionAutoAdvance() if ((sharedArguments.jvmTarget6IsUsed || executionArguments?.jvmTarget6IsUsed == true) && module.project.getUserData(KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED) != true ) { module.project.putUserData(KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED, true) displayJvmTarget6UsageNotification(module.project) } } private fun detectPlatform(mavenProject: MavenProject) = detectPlatformByExecutions(mavenProject) ?: detectPlatformByLibraries(mavenProject) private fun detectPlatformByExecutions(mavenProject: MavenProject): IdePlatformKind? { return mavenProject.findPlugin(KOTLIN_PLUGIN_GROUP_ID, KOTLIN_PLUGIN_ARTIFACT_ID)?.executions?.flatMap { it.goals } ?.mapNotNull { goal -> when (goal) { PomFile.KotlinGoals.Compile, PomFile.KotlinGoals.TestCompile -> JvmIdePlatformKind PomFile.KotlinGoals.Js, PomFile.KotlinGoals.TestJs -> JsIdePlatformKind PomFile.KotlinGoals.MetaData -> CommonIdePlatformKind else -> null } }?.distinct()?.singleOrNull() } private fun detectPlatformByLibraries(mavenProject: MavenProject): IdePlatformKind? { for (kind in IdePlatformKind.ALL_KINDS) { val mavenLibraryIds = kind.tooling.mavenLibraryIds if (mavenLibraryIds.any { mavenProject.findDependencies(KOTLIN_PLUGIN_GROUP_ID, it).isNotEmpty() }) { // TODO we could return here the correct version return kind } } return null } // TODO in theory it should work like this but it doesn't as it couldn't unmark source roots that are not roots anymore. // I believe this is something should be done by the underlying maven importer implementation or somewhere else in the IDEA // For now there is a contributeSourceDirectories implementation that deals with the issue // see https://youtrack.jetbrains.com/issue/IDEA-148280 // override fun collectSourceRoots(mavenProject: MavenProject, result: PairConsumer<String, JpsModuleSourceRootType<*>>) { // for ((type, dir) in collectSourceDirectories(mavenProject)) { // val jpsType: JpsModuleSourceRootType<*> = when (type) { // SourceType.PROD -> JavaSourceRootType.SOURCE // SourceType.TEST -> JavaSourceRootType.TEST_SOURCE // } // // result.consume(dir, jpsType) // } // } private fun contributeSourceDirectories(mavenProject: MavenProject, module: Module, rootModel: MavenRootModelAdapter) { val directories = collectSourceDirectories(mavenProject) val toBeAdded = directories.map { it.second }.toSet() val state = module.kotlinImporterComponent val isNonJvmModule = mavenProject .plugins .asSequence() .filter { it.isKotlinPlugin() } .flatMap { it.executions.asSequence() } .flatMap { it.goals.asSequence() } .any { it in PomFile.KotlinGoals.CompileGoals && it !in PomFile.KotlinGoals.JvmGoals } val prodSourceRootType: JpsModuleSourceRootType<*> = if (isNonJvmModule) SourceKotlinRootType else JavaSourceRootType.SOURCE val testSourceRootType: JpsModuleSourceRootType<*> = if (isNonJvmModule) TestSourceKotlinRootType else JavaSourceRootType.TEST_SOURCE for ((type, dir) in directories) { if (rootModel.getSourceFolder(File(dir)) == null) { val jpsType: JpsModuleSourceRootType<*> = when (type) { SourceType.TEST -> testSourceRootType SourceType.PROD -> prodSourceRootType } rootModel.addSourceFolder(dir, jpsType) } } if (isNonJvmModule) { mavenProject.sources.forEach { rootModel.addSourceFolder(it, SourceKotlinRootType) } mavenProject.testSources.forEach { rootModel.addSourceFolder(it, TestSourceKotlinRootType) } mavenProject.resources.forEach { rootModel.addSourceFolder(it.directory, ResourceKotlinRootType) } mavenProject.testResources.forEach { rootModel.addSourceFolder(it.directory, TestResourceKotlinRootType) } KotlinSdkType.setUpIfNeeded() } state.addedSources.filter { it !in toBeAdded }.forEach { rootModel.unregisterAll(it, true, true) state.addedSources.remove(it) } state.addedSources.addAll(toBeAdded) } private fun collectSourceDirectories(mavenProject: MavenProject): List<Pair<SourceType, String>> = mavenProject.plugins.filter { it.isKotlinPlugin() }.flatMap { plugin -> plugin.configurationElement.sourceDirectories().map { SourceType.PROD to it } + plugin.executions.flatMap { execution -> execution.configurationElement.sourceDirectories().map { execution.sourceType() to it } } }.distinct() private fun setImplementedModuleName(kotlinFacet: KotlinFacet, mavenProject: MavenProject, module: Module) { if (kotlinFacet.configuration.settings.targetPlatform.isCommon()) { kotlinFacet.configuration.settings.implementedModuleNames = emptyList() } else { val manager = MavenProjectsManager.getInstance(module.project) val mavenDependencies = mavenProject.dependencies.mapNotNull { manager?.findProject(it) } val implemented = mavenDependencies.filter { detectPlatformByExecutions(it).isCommon } kotlinFacet.configuration.settings.implementedModuleNames = implemented.map { manager.findModule(it)?.name ?: it.displayName } } } } private fun MavenPlugin.isKotlinPlugin() = groupId == KotlinMavenImporter.KOTLIN_PLUGIN_GROUP_ID && artifactId == KotlinMavenImporter.KOTLIN_PLUGIN_ARTIFACT_ID private fun Element?.sourceDirectories(): List<String> = this?.getChildren(KotlinMavenImporter.KOTLIN_PLUGIN_SOURCE_DIRS_CONFIG)?.flatMap { it.children ?: emptyList() }?.map { it.textTrim } ?: emptyList() private fun MavenPlugin.Execution.sourceType() = goals.map { if (isTestGoalName(it)) SourceType.TEST else SourceType.PROD } .distinct() .singleOrNull() ?: SourceType.PROD private fun isTestGoalName(goalName: String) = goalName.startsWith("test-") private enum class SourceType { PROD, TEST } @State( name = "AutoImportedSourceRoots", storages = [(Storage(StoragePathMacros.MODULE_FILE))] ) class KotlinImporterComponent : PersistentStateComponent<KotlinImporterComponent.State> { class State(var directories: List<String> = ArrayList()) val addedSources: MutableSet<String> = Collections.synchronizedSet(HashSet<String>()) override fun loadState(state: State) { addedSources.clear() addedSources.addAll(state.directories) } override fun getState(): State { return State(addedSources.sorted()) } } internal val Module.kotlinImporterComponent: KotlinImporterComponent get() = getService(KotlinImporterComponent::class.java) ?: error("Service ${KotlinImporterComponent::class.java} not found")
apache-2.0
d03f0e3890a6ab214a6ffacd870b1d42
46.826693
151
0.689408
5.408651
false
true
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/base/db/StandardRoundFactory.kt
1
46198
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.base.db import de.dreier.mytargets.shared.R import de.dreier.mytargets.shared.SharedApplicationInstance import de.dreier.mytargets.shared.models.Dimension import de.dreier.mytargets.shared.models.Dimension.Unit.* import de.dreier.mytargets.shared.models.Target import de.dreier.mytargets.shared.models.augmented.AugmentedStandardRound import de.dreier.mytargets.shared.models.db.RoundTemplate import de.dreier.mytargets.shared.models.db.StandardRound import de.dreier.mytargets.shared.targets.models.* object StandardRoundFactory { const val IFAA = 8 const val CUSTOM = 256 private const val ASA = 1 private const val AUSTRALIAN = 2 private const val ARCHERY_GB = 4 private const val NASP = 16 private const val NFAA = 32 private const val NFAS = 64 private const val WA = 128 private var idCounter: Long = 0 private var roundCounter: Long = 0 fun initTable(): List<AugmentedStandardRound> { val rounds = mutableListOf<AugmentedStandardRound>() /* * 3 arrows = 2 min * 4 arrows = 2 min * 5 arrows, indoor, gnas = 2 min * 5 arrows, indoor, i/nfaa, nasp = 4 min * 6 arrows = 4 min * */ idCounter = 0 roundCounter = 0 // Indoor rounds.add( build( AUSTRALIAN, R.string.australian_combined_indoor, METER, CENTIMETER, WA5Ring.ID, 0, 3, 18, 40, 10, 25, 60, 10 ) ) rounds.add( build( AUSTRALIAN, R.string.australian_indoor_1, METER, CENTIMETER, WA5Ring.ID, 0, 3, 18, 40, 10 ) ) rounds.add( build( AUSTRALIAN, R.string.australian_indoor_2, METER, CENTIMETER, WA5Ring.ID, 0, 3, 25, 60, 10 ) ) rounds.add( build( ASA, R.string.dair_380, METER, CENTIMETER, DAIR3D.ID, 0, 3, 25, 60, 10 ) ) rounds.add( build( WA, R.string.wa_18_40cm, METER, CENTIMETER, WA5Ring.ID, 0, 3, 18, 40, 20 ) ) rounds.add( build( WA, R.string.wa_18_60cm, METER, CENTIMETER, WA5Ring.ID, 0, 3, 18, 60, 20 ) ) rounds.add( build( WA, R.string.wa_25, METER, CENTIMETER, WAFull.ID, 0, 3, 25, 60, 20 ) ) rounds.add( build( WA, R.string.wa_combined, METER, CENTIMETER, WAFull.ID, 0, 3, 25, 60, 20, 18, 40, 20 ) ) rounds.add( build( WA, R.string.match_round, METER, CENTIMETER, WAVertical3Spot.ID, 0, 3, 18, 40, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.stafford, METER, CENTIMETER, WAFull.ID, 0, 3, 30, 80, 24 ) ) rounds.add( build( ARCHERY_GB, R.string.bray_i, YARDS, CENTIMETER, WAFull.ID, 0, 6, 20, 40, 5 ) ) rounds.add( build( ARCHERY_GB, R.string.bray_ii, YARDS, CENTIMETER, WAFull.ID, 0, 6, 25, 60, 5 ) ) rounds.add( build( ARCHERY_GB, R.string.portsmouth, YARDS, CENTIMETER, WAFull.ID, 0, 3, 20, 60, 20 ) ) rounds.add( build( ARCHERY_GB, R.string.worcester, YARDS, INCH, Worcester.ID, 0, 5, 20, 16, 12 ) ) rounds.add( build( ARCHERY_GB, R.string.vegas_300, YARDS, CENTIMETER, WA5Ring.ID, 0, 3, 20, 40, 20 ) ) rounds.add( build( IFAA, R.string.ifaa_150_indoor, YARDS, CENTIMETER, WA5Ring.ID, 0, 5, 20, 40, 6 ) ) rounds.add( build( IFAA, R.string.ifaa_150_indoor_cub, YARDS, CENTIMETER, WA5Ring.ID, 0, 5, 10, 40, 6 ) ) rounds.add( build( NASP, R.string.nasp_300, METER, CENTIMETER, WA5Ring.ID, 0, 5, 10, 80, 3, 15, 80, 3 ) ) rounds.add( build( NFAA, R.string.nfaa_420, YARDS, CENTIMETER, NFAAIndoor.ID, 2, 5, 10, 40, 12 ) ) rounds.add( build( NFAA, R.string.nfaa_300_cub, YARDS, CENTIMETER, NFAAIndoor.ID, 2, 5, 20, 40, 12 ) ) rounds.add( build( NFAA, R.string.flint_bowman_indoor, YARDS, CENTIMETER, NFAAField.ID, 0, 4, -1, -1, 7 ) ) // WA rounds.add( build( WA, R.string.wa_50, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 80, 12 ) ) rounds.add( build( WA, R.string.wa_60, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 12 ) ) rounds.add( build( WA, R.string.wa_70, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 12 ) ) rounds.add( build( WA, R.string.wa_900, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 5, 50, 122, 5, 40, 122, 5 ) ) rounds.add( build( WA, R.string.wa_bowman, METER, CENTIMETER, WAFull.ID, 0, 6, 30, 122, 6, 25, 122, 6, 25, 80, 6, 20, 80, 6 ) ) rounds.add( build( WA, R.string.wa_1440_cadet_men, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 6, 60, 122, 6, 50, 80, 6, 30, 80, 6 ) ) rounds.add( build( WA, R.string.wa_1440_cadet_women, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 6, 50, 122, 6, 40, 80, 6, 30, 80, 6 ) ) rounds.add( build( WA, R.string.wa_compound_individual, METER, CENTIMETER, WA6Ring.ID, 0, 3, 50, 80, 5 ) ) rounds.add( build( WA, R.string.wa_compound_qualification, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 80, 12 ) ) rounds.add( build( WA, R.string.wa_cub, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 122, 6, 40, 122, 6, 30, 80, 6, 20, 80, 6 ) ) rounds.add( build( WA, R.string.wa_standard, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 122, 6, 30, 122, 6 ) ) rounds.add( build( WA, R.string.olympic_round, METER, CENTIMETER, WAFull.ID, 0, 3, 70, 122, 4 ) ) rounds.add( build( WA, R.string.wa_1440_junior_men, METER, CENTIMETER, WAFull.ID, 0, 6, 90, 122, 6, 70, 122, 6, 50, 80, 6, 30, 80, 6 ) ) rounds.add( build( WA, R.string.wa_1440_junior_women, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 6, 60, 122, 6, 50, 80, 6, 30, 80, 6 ) ) rounds.add( build( WA, R.string.wa_1440_men_master_50, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 6, 60, 122, 6, 50, 80, 6, 30, 80, 6 ) ) rounds.add( build( WA, R.string.wa_1440_men_master_60, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 6, 60, 122, 6, 50, 80, 6, 30, 80, 6 ) ) rounds.add( build( WA, R.string.wa_1440_men_master_70, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 6, 50, 122, 6, 40, 80, 6, 30, 80, 6 ) ) rounds.add( build( WA, R.string.wa_1440_men_senior, METER, CENTIMETER, WAFull.ID, 0, 6, 90, 122, 6, 70, 122, 6, 50, 80, 6, 30, 80, 6 ) ) rounds.add( build( WA, R.string.wa_1440_women_master_50, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 6, 50, 122, 6, 40, 80, 6, 30, 80, 6 ) ) rounds.add( build( WA, R.string.wa_1440_women_master_60, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 6, 50, 122, 6, 40, 80, 6, 30, 80, 6 ) ) rounds.add( build( WA, R.string.wa_1440_women_master_70, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 6, 50, 122, 6, 40, 80, 6, 30, 80, 6 ) ) rounds.add( build( WA, R.string.wa_1440_women_senior, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 6, 60, 122, 6, 50, 80, 6, 30, 80, 6 ) ) rounds.add( build( WA, R.string.half_wa_1440_cadet_men, METER, METER, WAFull.ID, 0, 6, 70, 122, 3, 60, 122, 3, 50, 80, 3, 30, 80, 3 ) ) rounds.add( build( WA, R.string.half_wa_1440_cadet_women, METER, METER, WAFull.ID, 0, 6, 60, 122, 3, 50, 122, 3, 40, 80, 3, 30, 80, 3 ) ) rounds.add( build( WA, R.string.half_wa_1440_junior_men, METER, CENTIMETER, WAFull.ID, 0, 6, 90, 122, 3, 70, 122, 3, 50, 80, 3, 30, 80, 3 ) ) rounds.add( build( WA, R.string.half_wa_1440_junior_women, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 3, 60, 122, 3, 50, 80, 3, 30, 80, 3 ) ) rounds.add( build( WA, R.string.half_wa_1440_men_master_50, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 3, 60, 122, 3, 50, 80, 3, 30, 80, 3 ) ) rounds.add( build( WA, R.string.half_wa_1440_men_master_60, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 3, 60, 122, 3, 50, 80, 3, 30, 80, 3 ) ) rounds.add( build( WA, R.string.half_wa_1440_men_master_70, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 3, 50, 122, 3, 40, 80, 3, 30, 80, 3 ) ) rounds.add( build( WA, R.string.half_wa_1440_men_senior, METER, CENTIMETER, WAFull.ID, 0, 6, 90, 122, 3, 70, 122, 3, 50, 80, 3, 30, 80, 3 ) ) rounds.add( build( WA, R.string.half_wa_1440_women_master_50, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 3, 50, 122, 3, 40, 80, 3, 30, 80, 3 ) ) rounds.add( build( WA, R.string.half_wa_1440_women_master_60, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 3, 50, 122, 3, 40, 80, 3, 30, 80, 3 ) ) rounds.add( build( WA, R.string.half_wa_1440_women_master_70, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 3, 50, 122, 3, 40, 80, 3, 30, 80, 3 ) ) rounds.add( build( WA, R.string.half_wa_1440_women_senior, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 3, 60, 122, 3, 50, 80, 3, 30, 80, 3 ) ) rounds.add( build( WA, R.string.wa_double_720_30_80cm, METER, CENTIMETER, WAFull.ID, 0, 6, 30, 80, 12, 30, 80, 12 ) ) rounds.add( build( WA, R.string.wa_double_720_40_80cm, METER, CENTIMETER, WAFull.ID, 0, 6, 40, 80, 12, 40, 80, 12 ) ) rounds.add( build( WA, R.string.wa_double_720_40_122cm, METER, CENTIMETER, WAFull.ID, 0, 6, 40, 122, 12, 40, 122, 12 ) ) rounds.add( build( WA, R.string.wa_double_720_50_80cm, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 80, 12, 50, 80, 12 ) ) rounds.add( build( WA, R.string.wa_double_720_50_122cm, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 122, 12, 50, 122, 12 ) ) rounds.add( build( WA, R.string.wa_double_720_60_122cm, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 12, 60, 122, 12 ) ) rounds.add( build( WA, R.string.wa_double_720_70_122cm, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 12, 70, 122, 12 ) ) rounds.add( build( WA, R.string.wa_individual_compound_eleminiation_18, METER, CENTIMETER, WAFull.ID, 0, 3, 18, 40, 5 ) ) rounds.add( build( WA, R.string.wa_individual_compound_eleminiation_40, METER, CENTIMETER, WA6Ring.ID, 0, 3, 40, 80, 5 ) ) rounds.add( build( WA, R.string.wa_individual_compound_eleminiation_50, METER, CENTIMETER, WA6Ring.ID, 0, 3, 50, 80, 5 ) ) rounds.add( build( WA, R.string.wa_recurve_elimination_18, METER, CENTIMETER, WAFull.ID, 0, 3, 18, 40, 5 ) ) rounds.add( build( WA, R.string.wa_recurve_elimination_50, METER, CENTIMETER, WA6Ring.ID, 0, 3, 50, 122, 5 ) ) rounds.add( build( WA, R.string.wa_recurve_elimination_60, METER, CENTIMETER, WA6Ring.ID, 0, 3, 60, 122, 5 ) ) rounds.add( build( WA, R.string.wa_recurve_elimination_70, METER, CENTIMETER, WA6Ring.ID, 0, 3, 70, 122, 5 ) ) // ARCHERY_GB Imperial rounds.add( build( ARCHERY_GB, R.string.albion, YARDS, CENTIMETER, WAFull.ID, 5, 6, 80, 122, 6, 60, 122, 6, 50, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.american, YARDS, CENTIMETER, WAFull.ID, 5, 6, 60, 122, 5, 50, 122, 5, 40, 122, 5 ) ) rounds.add( build( ARCHERY_GB, R.string.bristol_i, YARDS, CENTIMETER, WAFull.ID, 5, 6, 80, 122, 12, 60, 122, 8, 50, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.bristol_ii, YARDS, CENTIMETER, WAFull.ID, 5, 6, 60, 122, 12, 50, 122, 8, 40, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.bristol_iii, YARDS, CENTIMETER, WAFull.ID, 5, 6, 50, 122, 12, 40, 122, 8, 30, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.bristol_iv, YARDS, CENTIMETER, WAFull.ID, 5, 6, 40, 122, 12, 30, 122, 8, 20, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.bristol_v, YARDS, CENTIMETER, WAFull.ID, 5, 6, 30, 122, 12, 20, 122, 8, 10, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.hereford, YARDS, CENTIMETER, WAFull.ID, 5, 6, 80, 122, 12, 60, 122, 8, 50, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.short_junior_national, YARDS, CENTIMETER, WAFull.ID, 5, 6, 30, 122, 8, 20, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.short_junior_warwick, YARDS, CENTIMETER, WAFull.ID, 5, 6, 30, 122, 4, 20, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.short_junior_western, YARDS, CENTIMETER, WAFull.ID, 5, 6, 30, 122, 8, 20, 122, 8 ) ) rounds.add( build( ARCHERY_GB, R.string.short_junior_windsor, YARDS, CENTIMETER, WAFull.ID, 5, 6, 30, 122, 6, 20, 122, 6, 10, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.junior_national, YARDS, CENTIMETER, WAFull.ID, 5, 6, 40, 122, 8, 30, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.junior_warwick, YARDS, CENTIMETER, WAFull.ID, 5, 6, 40, 122, 4, 30, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.junior_western, YARDS, CENTIMETER, WAFull.ID, 5, 6, 40, 122, 8, 30, 122, 8 ) ) rounds.add( build( ARCHERY_GB, R.string.junior_windsor, YARDS, CENTIMETER, WAFull.ID, 5, 6, 40, 122, 6, 30, 122, 6, 20, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.short_national, YARDS, CENTIMETER, WAFull.ID, 5, 6, 50, 122, 8, 40, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.short_warwick, YARDS, CENTIMETER, WAFull.ID, 5, 6, 50, 122, 4, 40, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.short_western, YARDS, CENTIMETER, WAFull.ID, 5, 6, 50, 122, 8, 40, 122, 8 ) ) rounds.add( build( ARCHERY_GB, R.string.short_windsor, YARDS, CENTIMETER, WAFull.ID, 5, 6, 50, 122, 6, 40, 122, 6, 30, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.national, YARDS, CENTIMETER, WAFull.ID, 5, 6, 60, 122, 8, 50, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.st_george, YARDS, CENTIMETER, WAFull.ID, 5, 6, 100, 122, 6, 80, 122, 6, 60, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.st_nicholas, YARDS, CENTIMETER, WAFull.ID, 5, 6, 40, 122, 8, 30, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.warwick, YARDS, CENTIMETER, WAFull.ID, 5, 6, 60, 122, 4, 50, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.western, YARDS, CENTIMETER, WAFull.ID, 5, 6, 60, 122, 8, 50, 122, 8 ) ) rounds.add( build( ARCHERY_GB, R.string.windsor, YARDS, CENTIMETER, WAFull.ID, 5, 6, 60, 122, 6, 50, 122, 6, 40, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.york, YARDS, CENTIMETER, WAFull.ID, 5, 6, 100, 122, 12, 80, 122, 8, 60, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.long_national, YARDS, CENTIMETER, WAFull.ID, 5, 6, 80, 122, 8, 60, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.long_warwick, YARDS, CENTIMETER, WAFull.ID, 5, 6, 80, 122, 4, 60, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.long_western, YARDS, CENTIMETER, WAFull.ID, 5, 6, 80, 122, 8, 60, 122, 8 ) ) rounds.add( build( ARCHERY_GB, R.string.new_national, YARDS, CENTIMETER, WAFull.ID, 5, 6, 100, 122, 8, 80, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.new_warwick, YARDS, CENTIMETER, WAFull.ID, 5, 6, 100, 122, 4, 80, 122, 4 ) ) rounds.add( build( ARCHERY_GB, R.string.new_western, YARDS, CENTIMETER, WAFull.ID, 5, 6, 100, 122, 8, 80, 122, 8 ) ) // ARCHERY_GB Metric rounds.add( build( ARCHERY_GB, R.string.frostbite, METER, CENTIMETER, WAFull.ID, 0, 3, 30, 80, 12 ) ) rounds.add( build( ARCHERY_GB, R.string.half_metric_i, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 3, 60, 122, 3, 50, 80, 3, 30, 80, 3 ) ) rounds.add( build( ARCHERY_GB, R.string.half_metric_ii, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 3, 50, 122, 3, 40, 80, 3, 30, 80, 3 ) ) rounds.add( build( ARCHERY_GB, R.string.half_metric_iii, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 122, 3, 40, 122, 3, 30, 80, 3, 20, 80, 3 ) ) rounds.add( build( ARCHERY_GB, R.string.half_metric_iv, METER, CENTIMETER, WAFull.ID, 0, 6, 40, 122, 3, 30, 122, 3, 20, 80, 3, 10, 80, 3 ) ) rounds.add( build( ARCHERY_GB, R.string.half_metric_v, METER, CENTIMETER, WAFull.ID, 0, 6, 30, 122, 3, 20, 122, 3, 15, 80, 3, 10, 80, 3 ) ) rounds.add( build( ARCHERY_GB, R.string.short_metric_i, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 80, 6, 30, 80, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.short_metric_ii, METER, CENTIMETER, WAFull.ID, 0, 6, 40, 80, 6, 30, 80, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.short_metric_iii, METER, CENTIMETER, WAFull.ID, 0, 6, 30, 80, 6, 20, 80, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.short_metric_iv, METER, CENTIMETER, WAFull.ID, 0, 6, 20, 80, 6, 10, 80, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.short_metric_v, METER, CENTIMETER, WAFull.ID, 0, 6, 15, 80, 6, 10, 80, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.metric_i, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 6, 60, 122, 6, 50, 80, 6, 30, 80, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.metric_ii, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 6, 50, 122, 6, 40, 80, 6, 30, 80, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.metric_iii, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 122, 6, 40, 122, 6, 30, 80, 6, 20, 80, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.metric_iv, METER, CENTIMETER, WAFull.ID, 0, 6, 40, 122, 6, 30, 122, 6, 20, 80, 6, 10, 80, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.metric_v, METER, CENTIMETER, WAFull.ID, 0, 6, 30, 122, 6, 20, 122, 6, 15, 80, 6, 10, 80, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.long_metric_i, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 6, 60, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.long_metric_ii, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 6, 50, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.long_metric_iii, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 122, 6, 40, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.long_metric_iv, METER, CENTIMETER, WAFull.ID, 0, 6, 40, 122, 6, 30, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.long_metric_v, METER, CENTIMETER, WAFull.ID, 0, 6, 30, 122, 6, 20, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.long_metric_gents, METER, CENTIMETER, WAFull.ID, 0, 6, 90, 122, 6, 70, 122, 6 ) ) rounds.add( build( ARCHERY_GB, R.string.long_metric_ladies, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 6, 60, 122, 6 ) ) // Australia rounds.add( build( AUSTRALIAN, R.string.adelaide, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 5, 50, 122, 5, 40, 80, 5, 30, 80, 5 ) ) rounds.add( build( AUSTRALIAN, R.string.brisbane, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 5, 60, 122, 5, 50, 80, 5, 40, 80, 5 ) ) rounds.add( build( AUSTRALIAN, R.string.canberra, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 5, 50, 122, 5, 40, 122, 5 ) ) rounds.add( build( AUSTRALIAN, R.string.darwin, METER, CENTIMETER, WAFull.ID, 0, 6, 40, 122, 15 ) ) rounds.add( build( AUSTRALIAN, R.string.drake, METER, CENTIMETER, WAFull.ID, 0, 6, 30, 80, 15 ) ) rounds.add( build( AUSTRALIAN, R.string.fremantle, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 6, 50, 122, 6, 40, 80, 6, 30, 80, 6 ) ) rounds.add( build( AUSTRALIAN, R.string.geelong, METER, CENTIMETER, WAFull.ID, 0, 6, 30, 122, 15 ) ) rounds.add( build( AUSTRALIAN, R.string.grange, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 15 ) ) rounds.add( build( AUSTRALIAN, R.string.hobart, METER, CENTIMETER, WAFull.ID, 0, 6, 90, 122, 5, 70, 122, 5, 50, 122, 5 ) ) rounds.add( build( AUSTRALIAN, R.string.holt, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 80, 15 ) ) rounds.add( build( AUSTRALIAN, R.string.horsham, METER, CENTIMETER, WAFull.ID, 0, 6, 40, 122, 6, 35, 122, 6, 30, 80, 6, 25, 80, 6 ) ) rounds.add( build( AUSTRALIAN, R.string.intermediate, METER, CENTIMETER, WAFull.ID, 0, 6, 55, 122, 6, 45, 122, 6, 35, 80, 6, 25, 80, 6 ) ) rounds.add( build( AUSTRALIAN, R.string.junior_canberra, METER, CENTIMETER, WAFull.ID, 0, 6, 40, 122, 5, 30, 122, 5, 20, 122, 5 ) ) rounds.add( build( AUSTRALIAN, R.string.launcheston, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 80, 6, 30, 80, 6 ) ) rounds.add( build( AUSTRALIAN, R.string.long_brisbane, METER, CENTIMETER, WAFull.ID, 0, 6, 90, 122, 5, 70, 122, 5, 60, 80, 5, 50, 80, 5 ) ) rounds.add( build( AUSTRALIAN, R.string.long_sydney, METER, CENTIMETER, WAFull.ID, 0, 6, 90, 122, 5, 70, 122, 5, 60, 122, 5, 50, 122, 5 ) ) rounds.add( build( AUSTRALIAN, R.string.melbourne, METER, CENTIMETER, WAFull.ID, 0, 6, 90, 122, 15 ) ) rounds.add( build( AUSTRALIAN, R.string.newcastle, METER, CENTIMETER, WAFull.ID, 0, 6, 20, 122, 15 ) ) rounds.add( build( AUSTRALIAN, R.string.perth, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 5, 60, 122, 5, 50, 122, 5 ) ) rounds.add( build( AUSTRALIAN, R.string.short_adelaide, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 122, 5, 40, 122, 5, 30, 80, 5, 20, 80, 5 ) ) rounds.add( build( AUSTRALIAN, R.string.short_canberra, METER, CENTIMETER, WAFull.ID, 0, 6, 50, 122, 5, 40, 122, 5, 30, 122, 5 ) ) rounds.add( build( AUSTRALIAN, R.string.sydney, METER, CENTIMETER, WAFull.ID, 0, 6, 70, 122, 5, 60, 122, 5, 50, 122, 5, 40, 122, 5 ) ) rounds.add( build( AUSTRALIAN, R.string.townsville, METER, CENTIMETER, WAFull.ID, 0, 6, 60, 122, 6, 50, 122, 6 ) ) rounds.add( build( AUSTRALIAN, R.string.wollongong, METER, CENTIMETER, WAFull.ID, 0, 6, 90, 122, 6, 70, 122, 6 ) ) // NFAA rounds.add( build( NFAA, R.string.nfaa_600, YARDS, CENTIMETER, WAFull.ID, 0, 5, 60, 122, 4, 50, 122, 4, 40, 122, 4 ) ) rounds.add( build( NFAA, R.string.nfaa_600_classic, YARDS, CENTIMETER, WAFull.ID, 0, 5, 40, 92, 4, 50, 92, 4, 60, 92, 4 ) ) rounds.add( build( NFAA, R.string.nfaa_600_classic_cub, YARDS, CENTIMETER, WAFull.ID, 0, 5, 10, 92, 4, 20, 92, 4, 30, 92, 4 ) ) rounds.add( build( NFAA, R.string.nfaa_600_classic_junior, YARDS, CENTIMETER, WAFull.ID, 0, 5, 30, 92, 4, 40, 92, 4, 50, 92, 4 ) ) rounds.add( build( NFAA, R.string.nfaa_600_cub, YARDS, CENTIMETER, WAFull.ID, 0, 5, 30, 122, 4, 20, 122, 4, 10, 122, 4 ) ) rounds.add( build( NFAA, R.string.nfaa_600_junior, YARDS, CENTIMETER, WAFull.ID, 0, 5, 50, 122, 4, 40, 122, 4, 30, 122, 4 ) ) rounds.add( build( NFAA, R.string.nfaa_810, YARDS, CENTIMETER, WAFull.ID, 5, 5, 60, 122, 6, 50, 122, 6, 40, 122, 6 ) ) rounds.add( build( NFAA, R.string.nfaa_810_cub, YARDS, CENTIMETER, WAFull.ID, 5, 5, 30, 122, 6, 20, 122, 6, 10, 122, 6 ) ) rounds.add( build( NFAA, R.string.nfaa_810_junior, YARDS, CENTIMETER, WAFull.ID, 5, 5, 50, 122, 6, 40, 122, 6, 30, 122, 6 ) ) rounds.add( build( NFAA, R.string.nfaa_900, YARDS, CENTIMETER, WAFull.ID, 0, 5, 60, 122, 6, 50, 122, 6, 40, 122, 6 ) ) rounds.add( build( NFAA, R.string.nfaa_900_cub, YARDS, CENTIMETER, WAFull.ID, 0, 5, 30, 122, 6, 20, 122, 6, 10, 122, 6 ) ) rounds.add( build( NFAA, R.string.nfaa_900_junior, YARDS, CENTIMETER, WAFull.ID, 0, 5, 50, 122, 6, 40, 122, 6, 30, 122, 6 ) ) // Other rounds.add( build( NFAA, R.string.canadian_900, YARDS, CENTIMETER, WAFull.ID, 0, 6, 55, 122, 5, 45, 122, 5, 35, 122, 5 ) ) rounds.add( build( NFAA, R.string.t2s_900, YARDS, CENTIMETER, WAFull.ID, 0, 6, 35, 80, 5, 30, 80, 5, 25, 80, 5 ) ) // Field rounds.add( build( IFAA, R.string.ifaa_animal_280, METER, CENTIMETER, IFAAAnimal.ID, 0, 3, -1, -1, 14 ) ) rounds.add( build( IFAA, R.string.ifaa_animal_300, METER, CENTIMETER, IFAAAnimal.ID, 0, 3, -1, -1, 15 ) ) rounds.add( build( IFAA, R.string.ifaa_animal_560, METER, CENTIMETER, IFAAAnimal.ID, 0, 3, -1, -1, 14, -1, -1, 14 ) ) rounds.add( build( NFAA, R.string.nfaa_international_150, METER, CENTIMETER, NFAAHunter.ID, 0, 3, -1, -1, 10 ) ) rounds.add( build( NFAA, R.string.nfaa_international_300, METER, CENTIMETER, NFAAHunter.ID, 0, 3, -1, -1, 10, -1, -1, 10 ) ) rounds.add( build( NFAA, R.string.nfaa_animal_280, METER, CENTIMETER, NFAAAnimal.ID, 0, 3, -1, -1, 14 ) ) rounds.add( build( NFAA, R.string.nfaa_animal_300, METER, CENTIMETER, NFAAAnimal.ID, 0, 3, -1, -1, 15 ) ) rounds.add( build( NFAA, R.string.nfaa_animal_588, METER, CENTIMETER, NFAAAnimal.ID, 0, 3, -1, -1, 14, -1, -1, 14 ) ) rounds.add( build( NFAA, R.string.nfaa_lake_of_woods, METER, CENTIMETER, WAFull.ID, 4, 3, -1, -1, 10 ) ) rounds.add( build( NFAA, R.string.nfaa_expert_field_300, METER, CENTIMETER, NFAAExpertField.ID, 0, 4, -1, -1, 15 ) ) rounds.add( build( NFAA, R.string.nfaa_expert_field_only_560, METER, CENTIMETER, NFAAExpertField.ID, 0, 4, -1, -1, 14, -1, -1, 14 ) ) rounds.add( build( NFAA, R.string.nfaa_field_280, METER, CENTIMETER, NFAAField.ID, 0, 4, -1, -1, 14 ) ) rounds.add( build( NFAA, R.string.nfaa_field_300, METER, CENTIMETER, NFAAField.ID, 0, 4, -1, -1, 15 ) ) rounds.add( build( NFAA, R.string.nfaa_field_560, METER, CENTIMETER, NFAAField.ID, 0, 4, -1, -1, 14, -1, -1, 14 ) ) rounds.add( build( NFAA, R.string.nfaa_hunter_280, METER, CENTIMETER, NFAAHunter.ID, 0, 4, -1, -1, 14 ) ) rounds.add( build( NFAA, R.string.nfaa_hunter_300, METER, CENTIMETER, NFAAHunter.ID, 0, 4, -1, -1, 15 ) ) rounds.add( build( NFAA, R.string.nfaa_hunter_560, METER, CENTIMETER, NFAAHunter.ID, 0, 4, -1, -1, 14, -1, -1, 14 ) ) rounds.add( build( NFAA, R.string.nfaa_field_hunter_560, METER, CENTIMETER, NFAAField.ID, 0, Target(NFAAHunter.ID, 0, Dimension.UNKNOWN), 4, -1, -1, 14, -1, -1, 14 ) ) rounds.add( build( WA, R.string.wa_field_unmarked_marked_red, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 12, -1, -1, 12 ) ) rounds.add( build( WA, R.string.wa_field_marked_12_red, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 12 ) ) rounds.add( build( WA, R.string.wa_field_marked_24_red, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 24 ) ) rounds.add( build( WA, R.string.wa_field_unmarked_12_red, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 12 ) ) rounds.add( build( WA, R.string.wa_field_unmarked_24_red, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 24 ) ) rounds.add( build( WA, R.string.wa_field_unmarked_marked_blue, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 12, -1, -1, 12 ) ) rounds.add( build( WA, R.string.wa_field_marked_12_blue, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 12 ) ) rounds.add( build( WA, R.string.wa_field_marked_24_blue, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 24 ) ) rounds.add( build( WA, R.string.wa_field_unmarked_12_blue, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 12 ) ) rounds.add( build( WA, R.string.wa_field_unmarked_24_blue, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 24 ) ) rounds.add( build( WA, R.string.wa_field_unmarked_marked_yellow, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 12, -1, -1, 12 ) ) rounds.add( build( WA, R.string.wa_field_marked_12_yellow, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 12 ) ) rounds.add( build( WA, R.string.wa_field_marked_24_yellow, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 24 ) ) rounds.add( build( WA, R.string.wa_field_unmarked_12_yellow, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 12 ) ) rounds.add( build( WA, R.string.wa_field_unmarked_24_yellow, METER, CENTIMETER, WAField.ID, 1, 3, -1, -1, 24 ) ) rounds.add( build( NFAS, R.string.big_game_36, METER, CENTIMETER, NFASField.ID, 0, 3, -1, -1, 24 ) ) rounds.add( build( NFAS, R.string.big_game_40, METER, CENTIMETER, NFASField.ID, 0, 3, -1, -1, 40 ) ) return rounds } /** * Builds a new standard round instance * * @param institution Institution that specified the round (ARCHERY_GB or FITA) * @param name Name of the round * @param distanceUnit Unit of the distance specified in round Details * @param targetUnit Unit of the target size specified in roundDetails * @param target Index of the target that is used for shooting * @param shotsPerEnd Number of arrows that are shot per end * @param roundDetails Per round distance, targetSize and number of ends are expected * @return The standard round with the specified properties */ private fun build( institution: Int, name: Int, distanceUnit: Dimension.Unit, targetUnit: Dimension.Unit, target: Long, scoringStyle: Int, shotsPerEnd: Int, vararg roundDetails: Int ): AugmentedStandardRound { val standardRound = StandardRound() idCounter++ standardRound.id = idCounter standardRound.name = SharedApplicationInstance.context.getString(name) standardRound.club = institution val rounds = mutableListOf<RoundTemplate>() var i = 0 while (i < roundDetails.size) { roundCounter++ val roundTemplate = RoundTemplate() roundTemplate.id = roundCounter roundTemplate.shotsPerEnd = shotsPerEnd roundTemplate.distance = Dimension(roundDetails[i].toFloat(), distanceUnit) roundTemplate.targetTemplate = Target( target, scoringStyle, Dimension(roundDetails[i + 1].toFloat(), targetUnit) ) roundTemplate.endCount = roundDetails[i + 2] roundTemplate.index = rounds.size roundTemplate.standardRoundId = standardRound.id rounds.add(roundTemplate) i += 3 } return AugmentedStandardRound(standardRound, rounds) } private fun build( institution: Int, name: Int, distanceUnit: Dimension.Unit, targetUnit: Dimension.Unit, target: Long, scoringStyle: Int, target2: Target, shotsPerEnd: Int, vararg roundDetails: Int ): AugmentedStandardRound { val standardRound = build( institution, name, distanceUnit, targetUnit, target, scoringStyle, shotsPerEnd, *roundDetails ) val round2 = standardRound.roundTemplates[1] target2.diameter = round2.targetTemplate.diameter round2.targetTemplate = target2 return standardRound } }
gpl-2.0
c79fe161d2648f73e3bebf2a97dae648
28.671162
89
0.403113
3.713666
false
false
false
false
imageprocessor/cv4j
app/src/main/java/com/cv4j/app/fragment/QRFragment.kt
1
2716
package com.cv4j.app.fragment import android.graphics.* import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.cv4j.app.R import com.cv4j.app.app.BaseFragment import com.cv4j.core.datamodel.CV4JImage import com.cv4j.image.util.QRCodeScanner import kotlinx.android.synthetic.main.fragment_qr.* /** * * @FileName: * com.cv4j.app.fragment.QRFragment * @author: Tony Shen * @date: 2020-05-04 13:05 * @version: V1.0 <描述当前版本功能> */ class QRFragment : BaseFragment() { private var mIndex = 0 private var bitmap: Bitmap? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val bundle: Bundle? = arguments if (bundle != null) { mIndex = bundle.getInt(QR_INDEX) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.fragment_qr, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) detect_btn.setOnClickListener { val cv4JImage = CV4JImage(bitmap) val qrCodeScanner = QRCodeScanner() val rect = qrCodeScanner.findQRCodeBounding(cv4JImage.processor, 1, 6) val bm = bitmap!!.copy(Bitmap.Config.ARGB_8888, true) val canvas = Canvas(bm) val paint = Paint() paint.color = Color.RED paint.strokeWidth = 10.0.toFloat() paint.style = Paint.Style.STROKE val androidRect = Rect(rect.x - 20, rect.y - 20, rect.br().x + 20, rect.br().y + 20) canvas.drawRect(androidRect, paint) image.setImageBitmap(bm) } initData() } private fun initData() { bitmap = when (mIndex) { 0 -> BitmapFactory.decodeResource(getResources(), R.drawable.qr_1) 1 -> BitmapFactory.decodeResource(getResources(), R.drawable.qr_applepay) 2 -> BitmapFactory.decodeResource(getResources(), R.drawable.qr_jiazhigang) 3 -> BitmapFactory.decodeResource(getResources(), R.drawable.qr_tony) else -> BitmapFactory.decodeResource(getResources(), R.drawable.qr_1) } image.setImageBitmap(bitmap) } companion object { private const val QR_INDEX = "index" fun newInstance(index: Int): QRFragment { val args = Bundle() args.putInt(QR_INDEX, index) val fragment = QRFragment() fragment.arguments = args return fragment } } }
apache-2.0
e7f4a859f1e61694134a3b568ada3639
32.345679
172
0.638148
4.115854
false
false
false
false
kmagiera/react-native-gesture-handler
android/lib/src/main/java/com/swmansion/gesturehandler/GestureUtils.kt
1
1413
package com.swmansion.gesturehandler import android.view.MotionEvent object GestureUtils { fun getLastPointerX(event: MotionEvent, averageTouches: Boolean): Float { val offset = event.rawX - event.x val excludeIndex = if (event.actionMasked == MotionEvent.ACTION_POINTER_UP) event.actionIndex else -1 return if (averageTouches) { var sum = 0f var count = 0 for (i in 0 until event.pointerCount) { if (i != excludeIndex) { sum += event.getX(i) + offset count++ } } sum / count } else { var lastPointerIdx = event.pointerCount - 1 if (lastPointerIdx == excludeIndex) { lastPointerIdx-- } event.getX(lastPointerIdx) + offset } } fun getLastPointerY(event: MotionEvent, averageTouches: Boolean): Float { val offset = event.rawY - event.y val excludeIndex = if (event.actionMasked == MotionEvent.ACTION_POINTER_UP) event.actionIndex else -1 return if (averageTouches) { var sum = 0f var count = 0 for (i in 0 until event.pointerCount) { if (i != excludeIndex) { sum += event.getY(i) + offset count++ } } sum / count } else { var lastPointerIdx = event.pointerCount - 1 if (lastPointerIdx == excludeIndex) { lastPointerIdx -= 1 } event.getY(lastPointerIdx) + offset } } }
mit
0693c08070c36a403ab92f5018ece5af
27.836735
105
0.608634
4.037143
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/MidiPcmStream.kt
1
3819
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Type.* import org.runestar.client.common.startsWith import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 @DependsOn(PcmStream::class) class MidiPcmStream : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<PcmStream>() } .and { it.instanceFields.size == 27 } @DependsOn(NodeHashTable::class) class musicPatches : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<NodeHashTable>() } } @MethodParameters() @DependsOn(Node.remove::class) class removeAll : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.arguments.isEmpty() && it.returnType == VOID_TYPE } .and { it.instructions.any { it.isMethod && it.methodMark == method<Node.remove>().mark } } } @MethodParameters() @DependsOn(MusicPatch.clear::class) class clearAll : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.arguments.isEmpty() && it.returnType == VOID_TYPE } .and { it.instructions.any { it.isMethod && it.methodId == method<MusicPatch.clear>().id } } } @DependsOn(MidiFileReader::class) class midiFile : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<MidiFileReader>() } } @DependsOn(MusicPatchPcmStream::class) class patchStream : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<MusicPatchPcmStream>() } } @MethodParameters("musicTrack", "i", "s", "frequency") @DependsOn(MusicTrack::class, AbstractArchive::class) class loadMusicTrack : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.arguments.startsWith(type<MusicTrack>(), type<AbstractArchive>()) } } @MethodParameters("musicTrack", "b") @DependsOn(MusicTrack::class) class setMusicTrack : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.arguments == listOf(type<MusicTrack>(), BOOLEAN_TYPE) } } @DependsOn(setMusicTrack::class) class track : OrderMapper.InMethod.Field(setMusicTrack::class, -2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(setMusicTrack::class) class trackLength : OrderMapper.InMethod.Field(setMusicTrack::class, -1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @MethodParameters() @DependsOn(MidiFileReader.clear::class) class clear : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.arguments.isEmpty() && it.returnType == VOID_TYPE } .and { it.instructions.count() < 15 } .and { it.instructions.any { it.isMethod && it.methodId == method<MidiFileReader.clear>().id } } } @MethodParameters() class isReady : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.arguments.isEmpty() && it.returnType == BOOLEAN_TYPE } } }
mit
c0951ad1786675ed7044c70b08852136
43.941176
126
0.705158
4.1875
false
false
false
false
dzharkov/intellij-markdown
src/org/intellij/markdown/parser/markerblocks/providers/LinkReferenceDefinitionProvider.kt
1
3674
package org.intellij.markdown.parser.markerblocks.providers import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.MarkerProcessor import org.intellij.markdown.parser.ProductionHolder import org.intellij.markdown.parser.constraints.MarkdownConstraints import org.intellij.markdown.parser.markerblocks.MarkerBlock import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider import org.intellij.markdown.parser.markerblocks.impl.LinkReferenceDefinitionMarkerBlock import org.intellij.markdown.parser.sequentialparsers.SequentialParser import kotlin.text.Regex public class LinkReferenceDefinitionProvider : MarkerBlockProvider<MarkerProcessor.StateInfo> { override fun createMarkerBlocks(pos: LookaheadText.Position, productionHolder: ProductionHolder, stateInfo: MarkerProcessor.StateInfo): List<MarkerBlock> { if (!MarkerBlockProvider.isStartOfLineWithConstraints(pos, stateInfo.currentConstraints)) { return emptyList() } val matchResult = LINK_DEFINITION_REGEX.match(pos.textFromPosition) ?: return emptyList() var furthestOffset = 0 for (i in 1..matchResult.groups.size() - 1) { matchResult.groups[i]?.let { group -> productionHolder.addProduction(listOf(SequentialParser.Node( addToRangeAndWiden(group.range, pos.offset), when (i) { 1 -> MarkdownElementTypes.LINK_LABEL 2 -> MarkdownElementTypes.LINK_DESTINATION 3 -> MarkdownElementTypes.LINK_TITLE else -> throw AssertionError("There are no more than three groups in this regex") }))) furthestOffset = group.range.end } } val matchLength = furthestOffset - matchResult.range.start + 1 val endPosition = pos.nextPosition(matchLength) if (endPosition != null && !isEndOfLine(endPosition)) { return emptyList() } return listOf(LinkReferenceDefinitionMarkerBlock(stateInfo.currentConstraints, productionHolder.mark(), pos.offset + matchLength)) } override fun interruptsParagraph(pos: LookaheadText.Position, constraints: MarkdownConstraints): Boolean { return false } companion object { val WHSP = "[ \\t]*" val NOT_CHARS = { c: String -> val nonWhitespace = "(?:\\\\[$c]|[^ \\t\\n$c])" val anyChar = "(?:\\\\[$c]|[^$c\\n])" "$anyChar*(?:\\n$anyChar*$nonWhitespace$WHSP)*(?:\\n$WHSP)?" } val LINK_LABEL = "\\[${NOT_CHARS("\\[\\]")}\\]" val NONCONTROL = "(?:\\\\[\\(\\)]|[^ \\n\\t\\(\\)])" val LINK_DESTINATION = "(?:<(?:\\\\[<>]|[^<>])*>|${NONCONTROL}*\\(${NONCONTROL}*\\)${NONCONTROL}*|${NONCONTROL}+)" val LINK_TITLE = "(?:\"${NOT_CHARS("\"")}\"|'${NOT_CHARS("'")}'|\\(${NOT_CHARS("\\)")}\\))" val NO_MORE_ONE_NEWLINE = "[ \\t]*(?:\\n[ \\t]*)?" val LINK_DEFINITION_REGEX = Regex( "^ {0,3}(${LINK_LABEL}):" + "${NO_MORE_ONE_NEWLINE}(${LINK_DESTINATION})" + "(?:${NO_MORE_ONE_NEWLINE}(${LINK_TITLE})$WHSP(?:\\n|$))?" ) fun addToRangeAndWiden(range: IntRange, t: Int): IntRange { return IntRange(range.start + t, range.end + t + 1) } fun isEndOfLine(pos: LookaheadText.Position): Boolean { return pos.offsetInCurrentLine == -1 || pos.charsToNonWhitespace() == null } } }
apache-2.0
d3f49d4c2a9cf3db0b546088483d5b97
42.223529
122
0.604246
4.668361
false
false
false
false
sakki54/RLGdx
src/main/kotlin/com/brekcel/RLGdx/actor/Actor.kt
1
991
//=====Copyright 2017 Clayton Breckel=====// package com.brekcel.RLGdx.actor import com.brekcel.RLGdx.console.Cell /** Base class of all Actors. (Players and NPC's) */ open class Actor( /** Actor's current x pos */ var x: Int, /** Actor's current y pos */ var y: Int, /** The cell that is drawn for the actor */ var cell: Cell, /** Whether or not other actors can walk on/thru this actor */ var solid: Boolean, /** How far this actor can see */ var visLength: Short) { /** Where this actor is trying to walk to */ var goalX = y private set /** Where this actor is trying to walk to */ var goalY = x private set /** Sets the actors [goalX] and [goalY] to the given x,y coords */ fun moveTo(x: Int, y: Int) { goalX = x goalY = y } /** Displaces the actor based on the given coords */ fun move(x: Int, y: Int) { this.x += x this.y += y } /** Moves the actor to the given coords */ fun teleport(x: Int, y: Int) { this.x = x this.y = y } }
mit
fb6b348f6c1c9f399ece57b4bf8f0a03
21.044444
67
0.621594
2.906158
false
false
false
false
SimpleMobileTools/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/helpers/GridSpacingItemDecoration.kt
2
2509
package com.simplemobiletools.gallery.pro.helpers import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView import com.simplemobiletools.gallery.pro.models.Medium import com.simplemobiletools.gallery.pro.models.ThumbnailItem class GridSpacingItemDecoration(val spanCount: Int, val spacing: Int, val isScrollingHorizontally: Boolean, val addSideSpacing: Boolean, var items: ArrayList<ThumbnailItem>, val useGridPosition: Boolean) : RecyclerView.ItemDecoration() { override fun toString() = "spanCount: $spanCount, spacing: $spacing, isScrollingHorizontally: $isScrollingHorizontally, addSideSpacing: $addSideSpacing, " + "items: ${items.hashCode()}, useGridPosition: $useGridPosition" override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { if (spacing <= 1) { return } val position = parent.getChildAdapterPosition(view) val medium = items.getOrNull(position) as? Medium ?: return val gridPositionToUse = if (useGridPosition) medium.gridPosition else position val column = gridPositionToUse % spanCount if (isScrollingHorizontally) { if (addSideSpacing) { outRect.top = spacing - column * spacing / spanCount outRect.bottom = (column + 1) * spacing / spanCount outRect.right = spacing if (position < spanCount) { outRect.left = spacing } } else { outRect.top = column * spacing / spanCount outRect.bottom = spacing - (column + 1) * spacing / spanCount if (position >= spanCount) { outRect.left = spacing } } } else { if (addSideSpacing) { outRect.left = spacing - column * spacing / spanCount outRect.right = (column + 1) * spacing / spanCount outRect.bottom = spacing if (position < spanCount && !useGridPosition) { outRect.top = spacing } } else { outRect.left = column * spacing / spanCount outRect.right = spacing - (column + 1) * spacing / spanCount if (gridPositionToUse >= spanCount) { outRect.top = spacing } } } } }
gpl-3.0
e43a90735e503910e7851d672a2ffddd
40.816667
160
0.587884
5.194617
false
false
false
false
mikepenz/Storyblok-Android-SDK
library/src/main/java/com/mikepenz/storyblok/Storyblok.kt
1
9982
package com.mikepenz.storyblok import android.util.Log import com.mikepenz.storyblok.cache.Cache import com.mikepenz.storyblok.model.* import okhttp3.* import org.json.JSONException import org.json.JSONObject import java.io.IOException /** * Created by mikepenz on 14/04/2017. */ class Storyblok private constructor(token: String) { private val client = OkHttpClient() private var token: String? = null private var cache: Cache? = null private var editMode = false private var apiProtocol = API_PROTOCOL private var apiEndpoint = API_ENDPOINT private var apiVersion = API_VERSION private val requestBuild: Request.Builder get() = Request.Builder() init { this.token = token } fun withCache(cache: Cache): Storyblok { this.cache = cache return this } fun withToken(token: String): Storyblok { this.token = token return this } fun withApiProtocol(apiProtocol: String): Storyblok { this.apiProtocol = apiProtocol return this } fun withApiEndpoint(apiEndpoint: String): Storyblok { this.apiEndpoint = apiEndpoint return this } fun withApiVersion(apiVersion: String): Storyblok { this.apiVersion = apiVersion return this } fun withEditMode(editMode: Boolean): Storyblok { this.editMode = editMode return this } fun getStory(slug: String, successCallback: SuccessCallback<Story>, errorCallback: ErrorCallback?) { val cacheKey = buildCacheKey(ENDPOINT_STORIES, "slug", slug) reCacheOnPublish(cacheKey) client.newCall(buildRequest(buildUrl(ENDPOINT_STORIES).addPathSegments(slug))).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { errorCallback?.onFailure(e, null) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { if (response.code() >= 300) { errorCallback?.onFailure(null, response.body().string()) } else { successCallback.onResponse(Result(response.headers(), Story.parseStory(toJsonObjectAndCache(cacheKey, response.body().string())))) } } }) } fun getStories(startsWith: String?, withTag: String?, sortBy: String?, perPage: Int?, page: Int?, successCallback: SuccessCallback<List<Story>>, errorCallback: ErrorCallback?) { val cacheKey = buildCacheKey(ENDPOINT_STORIES, "starts_with", startsWith, "with_tag", withTag, "sort_by", sortBy, "per_page", perPage.toString(), "page", page.toString()) reCacheOnPublish(cacheKey) client.newCall( buildRequest( buildUrl(ENDPOINT_STORIES) .addQueryParameter("starts_with", startsWith) .addQueryParameter("with_tag", withTag) .addQueryParameter("sort_by", sortBy) .addQueryParameter("per_page", perPage?.toString()) .addQueryParameter("page", page?.toString()) .addQueryParameter("cache_version", cache?.cacheVersion?.toString()) ) ).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { errorCallback?.onFailure(e, null) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { if (response.code() >= 300) { errorCallback?.onFailure(null, response.body().string()) } else { successCallback.onResponse(Result(response.headers(), Story.parseStories(toJsonObjectAndCache(cacheKey, response.body().string())))) } } }) } fun getTags(startsWith: String?, successCallback: SuccessCallback<List<Tag>>, errorCallback: ErrorCallback?) { val cacheKey = buildCacheKey(ENDPOINT_TAGS, "starts_with", startsWith) reCacheOnPublish(cacheKey) client.newCall(buildRequest(buildUrl(ENDPOINT_TAGS).addQueryParameter("starts_with", startsWith))).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { errorCallback?.onFailure(e, null) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { if (response.code() >= 300) { errorCallback?.onFailure(null, response.body().string()) } else { successCallback.onResponse(Result(response.headers(), Tag.parseTags(toJsonObjectAndCache(cacheKey, response.body().string())))) } } }) } fun getLinks(successCallback: SuccessCallback<Map<String, Link>>, errorCallback: ErrorCallback?) { val cacheKey = buildCacheKey(ENDPOINT_LINKS) reCacheOnPublish(cacheKey) client.newCall(buildRequest(buildUrl(ENDPOINT_LINKS))).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { errorCallback?.onFailure(e, null) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { if (response.code() >= 300) { errorCallback?.onFailure(null, response.body().string()) } else { successCallback.onResponse(Result(response.headers(), Link.parseLinks(toJsonObjectAndCache(cacheKey, response.body().string())))) } } }) } fun getDatasource(datasource: String?, successCallback: SuccessCallback<List<Datasource>>, errorCallback: ErrorCallback?) { val cacheKey = buildCacheKey(ENDPOINT_DATASOURCE, "datasource", datasource) reCacheOnPublish(cacheKey) client.newCall(buildRequest(buildUrl(ENDPOINT_DATASOURCE).addQueryParameter("datasource", datasource))).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { errorCallback?.onFailure(e, null) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { if (response.code() >= 300) { errorCallback?.onFailure(null, response.body().string()) } else { successCallback.onResponse(Result(response.headers(), Datasource.parseDatasource(toJsonObjectAndCache(cacheKey, response.body().string())))) } } }) } private fun toJsonObjectAndCache(key: String, result: String?): JSONObject? { try { val jsonObject = JSONObject(result) cache?.save(jsonObject, key) return jsonObject } catch (e: JSONException) { Log.e(ERROR_TAG, ERROR_TEXT) } return null } private fun buildCacheKey(vararg `val`: String?): String { if (cache == null) { return "" } val res = StringBuilder() for (v in `val`) { res.append(v) } return res.toString() } private fun reCacheOnPublish(key: String) { if (cache == null) { return } val storyblokPublished = "" // FIXME val item = cache?.load(key) if (item != null) { try { if (item.has("story") && item.getJSONObject("story").get("id") === storyblokPublished) { cache?.delete(key) } } catch (e: JSONException) { Log.e(ERROR_TAG, ERROR_TEXT) } // Always refresh cache of links cache?.delete(ENDPOINT_LINKS) setCacheVersion() } } private fun setCacheVersion() { cache?.withCacheVersion(System.currentTimeMillis()) } private fun buildRequest(url: HttpUrl.Builder): Request { return requestBuild .url(url.build()) .header("User-Agent", SDK_USER_AGENT) .build() } private fun buildUrl(method: String): HttpUrl.Builder { return HttpUrl.Builder() .scheme(apiProtocol) .host(apiEndpoint) .addPathSegment(apiVersion) .addPathSegment("cdn") .addPathSegment(method) .addQueryParameter("token", token) .addQueryParameter("version", if (editMode) VERSION_DRAFT else VERSION_PUBLISHED) } interface SuccessCallback<Model> { fun onResponse(result: Result<Model>) } interface ErrorCallback { fun onFailure(exception: IOException?, response: String?) } companion object { const val ERROR_TAG = "Storyblok" const val ERROR_TEXT = "Sorry for the inconvience. Something broken was sent by the server" private const val API_PROTOCOL = "https" private const val API_ENDPOINT = "api.storyblok.com" private const val API_VERSION = "v1" private const val SDK_VERSION = "0.1" private const val SDK_USER_AGENT = "storyblok-sdk-android/$SDK_VERSION" private const val VERSION_PUBLISHED = "published" private const val VERSION_DRAFT = "draft" private const val ENDPOINT_STORIES = "stories" private const val ENDPOINT_LINKS = "links" private const val ENDPOINT_TAGS = "tags" private const val ENDPOINT_DATASOURCE = "datasource_entries" private var SINGLETON: Storyblok? = null fun init(token: String): Storyblok { if (SINGLETON == null) { SINGLETON = Storyblok(token) } return SINGLETON as Storyblok } } }
apache-2.0
4612963d484a4f15d3777dfe50f13736
35.166667
181
0.586856
4.909985
false
false
false
false
mikepenz/Android-Iconics
iconics-core/src/main/java/com/mikepenz/iconics/animation/SpinProcessor.kt
1
2835
/* * Copyright 2020 Mike Penz * * 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.mikepenz.iconics.animation import android.animation.TimeInterpolator import android.graphics.Canvas import android.graphics.Paint import android.text.TextPaint import com.mikepenz.iconics.IconicsBrush import com.mikepenz.iconics.animation.IconicsAnimationProcessor.RepeatMode.RESTART import com.mikepenz.iconics.animation.SpinProcessor.Direction.CLOCKWISE /** * @author pa.gulko zTrap (30.11.2018) */ open class SpinProcessor( /** The direction of the spin */ open var direction: SpinProcessor.Direction = CLOCKWISE, override var interpolator: TimeInterpolator = DEFAULT_INTERPOLATOR, override var duration: Long = DEFAULT_DURATION, override var repeatCount: Int = INFINITE, override var repeatMode: IconicsAnimationProcessor.RepeatMode = RESTART, override var isStartImmediately: Boolean = true ) : IconicsAnimationProcessor(interpolator, duration, repeatCount, repeatMode, isStartImmediately) { companion object { /** Duration used for all instances of this processor by default. 2000 ms by default. */ @JvmField var DEFAULT_DURATION = 2000L } private var isDrawableShadowCleared = false override val animationTag: String = "spin" override fun processPreDraw( canvas: Canvas, iconBrush: IconicsBrush<TextPaint>, iconContourBrush: IconicsBrush<Paint>, backgroundBrush: IconicsBrush<Paint>, backgroundContourBrush: IconicsBrush<Paint> ) { // Shadow are not recalculate while drawable are spinning. It looks ugly! // Turn off ugly shadow! if (!isDrawableShadowCleared) { iconBrush.paint.clearShadowLayer() isDrawableShadowCleared = true } canvas.save() val bounds = drawableBounds val degrees = animatedPercent * 3.6f * direction.sign bounds?.let { canvas.rotate(degrees, (it.width() / 2).toFloat(), (it.height() / 2).toFloat()) } } override fun processPostDraw(canvas: Canvas) { canvas.restore() } override fun onDrawableDetached() { isDrawableShadowCleared = false } enum class Direction(internal val sign: Int) { CLOCKWISE(+1), COUNTER_CLOCKWISE(-1) } }
apache-2.0
7b2525b45a00eeb068031117e6189900
32.75
100
0.708995
4.521531
false
false
false
false
allotria/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenWslUtil.kt
1
8178
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.utils import com.intellij.execution.wsl.WSLCommandLineOptions import com.intellij.execution.wsl.WSLDistribution import com.intellij.execution.wsl.WslPath import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.io.FileUtil import org.jetbrains.idea.maven.execution.SyncBundle import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.server.MavenDistributionsCache import org.jetbrains.idea.maven.server.MavenServerManager import org.jetbrains.idea.maven.server.WslMavenDistribution import java.io.File import java.util.function.Function import java.util.function.Supplier object MavenWslUtil : MavenUtil() { @JvmStatic fun getPropertiesFromMavenOpts(distribution: WSLDistribution): Map<String, String> { return parseMavenProperties(distribution.getEnvironmentVariable("MAVEN_OPTS")) } @JvmStatic fun getWslDistribution(project: Project): WSLDistribution { val basePath = project.basePath ?: throw IllegalArgumentException("Project $project with null base path") return WslPath.getDistributionByWindowsUncPath(basePath) ?: throw IllegalArgumentException("Distribution for path $basePath not found, check your WSL installation") } @JvmStatic fun tryGetWslDistribution(project: Project): WSLDistribution? { return project.basePath?.let { WslPath.getDistributionByWindowsUncPath(it) } } @JvmStatic fun tryGetWslDistributionForPath(path: String?): WSLDistribution? { return path?.let { WslPath.getDistributionByWindowsUncPath(it)} } /** * return file in windows-style ("\\wsl$\distrib-name\home\user\.m2\settings.xml") */ @JvmStatic fun WSLDistribution.resolveUserSettingsFile(overriddenUserSettingsFile: String?): File { val localFile = if (!isEmptyOrSpaces(overriddenUserSettingsFile)) File(overriddenUserSettingsFile) else File(this.resolveM2Dir(), SETTINGS_XML) return localFile } /** * return file in windows-style ("\\wsl$\distrib-name\home\user\.m2\settings.xml") */ @JvmStatic fun WSLDistribution.resolveGlobalSettingsFile(overriddenMavenHome: String?): File? { val directory = this.resolveMavenHomeDirectory(overriddenMavenHome) ?: return null return File(File(directory, CONF_DIR), SETTINGS_XML) } @JvmStatic fun WSLDistribution.resolveM2Dir(): File { return this.getWindowsFile(File(this.environment["HOME"], DOT_M2_DIR))!! } /** * return file in windows-style ("\\wsl$\distrib-name\home\user\.m2\settings.xml") */ @JvmStatic fun WSLDistribution.resolveMavenHomeDirectory(overrideMavenHome: String?): File? { MavenLog.LOG.debug("resolving maven home on WSL with override = \"${overrideMavenHome}\"") if (overrideMavenHome != null) { if (overrideMavenHome == MavenServerManager.BUNDLED_MAVEN_3) { return MavenDistributionsCache.resolveEmbeddedMavenHome().mavenHome } val home = File(overrideMavenHome) if (isValidMavenHome(home)) { MavenLog.LOG.debug("resolved maven home as ${overrideMavenHome}") return home } else { MavenLog.LOG.debug("Maven home ${overrideMavenHome} on WSL is invalid") return null } } val m2home = this.environment[ENV_M2_HOME] if (m2home != null && !isEmptyOrSpaces(m2home)) { val homeFromEnv = this.getWindowsPath(m2home)?.let(::File) if (isValidMavenHome(homeFromEnv)) { MavenLog.LOG.debug("resolved maven home using \$M2_HOME as ${homeFromEnv}") return homeFromEnv } else { MavenLog.LOG.debug("Maven home using \$M2_HOME is invalid") return null } } var home = this.getWindowsPath("/usr/share/maven")?.let(::File) if (isValidMavenHome(home)) { MavenLog.LOG.debug("Maven home found at /usr/share/maven") return home } home = this.getWindowsPath("/usr/share/maven2")?.let(::File) if (isValidMavenHome(home)) { MavenLog.LOG.debug("Maven home found at /usr/share/maven2") return home } val options = WSLCommandLineOptions() .setExecuteCommandInLoginShell(true) .setShellPath(this.shellPath) val processOutput = this.executeOnWsl(listOf("which", "mvn"), options, 10000, null) if (processOutput.exitCode == 0) { val path = processOutput.stdout.lines().find { it.isNotEmpty() }?.let(this::resolveSymlink)?.let(this::getWindowsPath)?.let(::File) if (path != null) { return path; } } MavenLog.LOG.debug("mvn not found in \$PATH") MavenLog.LOG.debug("Maven home not found on ${this.presentableName}") return null } /** * return file in windows style */ @JvmStatic fun WSLDistribution.resolveLocalRepository(overriddenLocalRepository: String?, overriddenMavenHome: String?, overriddenUserSettingsFile: String?): File { if (overriddenLocalRepository != null && !isEmptyOrSpaces(overriddenLocalRepository)) { return File(overriddenLocalRepository) } return doResolveLocalRepository(this.resolveUserSettingsFile(overriddenUserSettingsFile), this.resolveGlobalSettingsFile(overriddenMavenHome))?.let { this.getWindowsFile(it) } ?: File(this.resolveM2Dir(), REPOSITORY_DIR) } @JvmStatic fun WSLDistribution.getDefaultMavenDistribution(overriddenMavenHome: String? = null): WslMavenDistribution? { val file = this.resolveMavenHomeDirectory(overriddenMavenHome) ?: return null val wslFile = this.getWslPath(file.path) ?: return null return WslMavenDistribution(this, wslFile, "default") } @JvmStatic fun getJdkPath(wslDistribution: WSLDistribution): String? { return wslDistribution.getEnvironmentVariable("JDK_HOME") } @JvmStatic fun WSLDistribution.getWindowsFile(wslFile: File): File? { return FileUtil.toSystemIndependentName(wslFile.path).let(this::getWindowsPath)?.let(::File) } @JvmStatic fun WSLDistribution.getWslFile(windowsFile: File): File? { return windowsFile.path.let(this::getWslPath)?.let(::File) } @JvmStatic fun <T> resolveWslAware(project: Project?, ordinary: Supplier<T>, wsl: Function<WSLDistribution, T>): T { if (project == null && ApplicationManager.getApplication().isUnitTestMode) { MavenLog.LOG.error("resolveWslAware: Project is null"); } val wslDistribution = project?.let { tryGetWslDistribution(it) } ?: return ordinary.get() return wsl.apply(wslDistribution) } @JvmStatic fun useWslMaven(project: Project): Boolean { val projectWslDistr = tryGetWslDistribution(project) ?: return false val jdkWslDistr = tryGetWslDistributionForPath(ProjectRootManager.getInstance(project).projectSdk?.homePath) ?: return false return jdkWslDistr.id == projectWslDistr.id } @JvmStatic fun sameDistributions(first: WSLDistribution?, second: WSLDistribution?): Boolean { return first?.id == second?.id } @JvmStatic fun restartMavenConnectorsIfJdkIncorrect(project: Project) { ProgressManager.getInstance().runProcessWithProgressSynchronously( { val projectWslDistr = tryGetWslDistribution(project) var needReset = false; MavenServerManager.getInstance().allConnectors.forEach { if (it.project == project) { val jdkWslDistr = tryGetWslDistributionForPath(it.jdk.homePath) if ((projectWslDistr != null && it.supportType != "WSL") || !sameDistributions(projectWslDistr, jdkWslDistr)) { needReset = true; it.shutdown(true) } } } if (!needReset) { MavenProjectsManager.getInstance(project).embeddersManager.reset() } }, SyncBundle.message("maven.sync.restarting"), false, project) } }
apache-2.0
3629c8975a5014f952b3e65fe70797b4
37.758294
140
0.709831
4.620339
false
false
false
false
googlearchive/android-DownloadableFonts
kotlinApp/app/src/main/kotlin/com/example/android/downloadablefonts/MainActivity.kt
3
10117
/* * 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 com.example.android.downloadablefonts import android.graphics.Typeface import android.os.Bundle import android.os.Handler import android.os.HandlerThread import android.support.design.widget.TextInputLayout import android.support.v4.provider.FontRequest import android.support.v4.provider.FontsContractCompat import android.support.v4.util.ArraySet import android.support.v7.app.AppCompatActivity import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.View import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Button import android.widget.CheckBox import android.widget.ProgressBar import android.widget.SeekBar import android.widget.TextView import android.widget.Toast import java.util.Arrays import com.example.android.downloadablefonts.Constants.ITALIC_DEFAULT import com.example.android.downloadablefonts.Constants.WEIGHT_DEFAULT import com.example.android.downloadablefonts.Constants.WEIGHT_MAX import com.example.android.downloadablefonts.Constants.WIDTH_DEFAULT import com.example.android.downloadablefonts.Constants.WIDTH_MAX class MainActivity : AppCompatActivity() { lateinit private var mHandler: Handler lateinit private var mDownloadableFontTextView: TextView lateinit private var mWidthSeekBar: SeekBar lateinit private var mWeightSeekBar: SeekBar lateinit private var mItalicSeekBar: SeekBar lateinit private var mBestEffort: CheckBox lateinit private var mRequestDownloadButton: Button lateinit private var mFamilyNameSet: ArraySet<String> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val handlerThread = HandlerThread("fonts") handlerThread.start() mHandler = Handler(handlerThread.looper) initializeSeekBars() mFamilyNameSet = ArraySet<String>() mFamilyNameSet.addAll(Arrays.asList(*resources.getStringArray(R.array.family_names))) mDownloadableFontTextView = findViewById<TextView>(R.id.textview) val adapter = ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, resources.getStringArray(R.array.family_names)) val familyNameInput = findViewById<TextInputLayout>(R.id.auto_complete_family_name_input) val autoCompleteFamilyName = findViewById<AutoCompleteTextView>(R.id.auto_complete_family_name) autoCompleteFamilyName.setAdapter<ArrayAdapter<String>>(adapter) autoCompleteFamilyName.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence, start: Int, count: Int, after: Int) { // No op } override fun onTextChanged(charSequence: CharSequence, start: Int, count: Int, after: Int) { if (isValidFamilyName(charSequence.toString())) { familyNameInput.isErrorEnabled = false familyNameInput.error = "" } else { familyNameInput.isErrorEnabled = true familyNameInput.error = getString(R.string.invalid_family_name) } } override fun afterTextChanged(editable: Editable) { // No op } }) mRequestDownloadButton = findViewById<Button>(R.id.button_request) mRequestDownloadButton.setOnClickListener(View.OnClickListener { val familyName = autoCompleteFamilyName.getText().toString() if (!isValidFamilyName(familyName)) { familyNameInput.isErrorEnabled = true familyNameInput.error = getString(R.string.invalid_family_name) Toast.makeText( this@MainActivity, R.string.invalid_input, Toast.LENGTH_SHORT).show() return@OnClickListener } requestDownload(familyName) mRequestDownloadButton.isEnabled = false }) mBestEffort = findViewById<CheckBox>(R.id.checkbox_best_effort) } private fun requestDownload(familyName: String) { val queryBuilder = QueryBuilder(familyName, width = progressToWidth(mWidthSeekBar.progress), weight = progressToWeight(mWeightSeekBar.progress), italic = progressToItalic(mItalicSeekBar.progress), besteffort = mBestEffort.isChecked) val query = queryBuilder.build() Log.d(TAG, "Requesting a font. Query: " + query) val request = FontRequest( "com.google.android.gms.fonts", "com.google.android.gms", query, R.array.com_google_android_gms_fonts_certs) val progressBar = findViewById<ProgressBar>(R.id.progressBar) progressBar.visibility = View.VISIBLE val callback = object : FontsContractCompat.FontRequestCallback() { override fun onTypefaceRetrieved(typeface: Typeface) { mDownloadableFontTextView.typeface = typeface progressBar.visibility = View.GONE mRequestDownloadButton.isEnabled = true } override fun onTypefaceRequestFailed(reason: Int) { Toast.makeText(this@MainActivity, getString(R.string.request_failed, reason), Toast.LENGTH_LONG) .show() progressBar.visibility = View.GONE mRequestDownloadButton.isEnabled = true } } FontsContractCompat .requestFont(this@MainActivity, request, callback, mHandler) } private fun initializeSeekBars() { mWidthSeekBar = findViewById<SeekBar>(R.id.seek_bar_width) val widthValue = (100 * WIDTH_DEFAULT.toFloat() / WIDTH_MAX.toFloat()).toInt() mWidthSeekBar.progress = widthValue val widthTextView = findViewById<TextView>(R.id.textview_width) widthTextView.text = widthValue.toString() mWidthSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { widthTextView.text = progressToWidth(progress).toString() } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) mWeightSeekBar = findViewById(R.id.seek_bar_weight) val weightValue = WEIGHT_DEFAULT.toFloat() / WEIGHT_MAX.toFloat() * 100 mWeightSeekBar.progress = weightValue.toInt() val weightTextView = findViewById<TextView>(R.id.textview_weight) weightTextView.text = WEIGHT_DEFAULT.toString() mWeightSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { weightTextView .setText(progressToWeight(progress).toString()) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) mItalicSeekBar = findViewById<SeekBar>(R.id.seek_bar_italic) mItalicSeekBar.progress = ITALIC_DEFAULT.toInt() val italicTextView = findViewById<TextView>(R.id.textview_italic) italicTextView.text = ITALIC_DEFAULT.toString() mItalicSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { italicTextView .setText(progressToItalic(progress).toString()) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) } private fun isValidFamilyName(familyName: String?): Boolean { return familyName != null && mFamilyNameSet.contains(familyName) } /** * Converts progress from a SeekBar to the value of width. * @param progress is passed from 0 to 100 inclusive * * * @return the converted width */ private fun progressToWidth(progress: Int): Float { return (if (progress == 0) 1 else progress * WIDTH_MAX / 100).toFloat() } /** * Converts progress from a SeekBar to the value of weight. * @param progress is passed from 0 to 100 inclusive * * * @return the converted weight */ private fun progressToWeight(progress: Int): Int { if (progress == 0) { return 1 // The range of the weight is between (0, 1000) (exclusive) } else if (progress == 100) { return WEIGHT_MAX - 1 // The range of the weight is between (0, 1000) (exclusive) } else { return WEIGHT_MAX * progress / 100 } } /** * Converts progress from a SeekBar to the value of italic. * @param progress is passed from 0 to 100 inclusive. * * * @return the converted italic */ private fun progressToItalic(progress: Int): Float { return progress.toFloat() / 100f } companion object { private val TAG = "MainActivity" } }
apache-2.0
fb8286ba066581b51472081a09fb064e
39.630522
104
0.663339
4.961746
false
false
false
false
allotria/intellij-community
plugins/svn4idea/src/org/jetbrains/idea/svn/status/CmdStatusClient.kt
1
9921
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.svn.status import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Getter import com.intellij.openapi.util.Ref import com.intellij.openapi.util.io.FileUtil.* import com.intellij.openapi.util.text.StringUtil.isEmptyOrSpaces import com.intellij.util.containers.ContainerUtil.find import com.intellij.util.containers.Convertor import org.jetbrains.idea.svn.SvnBundle.message import org.jetbrains.idea.svn.SvnUtil import org.jetbrains.idea.svn.SvnUtil.append import org.jetbrains.idea.svn.SvnUtil.isSvnVersioned import org.jetbrains.idea.svn.api.* import org.jetbrains.idea.svn.api.Target import org.jetbrains.idea.svn.checkin.CommitInfo import org.jetbrains.idea.svn.commandLine.* import org.jetbrains.idea.svn.commandLine.CommandUtil.parse import org.jetbrains.idea.svn.commandLine.CommandUtil.requireExistingParent import org.jetbrains.idea.svn.info.Info import org.jetbrains.idea.svn.lock.Lock import java.io.File import javax.xml.bind.JAXBException import javax.xml.bind.annotation.* import javax.xml.bind.annotation.adapters.XmlAdapter import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter private fun putParameters(parameters: MutableList<String>, path: File, depth: Depth?, remote: Boolean, reportAll: Boolean, includeIgnored: Boolean) { CommandUtil.put(parameters, path) CommandUtil.put(parameters, depth) CommandUtil.put(parameters, remote, "-u") CommandUtil.put(parameters, reportAll, "--verbose") CommandUtil.put(parameters, includeIgnored, "--no-ignore") parameters.add("--xml") } private fun parseResult(base: File, infoBase: Info?, infoProvider: Convertor<File, Info>, result: String, handler: StatusConsumer): Boolean { val externalsMap = mutableMapOf<File, Info?>() var hasEntries = false fun setUrlAndNotifyHandler(builder: Status.Builder) { builder.infoProvider = Getter { infoProvider.convert(builder.file) } val file = builder.file val externalsBase = find(externalsMap.keys) { isAncestor(it, file, false) } val baseFile = externalsBase ?: base val baseInfo = if (externalsBase != null) externalsMap[externalsBase] else infoBase if (baseInfo != null) { builder.url = append(baseInfo.url!!, toSystemIndependentName(getRelativePath(baseFile, file)!!)) } val status = builder.build() if (status.`is`(StatusType.STATUS_EXTERNAL)) { externalsMap[status.file] = try { status.info } catch (e: SvnExceptionWrapper) { throw SvnBindException(e.cause) } } hasEntries = true handler.consume(status) } val statusRoot = parse(result, StatusRoot::class.java) if (statusRoot != null) { statusRoot.target?.entries?.forEach { entry -> val builder = entry.toBuilder(base) setUrlAndNotifyHandler(builder) } for (changeList in statusRoot.changeLists) { changeList.entries.forEach { entry -> val builder = entry.toBuilder(base) builder.changeListName = changeList.name setUrlAndNotifyHandler(builder) } } } return hasEntries } class CmdStatusClient : BaseSvnClient(), StatusClient { @Throws(SvnBindException::class) override fun doStatus(path: File, depth: Depth, remote: Boolean, reportAll: Boolean, includeIgnored: Boolean, collectParentExternals: Boolean, handler: StatusConsumer) { val base = requireExistingParent(path) val infoBase = myFactory.createInfoClient().doInfo(base, null) val parameters = mutableListOf<String>() putParameters(parameters, path, depth, remote, reportAll, includeIgnored) val command = execute(myVcs, Target.on(path), SvnCommandName.st, parameters, null) parseResult(path, base, infoBase, command, handler) } @Throws(SvnBindException::class) override fun doStatus(path: File, remote: Boolean): Status? { val status = Ref.create<Status>() doStatus(path, Depth.EMPTY, remote, false, false, false) { status.set(it) } return status.get() } @Throws(SvnBindException::class) private fun parseResult(path: File, base: File, infoBase: Info?, command: CommandExecutor, handler: StatusConsumer) { val result = command.output if (isEmptyOrSpaces(result)) throw SvnBindException(message("error.svn.status.with.no.output", command.commandText)) try { if (!parseResult(base, infoBase, createInfoGetter(), result, handler)) { if (!isSvnVersioned(myVcs, path)) { LOG.info("Status requested not in working copy. Command - ${command.commandText}. Result - $result") throw SvnBindException(ErrorCode.WC_NOT_WORKING_COPY, message("error.svn.status.not.in.working.copy", command.commandText)) } else { // return status indicating "NORMAL" state // typical output would be like // <status> // <target path="1.txt"></target> // </status> // so it does not contain any <entry> element and current parsing logic returns null val status = Status.Builder(path) status.itemStatus = StatusType.STATUS_NORMAL status.infoProvider = Getter { createInfoGetter().convert(path) } handler.consume(status.build()) } } } catch (e: JAXBException) { // status parsing errors are logged separately as sometimes there are parsing errors connected to terminal output handling. // these errors primarily occur when status output is rather large. // and status output could be large, for instance, when working copy is locked (seems that each file is listed in status output). command.logCommand() throw SvnBindException(e) } } private fun createInfoGetter() = Convertor<File, Info> { try { myFactory.createInfoClient().doInfo(it, null) } catch (e: SvnBindException) { throw SvnExceptionWrapper(e) } } companion object { private val LOG = logger<CmdStatusClient>() fun parseResult(base: File, result: String): Status? { val ref = Ref<Status?>() parseResult(base, null, Convertor { null }, result, StatusConsumer(ref::set)) return ref.get() } } } private class StatusRevisionNumberAdapter : XmlAdapter<String, Long>() { override fun marshal(v: Long) = throw UnsupportedOperationException() override fun unmarshal(v: String) = when (v) { Revision.UNDEFINED.toString() -> -1L else -> v.toLong() } } @XmlRootElement(name = "status") @XmlAccessorType(XmlAccessType.FIELD) private class StatusRoot { var target: StatusTarget? = null @XmlElement(name = "changelist") val changeLists = mutableListOf<ChangeList>() } @XmlAccessorType(XmlAccessType.NONE) private class StatusTarget { @XmlElement(name = "entry") val entries = mutableListOf<Entry>() } @XmlAccessorType(XmlAccessType.FIELD) private class ChangeList { @XmlAttribute(required = true) var name: String = "" @XmlElement(name = "entry") val entries = mutableListOf<Entry>() } @XmlAccessorType(XmlAccessType.FIELD) private class Entry { @XmlAttribute(required = true) var path: String = "" @XmlElement(name = "wc-status") var localStatus = WorkingCopyStatus() @XmlElement(name = "repos-status") var repositoryStatus: RepositoryStatus? = null fun toBuilder(base: File) = Status.Builder(SvnUtil.resolvePath(base, path)).apply { fileExists = file.exists() nodeKind = if (fileExists) NodeKind.from(file.isDirectory) else NodeKind.UNKNOWN if (!fileExists) fixInvalidOutputForUnversionedBase(base, this) itemStatus = localStatus.itemStatus propertyStatus = localStatus.propertyStatus revision = Revision.of(localStatus.revision ?: -1L) isWorkingCopyLocked = localStatus.isWorkingCopyLocked isCopied = localStatus.isCopied isSwitched = localStatus.isSwitched isTreeConflicted = localStatus.isTreeConflicted commitInfo = localStatus.commit localLock = localStatus.lock remoteItemStatus = repositoryStatus?.itemStatus remotePropertyStatus = repositoryStatus?.propertyStatus remoteLock = repositoryStatus?.lock } /** * Reproducible with svn 1.7 clients */ fun fixInvalidOutputForUnversionedBase(base: File, status: Status.Builder) { if (base.name == path && StatusType.MISSING != status.itemStatus && StatusType.STATUS_DELETED != status.itemStatus) { status.fileExists = true status.nodeKind = NodeKind.DIR status.file = base } } } @XmlAccessorType(XmlAccessType.FIELD) private class WorkingCopyStatus { @XmlAttribute(name = "item", required = true) var itemStatus = StatusType.STATUS_NONE @XmlAttribute(name = "props", required = true) var propertyStatus = StatusType.STATUS_NONE @XmlJavaTypeAdapter(StatusRevisionNumberAdapter::class) @XmlAttribute var revision: Long? = null @XmlAttribute(name = "wc-locked") var isWorkingCopyLocked = false @XmlAttribute(name = "copied") var isCopied = false @XmlAttribute(name = "switched") var isSwitched = false @XmlAttribute(name = "tree-conflicted") var isTreeConflicted = false var commit: CommitInfo.Builder? = null var lock: Lock.Builder? = null } @XmlAccessorType(XmlAccessType.FIELD) private class RepositoryStatus { @XmlAttribute(name = "item", required = true) var itemStatus = StatusType.STATUS_NONE @XmlAttribute(name = "props", required = true) var propertyStatus = StatusType.STATUS_NONE var lock: Lock.Builder? = null }
apache-2.0
03f01914008dab068e2a333ee28e5267
33.32872
140
0.694285
4.156263
false
false
false
false
zpao/buck
src/com/facebook/buck/multitenant/service/PotentiallyAffectedBuildPackages.kt
1
7331
/* * Copyright (c) Facebook, Inc. and its 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.buck.multitenant.service import com.facebook.buck.core.path.ForwardRelativePath /** * A collection of packages (package is represented by the relative path to its root) that may have * changed because of some input change and thus need to be reparsed */ data class PotentiallyAffectedBuildPackages( val commit: Commit, val added: List<ForwardRelativePath> = emptyList(), val modified: List<ForwardRelativePath> = emptyList(), val removed: List<ForwardRelativePath> = emptyList() ) { /** * True if no packages are affected by commit */ fun isEmpty() = added.isEmpty() && modified.isEmpty() && removed.isEmpty() /** * True if at least one package is affected by commit */ fun isNotEmpty() = !isEmpty() /** * Size of potentially affected packages */ fun size() = added.size + modified.size + removed.size } /** * Based on changed input files, determines packages that might have changed. We use defensive * approach to detect if package is changed because we overschedule reparsing rather than * sacrifice correctness. * * @param fsChanges Changes in files relative to the root of the repo * @param buildFileName Name of the build file (like 'BUCK'), expressed as [ForwardRelativePath], for * current cell being parsed * @param includesProvider returns paths to build packages that transitively includes passed include path * TODO: change to a function * @param cellPathNormalizer Function that transforms a path relative to the root of repo, to the * path relative to the root of the cell. Returns null if path does not belong to the cell. * @param packageExists Predicate used to check if some package exists in the universe of a current * cell * @return Paths to packages which may be affected by [fsChanges], relative to the cell */ fun getPotentiallyAffectedBuildPackages( fsChanges: FsChanges, buildFileName: ForwardRelativePath, includesProvider: (includePath: Include) -> Iterable<ForwardRelativePath>, cellPathNormalizer: (path: ForwardRelativePath) -> ForwardRelativePath?, packageExists: (path: ForwardRelativePath) -> Boolean ): PotentiallyAffectedBuildPackages { val newPackages = mutableSetOf<ForwardRelativePath>() val changedPackages = mutableSetOf<ForwardRelativePath>() val removedPackages = mutableSetOf<ForwardRelativePath>() fsChanges.added.forEach { added -> // Adding a new file cannot be a parse-time dependency, as they have to be explicitly // declared, so nothing to do here // Only if added file belongs to the cell cellPathNormalizer(added.path)?.let { path -> // Adding a new package: need to parse it and also its parent, because a parent may lose // targets if (path.nameAsPath().orElse(ForwardRelativePath.EMPTY) == buildFileName) { val newPackagePath = path.parent().orElse(ForwardRelativePath.EMPTY) newPackages.add(newPackagePath) getContainingPackage(newPackagePath.parent().orElse(ForwardRelativePath.EMPTY), packageExists)?.let { changedPackages.add(it) } return@forEach } // Adding a new source file: reparse package that potentially owns the file because // some target contents may change getContainingPackage(path.parent().orElse(ForwardRelativePath.EMPTY), packageExists)?.let { changedPackages.add(it) } } } fsChanges.modified.forEach { modified -> // Modifying a parse-time dependency: detect and reparse affected packages only // Modified file may belong to a different cell! changedPackages.addAll(includesProvider(modified.path)) // Only if modified file belongs to the cell cellPathNormalizer(modified.path)?.let { path -> // Modifying existing package: need to reparse it if (path.nameAsPath().orElse(ForwardRelativePath.EMPTY) == buildFileName) { val packagePath = path.parent().orElse(ForwardRelativePath.EMPTY) changedPackages.add(packagePath) } // Modifying a source file: it does not yield to changes in packages, so nothing more // to do } } fsChanges.removed.forEach { removed -> // Removing a parse-time dependency: detect and reparse affected packages only // Removed file may belong to a different cell! changedPackages.addAll(includesProvider(removed.path)) // Only if removed file belongs to the cell cellPathNormalizer(removed.path)?.let { path -> // Removing a package: need to remove the package itself and reparse the parent as its // targets can change because parent package may start to own more files if (path.nameAsPath().orElse(ForwardRelativePath.EMPTY) == buildFileName) { val packagePath = path.parent().orElse(ForwardRelativePath.EMPTY) removedPackages.add(packagePath) getContainingPackage(packagePath.parent().orElse(ForwardRelativePath.EMPTY), packageExists)?.let { changedPackages.add(it) } return@forEach } // Removing a source file: reparse package that potentially owns the file because // some target contents may change getContainingPackage(path.parent().orElse(ForwardRelativePath.EMPTY), packageExists)?.let { changedPackages.add(it) } } } return PotentiallyAffectedBuildPackages(commit = fsChanges.commit, added = newPackages.toList(), removed = removedPackages.toList(), modified = (changedPackages - newPackages - removedPackages).toList()) } /** * Return a package (by path) that potentially owns the specified path. There should be only one * package, or none, in which case null is returned. * * @param dir Path to a folder that might belong to some package; this folder * will be either directly a package root folder (folder that has build file) or some folder below * package root it in a directory tree * @param packageExists Predicate used to check if some package exists in the universe */ private fun getContainingPackage( dir: ForwardRelativePath, packageExists: (path: ForwardRelativePath) -> Boolean ): ForwardRelativePath? { var current = dir while (true) { if (packageExists(current)) { return current } if (current.isEmpty()) { return null } // traverse up the directory tree current = current.parent().orElse(ForwardRelativePath.EMPTY) } }
apache-2.0
9880acd54b83f88e8bbb2c3d175c777b
42.378698
129
0.688856
4.874335
false
false
false
false
leafclick/intellij-community
plugins/git4idea/src/git4idea/repo/GitSubmodule.kt
1
907
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.repo class GitSubmodule( val repository: GitRepository, val parent: GitRepository) fun GitRepository.asSubmodule() : GitSubmodule? { val repositoryManager = GitRepositoryManager.getInstance(project) val parent = repositoryManager.repositories.find { it.isParentRepositoryFor(this) } return if (parent != null) GitSubmodule(this, parent) else null } private fun GitRepository.isParentRepositoryFor(submodule: GitRepository): Boolean { return submodules.any { module -> root.findFileByRelativePath(module.path) == submodule.root } } fun GitRepository.isSubmodule(): Boolean = asSubmodule() != null fun GitRepository.getDirectSubmodules(): Collection<GitRepository> = GitRepositoryManager.getInstance(project).getDirectSubmodules(this)
apache-2.0
5ac0e98a9e0dcc658435157fe1029450
44.4
140
0.794928
4.557789
false
false
false
false
zdary/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/WorkspaceBuilderChangeLog.kt
1
6148
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.intellij.openapi.diagnostic.logger import com.intellij.workspaceModel.storage.WorkspaceEntity internal typealias ChangeLog = MutableMap<EntityId, ChangeEntry> class WorkspaceBuilderChangeLog { var modificationCount: Long = 0 internal val changeLog: ChangeLog = LinkedHashMap() internal fun clear() { modificationCount++ changeLog.clear() } internal fun <T : WorkspaceEntity> addReplaceEvent(entityId: EntityId, copiedData: WorkspaceEntityData<T>, addedChildren: List<Pair<ConnectionId, EntityId>>, removedChildren: List<Pair<ConnectionId, EntityId>>, parentsMapRes: Map<ConnectionId, EntityId?>) { modificationCount++ val existingChange = changeLog[entityId] val replaceEvent = ChangeEntry.ReplaceEntity(copiedData, addedChildren, removedChildren, parentsMapRes) val makeReplaceEvent = { replaceEntity: ChangeEntry.ReplaceEntity<*> -> val removedChildrenSet = removedChildren.toSet() val addedChildrenSet = addedChildren.toSet() val newAddedChildren = (replaceEntity.newChildren.toSet() - removedChildrenSet + (addedChildrenSet - replaceEntity.removedChildren.toSet())).toList() val newRemovedChildren = (replaceEntity.removedChildren.toSet() - addedChildrenSet + (removedChildrenSet - replaceEntity.newChildren.toSet())).toList() val newChangedParents = replaceEntity.modifiedParents + parentsMapRes ChangeEntry.ReplaceEntity(copiedData, newAddedChildren, newRemovedChildren, newChangedParents) } if (existingChange == null) { changeLog[entityId] = replaceEvent } else { when (existingChange) { is ChangeEntry.AddEntity<*> -> changeLog[entityId] = ChangeEntry.AddEntity(copiedData, entityId.clazz) is ChangeEntry.RemoveEntity -> LOG.error("Trying to update removed entity. Skip change event. $copiedData") is ChangeEntry.ChangeEntitySource<*> -> changeLog[entityId] = ChangeEntry.ReplaceAndChangeSource.from(replaceEvent, existingChange) is ChangeEntry.ReplaceEntity<*> -> changeLog[entityId] = makeReplaceEvent(existingChange) is ChangeEntry.ReplaceAndChangeSource<*> -> { val newReplaceEvent = makeReplaceEvent(existingChange.dataChange) changeLog[entityId] = ChangeEntry.ReplaceAndChangeSource.from(newReplaceEvent, existingChange.sourceChange) } }.let { } } } internal fun <T : WorkspaceEntity> addAddEvent(pid: EntityId, pEntityData: WorkspaceEntityData<T>) { modificationCount++ // XXX: This check should exist, but some tests fails with it. //if (targetEntityId in it) LOG.error("Trying to add entity again. ") changeLog[pid] = ChangeEntry.AddEntity(pEntityData, pid.clazz) } internal fun <T : WorkspaceEntity> addChangeSourceEvent(entityId: EntityId, copiedData: WorkspaceEntityData<T>) { modificationCount++ val existingChange = changeLog[entityId] val changeSourceEvent = ChangeEntry.ChangeEntitySource(copiedData) if (existingChange == null) { changeLog[entityId] = changeSourceEvent } else { when (existingChange) { is ChangeEntry.AddEntity<*> -> changeLog[entityId] = ChangeEntry.AddEntity(copiedData, entityId.clazz) is ChangeEntry.RemoveEntity -> LOG.error("Trying to update removed entity. Skip change event. $copiedData") is ChangeEntry.ChangeEntitySource<*> -> changeLog[entityId] = changeSourceEvent is ChangeEntry.ReplaceEntity<*> -> changeLog[entityId] = ChangeEntry.ReplaceAndChangeSource.from(existingChange, changeSourceEvent) is ChangeEntry.ReplaceAndChangeSource<*> -> changeLog[entityId] = ChangeEntry.ReplaceAndChangeSource.from(existingChange.dataChange, changeSourceEvent) }.let { } } } internal fun addRemoveEvent(removedEntityId: EntityId) { modificationCount++ val existingChange = changeLog[removedEntityId] val removeEvent = ChangeEntry.RemoveEntity(removedEntityId) if (existingChange == null) { changeLog[removedEntityId] = removeEvent } else { when (existingChange) { is ChangeEntry.AddEntity<*> -> changeLog.remove(removedEntityId) is ChangeEntry.RemoveEntity -> LOG.error("Trying to remove the entity twice. $removedEntityId") is ChangeEntry.ChangeEntitySource<*> -> changeLog[removedEntityId] = removeEvent is ChangeEntry.ReplaceEntity<*> -> changeLog[removedEntityId] = removeEvent is ChangeEntry.ReplaceAndChangeSource<*> -> changeLog[removedEntityId] = removeEvent } } } companion object { val LOG = logger<WorkspaceBuilderChangeLog>() } } internal sealed class ChangeEntry { data class AddEntity<E : WorkspaceEntity>(val entityData: WorkspaceEntityData<E>, val clazz: Int) : ChangeEntry() data class RemoveEntity(val id: EntityId) : ChangeEntry() data class ChangeEntitySource<E : WorkspaceEntity>(val newData: WorkspaceEntityData<E>) : ChangeEntry() data class ReplaceEntity<E : WorkspaceEntity>( val newData: WorkspaceEntityData<E>, val newChildren: List<Pair<ConnectionId, EntityId>>, val removedChildren: List<Pair<ConnectionId, EntityId>>, val modifiedParents: Map<ConnectionId, EntityId?> ) : ChangeEntry() data class ReplaceAndChangeSource<E : WorkspaceEntity>( val dataChange: ReplaceEntity<E>, val sourceChange: ChangeEntitySource<E>, ) : ChangeEntry() { companion object { fun <T : WorkspaceEntity> from(dataChange: ReplaceEntity<T>, sourceChange: ChangeEntitySource<*>): ReplaceAndChangeSource<T> { return ReplaceAndChangeSource(dataChange, sourceChange as ChangeEntitySource<T>) } } } }
apache-2.0
d90dbe5d3988c7e931f6b2d9d2ccc6ea
45.575758
157
0.699577
4.754834
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/builtinStubMethods/Collection.kt
2
1082
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE class MyCollection<T>: Collection<T> { override val size: Int get() = 0 override fun isEmpty(): Boolean = true override fun contains(o: T): Boolean = false override fun iterator(): Iterator<T> = throw UnsupportedOperationException() override fun containsAll(c: Collection<T>): Boolean = false override fun hashCode(): Int = 0 override fun equals(other: Any?): Boolean = false } fun expectUoe(block: () -> Any) { try { block() throw AssertionError() } catch (e: UnsupportedOperationException) { } } fun box(): String { val myCollection = MyCollection<String>() val collection = myCollection as java.util.Collection<String> expectUoe { collection.add("") } expectUoe { collection.remove("") } expectUoe { collection.addAll(myCollection) } expectUoe { collection.removeAll(myCollection) } expectUoe { collection.retainAll(myCollection) } expectUoe { collection.clear() } return "OK" }
apache-2.0
bd48cdcec9f2dd82da23957d323ca802
30.823529
80
0.676525
4.129771
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/operatorConventions/assignmentOperations.kt
2
891
class A() { var x = 0 } operator fun A.plusAssign(y: Int) { x += y } operator fun A.minusAssign(y: Int) { x -= y } operator fun A.timesAssign(y: Int) { x *= y } operator fun A.divAssign(y: Int) { x /= y } operator fun A.modAssign(y: Int) { x %= y } fun box(): String { val original = A() val a = original a += 1 if (a !== original) return "Fail 1: $a !== $original" if (a.x != 1) return "Fail 2: ${a.x} != 1" a -= 2 if (a !== original) return "Fail 3: $a !== $original" if (a.x != -1) return "Fail 4: ${a.x} != -1" a *= -10 if (a !== original) return "Fail 5: $a !== $original" if (a.x != 10) return "Fail 6: ${a.x} != 10" a /= 3 if (a !== original) return "Fail 7: $a !== $original" if (a.x != 3) return "Fail 8: ${a.x} != 3" a %= 2 if (a !== original) return "Fail 9: $a !== $original" if (a.x != 1) return "Fail 10: ${a.x} != 1" return "OK" }
apache-2.0
54b2b48889dac2856cb87e1caaa5b850
23.777778
55
0.515152
2.612903
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GHTokenCredentialsUi.kt
5
5087
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.authentication.ui import com.intellij.ide.BrowserUtil.browse import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.DocumentAdapter import com.intellij.ui.components.JBTextField import com.intellij.ui.components.fields.ExtendableTextField import com.intellij.ui.layout.* import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.authentication.util.GHSecurityUtil import org.jetbrains.plugins.github.authentication.util.GHSecurityUtil.buildNewTokenUrl import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException import org.jetbrains.plugins.github.exceptions.GithubParseException import org.jetbrains.plugins.github.i18n.GithubBundle.message import org.jetbrains.plugins.github.ui.util.DialogValidationUtils.notBlank import org.jetbrains.plugins.github.ui.util.Validator import java.net.UnknownHostException import javax.swing.JComponent import javax.swing.JTextField import javax.swing.event.DocumentEvent internal class GHTokenCredentialsUi( private val serverTextField: ExtendableTextField, val factory: GithubApiRequestExecutor.Factory, val isAccountUnique: UniqueLoginPredicate ) : GHCredentialsUi() { private val tokenTextField = JBTextField() private var fixedLogin: String? = null fun setToken(token: String) { tokenTextField.text = token } override fun LayoutBuilder.centerPanel() { row(message("credentials.server.field")) { serverTextField(pushX, growX) } row(message("credentials.token.field")) { cell { tokenTextField( comment = message("login.insufficient.scopes", GHSecurityUtil.MASTER_SCOPES), constraints = *arrayOf(pushX, growX) ) button(message("credentials.button.generate")) { browseNewTokenUrl() } .enableIf(serverTextField.serverValid) } } } private fun browseNewTokenUrl() = browse(buildNewTokenUrl(serverTextField.tryParseServer()!!)) override fun getPreferredFocusableComponent(): JComponent = tokenTextField override fun getValidator(): Validator = { notBlank(tokenTextField, message("login.token.cannot.be.empty")) } override fun createExecutor() = factory.create(tokenTextField.text) override fun acquireLoginAndToken( server: GithubServerPath, executor: GithubApiRequestExecutor, indicator: ProgressIndicator ): Pair<String, String> { val login = acquireLogin(server, executor, indicator, isAccountUnique, fixedLogin) return login to tokenTextField.text } override fun handleAcquireError(error: Throwable): ValidationInfo = when (error) { is GithubParseException -> ValidationInfo(error.message ?: message("credentials.invalid.server.path"), serverTextField) else -> handleError(error) } override fun setBusy(busy: Boolean) { tokenTextField.isEnabled = !busy } fun setFixedLogin(fixedLogin: String?) { this.fixedLogin = fixedLogin } companion object { fun acquireLogin( server: GithubServerPath, executor: GithubApiRequestExecutor, indicator: ProgressIndicator, isAccountUnique: UniqueLoginPredicate, fixedLogin: String? ): String { val (details, scopes) = GHSecurityUtil.loadCurrentUserWithScopes(executor, indicator, server) if (scopes == null || !GHSecurityUtil.isEnoughScopes(scopes)) throw GithubAuthenticationException("Insufficient scopes granted to token.") val login = details.login if (fixedLogin != null && fixedLogin != login) throw GithubAuthenticationException("Token should match username \"$fixedLogin\"") if (!isAccountUnique(login, server)) throw LoginNotUniqueException(login) return login } fun handleError(error: Throwable): ValidationInfo = when (error) { is LoginNotUniqueException -> ValidationInfo(message("login.account.already.added", error.login)).withOKEnabled() is UnknownHostException -> ValidationInfo(message("server.unreachable")).withOKEnabled() is GithubAuthenticationException -> ValidationInfo(message("credentials.incorrect", error.message.orEmpty())).withOKEnabled() else -> ValidationInfo(message("credentials.invalid.auth.data", error.message.orEmpty())).withOKEnabled() } } } private val JTextField.serverValid: ComponentPredicate get() = object : ComponentPredicate() { override fun invoke(): Boolean = tryParseServer() != null override fun addListener(listener: (Boolean) -> Unit) = document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) = listener(tryParseServer() != null) }) } private fun JTextField.tryParseServer(): GithubServerPath? = try { GithubServerPath.from(text.trim()) } catch (e: GithubParseException) { null }
apache-2.0
a31704aebc4f66a3571719559c29c058
38.75
140
0.754865
4.723305
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/ScaledIconPresentation.kt
10
1552
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.hints.presentation import com.intellij.codeInsight.hints.fireContentChanged import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.util.IconUtil import org.jetbrains.annotations.ApiStatus import java.awt.AlphaComposite import java.awt.Component import java.awt.Graphics2D import javax.swing.Icon /** * Draws image. If you need to position image inside inlay, use [InsetPresentation] */ @ApiStatus.Internal class ScaledIconPresentation( private val metricsStorage: InlayTextMetricsStorage, val isSmall: Boolean, icon: Icon, private val component: Component) : BasePresentation() { var icon = icon set(value) { field = value fireContentChanged() } private fun getMetrics() = metricsStorage.getFontMetrics(isSmall) private fun getScaleFactor() = (getMetrics().fontHeight.toDouble() / icon.iconHeight) override val width: Int get() = (icon.iconWidth * getScaleFactor()).toInt() override val height: Int get() = getMetrics().fontHeight override fun paint(g: Graphics2D, attributes: TextAttributes) { val graphics = g.create() as Graphics2D graphics.composite = AlphaComposite.SrcAtop.derive(1.0f) val scaledIcon = IconUtil.scale(icon, component, (getScaleFactor()).toFloat()) scaledIcon.paintIcon(component, graphics, 0, 0) graphics.dispose() } override fun toString(): String = "<image>" }
apache-2.0
32ead85b59a2ffc5b426f70e8e2ae514
33.511111
140
0.757088
4.205962
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/inspections/AddFunctionReturnTypeIntention.kt
1
1820
/* * 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.inspections import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.frontend.api.KtAnalysisSession import org.jetbrains.kotlin.idea.frontend.api.types.* import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtPsiFactory class AddFunctionReturnTypeIntention : AbstractHighLevelApiBasedIntention<KtNamedFunction, TypeCandidate>( KtNamedFunction::class.java, { KotlinBundle.message("intention.add.function.return.type.specify.type.explicitly") } ) { override fun isApplicableByPsi(element: KtNamedFunction): Boolean = element.typeReference == null && !element.hasBlockBody() override fun KtAnalysisSession.analyzeAndGetData(element: KtNamedFunction): TypeCandidate? { val returnType = element.getReturnKtType() val approximated = approximateTypeToUpperDenotable(returnType) ?: return null return TypeCandidate(approximated.render()) } private tailrec fun approximateTypeToUpperDenotable(type: KtType): KtDenotableType? = when (type) { is KtNonDenotableType -> when (type) { is KtFlexibleType -> approximateTypeToUpperDenotable(type.upperBound) is KtIntersectionType -> null } is KtDenotableType -> type else -> null } override fun applyTo(element: KtNamedFunction, data: TypeCandidate, editor: Editor?) { element.typeReference = KtPsiFactory(element).createType(data.candidate) } } data class TypeCandidate(val candidate: String)
apache-2.0
9af7c35c95c063c51bf570dc6c3a1f0a
40.386364
115
0.747802
4.751958
false
false
false
false
smmribeiro/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/properties/PropertiesDialog.kt
7
2147
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.service.ui.properties import com.intellij.execution.util.setEmptyState import com.intellij.openapi.externalSystem.service.ui.util.ObservableDialogWrapper import com.intellij.openapi.externalSystem.util.ExternalSystemBundle import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign class PropertiesDialog( private val project: Project, private val info: PropertiesInfo ) : ObservableDialogWrapper(project) { private val table = PropertiesTable() var properties by table::properties override fun configureCenterPanel(panel: Panel) { with(panel) { row { label(info.dialogLabel) } row { table.setEmptyState(info.dialogEmptyState) cell(table.component) .horizontalAlign(HorizontalAlign.FILL) } } } override fun doOKAction() { val validationInfo = validateProperties() if (validationInfo != null) { val title = ExternalSystemBundle.message("external.system.properties.error.title") Messages.showErrorDialog(project, validationInfo.message, title) return } super.doOKAction() } private fun validateProperties(): ValidationInfo? { if (table.properties.any { it.name.isEmpty() }) { return ValidationInfo(ExternalSystemBundle.message("external.system.properties.error.empty.message")) } if (table.properties.any { it.name.contains(' ') }) { return ValidationInfo(ExternalSystemBundle.message("external.system.properties.error.space.message")) } if (table.properties.any { it.name.contains('=') }) { return ValidationInfo(ExternalSystemBundle.message("external.system.properties.error.assign.message")) } return null } init { title = info.dialogTitle setOKButtonText(info.dialogOkButton) init() } }
apache-2.0
c925d23743b460cf18c4c7ceaab68079
33.095238
158
0.737308
4.408624
false
false
false
false
WillowChat/Kale
src/main/kotlin/chat/willow/kale/irc/message/rfc1459/PassMessage.kt
2
990
package chat.willow.kale.irc.message.rfc1459 import chat.willow.kale.core.ICommand import chat.willow.kale.core.message.* object PassMessage : ICommand { override val command = "PASS" data class Command(val password: String) { object Descriptor : KaleDescriptor<Command>(matcher = commandMatcher(command), parser = Parser) object Parser : MessageParser<Command>() { override fun parseFromComponents(components: IrcMessageComponents): Command? { if (components.parameters.isEmpty()) { return null } val password = components.parameters[0] return Command(password) } } object Serialiser : MessageSerialiser<Command>(command) { override fun serialiseToComponents(message: Command): IrcMessageComponents { return IrcMessageComponents(parameters = listOf(message.password)) } } } }
isc
03ba14078cdf49ee779f6a0a76838d65
25.783784
103
0.625253
5.351351
false
false
false
false
TonicArtos/SuperSLiM
library/src/main/kotlin/com/tonicartos/superslim/internal/layout/header.kt
1
12767
package com.tonicartos.superslim.internal.layout import com.tonicartos.superslim.LayoutHelper import com.tonicartos.superslim.SectionConfig import com.tonicartos.superslim.SectionLayoutManager import com.tonicartos.superslim.internal.SectionState import com.tonicartos.superslim.internal.SectionState.HeaderLayoutState import com.tonicartos.superslim.internal.SectionState.LayoutState import com.tonicartos.superslim.internal.insetStickyStart import com.tonicartos.superslim.use private const val ABSENT = 1 shl 0 private const val ADDED = 1 shl 1 private const val FLOATING = 1 shl 2 internal object HeaderLayoutManager : SectionLayoutManager<SectionState> { override fun isAtTop(section: SectionState, layoutState: LayoutState) = selectHeaderLayout(section).isAtTop(section, layoutState) override fun onLayout(helper: LayoutHelper, section: SectionState, layoutState: LayoutState) = selectHeaderLayout(section).onLayout(helper, section, layoutState) override fun onFillTop(dy: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState) = selectHeaderLayout(section).onFillTop(dy, helper, section, layoutState) override fun onFillBottom(dy: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState) = selectHeaderLayout(section).onFillBottom(dy, helper, section, layoutState) override fun onTrimTop(scrolled: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState) = selectHeaderLayout(section).onTrimTop(scrolled, helper, section, layoutState) override fun onTrimBottom(scrolled: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState) = selectHeaderLayout(section).onTrimBottom(scrolled, helper, section, layoutState) private fun selectHeaderLayout(section: SectionState): SectionLayoutManager<SectionState> { return DoNothingSlm.takeUnless { section.hasHeader } ?: when (section.baseConfig.headerStyle) { SectionConfig.HEADER_INLINE -> InlineHlm SectionConfig.HEADER_START, SectionConfig.HEADER_END -> GutterHlm else -> StickyHlm } } } private interface BaseHlm : SectionLayoutManager<SectionState> { override fun isAtTop(section: SectionState, layoutState: LayoutState) = layoutState.overdraw == 0 && layoutState.headPosition <= 0 && section.atTop } private object InlineHlm : BaseHlm { override fun onLayout(helper: LayoutHelper, section: SectionState, layoutState: LayoutState) { val state = layoutState as HeaderLayoutState var y = -state.overdraw if (state.headPosition <= 0) { helper.getHeader(section)?.use { header -> header.addToRecyclerView() header.measure() header.layout(0, y, header.measuredWidth, y + header.measuredHeight) if (helper.isPreLayout && header.isRemoved) helper.addIgnoredHeight(header.height) state.disappearedOrRemovedHeight += header.disappearedHeight y += header.height helper.filledArea += header.height state.mode = ADDED state.headPosition = 0 state.tailPosition = 0 } } else { state.mode = ABSENT state.headPosition = 1 } section.layout(helper, section.leftGutter { 0 }, y, helper.layoutWidth - section.rightGutter { 0 }, if (state.mode == ADDED) 1 else 0) state.disappearedOrRemovedHeight += section.disappearedHeight y += section.height helper.filledArea += section.height if (section.numViews > 0) state.tailPosition = 1 state.bottom = y } override fun onFillTop(dy: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { val state = layoutState as HeaderLayoutState if (state.headPosition < 0) state.headPosition = 1 if (state.headPosition == 1) { // Must fill section children first. state.overdraw += section.fillTop(Math.max(0, dy - state.overdraw), section.leftGutter { 0 }, 0, helper.layoutWidth - section.rightGutter { 0 }, helper) state.tailPosition = 1 // Fill header if there is space left. if (dy - state.overdraw > 0) { helper.getHeader(section)?.use { header -> header.addToRecyclerView(0) header.measure() state.overdraw += header.fillTop(dy - state.overdraw, 0, -state.overdraw - header.measuredHeight, header.measuredWidth, -state.overdraw) state.mode = ADDED state.headPosition = 0 } } } val filled = Math.min(dy, state.overdraw) state.overdraw -= filled state.bottom += filled return filled } override fun onFillBottom(dy: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { val state = layoutState as HeaderLayoutState var filled = if (state.tailPosition == 0) Math.max(0, state.bottom - helper.layoutLimit) else 0 if (state.headPosition < 0) { helper.getHeader(section)?.use { header -> header.addToRecyclerView() header.measure() filled += header.fillBottom(dy, 0, -state.overdraw, header.measuredWidth, -state.overdraw + header.measuredHeight) state.bottom += header.height state.mode = ADDED state.headPosition = 0 } } val before = section.height filled += section.fillBottom(dy - filled, section.leftGutter { 0 }, state.bottom - section.height, helper.layoutWidth - section.rightGutter { 0 }, helper, if (state.mode == ADDED) 1 else 0) state.bottom += section.height - before state.tailPosition = 1 return Math.min(dy, filled) } override fun onTrimTop(scrolled: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { val state = layoutState as HeaderLayoutState var removedHeight = 0 var contentTop = 0 if (state.mode == ADDED) { helper.getAttachedViewAt(0) { header -> if (header.bottom < 0) { header.remove() removedHeight += Math.max(0, header.height - state.overdraw) state.overdraw = Math.max(0, state.overdraw - header.height) state.headPosition = 1 state.mode = ABSENT } else if (header.top < 0) { val before = state.overdraw state.overdraw = -header.top removedHeight += state.overdraw - before contentTop = header.bottom } } } removedHeight += section.trimTop(scrolled, contentTop, helper, if (state.mode == ADDED) 1 else 0) if (helper.numViews == 0) { state.headPosition = -1 state.headPosition = -1 } state.bottom -= removedHeight return removedHeight } override fun onTrimBottom(scrolled: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { val state = layoutState as HeaderLayoutState var removed = 0 removed += section.trimBottom(scrolled, state.bottom - section.height, helper, if (state.mode == ADDED) 1 else 0) if (section.numViews == 0) { state.tailPosition = 0 } if (state.mode == ADDED) { helper.getAttachedViewAt(0) { header -> if (header.top >= helper.layoutLimit) { removed += header.height header.remove() state.mode = ABSENT } } } if (helper.numViews == 0) { state.headPosition = -1 state.tailPosition = -1 } state.bottom -= removed return removed } } // Sticky headers are always attached after content. private object StickyHlm : BaseHlm { override fun onLayout(helper: LayoutHelper, section: SectionState, layoutState: LayoutState) { val state = layoutState as HeaderLayoutState var y = -state.overdraw helper.getHeader(section)?.use { header -> header.addToRecyclerView() header.measure() header.layout(0, y, header.measuredWidth, y + header.measuredHeight) if (state.headPosition <= 0) { if (helper.isPreLayout && header.isRemoved) helper.addIgnoredHeight(header.height) state.disappearedOrRemovedHeight += header.disappearedHeight y += header.height helper.filledArea += header.height state.mode = ADDED state.headPosition = 0 state.tailPosition = 0 } helper.insetStickyStart(header.measuredHeight) { section.layout(helper, section.leftGutter { 0 }, y, helper.layoutWidth - section.rightGutter { 0 }) state.disappearedOrRemovedHeight += section.disappearedHeight y += section.height helper.filledArea += section.height state.headPosition = 0 state.tailPosition = 0 } if (state.mode == ABSENT) { } // Detect and adjust positioning to sticky or not. var bottom = y + header.measuredHeight val limit = helper.layoutLimit - helper.stickyStartInset val floatOffset = if (bottom > limit) limit - bottom else 0 bottom += floatOffset header.layout(0, bottom - header.measuredHeight, header.measuredWidth, bottom, helper.numViews) // 100% floating header has 0 height. // val floatAdjustedHeight = Math.max(0, header.height + floatOffset) if (helper.isPreLayout && header.isRemoved) helper.addIgnoredHeight(header.height) helper.filledArea += header.height state.mode = FLOATING if (state.headPosition < 0) state.headPosition = 1 state.tailPosition = 1 y += header.height if (y < helper.layoutLimit) { state.mode = ADDED } } state.bottom = y } override fun onFillTop(dy: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { TODO("not implemented") } override fun onFillBottom(dy: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { TODO("not implemented") } override fun onTrimTop(scrolled: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { TODO("not implemented") } override fun onTrimBottom(scrolled: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { TODO("not implemented") } } private object GutterHlm : BaseHlm { override fun isAtTop(section: SectionState, layoutState: LayoutState) = section.atTop override fun onLayout(helper: LayoutHelper, section: SectionState, layoutState: LayoutState) { TODO("not implemented") } override fun onFillTop(dy: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { TODO("not implemented") } override fun onFillBottom(dy: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { TODO("not implemented") } override fun onTrimTop(scrolled: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { TODO("not implemented") } override fun onTrimBottom(scrolled: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { TODO("not implemented") } }
apache-2.0
0859b951f2038a742b9043ec318a3721
41.845638
119
0.591368
5.076342
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/util/Buffer.kt
1
5863
package de.fabmax.kool.util import de.fabmax.kool.KoolException /** * Super class for platform-dependent buffers. In the JVM these buffers directly map to the corresponding NIO buffers. * However, not all operations of NIO buffers are supported. * * Notice that Buffer is not generic, so that concrete types remain primitive. * * @author fabmax */ interface Buffer { var limit: Int var position: Int val remaining: Int val capacity: Int fun flip() fun clear() fun removeAt(index: Int) { if (position > index) { position-- } if (limit > index) { limit-- } } } /** * Represents a buffer for bytes. * * @author fabmax */ interface Uint8Buffer : Buffer { operator fun get(i: Int): Byte operator fun set(i: Int, value: Byte) operator fun plusAssign(value: Byte) { put(value) } fun put(value: Byte): Uint8Buffer fun put(data: ByteArray): Uint8Buffer = put(data, 0, data.size) fun put(data: ByteArray, offset: Int, len: Int): Uint8Buffer fun put(data: Uint8Buffer): Uint8Buffer fun toArray(): ByteArray { val array = ByteArray(capacity) for (i in 0 until capacity) { array[i] = get(i) } return array } override fun removeAt(index: Int) { for (i in index until position) { this[i] = this[i+1] } super.removeAt(index) } } /** * Represents a buffer for shorts. * * @author fabmax */ interface Uint16Buffer : Buffer { operator fun get(i: Int): Short operator fun set(i: Int, value: Short) operator fun plusAssign(value: Short) { put(value) } fun put(value: Short): Uint16Buffer fun put(data: ShortArray): Uint16Buffer = put(data, 0, data.size) fun put(data: ShortArray, offset: Int, len: Int): Uint16Buffer fun put(data: Uint16Buffer): Uint16Buffer override fun removeAt(index: Int) { for (i in index until position) { this[i] = this[i+1] } super.removeAt(index) } } /** * Represents a buffer for ints. * * @author fabmax */ interface Uint32Buffer : Buffer { operator fun get(i: Int): Int operator fun set(i: Int, value: Int) operator fun plusAssign(value: Int) { put(value) } fun put(value: Int): Uint32Buffer fun put(data: IntArray): Uint32Buffer = put(data, 0, data.size) fun put(data: IntArray, offset: Int, len: Int): Uint32Buffer fun put(data: Uint32Buffer): Uint32Buffer override fun removeAt(index: Int) { for (i in index until position) { this[i] = this[i+1] } super.removeAt(index) } } /** * Represents a buffer for floats. * * @author fabmax */ interface Float32Buffer : Buffer { operator fun get(i: Int): Float operator fun set(i: Int, value: Float) operator fun plusAssign(value: Float) { put(value) } fun put(value: Float): Float32Buffer fun put(data: FloatArray): Float32Buffer = put(data, 0, data.size) fun put(data: FloatArray, offset: Int, len: Int): Float32Buffer fun put(data: Float32Buffer): Float32Buffer override fun removeAt(index: Int) { for (i in index until position) { this[i] = this[i+1] } super.removeAt(index) } } /** * Represents a buffer containing mixed type data. All buffer positions are in bytes. * * @author fabmax */ interface MixedBuffer : Buffer { fun putInt8(value: Byte) = putUint8(value) fun putInt8(data: ByteArray) = putUint8(data) fun putInt8(data: ByteArray, offset: Int, len: Int) = putUint8(data, offset, len) fun putInt8(data: Uint8Buffer) = putUint8(data) fun putInt16(value: Short) = putUint16(value) fun putInt16(data: ShortArray) = putUint16(data) fun putInt16(data: ShortArray, offset: Int, len: Int) = putUint16(data, offset, len) fun putInt16(data: Uint16Buffer) = putUint16(data) fun putInt32(value: Int) = putUint32(value) fun putInt32(data: IntArray) = putUint32(data) fun putInt32(data: IntArray, offset: Int, len: Int) = putUint32(data, offset, len) fun putInt32(data: Uint32Buffer) = putUint32(data) fun putUint8(value: Byte): MixedBuffer fun putUint8(data: ByteArray): MixedBuffer = putUint8(data, 0, data.size) fun putUint8(data: ByteArray, offset: Int, len: Int): MixedBuffer fun putUint8(data: Uint8Buffer): MixedBuffer fun putUint16(value: Short): MixedBuffer fun putUint16(data: ShortArray): MixedBuffer = putUint16(data, 0, data.size) fun putUint16(data: ShortArray, offset: Int, len: Int): MixedBuffer fun putUint16(data: Uint16Buffer): MixedBuffer fun putUint32(value: Int): MixedBuffer fun putUint32(data: IntArray): MixedBuffer = putUint32(data, 0, data.size) fun putUint32(data: IntArray, offset: Int, len: Int): MixedBuffer fun putUint32(data: Uint32Buffer): MixedBuffer fun putFloat32(value: Float): MixedBuffer fun putFloat32(data: FloatArray): MixedBuffer = putFloat32(data, 0, data.size) fun putFloat32(data: FloatArray, offset: Int, len: Int): MixedBuffer fun putFloat32(data: Float32Buffer): MixedBuffer fun padding(nBytes: Int): MixedBuffer override fun removeAt(index: Int) { throw KoolException("MixedBuffer does not support element removal") } } expect fun createUint8Buffer(capacity: Int): Uint8Buffer expect fun createUint16Buffer(capacity: Int): Uint16Buffer expect fun createUint32Buffer(capacity: Int): Uint32Buffer expect fun createFloat32Buffer(capacity: Int): Float32Buffer expect fun createMixedBuffer(capacity: Int): MixedBuffer expect object BufferUtil { fun inflate(zipData: Uint8Buffer): Uint8Buffer fun deflate(data: Uint8Buffer): Uint8Buffer fun encodeBase64(data: Uint8Buffer): String fun decodeBase64(base64: String): Uint8Buffer }
apache-2.0
ac6021fad660f691f01d5df92d00a808
28.611111
118
0.667747
3.588127
false
false
false
false
Flank/flank
flank-scripts/src/test/kotlin/flank/scripts/ops/dependencies/UpdateDependenciesTest.kt
1
1129
package flank.scripts.ops.dependencies import flank.common.isWindows import flank.scripts.ops.dependencies.testfiles.testFilesPath import org.junit.Assert.assertEquals import org.junit.Assume.assumeFalse import org.junit.Test import java.io.File class UpdateDependenciesTest { private val testReport = File("${testFilesPath}report.json") private val testDependencies = File("${testFilesPath}TestDependencies") private val testVersions = File("${testFilesPath}TestVersions") @Test fun `should update dependencies`() { // assume assumeFalse(isWindows) // given val copyOfTestVersions = testVersions.copyTo( File("${testFilesPath}VersionsAfterUpdateDependencies") ) val expectedVersions = File("${testFilesPath}ExpectedVersionAfterUpdateDependencies") // when testReport.updateDependencies(testDependencies, copyOfTestVersions) // then assertEquals(copyOfTestVersions.readText(), expectedVersions.readText()) // clean up copyOfTestVersions.delete() } }
apache-2.0
fe9653fddf62c0e1fe0467f0675e0aaa
28.710526
80
0.692648
4.887446
false
true
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-db/src/main/kotlin/slatekit/db/builders/MySqlBuilder.kt
1
2948
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.db.builders import java.rmi.UnexpectedException import slatekit.common.Types import slatekit.common.data.DataType import slatekit.common.data.Encoding import slatekit.common.newline /** * Builds up database tables, indexes and other database components */ open class MySqlBuilder : DbBuilder { /** * Mapping of normalized types ot postgres type names */ val dataToColumnTypes = mapOf( DataType.DTString to "NVARCHAR", DataType.DTBool to "BIT", DataType.DTShort to "TINYINT", DataType.DTInt to "INTEGER", DataType.DTLong to "BIGINT", DataType.DTFloat to "FLOAT", DataType.DTDouble to "DOUBLE", DataType.DTDecimal to "DECIMAL", DataType.DTLocalDate to "DATE", DataType.DTLocalTime to "TIME", DataType.DTLocalDateTime to "DATETIME", DataType.DTZonedDateTime to "DATETIME", DataType.DTInstant to "INSTANT", DataType.DTDateTime to "DATETIME" ) /** * Builds the drop table DDL for the name supplied. */ override fun dropTable(name: String): String = build(name, "DROP TABLE IF EXISTS") /** * Builds a delete statement to delete all rows */ override fun truncate(name: String): String = build(name, "DELETE FROM") /** * Builds an add column DDL sql statement */ override fun addCol(name: String, dataType: DataType, required: Boolean, maxLen: Int): String { val nullText = if (required) "NOT NULL" else "" val colType = colType(dataType, maxLen) val colName = colName(name) val sql = " $newline$colName $colType $nullText" return sql } /** * Builds a valid column name */ override fun colName(name: String): String = "`" + Encoding.ensureField(name) + "`" /** * Builds a valid column type */ override fun colType(colType: DataType, maxLen: Int): String { return if (colType == DataType.DTString && maxLen == -1) "longtext" else if (colType == DataType.DTString) "VARCHAR($maxLen)" else getColTypeName(colType) } private fun build(name: String, prefix: String): String { val tableName = Encoding.ensureField(name) val sql = "$prefix `$tableName`;" return sql } private fun getColTypeName(sqlType: DataType): String { return if (dataToColumnTypes.containsKey(sqlType)) dataToColumnTypes[sqlType] ?: "" else throw UnexpectedException("Unexpected db type : $sqlType") } }
apache-2.0
03144b1abb968c9f763d98d04b17baab
29.081633
99
0.638399
4.309942
false
false
false
false
siosio/intellij-community
plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/trackers/KotlinOutOfBlockPsiTreeChangePreprocessor.kt
3
1806
/* * 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.trackers import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiTreeChangeEvent import com.intellij.psi.impl.PsiModificationTrackerImpl import com.intellij.psi.impl.PsiTreeChangeEventImpl import com.intellij.psi.impl.PsiTreeChangePreprocessor class KotlinOutOfBlockPsiTreeChangePreprocessor(private val project: Project) : PsiTreeChangePreprocessor { override fun treeChanged(event: PsiTreeChangeEventImpl) { if (!PsiModificationTrackerImpl.canAffectPsi(event)) return if (event.isOutOfBlockChange()) { incrementModificationsCount() } } private fun incrementModificationsCount() { project.service<KotlinFirModificationTrackerService>().increaseModificationCountForAllModules() } // Copy logic from PsiModificationTrackerImpl.treeChanged(). Some out-of-code-block events are written to language modification // tracker in PsiModificationTrackerImpl but don't have correspondent PomModelEvent. Increase kotlinOutOfCodeBlockTracker // manually if needed. private fun PsiTreeChangeEventImpl.isOutOfBlockChange() = when (code) { PsiTreeChangeEventImpl.PsiEventType.PROPERTY_CHANGED -> propertyName === PsiTreeChangeEvent.PROP_UNLOADED_PSI || propertyName === PsiTreeChangeEvent.PROP_ROOTS PsiTreeChangeEventImpl.PsiEventType.CHILD_MOVED -> oldParent is PsiDirectory || newParent is PsiDirectory else -> parent is PsiDirectory } }
apache-2.0
a034d2864fb41973b2b3aad01fce94c3
47.837838
131
0.779623
5.101695
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/KotlinElementActionsFactory.kt
1
22799
// 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.crossLanguage import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.QuickFixFactory import com.intellij.lang.java.beans.PropertyKind import com.intellij.lang.jvm.* import com.intellij.lang.jvm.actions.* import com.intellij.lang.jvm.types.JvmType import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtilRt import com.intellij.psi.* import com.intellij.psi.impl.source.tree.java.PsiReferenceExpressionImpl import com.intellij.psi.util.PropertyUtil import com.intellij.psi.util.PropertyUtilBase import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget import org.jetbrains.kotlin.descriptors.resolveClassByFqName import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.appendModifier import org.jetbrains.kotlin.idea.quickfix.AddModifierFix import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFix import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.* import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable.CreateCallableFromUsageFix import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.resolveToKotlinType import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType import org.jetbrains.kotlin.resolve.AnnotationChecker import org.jetbrains.kotlin.resolve.annotations.JVM_STATIC_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.typeUtil.supertypes class KotlinElementActionsFactory : JvmElementActionsFactory() { companion object { val javaPsiModifiersMapping = mapOf( JvmModifier.PRIVATE to KtTokens.PRIVATE_KEYWORD, JvmModifier.PUBLIC to KtTokens.PUBLIC_KEYWORD, JvmModifier.PROTECTED to KtTokens.PUBLIC_KEYWORD, JvmModifier.ABSTRACT to KtTokens.ABSTRACT_KEYWORD ) } private class FakeExpressionFromParameter(private val psiParam: PsiParameter) : PsiReferenceExpressionImpl() { override fun getText(): String = psiParam.name!! override fun getProject(): Project = psiParam.project override fun getParent(): PsiElement = psiParam.parent override fun getType(): PsiType? = psiParam.type override fun isValid(): Boolean = true override fun getContainingFile(): PsiFile = psiParam.containingFile override fun getReferenceName(): String? = psiParam.name override fun resolve(): PsiElement? = psiParam } private class ModifierBuilder( private val targetContainer: KtElement, private val allowJvmStatic: Boolean = true ) { private val psiFactory = KtPsiFactory(targetContainer.project) val modifierList = psiFactory.createEmptyModifierList() private fun JvmModifier.transformAndAppend(): Boolean { javaPsiModifiersMapping[this]?.let { modifierList.appendModifier(it) return true } when (this) { JvmModifier.STATIC -> { if (allowJvmStatic && targetContainer is KtClassOrObject) { addAnnotation(JVM_STATIC_ANNOTATION_FQ_NAME) } } JvmModifier.ABSTRACT -> modifierList.appendModifier(KtTokens.ABSTRACT_KEYWORD) JvmModifier.FINAL -> modifierList.appendModifier(KtTokens.FINAL_KEYWORD) else -> return false } return true } var isValid = true private set fun addJvmModifier(modifier: JvmModifier) { isValid = isValid && modifier.transformAndAppend() } fun addJvmModifiers(modifiers: Iterable<JvmModifier>) { modifiers.forEach { addJvmModifier(it) } } fun addAnnotation(fqName: FqName) { if (!isValid) return modifierList.add(psiFactory.createAnnotationEntry("@${fqName.asString()}")) } } class CreatePropertyFix( contextElement: KtElement, propertyInfo: PropertyInfo, private val classOrFileName: String? ) : CreateCallableFromUsageFix<KtElement>(contextElement, listOf(propertyInfo)) { override fun getFamilyName() = KotlinBundle.message("add.property") override fun getText(): String { val info = callableInfos.first() as PropertyInfo return buildString { append(KotlinBundle.message("text.add")) if (info.isLateinitPreferred || info.modifierList?.hasModifier(KtTokens.LATEINIT_KEYWORD) == true) { append("lateinit ") } append(if (info.writable) "var" else "val") append(KotlinBundle.message("property.0.to.1", info.name, classOrFileName.toString())) } } } private fun JvmClass.toKtClassOrFile(): KtElement? = when (val psi = sourceElement) { is KtClassOrObject -> psi is KtLightClassForSourceDeclaration -> psi.kotlinOrigin is KtLightClassForFacade -> psi.files.firstOrNull() else -> null } private inline fun <reified T : KtElement> JvmElement.toKtElement() = sourceElement?.unwrapped as? T private fun fakeParametersExpressions(parameters: List<ExpectedParameter>, project: Project): Array<PsiExpression>? = when { parameters.isEmpty() -> emptyArray() else -> JavaPsiFacade .getElementFactory(project) .createParameterList( parameters.map { it.semanticNames.firstOrNull() }.toTypedArray(), parameters.map { it.expectedTypes.firstOrNull()?.theType ?.let { JvmPsiConversionHelper.getInstance(project).convertType(it) } ?: return null }.toTypedArray() ) .parameters .map(::FakeExpressionFromParameter) .toTypedArray() } private fun ExpectedTypes.toKotlinTypeInfo(resolutionFacade: ResolutionFacade): TypeInfo { val candidateTypes = flatMapTo(LinkedHashSet<KotlinType>()) { val ktType = (it.theType as? PsiType)?.resolveToKotlinType(resolutionFacade) ?: return@flatMapTo emptyList() when (it.theKind) { ExpectedType.Kind.EXACT, ExpectedType.Kind.SUBTYPE -> listOf(ktType) ExpectedType.Kind.SUPERTYPE -> listOf(ktType) + ktType.supertypes() } } if (candidateTypes.isEmpty()) { val nullableAnyType = resolutionFacade.moduleDescriptor.builtIns.nullableAnyType return TypeInfo(nullableAnyType, Variance.INVARIANT) } return TypeInfo.ByExplicitCandidateTypes(candidateTypes.toList()) } override fun createChangeModifierActions(target: JvmModifiersOwner, request: ChangeModifierRequest): List<IntentionAction> { val kModifierOwner = target.toKtElement<KtModifierListOwner>() ?: return emptyList() val modifier = request.modifier val shouldPresent = request.shouldBePresent() //TODO: make similar to `createAddMethodActions` val (kToken, shouldPresentMapped) = when { modifier == JvmModifier.FINAL -> KtTokens.OPEN_KEYWORD to !shouldPresent modifier == JvmModifier.PUBLIC && shouldPresent -> kModifierOwner.visibilityModifierType() ?.takeIf { it != KtTokens.DEFAULT_VISIBILITY_KEYWORD } ?.let { it to false } ?: return emptyList() else -> javaPsiModifiersMapping[modifier] to shouldPresent } if (kToken == null) return emptyList() val action = if (shouldPresentMapped) AddModifierFix.createIfApplicable(kModifierOwner, kToken) else RemoveModifierFix(kModifierOwner, kToken, false) return listOfNotNull(action) } override fun createAddConstructorActions(targetClass: JvmClass, request: CreateConstructorRequest): List<IntentionAction> { val targetKtClass = targetClass.toKtClassOrFile() as? KtClass ?: return emptyList() val modifierBuilder = ModifierBuilder(targetKtClass).apply { addJvmModifiers(request.modifiers) } if (!modifierBuilder.isValid) return emptyList() val resolutionFacade = targetKtClass.getResolutionFacade() val nullableAnyType = resolutionFacade.moduleDescriptor.builtIns.nullableAnyType val helper = JvmPsiConversionHelper.getInstance(targetKtClass.project) val parameters = request.expectedParameters val parameterInfos = parameters.mapIndexed { index, param -> val ktType = param.expectedTypes.firstOrNull()?.theType?.let { helper.convertType(it).resolveToKotlinType(resolutionFacade) } ?: nullableAnyType val name = param.semanticNames.firstOrNull() ?: "arg${index + 1}" ParameterInfo(TypeInfo(ktType, Variance.IN_VARIANCE), listOf(name)) } val needPrimary = !targetKtClass.hasExplicitPrimaryConstructor() val constructorInfo = ConstructorInfo( parameterInfos, targetKtClass, isPrimary = needPrimary, modifierList = modifierBuilder.modifierList, withBody = true ) val targetClassName = targetClass.name val addConstructorAction = object : CreateCallableFromUsageFix<KtElement>(targetKtClass, listOf(constructorInfo)) { override fun getFamilyName() = KotlinBundle.message("add.method") override fun getText() = KotlinBundle.message( "add.0.constructor.to.1", if (needPrimary) KotlinBundle.message("text.primary") else KotlinBundle.message("text.secondary"), targetClassName.toString() ) } val changePrimaryConstructorAction = run { val primaryConstructor = targetKtClass.primaryConstructor ?: return@run null val lightMethod = primaryConstructor.toLightMethods().firstOrNull() ?: return@run null val project = targetKtClass.project val fakeParametersExpressions = fakeParametersExpressions(parameters, project) ?: return@run null QuickFixFactory.getInstance().createChangeMethodSignatureFromUsageFix( lightMethod, fakeParametersExpressions, PsiSubstitutor.EMPTY, targetKtClass, false, 2 ).takeIf { it.isAvailable(project, null, targetKtClass.containingFile) } } return listOfNotNull(changePrimaryConstructorAction, addConstructorAction) } private fun createAddPropertyActions( targetContainer: KtElement, modifiers: Iterable<JvmModifier>, propertyType: JvmType, propertyName: String, setterRequired: Boolean, classOrFileName: String? ): List<IntentionAction> { val modifierBuilder = ModifierBuilder(targetContainer).apply { addJvmModifiers(modifiers) } if (!modifierBuilder.isValid) return emptyList() val resolutionFacade = targetContainer.getResolutionFacade() val nullableAnyType = resolutionFacade.moduleDescriptor.builtIns.nullableAnyType val ktType = (propertyType as? PsiType)?.resolveToKotlinType(resolutionFacade) ?: nullableAnyType val propertyInfo = PropertyInfo( propertyName, TypeInfo.Empty, TypeInfo(ktType, Variance.INVARIANT), setterRequired, listOf(targetContainer), modifierList = modifierBuilder.modifierList, withInitializer = true ) val propertyInfos = if (setterRequired) { listOf(propertyInfo, propertyInfo.copyProperty(isLateinitPreferred = true)) } else { listOf(propertyInfo) } return propertyInfos.map { CreatePropertyFix(targetContainer, it, classOrFileName) } } override fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> { val targetContainer = targetClass.toKtClassOrFile() ?: return emptyList() val resolutionFacade = targetContainer.getResolutionFacade() val typeInfo = request.fieldType.toKotlinTypeInfo(resolutionFacade) val writable = JvmModifier.FINAL !in request.modifiers fun propertyInfo(lateinit: Boolean) = PropertyInfo( request.fieldName, TypeInfo.Empty, typeInfo, writable, listOf(targetContainer), isLateinitPreferred = false, // Dont set it to `lateinit` because it works via templates that brings issues in batch field adding isForCompanion = JvmModifier.STATIC in request.modifiers, modifierList = ModifierBuilder(targetContainer, allowJvmStatic = false).apply { addJvmModifiers(request.modifiers) if (modifierList.children.none { it.node.elementType in KtTokens.VISIBILITY_MODIFIERS }) addJvmModifier(JvmModifier.PUBLIC) if (lateinit) modifierList.appendModifier(KtTokens.LATEINIT_KEYWORD) if (!request.modifiers.contains(JvmModifier.PRIVATE) && !lateinit) addAnnotation(JVM_FIELD_ANNOTATION_FQ_NAME) }.modifierList, withInitializer = !lateinit ) val propertyInfos = if (writable) { listOf(propertyInfo(false), propertyInfo(true)) } else { listOf(propertyInfo(false)) } return propertyInfos.map { CreatePropertyFix(targetContainer, it, targetClass.name) } } override fun createAddMethodActions(targetClass: JvmClass, request: CreateMethodRequest): List<IntentionAction> { val targetContainer = targetClass.toKtClassOrFile() ?: return emptyList() val modifierBuilder = ModifierBuilder(targetContainer).apply { addJvmModifiers(request.modifiers) } if (!modifierBuilder.isValid) return emptyList() val resolutionFacade = KotlinCacheService.getInstance(targetContainer.project) .getResolutionFacadeByFile(targetContainer.containingFile, JvmPlatforms.unspecifiedJvmPlatform) ?: return emptyList() val returnTypeInfo = request.returnType.toKotlinTypeInfo(resolutionFacade) val parameters = request.expectedParameters val parameterInfos = parameters.map { parameter -> ParameterInfo(parameter.expectedTypes.toKotlinTypeInfo(resolutionFacade), parameter.semanticNames.toList()) } val methodName = request.methodName val functionInfo = FunctionInfo( methodName, TypeInfo.Empty, returnTypeInfo, listOf(targetContainer), parameterInfos, isForCompanion = JvmModifier.STATIC in request.modifiers, modifierList = modifierBuilder.modifierList, preferEmptyBody = true ) val targetClassName = targetClass.name val action = object : CreateCallableFromUsageFix<KtElement>(targetContainer, listOf(functionInfo)) { override fun getFamilyName() = KotlinBundle.message("add.method") override fun getText() = KotlinBundle.message("add.method.0.to.1", methodName, targetClassName.toString()) } val nameAndKind = PropertyUtilBase.getPropertyNameAndKind(methodName) ?: return listOf(action) val propertyType = (request.expectedParameters.singleOrNull()?.expectedTypes ?: request.returnType) .firstOrNull { JvmPsiConversionHelper.getInstance(targetContainer.project).convertType(it.theType) != PsiType.VOID } ?: return listOf(action) return createAddPropertyActions( targetContainer, request.modifiers, propertyType.theType, nameAndKind.first, nameAndKind.second == PropertyKind.SETTER, targetClass.name ) } override fun createAddAnnotationActions(target: JvmModifiersOwner, request: AnnotationRequest): List<IntentionAction> { val declaration = (target as? KtLightElement<*, *>)?.kotlinOrigin as? KtModifierListOwner ?: return emptyList() if (declaration.language != KotlinLanguage.INSTANCE) return emptyList() val annotationUseSiteTarget = when (target) { is JvmField -> AnnotationUseSiteTarget.FIELD is JvmMethod -> when { PropertyUtil.isSimplePropertySetter(target as? PsiMethod) -> AnnotationUseSiteTarget.PROPERTY_SETTER PropertyUtil.isSimplePropertyGetter(target as? PsiMethod) -> AnnotationUseSiteTarget.PROPERTY_GETTER else -> null } else -> null } return listOf(CreateAnnotationAction(declaration, annotationUseSiteTarget, request)) } private class CreateAnnotationAction( target: KtModifierListOwner, val annotationTarget: AnnotationUseSiteTarget?, val request: AnnotationRequest ) : IntentionAction { private val pointer = target.createSmartPointer() override fun startInWriteAction(): Boolean = true override fun getText(): String = QuickFixBundle.message("create.annotation.text", StringUtilRt.getShortName(request.qualifiedName)) override fun getFamilyName(): String = QuickFixBundle.message("create.annotation.family") override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = pointer.element != null override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { val target = pointer.element ?: return val entry = addAnnotationEntry(target, request, annotationTarget) ShortenReferences.DEFAULT.process(entry) } } override fun createChangeParametersActions(target: JvmMethod, request: ChangeParametersRequest): List<IntentionAction> { val ktNamedFunction = (target as? KtLightElement<*, *>)?.kotlinOrigin as? KtNamedFunction ?: return emptyList() return listOfNotNull(ChangeMethodParameters.create(ktNamedFunction, request)) } } internal fun addAnnotationEntry( target: KtModifierListOwner, request: AnnotationRequest, annotationTarget: AnnotationUseSiteTarget? ): KtAnnotationEntry { val annotationUseSiteTargetPrefix = run prefixEvaluation@{ if (annotationTarget == null) return@prefixEvaluation "" val moduleDescriptor = (target as? KtDeclaration)?.resolveToDescriptorIfAny()?.module ?: return@prefixEvaluation "" val annotationClassDescriptor = moduleDescriptor.resolveClassByFqName( FqName(request.qualifiedName), NoLookupLocation.FROM_IDE ) ?: return@prefixEvaluation "" val applicableTargetSet = AnnotationChecker.applicableTargetSet(annotationClassDescriptor) ?: KotlinTarget.DEFAULT_TARGET_SET if (KotlinTarget.PROPERTY !in applicableTargetSet) return@prefixEvaluation "" "${annotationTarget.renderName}:" } val javaPsiFacade = JavaPsiFacade.getInstance(target.project) fun isKotlinAnnotation(annotation: AnnotationRequest): Boolean = javaPsiFacade.findClass(annotation.qualifiedName, target.resolveScope)?.language == KotlinLanguage.INSTANCE val psiFactory = KtPsiFactory(target) // could be generated via descriptor when KT-30478 is fixed val annotationText = '@' + annotationUseSiteTargetPrefix + renderAnnotation(request, psiFactory, ::isKotlinAnnotation) return target.addAnnotationEntry(psiFactory.createAnnotationEntry(annotationText)) } private fun renderAnnotation( request: AnnotationRequest, psiFactory: KtPsiFactory, isKotlinAnnotation: (AnnotationRequest) -> Boolean ): String { return "${request.qualifiedName}${ request.attributes.takeIf { it.isNotEmpty() }?.mapIndexed { i, p -> if (!isKotlinAnnotation(request) && i == 0 && p.name == "value") renderAttributeValue(p.value, psiFactory, isKotlinAnnotation) else "${p.name} = ${renderAttributeValue(p.value, psiFactory, isKotlinAnnotation)}" }?.joinToString(", ", "(", ")") ?: "" }" } private fun renderAttributeValue( annotationAttributeRequest: AnnotationAttributeValueRequest, psiFactory: KtPsiFactory, isKotlinAnnotation: (AnnotationRequest) -> Boolean, ): String = when (annotationAttributeRequest) { is AnnotationAttributeValueRequest.PrimitiveValue -> annotationAttributeRequest.value.toString() is AnnotationAttributeValueRequest.StringValue -> "\"" + annotationAttributeRequest.value + "\"" is AnnotationAttributeValueRequest.ClassValue -> annotationAttributeRequest.classFqn + "::class" is AnnotationAttributeValueRequest.ConstantValue -> annotationAttributeRequest.text is AnnotationAttributeValueRequest.NestedAnnotation -> renderAnnotation(annotationAttributeRequest.annotationRequest, psiFactory, isKotlinAnnotation) is AnnotationAttributeValueRequest.ArrayValue -> annotationAttributeRequest.members.joinToString(", ", "[", "]") { memberRequest -> renderAttributeValue(memberRequest, psiFactory, isKotlinAnnotation) } }
apache-2.0
3c1d5fc3314036fcf40a29401f94508f
46.796646
158
0.69468
5.555312
false
false
false
false
chemickypes/Glitchy
glitch/src/main/java/me/bemind/glitch/Shapes.kt
1
3236
package me.bemind.glitch import android.graphics.Point import android.graphics.Region /** * Created by angelomoroni on 21/07/17. */ abstract class GShape{ val SCALE_SLOP: Float = 0.005f abstract var vertices : List<Point> abstract fun contains(tap: Point): Boolean } class GRect : GShape{ var w :Int = 0 var h :Int = 0 var BASE_W : Int = 0 var BASE_H : Int = 0 val center :Point = Point(0,0) var angle : Int = 0 var xScaleFactor: Float = 1f var yScaleFactor: Float = 1f override var vertices : List<Point> = arrayListOf() init { vertices = generateVertices() } constructor(w: Int,h: Int, center :Point = Point(0,0)){ this.w = w this.h = h this.center.copy(center) this.BASE_H = h this.BASE_W = w vertices = generateVertices() } constructor(w: Int,h: Int,imageW:Float,imageH:Float):this(w,h, Point((imageW/2).toInt(),(imageH/2).toInt())) override fun contains(tap: Point): Boolean { return false } fun move(deltaX:Int,deltaY:Int) : List<Point>{ center.x += deltaX center.y += deltaY vertices = moveVertices(vertices,deltaX,deltaY) return vertices } fun rotate(angle:Int) : List<Point>{ this.angle = angle // vertices = rotateVertices(vertices) return vertices } private fun rotateVertices(vl :List<Point>) : List<Point> { val vertices = vl.copy() for(p in vertices){ val rotatedP = rotate(p) p.copy(rotatedP) } return vertices } private fun moveVertices(vl :List<Point>,deltaX:Int,deltaY:Int) : List<Point>{ val vertices = vl.copy() for(p in vertices){ p.x += deltaX p.y += deltaY } return vertices } fun scale(xScaledFactor: Float, yScaledFactor:Float) :List<Point> { if(Math.abs(this.xScaleFactor - Math.abs(xScaledFactor)) > SCALE_SLOP || Math.abs(this.yScaleFactor - Math.abs(yScaledFactor)) > SCALE_SLOP) { this.yScaleFactor = yScaledFactor this.xScaleFactor = xScaledFactor w = (BASE_W * xScaleFactor).toInt() h = (BASE_H * yScaleFactor).toInt() vertices = generateVertices() } return vertices } private fun rotate(p: Point) : Point{ val x:Int = p.x val y:Int = p.y val radians = (Math.PI/180) * angle val cos = Math.cos(radians) val sin = Math.sin(radians) val nx = (cos * (x - center.x)) + (sin * (y - center.y)) + center.x val ny = (cos * (y - center.y)) - (sin * (x - center.x)) + center.y return Point(nx.toInt(),ny.toInt()) } private fun generateVertices() : List<Point>{ val vv : MutableList<Point> = arrayListOf() val topLeft = Point(center.x - w/2,center.y - h/2) vv.add(topLeft) vv.add(Point(topLeft.x + w,topLeft.y)) vv.add(Point(topLeft.x + w,topLeft.y+h)) vv.add(Point(topLeft.x,topLeft.y+h)) return rotateVertices(vv) } } private fun <E> List<E>.copy(): List<E> { val copy = this.toList() return copy }
apache-2.0
9ab5e6688da20775d9ddc62cec6020d7
23.149254
150
0.571693
3.498378
false
false
false
false
SimpleMobileTools/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuItemPopup.kt
1
10549
package com.simplemobiletools.commons.views.bottomactionmenu import android.content.Context import android.graphics.Color import android.graphics.Rect import android.view.* import android.view.View.MeasureSpec import android.widget.ArrayAdapter import android.widget.FrameLayout import android.widget.ListView import android.widget.PopupWindow import androidx.core.content.ContextCompat import androidx.core.widget.PopupWindowCompat import com.simplemobiletools.commons.R import com.simplemobiletools.commons.extensions.applyColorFilter import com.simplemobiletools.commons.extensions.windowManager import com.simplemobiletools.commons.helpers.isRPlus import kotlinx.android.synthetic.main.item_action_mode_popup.view.cab_item class BottomActionMenuItemPopup( private val context: Context, private val items: List<BottomActionMenuItem>, private val onSelect: (BottomActionMenuItem) -> Unit, ) { private val popup = PopupWindow(context, null, android.R.attr.popupMenuStyle) private var anchorView: View? = null private var dropDownWidth = ViewGroup.LayoutParams.WRAP_CONTENT private var dropDownHeight = ViewGroup.LayoutParams.WRAP_CONTENT private val tempRect = Rect() private val popupMinWidth: Int private val popupPaddingBottom: Int private val popupPaddingStart: Int private val popupPaddingEnd: Int private val popupPaddingTop: Int val isShowing: Boolean get() = popup.isShowing private val popupListAdapter = object : ArrayAdapter<BottomActionMenuItem>(context, R.layout.item_action_mode_popup, items) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var view = convertView if (view == null) { view = LayoutInflater.from(context).inflate(R.layout.item_action_mode_popup, parent, false) } val item = items[position] view!!.cab_item.text = item.title if (item.icon != View.NO_ID) { val icon = ContextCompat.getDrawable(context, item.icon) icon?.applyColorFilter(Color.WHITE) view.cab_item.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null) } view.setOnClickListener { onSelect.invoke(item) popup.dismiss() } return view } } init { popup.isFocusable = true popupMinWidth = context.resources.getDimensionPixelSize(R.dimen.cab_popup_menu_min_width) popupPaddingStart = context.resources.getDimensionPixelSize(R.dimen.smaller_margin) popupPaddingEnd = context.resources.getDimensionPixelSize(R.dimen.smaller_margin) popupPaddingTop = context.resources.getDimensionPixelSize(R.dimen.smaller_margin) popupPaddingBottom = context.resources.getDimensionPixelSize(R.dimen.smaller_margin) } fun show(anchorView: View) { this.anchorView = anchorView buildDropDown() PopupWindowCompat.setWindowLayoutType(popup, WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL) popup.isOutsideTouchable = true popup.width = dropDownWidth popup.height = dropDownHeight var x = 0 var y = 0 val contentView: View = popup.contentView val windowRect = Rect() contentView.getWindowVisibleDisplayFrame(windowRect) val windowW = windowRect.width() val windowH = windowRect.height() contentView.measure( makeDropDownMeasureSpec(dropDownWidth, windowW), makeDropDownMeasureSpec(dropDownHeight, windowH) ) val anchorLocation = IntArray(2) anchorView.getLocationInWindow(anchorLocation) x += anchorLocation[0] y += anchorView.height * 2 x -= dropDownWidth - anchorView.width popup.showAtLocation(contentView, Gravity.BOTTOM, x, y) } internal fun dismiss() { popup.dismiss() popup.contentView = null } private fun buildDropDown() { var otherHeights = 0 val dropDownList = ListView(context).apply { adapter = popupListAdapter isFocusable = true divider = null isFocusableInTouchMode = true clipToPadding = false isVerticalScrollBarEnabled = true isHorizontalScrollBarEnabled = false clipToOutline = true elevation = 3f setPaddingRelative(popupPaddingStart, popupPaddingTop, popupPaddingEnd, popupPaddingBottom) } val screenWidth = if (isRPlus()) { context.windowManager.currentWindowMetrics.bounds.width() } else { context.windowManager.defaultDisplay.width } val width = measureMenuSizeAndGetWidth((0.8 * screenWidth).toInt()) updateContentWidth(width) popup.contentView = dropDownList // getMaxAvailableHeight() subtracts the padding, so we put it back // to get the available height for the whole window. val padding: Int val popupBackground = popup.background padding = if (popupBackground != null) { popupBackground.getPadding(tempRect) tempRect.top + tempRect.bottom } else { tempRect.setEmpty() 0 } val maxHeight = popup.getMaxAvailableHeight(anchorView!!, 0) val listContent = measureHeightOfChildrenCompat(maxHeight - otherHeights) if (listContent > 0) { val listPadding = dropDownList.paddingTop + dropDownList.paddingBottom otherHeights += padding + listPadding } dropDownHeight = listContent + otherHeights dropDownList.layoutParams = ViewGroup.LayoutParams(dropDownWidth, dropDownHeight) } private fun updateContentWidth(width: Int) { val popupBackground = popup.background dropDownWidth = if (popupBackground != null) { popupBackground.getPadding(tempRect) tempRect.left + tempRect.right + width } else { width } } /** * @see androidx.appcompat.widget.DropDownListView.measureHeightOfChildrenCompat */ private fun measureHeightOfChildrenCompat(maxHeight: Int): Int { val parent = FrameLayout(context) val widthMeasureSpec = MeasureSpec.makeMeasureSpec(dropDownWidth, MeasureSpec.EXACTLY) // Include the padding of the list var returnedHeight = 0 val count = popupListAdapter.count var child: View? = null var viewType = 0 for (i in 0 until count) { val positionType = popupListAdapter.getItemViewType(i) if (positionType != viewType) { child = null viewType = positionType } child = popupListAdapter.getView(i, child, parent) // Compute child height spec val heightMeasureSpec: Int var childLayoutParams: ViewGroup.LayoutParams? = child.layoutParams if (childLayoutParams == null) { childLayoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) child.layoutParams = childLayoutParams } heightMeasureSpec = if (childLayoutParams.height > 0) { MeasureSpec.makeMeasureSpec( childLayoutParams.height, MeasureSpec.EXACTLY ) } else { MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) } child.measure(widthMeasureSpec, heightMeasureSpec) // Since this view was measured directly against the parent measure // spec, we must measure it again before reuse. child.forceLayout() val marginLayoutParams = childLayoutParams as? ViewGroup.MarginLayoutParams val topMargin = marginLayoutParams?.topMargin ?: 0 val bottomMargin = marginLayoutParams?.bottomMargin ?: 0 val verticalMargin = topMargin + bottomMargin returnedHeight += child.measuredHeight + verticalMargin if (returnedHeight >= maxHeight) { // We went over, figure out which height to return. If returnedHeight > // maxHeight, then the i'th position did not fit completely. return maxHeight } } // At this point, we went through the range of children, and they each // completely fit, so return the returnedHeight return returnedHeight } /** * @see androidx.appcompat.view.menu.MenuPopup.measureIndividualMenuWidth */ private fun measureMenuSizeAndGetWidth(maxAllowedWidth: Int): Int { val parent = FrameLayout(context) var maxWidth = popupMinWidth var itemView: View? = null var itemType = 0 val widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) val heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) for (i in 0 until popupListAdapter.count) { val positionType: Int = popupListAdapter.getItemViewType(i) if (positionType != itemType) { itemType = positionType itemView = null } itemView = popupListAdapter.getView(i, itemView, parent) itemView.measure(widthMeasureSpec, heightMeasureSpec) val itemWidth = itemView.measuredWidth if (itemWidth >= maxAllowedWidth) { return maxAllowedWidth } else if (itemWidth > maxWidth) { maxWidth = itemWidth } } return maxWidth } private fun makeDropDownMeasureSpec(measureSpec: Int, maxSize: Int): Int { return MeasureSpec.makeMeasureSpec( getDropDownMeasureSpecSize(measureSpec, maxSize), getDropDownMeasureSpecMode(measureSpec) ) } private fun getDropDownMeasureSpecSize(measureSpec: Int, maxSize: Int): Int { return when (measureSpec) { ViewGroup.LayoutParams.MATCH_PARENT -> maxSize else -> MeasureSpec.getSize(measureSpec) } } private fun getDropDownMeasureSpecMode(measureSpec: Int): Int { return when (measureSpec) { ViewGroup.LayoutParams.WRAP_CONTENT -> MeasureSpec.UNSPECIFIED else -> MeasureSpec.EXACTLY } } }
gpl-3.0
f04f9cc087f6ebc9b636a72df01d1cf2
37.083032
132
0.649635
5.28507
false
false
false
false
jsocle/jsocle-form
src/main/kotlin/com/github/jsocle/form/fields/SelectField.kt
2
703
package com.github.jsocle.form.fields import com.github.jsocle.form.FieldMapper import com.github.jsocle.form.SingleValueField import com.github.jsocle.html.elements.Select import kotlin.collections.forEach open class SelectField<T : Any>(var choices: List<Pair<T, String>>, mapper: FieldMapper<T>, default: T? = null) : SingleValueField<T, Select>(mapper, default) { override fun render(): Select { return Select(name = name) { choices.forEach { option( value = mapper.toString(it.first), text_ = it.second, selected = if (it.first == value) "selected" else null ) } } } }
mit
8cb28e9ce113ac7a6fcea2761da54718
34.2
111
0.614509
3.927374
false
false
false
false
GunoH/intellij-community
plugins/evaluation-plugin/core/src/com/intellij/cce/actions/UserEmulator.kt
8
1322
package com.intellij.cce.actions import kotlin.random.Random class UserEmulator private constructor(private val settings: Settings) { companion object { private val defaultSettings = Settings( listOf(0.0, 0.8, 0.2), listOf( listOf(0.5, 0.5, 0.6, 0.6, 0.7), listOf(0.2, 0.2, 0.3), listOf(0.15, 0.2, 0.3), listOf(0.15, 0.15, 0.2), listOf(0.15, 0.15, 0.2), listOf(0.1) ) ) fun create(settings: Settings?): UserEmulator = if (settings != null) UserEmulator(settings) else UserEmulator(defaultSettings) } data class Settings( val firstPrefixLen: List<Double>, val selectElement: List<List<Double>> ) fun firstPrefixLen(): Int = selectWithProbability(settings.firstPrefixLen) fun selectElement(position: Int, order: Int): Boolean = isSuccess(settings.selectElement.getAt(position).getAt(order)) private fun isSuccess(p: Double): Boolean = Random.Default.nextDouble() < p private fun selectWithProbability(probs: List<Double>): Int { val point = Random.Default.nextDouble() var cur = 0.0 for ((i, p) in probs.withIndex()) { cur += p if (point < cur) return i } return probs.lastIndex } private fun <T> List<T>.getAt(i: Int): T = if (this.size <= i) this.last() else this[i] }
apache-2.0
25891abefc135a0315341a1e4ab9ac20
28.377778
120
0.643722
3.451697
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/impl/KotlinChainBuilderBase.kt
4
3353
// 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.debugger.sequence.psi.impl import com.intellij.debugger.streams.psi.ChainTransformer import com.intellij.debugger.streams.psi.PsiUtil import com.intellij.debugger.streams.wrapper.StreamChain import com.intellij.debugger.streams.wrapper.StreamChainBuilder import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.psi.* abstract class KotlinChainBuilderBase(private val transformer: ChainTransformer<KtCallExpression>) : StreamChainBuilder { protected abstract val existenceChecker: ExistenceChecker override fun isChainExists(startElement: PsiElement): Boolean { val start = if (startElement is PsiWhiteSpace) PsiUtil.ignoreWhiteSpaces(startElement) else startElement var element = getLatestElementInScope(start) existenceChecker.reset() while (element != null && !existenceChecker.isFound()) { existenceChecker.reset() element.accept(existenceChecker) element = toUpperLevel(element) } return existenceChecker.isFound() } override fun build(startElement: PsiElement): List<StreamChain> { val visitor = createChainsBuilder() val start = if (startElement is PsiWhiteSpace) PsiUtil.ignoreWhiteSpaces(startElement) else startElement var element = getLatestElementInScope(start) while (element != null) { element.accept(visitor) element = toUpperLevel(element) } return visitor.chains().map { transformer.transform(it, startElement) } } private fun toUpperLevel(element: PsiElement): PsiElement? { var current = element.parent while (current != null && !(current is KtLambdaExpression || current is KtAnonymousInitializer || current is KtObjectDeclaration)) { current = current.parent } return getLatestElementInScope(current) } protected abstract fun createChainsBuilder(): ChainBuilder private fun getLatestElementInScope(element: PsiElement?): PsiElement? { var current = element while (current != null) { if (current is KtNamedFunction && current.hasInitializer()) { break } val parent = current.parent if (parent is KtBlockExpression || parent is KtLambdaExpression) { break } current = parent } return current } protected abstract class ExistenceChecker : MyTreeVisitor() { private var myIsFound: Boolean = false fun isFound(): Boolean = myIsFound fun reset() = setFound(false) protected fun fireElementFound() = setFound(true) private fun setFound(value: Boolean) { myIsFound = value } } protected abstract class ChainBuilder : MyTreeVisitor() { abstract fun chains(): List<List<KtCallExpression>> } protected abstract class MyTreeVisitor : KtTreeVisitorVoid() { override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {} override fun visitBlockExpression(expression: KtBlockExpression) {} } }
apache-2.0
2dea93426f8b47d7456faa020eb8b0d6
35.857143
158
0.687146
5.18238
false
false
false
false
idea4bsd/idea4bsd
platform/projectModel-api/src/org/jetbrains/concurrency/promise.kt
4
8205
/* * 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. */ @file:JvmName("Promises") package org.jetbrains.concurrency import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.util.ActionCallback import com.intellij.util.Consumer import com.intellij.util.Function import com.intellij.util.SmartList import com.intellij.util.ThreeState import com.intellij.util.concurrency.AppExecutorUtil import java.util.* val Promise<*>.isRejected: Boolean get() = state == Promise.State.REJECTED val Promise<*>.isPending: Boolean get() = state == Promise.State.PENDING val Promise<*>.isFulfilled: Boolean get() = state == Promise.State.FULFILLED internal val OBSOLETE_ERROR by lazy { createError("Obsolete") } private val REJECTED: Promise<*> by lazy { RejectedPromise<Any?>(createError("rejected")) } private val DONE: Promise<*> by lazy(LazyThreadSafetyMode.NONE) { Promise.DONE } private val CANCELLED_PROMISE: Promise<*> by lazy { RejectedPromise<Any?>(OBSOLETE_ERROR) } @Suppress("UNCHECKED_CAST") fun <T> resolvedPromise(): Promise<T> = DONE as Promise<T> fun nullPromise(): Promise<*> = DONE fun <T> resolvedPromise(result: T): Promise<T> = if (result == null) resolvedPromise() else DonePromise(result) @Suppress("UNCHECKED_CAST") fun <T> rejectedPromise(): Promise<T> = REJECTED as Promise<T> fun <T> rejectedPromise(error: String): Promise<T> = RejectedPromise(createError(error, true)) fun <T> rejectedPromise(error: Throwable?): Promise<T> = if (error == null) rejectedPromise() else RejectedPromise(error) @Suppress("UNCHECKED_CAST") fun <T> cancelledPromise(): Promise<T> = CANCELLED_PROMISE as Promise<T> // only internal usage interface ObsolescentFunction<Param, Result> : Function<Param, Result>, Obsolescent abstract class ValueNodeAsyncFunction<PARAM, RESULT>(private val node: Obsolescent) : Function<PARAM, Promise<RESULT>>, Obsolescent { override fun isObsolete() = node.isObsolete } abstract class ObsolescentConsumer<T>(private val obsolescent: Obsolescent) : Obsolescent, Consumer<T> { override fun isObsolete() = obsolescent.isObsolete } inline fun <T, SUB_RESULT> Promise<T>.then(obsolescent: Obsolescent, crossinline handler: (T) -> SUB_RESULT) = then(object : ObsolescentFunction<T, SUB_RESULT> { override fun `fun`(param: T) = handler(param) override fun isObsolete() = obsolescent.isObsolete }) inline fun <T> Promise<T>.done(node: Obsolescent, crossinline handler: (T) -> Unit) = done(object : ObsolescentConsumer<T>(node) { override fun consume(param: T) = handler(param) }) @Suppress("UNCHECKED_CAST") inline fun Promise<*>.processed(node: Obsolescent, crossinline handler: () -> Unit) = (this as Promise<Any?>).processed(object : ObsolescentConsumer<Any?>(node) { override fun consume(param: Any?) = handler() }) @Suppress("UNCHECKED_CAST") inline fun Promise<*>.doneRun(crossinline handler: () -> Unit) = done({ handler() }) @Suppress("UNCHECKED_CAST") inline fun <T> Promise<*>.thenRun(crossinline handler: () -> T): Promise<T> = (this as Promise<Any?>).then({ handler() }) @Suppress("UNCHECKED_CAST") inline fun Promise<*>.processedRun(crossinline handler: () -> Unit): Promise<*> = (this as Promise<Any?>).processed({ handler() }) inline fun <T, SUB_RESULT> Promise<T>.thenAsync(node: Obsolescent, crossinline handler: (T) -> Promise<SUB_RESULT>) = thenAsync(object : ValueNodeAsyncFunction<T, SUB_RESULT>(node) { override fun `fun`(param: T) = handler(param) }) @Suppress("UNCHECKED_CAST") inline fun <T> Promise<T>.thenAsyncAccept(node: Obsolescent, crossinline handler: (T) -> Promise<*>) = thenAsync(object : ValueNodeAsyncFunction<T, Any?>(node) { override fun `fun`(param: T) = handler(param) as Promise<Any?> }) inline fun <T> Promise<T>.thenAsyncAccept(crossinline handler: (T) -> Promise<*>) = thenAsync(Function<T, Promise<Any?>> { param -> @Suppress("UNCHECKED_CAST") (return@Function handler(param) as Promise<Any?>) }) inline fun Promise<*>.rejected(node: Obsolescent, crossinline handler: (Throwable) -> Unit) = rejected(object : ObsolescentConsumer<Throwable>(node) { override fun consume(param: Throwable) = handler(param) }) fun <T> collectResults(promises: List<Promise<T>>): Promise<List<T>> { if (promises.isEmpty()) { return resolvedPromise(emptyList()) } val results: MutableList<T> = if (promises.size == 1) SmartList<T>() else ArrayList<T>(promises.size) for (promise in promises) { promise.done { results.add(it) } } return all(promises, results) } @JvmOverloads fun createError(error: String, log: Boolean = false): RuntimeException = MessageError(error, log) inline fun <T> AsyncPromise<T>.compute(runnable: () -> T) { val result = catchError(runnable) if (!isRejected) { setResult(result) } } inline fun <T> runAsync(crossinline runnable: () -> T): Promise<T> { val promise = AsyncPromise<T>() AppExecutorUtil.getAppExecutorService().execute { val result = try { runnable() } catch (e: Throwable) { promise.setError(e) return@execute } promise.setResult(result) } return promise } @SuppressWarnings("ExceptionClassNameDoesntEndWithException") internal class MessageError(error: String, log: Boolean) : RuntimeException(error) { internal val log = ThreeState.fromBoolean(log) fun fillInStackTrace() = this } /** * Log error if not a message error */ fun Logger.errorIfNotMessage(e: Throwable): Boolean { if (e is MessageError) { val log = e.log if (log == ThreeState.YES || (log == ThreeState.UNSURE && (ApplicationManager.getApplication()?.isUnitTestMode ?: false))) { error(e) return true } } else if (e !is ProcessCanceledException) { error(e) return true } return false } fun ActionCallback.toPromise(): Promise<Void> { val promise = AsyncPromise<Void>() doWhenDone { promise.setResult(null) }.doWhenRejected { error -> promise.setError(createError(error ?: "Internal error")) } return promise } fun all(promises: Collection<Promise<*>>): Promise<*> = if (promises.size == 1) promises.first() else all(promises, null) fun <T> all(promises: Collection<Promise<*>>, totalResult: T?): Promise<T> { if (promises.isEmpty()) { @Suppress("UNCHECKED_CAST") return DONE as Promise<T> } val totalPromise = AsyncPromise<T>() val done = CountDownConsumer(promises.size, totalPromise, totalResult) val rejected = Consumer<Throwable> { error -> totalPromise.setError(error) } for (promise in promises) { promise.done(done) promise.rejected(rejected) } return totalPromise } private class CountDownConsumer<T>(@Volatile private var countDown: Int, private val promise: AsyncPromise<T>, private val totalResult: T?) : Consumer<Any?> { override fun consume(t: Any?) { if (--countDown == 0) { promise.setResult(totalResult) } } } fun <T> any(promises: Collection<Promise<T>>, totalError: String): Promise<T> { if (promises.isEmpty()) { @Suppress("UNCHECKED_CAST") return DONE as Promise<T> } else if (promises.size == 1) { return promises.first() } val totalPromise = AsyncPromise<T>() val done = Consumer<T> { result -> totalPromise.setResult(result) } val rejected = object : Consumer<Throwable> { @Volatile private var toConsume = promises.size override fun consume(throwable: Throwable) { if (--toConsume <= 0) { totalPromise.setError(totalError) } } } for (promise in promises) { promise.done(done) promise.rejected(rejected) } return totalPromise }
apache-2.0
dc35eec34995f33e492211d28079e923
33.049793
182
0.713589
3.935252
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/objc/ObjCCodeGenerator.kt
2
1650
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan.llvm.objc import llvm.LLVMTypeRef import llvm.LLVMValueRef import org.jetbrains.kotlin.backend.konan.llvm.* internal open class ObjCCodeGenerator(val codegen: CodeGenerator) { val context = codegen.context val dataGenerator = codegen.objCDataGenerator!! fun FunctionGenerationContext.genSelector(selector: String): LLVMValueRef = genObjCSelector(selector) fun FunctionGenerationContext.genGetLinkedClass(name: String): LLVMValueRef { val classRef = dataGenerator.genClassRef(name) return load(classRef.llvm) } private val objcMsgSend = constPointer( context.llvm.externalFunction( "objc_msgSend", functionType(int8TypePtr, true, int8TypePtr, int8TypePtr), context.stdlibModule.llvmSymbolOrigin ) ) val objcRelease = context.llvm.externalFunction( "objc_release", functionType(voidType, false, int8TypePtr), context.stdlibModule.llvmSymbolOrigin ) // TODO: this doesn't support stret. fun msgSender(functionType: LLVMTypeRef): LLVMValueRef = objcMsgSend.bitcast(pointerType(functionType)).llvm } internal fun FunctionGenerationContext.genObjCSelector(selector: String): LLVMValueRef { val selectorRef = codegen.objCDataGenerator!!.genSelectorRef(selector) // TODO: clang emits it with `invariant.load` metadata. return load(selectorRef.llvm) }
apache-2.0
9254453d413043f1b2d2d904ca4a3fd6
34.12766
105
0.710303
4.423592
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/dto/JsonConverter.kt
1
9955
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.util.indexing.diagnostic.dto import com.intellij.util.indexing.diagnostic.* import java.time.Duration fun TimeNano.toMillis(): TimeMillis = this / 1_000_000 // Int value that is greater than zero. // Can be used to skip int value from JSON if it is equal to 0 (to not pollute the JSON report). typealias PositiveInt = Int? fun ScanningStatistics.toJsonStatistics(): JsonScanningStatistics { val jsonScannedFiles = if (IndexDiagnosticDumper.shouldDumpPathsOfIndexedFiles) { scannedFiles.map { it.toJson() } } else { null } return JsonScanningStatistics( providerName = fileSetName, numberOfScannedFiles = numberOfScannedFiles, numberOfFilesForIndexing = numberOfFilesForIndexing, numberOfSkippedFiles = numberOfSkippedFiles, numberOfFilesFullyIndexedByInfrastructureExtensions = numberOfFilesFullyIndexedByInfrastructureExtension, filesFullyIndexedByInfrastructureExtensions = listOfFilesFullyIndexedByInfrastructureExtension, statusTime = JsonDuration(statusTime), scanningTime = JsonDuration(scanningTime), timeProcessingUpToDateFiles = JsonDuration(timeProcessingUpToDateFiles), timeUpdatingContentLessIndexes = JsonDuration(timeUpdatingContentLessIndexes), timeIndexingWithoutContent = JsonDuration(timeIndexingWithoutContent), roots = providerRoots, scannedFiles = jsonScannedFiles ) } fun ScanningStatistics.ScannedFile.toJson(): JsonScanningStatistics.JsonScannedFile = JsonScanningStatistics.JsonScannedFile( path = portableFilePath, isUpToDate = isUpToDate, wasFullyIndexedByInfrastructureExtension = wasFullyIndexedByInfrastructureExtension ) @Suppress("DuplicatedCode") fun IndexingFileSetStatistics.toJsonStatistics(visibleTimeToAllThreadsTimeRatio: Double): JsonFileProviderIndexStatistics { val jsonIndexedFiles = if (IndexDiagnosticDumper.shouldDumpPathsOfIndexedFiles) { indexedFiles.map { it.toJson() } } else { null } return JsonFileProviderIndexStatistics( providerName = fileSetName, totalNumberOfIndexedFiles = numberOfIndexedFiles, totalNumberOfFilesFullyIndexedByExtensions = numberOfFilesFullyIndexedByExtensions, filesFullyIndexedByExtensions = listOfFilesFullyIndexedByExtensions, totalIndexingVisibleTime = convertAllThreadsTimeToVisibleDuration(indexingTimeInAllThreads, visibleTimeToAllThreadsTimeRatio), contentLoadingVisibleTime = convertAllThreadsTimeToVisibleDuration(contentLoadingTimeInAllThreads, visibleTimeToAllThreadsTimeRatio), numberOfTooLargeForIndexingFiles = numberOfTooLargeForIndexingFiles, slowIndexedFiles = slowIndexedFiles.biggestElements.map { it.toJson() }, isAppliedAllValuesSeparately = allValuesAppliedSeparately, separateApplyingIndexesVisibleTime = convertAllThreadsTimeToVisibleDuration(allSeparateApplicationTimeInAllThreads, visibleTimeToAllThreadsTimeRatio), indexedFiles = jsonIndexedFiles ) } private fun convertAllThreadsTimeToVisibleDuration(allThreadsTime: TimeNano, visibleTimeToAllThreadsTimeRatio: Double) = JsonDuration((allThreadsTime * visibleTimeToAllThreadsTimeRatio).toLong()) fun SlowIndexedFile.toJson() = JsonFileProviderIndexStatistics.JsonSlowIndexedFile( fileName = fileName, processingTime = JsonDuration(processingTime), indexingTime = JsonDuration(indexingTime), contentLoadingTime = JsonDuration(contentLoadingTime) ) fun IndexingFileSetStatistics.IndexedFile.toJson() = JsonFileProviderIndexStatistics.JsonIndexedFile( path = portableFilePath, wasFullyIndexedByExtensions = wasFullyIndexedByExtensions ) fun IndexingTimes.toJson() = JsonProjectIndexingHistoryTimes( indexingReason = indexingReason, wasFullIndexing = wasFullIndexing, totalUpdatingTime = JsonDuration(totalUpdatingTime), indexingTime = JsonDuration(indexingDuration.toNanos()), contentLoadingVisibleTime = JsonDuration(contentLoadingVisibleDuration.toNanos()), creatingIteratorsTime = JsonDuration(creatingIteratorsDuration.toNanos()), scanFilesTime = JsonDuration(scanFilesDuration.toNanos()), pushPropertiesTime = JsonDuration(pushPropertiesDuration.toNanos()), indexExtensionsTime = JsonDuration(indexExtensionsDuration.toNanos()), isAppliedAllValuesSeparately = appliedAllValuesSeparately, separateApplyingIndexesVisibleTime = JsonDuration(separateValueApplicationVisibleTime), updatingStart = JsonDateTime(updatingStart), updatingEnd = JsonDateTime(updatingEnd), totalSuspendedTime = JsonDuration(suspendedDuration.toNanos()), wasInterrupted = wasInterrupted ) private fun calculatePercentages(part: Long, total: Long): JsonPercentages = JsonPercentages(part, total) fun ProjectIndexingHistoryImpl.toJson(): JsonProjectIndexingHistory { val timesImpl = times as ProjectIndexingHistoryImpl.IndexingTimesImpl timesImpl.contentLoadingVisibleDuration = Duration.ofNanos(providerStatistics.sumOf { it.contentLoadingVisibleTime.nano }) if (providerStatistics.all { it.isAppliedAllValuesSeparately }) { timesImpl.appliedAllValuesSeparately = true timesImpl.separateValueApplicationVisibleTime = providerStatistics.sumOf { it.separateApplyingIndexesVisibleTime.nano } } else { timesImpl.appliedAllValuesSeparately = false timesImpl.separateValueApplicationVisibleTime = 0 } return JsonProjectIndexingHistory( projectName = project.name, times = times.toJson(), fileCount = getFileCount(), totalStatsPerFileType = aggregateStatsPerFileType().sortedByDescending { it.partOfTotalProcessingTime.doublePercentages }, totalStatsPerIndexer = aggregateStatsPerIndexer().sortedByDescending { it.partOfTotalIndexingTime.doublePercentages }, scanningStatistics = scanningStatistics.sortedByDescending { it.scanningTime.nano }, fileProviderStatistics = providerStatistics.sortedByDescending { it.totalIndexingVisibleTime.nano }, visibleTimeToAllThreadTimeRatio = visibleTimeToAllThreadsTimeRatio ) } private fun ProjectIndexingHistoryImpl.getFileCount() = JsonProjectIndexingFileCount( numberOfFileProviders = scanningStatistics.size, numberOfScannedFiles = scanningStatistics.sumOf { it.numberOfScannedFiles }, numberOfFilesIndexedByInfrastructureExtensionsDuringScan = scanningStatistics.sumOf { it.numberOfFilesFullyIndexedByInfrastructureExtensions }, numberOfFilesScheduledForIndexingAfterScan = scanningStatistics.sumOf { it.numberOfFilesForIndexing }, numberOfFilesIndexedByInfrastructureExtensionsDuringIndexingStage = providerStatistics.sumOf { it.totalNumberOfFilesFullyIndexedByExtensions }, numberOfFilesIndexedWithLoadingContent = providerStatistics.sumOf { it.totalNumberOfIndexedFiles } ) private fun ProjectIndexingHistoryImpl.aggregateStatsPerFileType(): List<JsonProjectIndexingHistory.JsonStatsPerFileType> { val totalProcessingTime = totalStatsPerFileType.values.sumOf { it.totalProcessingTimeInAllThreads } val fileTypeToProcessingTimePart = totalStatsPerFileType.mapValues { calculatePercentages(it.value.totalProcessingTimeInAllThreads, totalProcessingTime) } @Suppress("DuplicatedCode") val totalContentLoadingTime = totalStatsPerFileType.values.sumOf { it.totalContentLoadingTimeInAllThreads } val fileTypeToContentLoadingTimePart = totalStatsPerFileType.mapValues { calculatePercentages(it.value.totalContentLoadingTimeInAllThreads, totalContentLoadingTime) } val fileTypeToProcessingSpeed = totalStatsPerFileType.mapValues { JsonProcessingSpeed(it.value.totalBytes, it.value.totalProcessingTimeInAllThreads) } return totalStatsPerFileType.map { (fileType, stats) -> val jsonBiggestFileTypeContributors = stats.biggestFileTypeContributors.biggestElements.map { JsonProjectIndexingHistory.JsonStatsPerFileType.JsonBiggestFileTypeContributor( it.providerName, it.numberOfFiles, JsonFileSize(it.totalBytes), calculatePercentages(it.processingTimeInAllThreads, stats.totalProcessingTimeInAllThreads) ) } JsonProjectIndexingHistory.JsonStatsPerFileType( fileType, fileTypeToProcessingTimePart.getValue(fileType), fileTypeToContentLoadingTimePart.getValue(fileType), stats.totalNumberOfFiles, JsonFileSize(stats.totalBytes), fileTypeToProcessingSpeed.getValue(fileType), jsonBiggestFileTypeContributors.sortedByDescending { it.partOfTotalProcessingTimeOfThisFileType.doublePercentages } ) } } private fun ProjectIndexingHistoryImpl.aggregateStatsPerIndexer(): List<JsonProjectIndexingHistory.JsonStatsPerIndexer> { val totalIndexingTime = totalStatsPerIndexer.values.sumOf { it.totalIndexingTimeInAllThreads } val indexIdToIndexingTimePart = totalStatsPerIndexer.mapValues { calculatePercentages(it.value.totalIndexingTimeInAllThreads, totalIndexingTime) } val indexIdToProcessingSpeed = totalStatsPerIndexer.mapValues { JsonProcessingSpeed(it.value.totalBytes, it.value.totalIndexingTimeInAllThreads) } return totalStatsPerIndexer.map { (indexId, stats) -> JsonProjectIndexingHistory.JsonStatsPerIndexer( indexId = indexId, partOfTotalIndexingTime = indexIdToIndexingTimePart.getValue(indexId), totalNumberOfFiles = stats.totalNumberOfFiles, totalNumberOfFilesIndexedByExtensions = stats.totalNumberOfFilesIndexedByExtensions, totalFilesSize = JsonFileSize(stats.totalBytes), indexingSpeed = indexIdToProcessingSpeed.getValue(indexId), snapshotInputMappingStats = JsonProjectIndexingHistory.JsonStatsPerIndexer.JsonSnapshotInputMappingStats( totalRequests = stats.snapshotInputMappingStats.requests, totalMisses = stats.snapshotInputMappingStats.misses, totalHits = stats.snapshotInputMappingStats.hits ) ) } }
apache-2.0
24ca3ce047d6f6426a1ddd5d309e16ff
48.78
145
0.814164
5.598988
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/impl/RepositoryBrowser.kt
2
8068
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.impl import com.intellij.icons.AllIcons import com.intellij.ide.impl.ContentManagerWatcher import com.intellij.openapi.Disposable import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.* import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.ex.FileSystemTreeImpl import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileEditor.impl.LoadTextUtil import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.RemoteFilePath import com.intellij.openapi.vcs.VcsActions import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffAction import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.openapi.vcs.impl.RepositoryBrowserPanel.Companion.REPOSITORY_BROWSER_DATA_KEY import com.intellij.openapi.vcs.vfs.AbstractVcsVirtualFile import com.intellij.openapi.vcs.vfs.VcsVirtualFile import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.RegisterToolWindowTask import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.ExperimentalUI import com.intellij.ui.ScrollPaneFactory import com.intellij.ui.content.ContentFactory import com.intellij.util.PlatformIcons import com.intellij.vcsUtil.VcsUtil import java.awt.BorderLayout import java.io.File import javax.swing.Icon import javax.swing.JPanel object RepositoryBrowser { const val TOOLWINDOW_ID: String = "Repositories" // NON-NLS fun showRepositoryBrowser(project: Project, root: AbstractVcsVirtualFile, localRoot: VirtualFile, @NlsContexts.TabTitle title: String) { val toolWindowManager = ToolWindowManager.getInstance(project) val repoToolWindow = toolWindowManager.getToolWindow(TOOLWINDOW_ID) ?: registerRepositoriesToolWindow(toolWindowManager) for (content in repoToolWindow.contentManager.contents) { val component = content.component as? RepositoryBrowserPanel ?: continue if (component.root == root) { repoToolWindow.contentManager.setSelectedContent(content) return } } val contentPanel = RepositoryBrowserPanel(project, root, localRoot) val content = ContentFactory.getInstance().createContent(contentPanel, title, true) repoToolWindow.contentManager.addContent(content) repoToolWindow.contentManager.setSelectedContent(content, true) repoToolWindow.activate(null) } private fun registerRepositoriesToolWindow(toolWindowManager: ToolWindowManager): ToolWindow { val toolWindow = toolWindowManager.registerToolWindow(RegisterToolWindowTask( id = TOOLWINDOW_ID, anchor = ToolWindowAnchor.LEFT, canCloseContent = true, canWorkInDumbMode = true, stripeTitle = { VcsBundle.message("RepositoryBrowser.toolwindow.name") }, icon = getIcon() )) ContentManagerWatcher.watchContentManager(toolWindow, toolWindow.contentManager) return toolWindow } private fun getIcon(): Icon? = when { ExperimentalUI.isNewUI() -> IconLoader.getIcon("expui/toolwindow/repositories.svg", AllIcons::class.java) else -> null } } class RepositoryBrowserPanel( val project: Project, val root: AbstractVcsVirtualFile, private val localRoot: VirtualFile ) : JPanel(BorderLayout()), DataProvider, Disposable { companion object { val REPOSITORY_BROWSER_DATA_KEY = DataKey.create<RepositoryBrowserPanel>("com.intellij.openapi.vcs.impl.RepositoryBrowserPanel") } private val fileSystemTree: FileSystemTreeImpl init { val fileChooserDescriptor = object : FileChooserDescriptor(true, false, false, false, false, true) { override fun getRoots(): List<VirtualFile> = listOf(root) override fun getIcon(file: VirtualFile): Icon? { if (file.isDirectory) { return PlatformIcons.FOLDER_ICON } if (file is VcsVirtualFile) { val localPath = getLocalFilePath(file) val icon = FilePathIconProvider.EP_NAME.computeSafeIfAny { it.getIcon(localPath, project) } if (icon != null) return icon } return FileTypeManager.getInstance().getFileTypeByFileName(file.nameSequence).icon } } fileSystemTree = object : FileSystemTreeImpl(project, fileChooserDescriptor) { } fileSystemTree.addOkAction { val files = fileSystemTree.selectedFiles for (file in files) { FileEditorManager.getInstance(project).openFile(file, true) } } val actionGroup = DefaultActionGroup() actionGroup.add(ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE)) actionGroup.add(ActionManager.getInstance().getAction(VcsActions.DIFF_AFTER_WITH_LOCAL)) fileSystemTree.registerMouseListener(actionGroup) val scrollPane = ScrollPaneFactory.createScrollPane(fileSystemTree.tree, true) add(scrollPane, BorderLayout.CENTER) } override fun getData(dataId: String): Any? { return when { CommonDataKeys.VIRTUAL_FILE_ARRAY.`is`(dataId) -> fileSystemTree.selectedFiles CommonDataKeys.NAVIGATABLE_ARRAY.`is`(dataId) -> fileSystemTree.selectedFiles .filter { !it.isDirectory } .map { OpenFileDescriptor(project, it) } .toTypedArray() REPOSITORY_BROWSER_DATA_KEY.`is`(dataId) -> this else -> null } } override fun dispose() { Disposer.dispose(fileSystemTree) } fun hasSelectedFiles() = fileSystemTree.selectedFiles.any { it is VcsVirtualFile } fun getSelectionAsChanges(): List<Change> { return fileSystemTree.selectedFiles .filterIsInstance<VcsVirtualFile>() .map { createChangeVsLocal(it) } } private fun createChangeVsLocal(file: VcsVirtualFile): Change { val repoRevision = VcsVirtualFileContentRevision(file) val localPath = getLocalFilePath(file) val localRevision = CurrentContentRevision(localPath) return Change(repoRevision, localRevision) } private fun getLocalFilePath(file: VcsVirtualFile): FilePath { val localFile = File(localRoot.path, file.path) return VcsUtil.getFilePath(localFile) } } class DiffRepoWithLocalAction : AnActionExtensionProvider { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun isActive(e: AnActionEvent): Boolean { return e.getData(REPOSITORY_BROWSER_DATA_KEY) != null } override fun update(e: AnActionEvent) { val repoBrowser = e.getData(REPOSITORY_BROWSER_DATA_KEY) ?: return e.presentation.isEnabled = repoBrowser.hasSelectedFiles() } override fun actionPerformed(e: AnActionEvent) { val repoBrowser = e.getData(REPOSITORY_BROWSER_DATA_KEY) ?: return val selection = ListSelection.createAt(repoBrowser.getSelectionAsChanges(), 0) .asExplicitSelection() ShowDiffAction.showDiffForChange(repoBrowser.project, selection) } } class VcsVirtualFileContentRevision(private val vcsVirtualFile: VcsVirtualFile) : ContentRevision, ByteBackedContentRevision { override fun getContent(): String? { return contentAsBytes?.let { LoadTextUtil.getTextByBinaryPresentation(it, vcsVirtualFile).toString() } } override fun getContentAsBytes(): ByteArray? { return vcsVirtualFile.fileRevision?.loadContent() } override fun getFile(): FilePath { return RemoteFilePath(vcsVirtualFile.path, vcsVirtualFile.isDirectory) } override fun getRevisionNumber(): VcsRevisionNumber { return vcsVirtualFile.fileRevision?.revisionNumber ?: VcsRevisionNumber.NULL } }
apache-2.0
2869a523fc40c020a26f9214e7ccb503
37.793269
138
0.767848
4.793821
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/hints/types/QualifiedReferences.kt
10
389
// MODE: local_variable package p class A { class B { class C { class D } } inner class E enum class F { enumCase } } fun foo() { val v1 = A.B.C.D() val v2 = p.A.B.C.D() val v3<# [: [temp:///src/KotlinReferencesTypeHintsProvider.kt:34]A .E] #> = A().E() val v4 = p.A.F.enumCase val v5 = A.F.enumCase val v6 = p.A() }
apache-2.0
d78c442951fdbb3de860d80e82df8595
16.681818
88
0.498715
2.72028
false
false
false
false
smmribeiro/intellij-community
plugins/configuration-script/src/ItemTypeInfoProvider.kt
12
1192
package com.intellij.configurationScript import com.intellij.openapi.components.BaseState import com.intellij.util.xmlb.BeanBinding import java.lang.reflect.ParameterizedType internal class ItemTypeInfoProvider(private val hostClass: Class<out BaseState>) { private val accessors by lazy(LazyThreadSafetyMode.NONE) { BeanBinding.getAccessors(hostClass) } fun getListItemType(propertyName: String, logAsErrorIfPropertyNotFound: Boolean): Class<out BaseState>? { val accessor = accessors.find { it.name == propertyName } if (accessor == null) { val message = "Property not found (name=$propertyName, hostClass=${hostClass.name})" if (logAsErrorIfPropertyNotFound) { LOG.error(message) } else { LOG.warn(message) } return null } val type = accessor.genericType if (type !is ParameterizedType) { LOG.error("$type not supported (name=$propertyName, hostClass=${hostClass.name})") return null } val actualTypeArguments = type.actualTypeArguments LOG.assertTrue(actualTypeArguments.size == 1) @Suppress("UNCHECKED_CAST") return actualTypeArguments[0] as Class<out BaseState> } }
apache-2.0
f1faf6d88630fc7be78648f2902a03dc
32.138889
107
0.718121
4.414815
false
false
false
false
smmribeiro/intellij-community
platform/external-system-api/src/com/intellij/openapi/externalSystem/autoimport/ExternalSystemProjectNotificationAware.kt
1
2843
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.autoimport import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.project.Project import com.intellij.util.messages.Topic /** * Bridge between auto-reload backend and notification view about that project is needed to reload. * Notifications can be shown in editor floating toolbar, editor banner, etc. */ interface ExternalSystemProjectNotificationAware { /** * Requests to show notifications for reload project that defined by [projectAware] */ fun notificationNotify(projectAware: ExternalSystemProjectAware) /** * Requests to hide all notifications for all projects. */ fun notificationExpire() /** * Requests to hide all notifications for project that defined by [projectId] * @see ExternalSystemProjectAware.projectId */ fun notificationExpire(projectId: ExternalSystemProjectId) /** * Checks that notifications should be shown. */ fun isNotificationVisible(): Boolean /** * Gets list of project ids which should be reloaded. */ fun getSystemIds(): Set<ProjectSystemId> interface Listener { /** * Happens when notification should be shown or hidden. */ @JvmDefault fun onNotificationChanged(project: Project) { } } companion object { @JvmField @Topic.AppLevel val TOPIC = Topic.create("ExternalSystemProjectNotificationAware", Listener::class.java) @JvmStatic fun getInstance(project: Project): ExternalSystemProjectNotificationAware = project.getService(ExternalSystemProjectNotificationAware::class.java) /** * Function for simple subscription onto notification change events * @see ExternalSystemProjectNotificationAware.Listener.onNotificationChanged */ fun whenNotificationChanged(project: Project, listener: () -> Unit) = whenNotificationChanged(project, listener, null) /** * Function for simple subscription onto notification change events * @see ExternalSystemProjectNotificationAware.Listener.onNotificationChanged */ fun whenNotificationChanged(project: Project, listener: () -> Unit, parentDisposable: Disposable? = null) { val aProject = project val messageBus = ApplicationManager.getApplication().messageBus val connection = messageBus.connect(parentDisposable ?: project) connection.subscribe(TOPIC, object : Listener { override fun onNotificationChanged(project: Project) { if (aProject === project) { listener() } } }) } } }
apache-2.0
a875def745d58a015fa767b377378018
32.857143
158
0.734084
5.274583
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/java/src/service/resolve/GradleTaskProperty.kt
2
1661
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.service.resolve import com.intellij.codeInsight.javadoc.JavaDocInfoGeneratorFactory import com.intellij.ide.presentation.Presentation import com.intellij.openapi.util.Key import com.intellij.psi.OriginInfoAwareElement import com.intellij.psi.PsiElement import com.intellij.util.lazyPub import icons.ExternalSystemIcons import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings.GradleTask import org.jetbrains.plugins.groovy.dsl.holders.NonCodeMembersHolder.DOCUMENTATION import org.jetbrains.plugins.groovy.lang.resolve.api.LazyTypeProperty import javax.swing.Icon @Presentation(typeName = "Gradle Task") class GradleTaskProperty( val task: GradleTask, context: PsiElement ) : LazyTypeProperty(task.name, task.typeFqn, context), OriginInfoAwareElement { override fun getIcon(flags: Int): Icon? = ExternalSystemIcons.Task override fun getOriginInfo(): String? = "task" private val doc by lazyPub { val result = StringBuilder() result.append("<PRE>") JavaDocInfoGeneratorFactory.create(context.project, null).generateType(result, propertyType, myContext, true) result.append(" " + task.name) result.append("</PRE>") task.description?.let(result::append) result.toString() } override fun <T : Any?> getUserData(key: Key<T>): T? { if (key == DOCUMENTATION) { @Suppress("UNCHECKED_CAST") return doc as T } return super.getUserData(key) } override fun toString(): String = "Gradle Task: $name" }
apache-2.0
26c9b737d16c740b568d6ba7cdeff8f1
35.108696
140
0.763396
4.101235
false
false
false
false
DuckDeck/AndroidDemo
app/src/main/java/stan/androiddemo/project/petal/Module/UserInfo/PetalUserBoardFragment.kt
1
9286
package stan.androiddemo.project.petal.Module.UserInfo import android.content.Context import android.content.DialogInterface import android.graphics.drawable.Drawable import android.os.Bundle import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import android.widget.LinearLayout import android.widget.TextView import com.chad.library.adapter.base.BaseViewHolder import com.facebook.drawee.view.SimpleDraweeView import rx.Observable import rx.Subscriber import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import stan.androiddemo.R import stan.androiddemo.UI.BasePetalRecyclerFragment import stan.androiddemo.project.petal.API.OperateAPI import stan.androiddemo.project.petal.API.UserAPI import stan.androiddemo.project.petal.Config.Config import stan.androiddemo.project.petal.Event.OnBoardFragmentInteractionListener import stan.androiddemo.project.petal.Event.OnEditDialogInteractionListener import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient import stan.androiddemo.project.petal.Widget.BoardEditDialogFragment import stan.androiddemo.tool.CompatUtils import stan.androiddemo.tool.DialogUtils import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder import stan.androiddemo.tool.Logger class PetalUserBoardFragment : BasePetalRecyclerFragment<UserBoardItemBean>(), OnEditDialogInteractionListener { private var mMaxId: Int = 0 private var isMe: Boolean = false var mLimit = Config.LIMIT var maxId = 0 lateinit var mAttentionFormat: String//关注数量 lateinit var mGatherFormat: String//采集数量 lateinit var mOperateEdit: String//编辑 lateinit var mOperateFollowing: String//关注 lateinit var mOperateFollowed: String//已关注 lateinit var mDrawableBlock: Drawable lateinit var mDrawableEdit: Drawable lateinit var mDrawableFollowing: Drawable lateinit var mDrawableFollowed: Drawable private var mListener: OnBoardFragmentInteractionListener<UserBoardItemBean>? = null companion object { fun newInstance(key:String):PetalUserBoardFragment{ val fragment = PetalUserBoardFragment() val bundle = Bundle() bundle.putString("key",key) fragment.arguments = bundle return fragment } } override fun getTheTAG(): String { return this.toString() } override fun initView() { super.initView() mGatherFormat = resources.getString(R.string.text_gather_number) mAttentionFormat = resources.getString(R.string.text_attention_number) mOperateEdit = resources.getString(R.string.text_edit) mOperateFollowing = resources.getString(R.string.text_following) mOperateFollowed = resources.getString(R.string.text_followed) mDrawableBlock = CompatUtils.getTintListDrawable(context,R.drawable.ic_block_black_24dp,R.color.tint_list_grey) mDrawableEdit = CompatUtils.getTintListDrawable(context,R.drawable.ic_mode_edit_black_24dp,R.color.tint_list_grey) mDrawableFollowing = CompatUtils.getTintListDrawable(context,R.drawable.ic_add_black_24dp,R.color.tint_list_grey) mDrawableFollowed = CompatUtils.getTintListDrawable(context,R.drawable.ic_check_black_24dp,R.color.tint_list_grey) } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnBoardFragmentInteractionListener<*>){ mListener = context as OnBoardFragmentInteractionListener<UserBoardItemBean> } if (context is PetalUserInfoActivity){ mAuthorization = context.mAuthorization isMe = context.isMe } } override fun initListener() { super.initListener() } override fun getItemLayoutId(): Int { return R.layout.petal_cardview_board_user_item } override fun itemLayoutConvert(helper: BaseViewHolder, userBoardItemBean: UserBoardItemBean) { var isOperate = false if (userBoardItemBean.deleting != 0){ isOperate = true } val isFollowing = userBoardItemBean.following val drawable: Drawable val text: String if (isOperate) { if (isMe) { text = mOperateEdit drawable = mDrawableEdit } else { if (isFollowing) { text = mOperateFollowed drawable = mDrawableFollowed } else { text = mOperateFollowing drawable = mDrawableFollowing } } } else { drawable = mDrawableBlock text = "" } helper.getView<TextView>(R.id.tv_board_operate).text = text helper.getView<LinearLayout>(R.id.linearlayout_group).tag = isOperate helper.getView<TextView>(R.id.tv_board_operate).setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null) helper.getView<TextView>(R.id.tv_board_title).text = userBoardItemBean.title helper.getView<TextView>(R.id.tv_board_gather).text = String.format(mGatherFormat,userBoardItemBean.pin_count) helper.getView<TextView>(R.id.tv_board_attention).text = String.format(mAttentionFormat,userBoardItemBean.follow_count) val img = helper.getView<SimpleDraweeView>(R.id.img_card_image) img.setOnClickListener { mListener?.onClickBoardItemImage(userBoardItemBean,it) } helper.getView<TextView>(R.id.tv_board_operate).setOnClickListener { handleOperate(userBoardItemBean,it) } if (userBoardItemBean.pins!!.size > 0){ val url = String.format(mUrlGeneralFormat,userBoardItemBean.pins!![0].file!!.key) img.aspectRatio = 1F ImageLoadBuilder.Start(context,img,url).setPlaceHolderImage(progressLoading).build() } else{ ImageLoadBuilder.Start(context,img,"").setPlaceHolderImage(progressLoading).build() } } fun handleOperate(bean: UserBoardItemBean, view: View) { if (isMe) { //如果是我的画板 弹出编辑对话框 val fragment = BoardEditDialogFragment.create(bean.board_id.toString(), bean.title!!, bean.description!!, bean.category_id.toString()) fragment.mListener = this//注入已经实现接口的 自己 fragment.show(activity.supportFragmentManager, null) } else { //如果是其他用户的画板 直接操作 Logger.d() } } override fun requestListData(page: Int): Subscription { val request = RetrofitClient.createService(UserAPI::class.java) var result : Observable<UserBoardListBean> if (page == 0){ result = request.httpsUserBoardRx(mAuthorization!!,mKey,mLimit) } else{ result = request.httpsUserBoardMaxRx(mAuthorization!!,mKey,maxId, mLimit) } return result.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .map { it.boards } .subscribe(object:Subscriber<List<UserBoardItemBean>>(){ override fun onNext(t: List<UserBoardItemBean>?) { if (t == null){ loadError() return } if( t!!.size > 0 ){ maxId = t!!.last()!!.board_id } loadSuccess(t!!) if (t!!.size < mLimit){ setNoMoreData() } } override fun onCompleted() { } override fun onError(e: Throwable?) { e?.printStackTrace() loadError() checkException(e) } }) } override fun getLayoutManager(): RecyclerView.LayoutManager { return GridLayoutManager(context,2) } override fun onDialogPositiveClick(boardId: String, name: String, describe: String, selectType: String) { Logger.d("name=$name describe=$describe selectPosition=$selectType") RetrofitClient.createService(OperateAPI::class.java).httpsEditBoard(mAuthorization!!,boardId,name,describe,selectType) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { setRefresh() } } override fun onDialogNeutralClick(boardId: String, boardTitle: String) { DialogUtils.showDeleteDialog(context, boardTitle, DialogInterface.OnClickListener { dialog, which -> startDeleteBoard(boardId) }) } fun startDeleteBoard(boardId:String){ RetrofitClient.createService(OperateAPI::class.java).httpsDeleteBoard(mAuthorization!!,boardId,Config.OPERATEDELETEBOARD) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { setRefresh() } } }
mit
d872d37dc92ecc9a7be389d6de950fc1
38.055319
146
0.65036
4.723623
false
false
false
false
neverwoodsS/StudyWithKotlin
src/linearlist/LoopChain.kt
1
2308
package linearlist /** * Created by zhangll on 2017/1/17. */ class LoopChain { val head by lazy { Node("head") } init { head.next = head for (i in 0..4) { addToLast(Node(i.toString())) } } fun addToFirst(node: Node) { node.next = head.next head.next = node } fun addToLast(node: Node) { var temp: Node = head while (temp.next != head) { temp = temp.next!! } node.next = temp.next temp.next = node } fun addToIndex(element: Node, index: Int) { var temp: Node? = head var position = 0 while (temp != null) { if (position == index) { element.next = temp.next temp.next = element break } temp = temp.next // 如果遇到 temp.next == head 的情况则再进一步,将 head 排除在计数以外 if (temp!!.next == head) temp = temp.next position++ } } fun removeFirst() { head.next = head.next!!.next } fun removeLast() { var temp: Node = head while (temp.next!!.next != head) { temp = temp.next!! } temp.next = temp.next!!.next } fun removeNode(node: Node) { var temp: Node = head while (temp.next != node) { if (temp.next == head) { println("i don't have this element") return } temp = temp.next!! } temp.next = node.next } fun removeAtIndex(index: Int) { var temp: Node? = head var position = 0 while (temp != null) { if (position == index) { temp.next = temp.next!!.next break } temp = temp.next // 如果遇到 temp.next == head 的情况则再进一步,将 head 排除在计数以外 if (temp!!.next == head) temp = temp.next position++ } } fun log() { var temp: Node = head do { print("${temp.content} -> ") temp = temp.next!! } while (temp != head) print("${temp.content} -> ") println("\n") } }
mit
d275b4282dfb6978429f81ab9ff131e5
20.601942
61
0.444694
3.957295
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/groups/GroupsViewModel.kt
1
18948
package com.ivanovsky.passnotes.presentation.groups import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.github.terrakok.cicerone.Router import com.ivanovsky.passnotes.R import com.ivanovsky.passnotes.data.ObserverBus import com.ivanovsky.passnotes.data.entity.Group import com.ivanovsky.passnotes.data.entity.Note import com.ivanovsky.passnotes.data.entity.Template import com.ivanovsky.passnotes.domain.ResourceProvider import com.ivanovsky.passnotes.domain.entity.DatabaseStatus import com.ivanovsky.passnotes.domain.entity.SelectionItem import com.ivanovsky.passnotes.domain.entity.SelectionItemType import com.ivanovsky.passnotes.domain.interactor.ErrorInteractor import com.ivanovsky.passnotes.domain.interactor.SelectionHolder import com.ivanovsky.passnotes.domain.interactor.SelectionHolder.ActionType import com.ivanovsky.passnotes.domain.interactor.groups.GroupsInteractor import com.ivanovsky.passnotes.presentation.Screens.GroupEditorScreen import com.ivanovsky.passnotes.presentation.Screens.GroupsScreen import com.ivanovsky.passnotes.presentation.Screens.MainSettingsScreen import com.ivanovsky.passnotes.presentation.Screens.NoteEditorScreen import com.ivanovsky.passnotes.presentation.Screens.NoteScreen import com.ivanovsky.passnotes.presentation.Screens.SearchScreen import com.ivanovsky.passnotes.presentation.Screens.UnlockScreen import com.ivanovsky.passnotes.presentation.core.BaseScreenViewModel import com.ivanovsky.passnotes.presentation.core.DefaultScreenStateHandler import com.ivanovsky.passnotes.presentation.core.ScreenState import com.ivanovsky.passnotes.presentation.core.ViewModelTypes import com.ivanovsky.passnotes.presentation.core.event.SingleLiveEvent import com.ivanovsky.passnotes.presentation.core.factory.DatabaseStatusCellModelFactory import com.ivanovsky.passnotes.presentation.core.viewmodel.DatabaseStatusCellViewModel import com.ivanovsky.passnotes.presentation.core.viewmodel.GroupCellViewModel import com.ivanovsky.passnotes.presentation.core.viewmodel.NoteCellViewModel import com.ivanovsky.passnotes.presentation.core.viewmodel.OptionPanelCellViewModel import com.ivanovsky.passnotes.presentation.group_editor.GroupEditorArgs import com.ivanovsky.passnotes.presentation.groups.factory.GroupsCellModelFactory import com.ivanovsky.passnotes.presentation.groups.factory.GroupsCellViewModelFactory import com.ivanovsky.passnotes.presentation.note_editor.LaunchMode import com.ivanovsky.passnotes.presentation.note_editor.NoteEditorArgs import com.ivanovsky.passnotes.util.StringUtils.EMPTY import com.ivanovsky.passnotes.util.toUUID import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.UUID class GroupsViewModel( private val interactor: GroupsInteractor, private val errorInteractor: ErrorInteractor, private val observerBus: ObserverBus, private val resourceProvider: ResourceProvider, private val cellModelFactory: GroupsCellModelFactory, private val statusCellModelFactory: DatabaseStatusCellModelFactory, private val cellViewModelFactory: GroupsCellViewModelFactory, private val selectionHolder: SelectionHolder, private val router: Router ) : BaseScreenViewModel(), ObserverBus.GroupDataSetObserver, ObserverBus.NoteDataSetChanged, ObserverBus.NoteContentObserver, ObserverBus.DatabaseCloseObserver, ObserverBus.DatabaseStatusObserver { val viewTypes = ViewModelTypes() .add(NoteCellViewModel::class, R.layout.grid_cell_note) .add(GroupCellViewModel::class, R.layout.grid_cell_group) val screenStateHandler = DefaultScreenStateHandler() val screenState = MutableLiveData(ScreenState.notInitialized()) val statusViewModel = cellViewModelFactory.createCellViewModel( model = statusCellModelFactory.createDefaultStatusCellModel(), eventProvider = eventProvider ) as DatabaseStatusCellViewModel val optionPanelViewModel = cellViewModelFactory.createCellViewModel( model = cellModelFactory.createDefaultOptionPanelCellModel(), eventProvider = eventProvider ) as OptionPanelCellViewModel val screenTitle = MutableLiveData(EMPTY) val isMenuVisible = MutableLiveData(false) val isAddTemplatesMenuVisible = MutableLiveData(false) val showToastEvent = SingleLiveEvent<String>() val showNewEntryDialogEvent = SingleLiveEvent<List<Template>>() val showGroupActionsDialogEvent = SingleLiveEvent<Group>() val showNoteActionsDialogEvent = SingleLiveEvent<Note>() val showRemoveConfirmationDialogEvent = SingleLiveEvent<Pair<Group?, Note?>>() val showAddTemplatesDialogEvent = SingleLiveEvent<Unit>() private var currentDataItems: List<GroupsInteractor.Item>? = null private var rootGroupUid: UUID? = null private var groupUid: UUID? = null private var templates: List<Template>? = null private var args: GroupsArgs? = null init { observerBus.register(this) subscribeToEvents() } override fun onCleared() { super.onCleared() observerBus.unregister(this) } override fun onGroupDataSetChanged() { loadData() } override fun onNoteDataSetChanged(groupUid: UUID) { if (groupUid == getCurrentGroupUid()) { loadData() } } override fun onNoteContentChanged(groupUid: UUID, oldNoteUid: UUID, newNoteUid: UUID) { if (groupUid == getCurrentGroupUid()) { loadData() } } override fun onDatabaseClosed() { router.backTo(UnlockScreen()) } override fun onDatabaseStatusChanged(status: DatabaseStatus) { updateStatusViewModel(status) } fun start(args: GroupsArgs) { this.args = args this.groupUid = args.groupUid if (groupUid == null) { screenTitle.value = resourceProvider.getString(R.string.groups) } loadData() } fun loadData() { showLoading() viewModelScope.launch { templates = interactor.getTemplates() val data = withContext(Dispatchers.IO) { groupUid.let { if (it == null) { interactor.getRootGroupData() } else { interactor.getGroupData(it) } } } if (groupUid == null && rootGroupUid == null) { rootGroupUid = withContext(Dispatchers.IO) { interactor.getRootUid() } } groupUid?.let { val group = interactor.getGroup(it) if (group.isSucceededOrDeferred) { screenTitle.value = group.obj.title ?: "" } } val status = interactor.getDatabaseStatus() if (data.isSucceededOrDeferred) { val dataItems = data.obj currentDataItems = dataItems if (dataItems.isNotEmpty()) { val models = cellModelFactory.createCellModels(dataItems) val viewModels = cellViewModelFactory.createCellViewModels(models, eventProvider) setCellElements(viewModels) screenState.value = ScreenState.data() } else { val emptyText = resourceProvider.getString(R.string.no_items) screenState.value = ScreenState.empty(emptyText) } if (status.isSucceededOrDeferred) { updateStatusViewModel(status.obj) } showMenu() } else { val message = errorInteractor.processAndGetMessage(data.error) screenState.value = ScreenState.error(message) } updateOptionPanelViewModel( isVisible = selectionHolder.hasSelection() && data.isSucceededOrDeferred ) } } fun onAddButtonClicked() { showNewEntryDialogEvent.call(templates ?: emptyList()) } fun onCreateNewGroupClicked() { val currentGroupUid = getCurrentGroupUid() ?: return router.navigateTo( GroupEditorScreen( GroupEditorArgs.NewGroup( parentGroupUid = currentGroupUid ) ) ) } fun onCreateNewNoteClicked() { val currentGroupUid = getCurrentGroupUid() ?: return router.navigateTo( NoteEditorScreen( NoteEditorArgs( launchMode = LaunchMode.NEW, groupUid = currentGroupUid, template = null, title = resourceProvider.getString(R.string.new_note) ) ) ) } fun onCreateNewNoteFromTemplateClicked(template: Template) { val currentGroupUid = getCurrentGroupUid() ?: return router.navigateTo( NoteEditorScreen( NoteEditorArgs( launchMode = LaunchMode.NEW, groupUid = currentGroupUid, template = template, title = resourceProvider.getString(R.string.new_note) ) ) ) } fun onEditGroupClicked(group: Group) { router.navigateTo( GroupEditorScreen( GroupEditorArgs.EditGroup( groupUid = group.uid ) ) ) } fun onRemoveGroupClicked(group: Group) { showRemoveConfirmationDialogEvent.call(Pair(group, null)) } fun onCutGroupClicked(group: Group) { val groupUid = group.uid ?: return val currentGroupUid = getCurrentGroupUid() ?: return selectionHolder.select( action = ActionType.CUT, selection = SelectionItem( uid = groupUid, parentUid = currentGroupUid, type = SelectionItemType.GROUP_UID ) ) updateOptionPanelViewModel(isVisible = true) } fun onEditNoteClicked(note: Note) { router.navigateTo( NoteEditorScreen( NoteEditorArgs( launchMode = LaunchMode.EDIT, noteUid = note.uid, title = note.title ) ) ) } fun onRemoveNoteClicked(note: Note) { showRemoveConfirmationDialogEvent.call(Pair(null, note)) } fun onCutNoteClicked(note: Note) { val noteUid = note.uid ?: return val currentGroupUid = getCurrentGroupUid() ?: return selectionHolder.select( action = ActionType.CUT, selection = SelectionItem( uid = noteUid, parentUid = currentGroupUid, type = SelectionItemType.NOTE_UID ) ) updateOptionPanelViewModel(isVisible = true) } fun onRemoveConfirmed(group: Group?, note: Note?) { val groupUid = group?.uid val noteUid = note?.uid if (groupUid != null) { removeGroup(groupUid) } else if (noteUid != null) { removeNote(note.groupUid, noteUid) } } fun onBackClicked() { val isCloseDatabase = args?.isCloseDatabaseOnExit ?: return if (isCloseDatabase) { interactor.closeDatabase() } router.exit() } fun onLockButtonClicked() { interactor.closeDatabase() router.backTo(UnlockScreen()) } fun onAddTemplatesClicked() { showAddTemplatesDialogEvent.call() } fun onAddTemplatesConfirmed() { showLoading() viewModelScope.launch { val isAdded = interactor.addTemplates() if (isAdded.isSucceededOrDeferred) { screenState.value = ScreenState.data() showToastEvent.call(resourceProvider.getString(R.string.successfully_added)) showMenu() } else { val message = errorInteractor.processAndGetMessage(isAdded.error) screenState.value = ScreenState.error(message) } } } fun onSearchButtonClicked() = router.navigateTo(SearchScreen()) fun onSettingsButtonClicked() = router.navigateTo(MainSettingsScreen()) private fun subscribeToEvents() { eventProvider.subscribe(this) { event -> when { event.containsKey(GroupCellViewModel.CLICK_EVENT) -> { event.getString(GroupCellViewModel.CLICK_EVENT)?.toUUID()?.let { onGroupClicked(it) } } event.containsKey(GroupCellViewModel.LONG_CLICK_EVENT) -> { event.getString(GroupCellViewModel.LONG_CLICK_EVENT)?.toUUID()?.let { onGroupLongClicked(it) } } event.containsKey(NoteCellViewModel.CLICK_EVENT) -> { event.getString(NoteCellViewModel.CLICK_EVENT)?.toUUID()?.let { onNoteClicked(it) } } event.containsKey(NoteCellViewModel.LONG_CLICK_EVENT) -> { event.getString(NoteCellViewModel.LONG_CLICK_EVENT)?.toUUID()?.let { onNoteLongClicked(it) } } event.containsKey(OptionPanelCellViewModel.POSITIVE_BUTTON_CLICK_EVENT) -> { onPositiveOptionSelected() } event.containsKey(OptionPanelCellViewModel.NEGATIVE_BUTTON_CLICK_EVENT) -> { onNegativeOptionSelected() } } } } private fun onGroupClicked(groupUid: UUID) { router.navigateTo( GroupsScreen( GroupsArgs( groupUid = groupUid, isCloseDatabaseOnExit = false ) ) ) } private fun onGroupLongClicked(groupUid: UUID) { val group = findGroupInItems(groupUid) ?: return showGroupActionsDialogEvent.call(group) } private fun findGroupInItems(groupUid: UUID): Group? { return (currentDataItems?.firstOrNull { item -> if (item is GroupsInteractor.GroupItem) { item.group.uid == groupUid } else { false } } as? GroupsInteractor.GroupItem)?.group } private fun onNoteClicked(noteUid: UUID) { router.navigateTo(NoteScreen(noteUid)) } private fun onNoteLongClicked(noteUid: UUID) { val note = findNoteInItems(noteUid) ?: return showNoteActionsDialogEvent.call(note) } private fun findNoteInItems(noteUid: UUID): Note? { return (currentDataItems?.firstOrNull { item -> if (item is GroupsInteractor.NoteItem) { item.note.uid == noteUid } else { false } } as? GroupsInteractor.NoteItem)?.note } private fun getCurrentGroupUid(): UUID? { return when { groupUid != null -> groupUid rootGroupUid != null -> rootGroupUid else -> null } } private fun removeGroup(groupUid: UUID) { showLoading() viewModelScope.launch { val removeResult = withContext(Dispatchers.Default) { interactor.removeGroup(groupUid) } if (removeResult.isSucceededOrDeferred) { showToastEvent.call(resourceProvider.getString(R.string.successfully_removed)) showMenu() } else { val message = errorInteractor.processAndGetMessage(removeResult.error) screenState.value = ScreenState.error(message) } } } private fun removeNote(groupUid: UUID, noteUid: UUID) { showLoading() viewModelScope.launch { val removeResult = withContext(Dispatchers.Default) { interactor.removeNote(groupUid, noteUid) } if (removeResult.isSucceededOrDeferred) { showToastEvent.call(resourceProvider.getString(R.string.successfully_removed)) showMenu() } else { val message = errorInteractor.processAndGetMessage(removeResult.error) screenState.value = ScreenState.error(message) } } } private fun hideStatusCell() { updateStatusViewModel(DatabaseStatus.NORMAL) } private fun updateStatusViewModel(status: DatabaseStatus) { statusViewModel.setModel(statusCellModelFactory.createStatusCellModel(status)) } private fun updateOptionPanelViewModel(isVisible: Boolean) { val model = if (isVisible) { cellModelFactory.createPasteOptionPanelCellModel() } else { cellModelFactory.createHiddenOptionPanelCellModel() } optionPanelViewModel.setModel(model) } private fun onPositiveOptionSelected() { val currentGroupUid = getCurrentGroupUid() ?: return val selection = selectionHolder.getSelection() ?: return val action = selectionHolder.getAction() ?: return if (selection.parentUid == currentGroupUid) { showToastEvent.value = resourceProvider.getString(R.string.selected_item_is_already_here) return } showLoading() viewModelScope.launch { val actionResult = interactor.doActionOnSelection( selectedGroupUid = currentGroupUid, action = action, selection = selection ) selectionHolder.clear() if (actionResult.isSucceededOrDeferred) { showToastEvent.call(resourceProvider.getString(R.string.successfully)) screenState.value = ScreenState.data() showMenu() } else { val message = errorInteractor.processAndGetMessage(actionResult.error) screenState.value = ScreenState.error(message) } } } private fun onNegativeOptionSelected() { selectionHolder.clear() updateOptionPanelViewModel(isVisible = false) } private fun hideMenu() { isMenuVisible.value = false isAddTemplatesMenuVisible.value = false } private fun showMenu() { isMenuVisible.value = true isAddTemplatesMenuVisible.value = templates.isNullOrEmpty() } private fun showLoading() { hideMenu() hideStatusCell() updateOptionPanelViewModel(isVisible = false) } }
gpl-2.0
c1069851a594cd42bcb92e2041e4c669
32.898032
101
0.626346
5.282409
false
false
false
false
geeniuss01/PWM
app/src/main/java/me/samen/pwm/common/Data.kt
1
1736
package me.samen.pwm.common import android.app.Application import android.content.Context import android.content.SharedPreferences import com.orm.SugarRecord import java.util.* /** * Handles user prefs, SugarORM DB, all strings are encrypted before storing to db * * Created by santosh on 27/8/16. */ class Data(val appContext: Application, val encryptionUtil: EncryptionUtil) { private var _authenticated: Boolean? = null var authenticated: Boolean = false var accounts: ArrayList<UserAccount> = ArrayList<UserAccount>() val prefs: SharedPreferences = appContext.getSharedPreferences("prefs", Context.MODE_PRIVATE) fun getSugarAcc(): ArrayList<UserAccount> { accounts.clear() accounts.addAll(SugarRecord.listAll(UserAccount::class.java)) accounts.map { it.website = encryptionUtil.decryptMsg(it._website!!) it.username = encryptionUtil.decryptMsg(it._username!!) it.pwd = encryptionUtil.decryptMsg(it._pwd!!) } return accounts } fun encrpt(ua: UserAccount): UserAccount { ua._website = encryptionUtil.encryptMsg(ua.website!!) ua.website = null ua._username = encryptionUtil.encryptMsg(ua.username!!) ua.username = null ua._pwd = encryptionUtil.encryptMsg(ua.pwd!!) ua.pwd = null return ua } fun savePin(pin: String): Boolean { var editor = prefs.edit() editor.putString("pin", pin) editor.commit() return true } fun getPin(): String? { return prefs.getString("pin", null) } fun convert(): Array<UserAccount> { val elems = arrayListOf<UserAccount>() return elems.toTypedArray() } }
apache-2.0
41dde0384ea4aee815d8a1389f0d9d26
30.017857
97
0.65841
4.275862
false
false
false
false
google/intellij-gn-plugin
src/main/java/com/google/idea/gn/config/GnSettingsServiceImpl.kt
1
1483
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package com.google.idea.gn.config import com.intellij.configurationStore.serializeObjectInto import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.project.Project import com.intellij.util.xmlb.XmlSerializer import org.jdom.Element private const val serviceName: String = "GnSettings" @com.intellij.openapi.components.State(name = serviceName, storages = [ Storage(StoragePathMacros.WORKSPACE_FILE), Storage("misc.xml", deprecated = true) ]) class GnSettingsServiceImpl( private val project: Project ) : PersistentStateComponent<Element>, GnSettingsService { @Volatile private var state: GnSettingsService.State = GnSettingsService.State() override fun getState(): Element { val element = Element(serviceName) serializeObjectInto(state, element) return element } override fun loadState(element: Element) { val rawState = element.clone() XmlSerializer.deserializeInto(state, rawState) } override val projectRoot: String? get() = state.projectRoot override fun modify(action: (GnSettingsService.State) -> Unit) { val newState = state.copy().also(action) if (state != newState) { state = newState.copy() } } }
bsd-3-clause
f61c77f1c19d167c7f04a73cddd61d7a
29.895833
72
0.759946
4.336257
false
false
false
false
google/audio-to-tactile
extras/android/java/com/google/audio_to_tactile/LogFragment.kt
1
4170
/* 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.audio_to_tactile import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.RecyclerView import dagger.hilt.android.AndroidEntryPoint /** * Define the Log fragment, accessed from the nav drawer. This is intended as a tool for * development. The Log fragment shows timestamped log messages about BLE and other events. */ @AndroidEntryPoint class LogFragment : Fragment() { private val bleViewModel: BleViewModel by activityViewModels() private var prevNumLines = 0 private val handler = Handler(Looper.getMainLooper()) private var scrollToBottomOnNewMessage = true private class LogItemViewHolder(val view: View) : RecyclerView.ViewHolder(view) { val logTimestamp: TextView = view.findViewById(R.id.log_item_timestamp) val logMessage: TextView = view.findViewById(R.id.log_item_message) } /** Adapter to display a list of all the tuning knob names and values. */ private val logItemAdapter = object : RecyclerView.Adapter<LogItemViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LogItemViewHolder { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.log_list_item, parent, false) return LogItemViewHolder(view) } override fun getItemCount(): Int = bleViewModel.logLines.value?.size ?: 0 override fun onBindViewHolder(holder: LogItemViewHolder, position: Int) { bleViewModel.logLines.value?.let { logLines -> val logLine = logLines[position] holder.logTimestamp.text = logLine.timestamp holder.logMessage.text = logLine.message } } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val root: View = inflater.inflate(R.layout.fragment_log, container, false) val recyclerView = root.findViewById<RecyclerView>(R.id.log_recycler_view).apply { adapter = logItemAdapter setHasFixedSize(false) // Add a listener such that `scrollToBottomOnNewMessage` is disabled for a few seconds when // the user scrolls the log. addOnScrollListener( object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { if (newState == RecyclerView.SCROLL_STATE_DRAGGING) { scrollToBottomOnNewMessage = false // Disable scrolling temporarily. handler.removeCallbacksAndMessages(null) // If a callback is pending, cancel it. handler.postDelayed({ // After a delay, re-enable scrolling and scroll to bottom. scrollToBottomOnNewMessage = true recyclerView.scrollToPosition(logItemAdapter.getItemCount() - 1) }, 3000L /* milliseconds */) } } } ) } // Observe [BleViewModel.logLines], so UI updates on change. bleViewModel.logLines.observe(viewLifecycleOwner) { it?.let { logLines -> logItemAdapter.notifyItemRangeChanged(prevNumLines, logLines.size - prevNumLines) if (scrollToBottomOnNewMessage) { recyclerView.scrollToPosition(logItemAdapter.getItemCount() - 1) } prevNumLines = logLines.size } } return root } }
apache-2.0
dd2c6ead2f7d2e8932924f200b23e97d
36.909091
97
0.709113
4.717195
false
false
false
false
AdamMc331/CashCaretaker
app/src/main/java/com/androidessence/cashcaretaker/ui/addaccount/AddAccountViewModel.kt
1
2454
package com.androidessence.cashcaretaker.ui.addaccount import android.database.sqlite.SQLiteConstraintException import androidx.lifecycle.viewModelScope import com.adammcneilly.cashcaretaker.analytics.AnalyticsTracker import com.androidessence.cashcaretaker.R import com.androidessence.cashcaretaker.core.BaseViewModel import com.androidessence.cashcaretaker.core.models.Account import com.androidessence.cashcaretaker.data.CCRepository import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch class AddAccountViewModel( private val repository: CCRepository, private val analyticsTracker: AnalyticsTracker, ) : BaseViewModel() { private val _viewState: MutableStateFlow<AddAccountViewState> = MutableStateFlow( AddAccountViewState() ) val viewState: StateFlow<AddAccountViewState> = _viewState private val dismissEventChannel: Channel<Boolean> = Channel() val dismissEvents: Flow<Boolean> = dismissEventChannel.receiveAsFlow() /** * Checks that the information passed in is valid, and inserts an account if it is. */ fun addAccount(name: String?, balanceString: String?) { if (name == null || name.isEmpty()) { _viewState.value = _viewState.value.copy( accountNameErrorTextRes = R.string.err_account_name_invalid ) return } val balance = balanceString?.toDoubleOrNull() if (balance == null) { _viewState.value = _viewState.value.copy( accountBalanceErrorTextRes = R.string.err_account_balance_invalid ) return } val account = Account(name, balance) viewModelScope.launch { try { repository.insertAccount(account) analyticsTracker.trackAccountAdded() dismissEventChannel.send(true) dismissEventChannel.close() } catch (constraintException: SQLiteConstraintException) { _viewState.value = _viewState.value.copy( accountNameErrorTextRes = R.string.err_account_name_exists ) } } } override fun onCleared() { super.onCleared() dismissEventChannel.close() } }
mit
59dfb2089de29e7a440bccf4528a0abd
34.565217
87
0.685412
4.987805
false
false
false
false
randombyte-developer/MobRepeller
src/main/kotlin/de/randombyte/mobrepeller/database/DatabaseManager.kt
1
1622
package de.randombyte.mobrepeller.database import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.transactions.transaction import org.spongepowered.api.service.sql.SqlService import org.spongepowered.api.world.Location import org.spongepowered.api.world.World object DatabaseManager { lateinit var databasePath: String val sqlService: SqlService by SqlServiceDelegate() // lazyinit fun getDataSource() = sqlService.getDataSource("jdbc:h2:$databasePath") fun getAllRepellers(): Map<Location<World>, Repeller> { Database.connect(getDataSource()) return transaction { if (!Repellers.exists()) SchemaUtils.create(Repellers) Repeller.fromQuery(Repellers.selectAll()) } } fun updateRepellerRadius(id: Int, newRadius: Int) { Database.connect(getDataSource()) transaction { Repellers.update(where = { Repellers.id eq id }) { it[Repellers.radius] = newRadius } } } fun createRepeller(centerBlock: Location<World>, radius: Int) { Database.connect(getDataSource()) transaction { Repellers.insert { it[Repellers.worldUUID] = centerBlock.extent.uniqueId.toString() it[Repellers.x] = centerBlock.blockX it[Repellers.y] = centerBlock.blockY it[Repellers.z] = centerBlock.blockZ it[Repellers.radius] = radius } } } fun removeRepeller(id: Int) { Database.connect(getDataSource()) transaction { Repellers.deleteWhere { Repellers.id eq id } } } }
gpl-2.0
dc38dcc9a53cbfc1e70020bcffb88224
32.102041
97
0.654131
4.004938
false
false
false
false
fobo66/BookcrossingMobile
app/src/main/java/com/bookcrossing/mobile/models/Book.kt
1
1090
/* * Copyright 2019 Andrey Mukamolov * * 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.bookcrossing.mobile.models import com.google.firebase.database.IgnoreExtraProperties /** Entity representing free book registered in the system */ @IgnoreExtraProperties data class Book( var author: String? = "", var name: String? = "", var description: String? = "", var isFree: Boolean? = false, var positionName: String? = "", var position: Coordinates? = Coordinates(), var city: String? = "", var wentFreeAt: Date? = Date() )
apache-2.0
77af343d2fcbecb93831db3b7a421b24
34.193548
78
0.704587
4.160305
false
false
false
false
duftler/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteStageHandler.kt
1
11518
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spectator.api.Registry import com.netflix.spectator.api.histogram.PercentileTimer import com.netflix.spinnaker.orca.ExecutionStatus import com.netflix.spinnaker.orca.ExecutionStatus.CANCELED import com.netflix.spinnaker.orca.ExecutionStatus.FAILED_CONTINUE import com.netflix.spinnaker.orca.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.ExecutionStatus.SKIPPED import com.netflix.spinnaker.orca.ExecutionStatus.STOPPED import com.netflix.spinnaker.orca.ExecutionStatus.SUCCEEDED import com.netflix.spinnaker.orca.ExecutionStatus.TERMINAL import com.netflix.spinnaker.orca.events.StageComplete import com.netflix.spinnaker.orca.exceptions.ExceptionHandler import com.netflix.spinnaker.orca.ext.afterStages import com.netflix.spinnaker.orca.ext.failureStatus import com.netflix.spinnaker.orca.ext.firstAfterStages import com.netflix.spinnaker.orca.ext.syntheticStages import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.graph.StageGraphBuilder import com.netflix.spinnaker.orca.pipeline.model.Stage import com.netflix.spinnaker.orca.pipeline.model.Task import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.pipeline.util.StageNavigator import com.netflix.spinnaker.orca.q.CancelStage import com.netflix.spinnaker.orca.q.CompleteExecution import com.netflix.spinnaker.orca.q.CompleteStage import com.netflix.spinnaker.orca.q.StartStage import com.netflix.spinnaker.orca.q.appendAfterStages import com.netflix.spinnaker.orca.q.buildAfterStages import com.netflix.spinnaker.q.Queue import org.springframework.beans.factory.annotation.Qualifier import org.springframework.context.ApplicationEventPublisher import org.springframework.stereotype.Component import java.time.Clock import java.util.concurrent.TimeUnit import kotlin.collections.List import kotlin.collections.all import kotlin.collections.any import kotlin.collections.emptyList import kotlin.collections.filter import kotlin.collections.forEach import kotlin.collections.forEachIndexed import kotlin.collections.isNotEmpty import kotlin.collections.listOf import kotlin.collections.map import kotlin.collections.minus import kotlin.collections.plus import kotlin.collections.set import kotlin.collections.setOf import kotlin.collections.toList @Component class CompleteStageHandler( override val queue: Queue, override val repository: ExecutionRepository, override val stageNavigator: StageNavigator, @Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher, private val clock: Clock, private val exceptionHandlers: List<ExceptionHandler>, override val contextParameterProcessor: ContextParameterProcessor, private val registry: Registry, override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory ) : OrcaMessageHandler<CompleteStage>, StageBuilderAware, ExpressionAware, AuthenticationAware { override fun handle(message: CompleteStage) { message.withStage { stage -> if (stage.status in setOf(RUNNING, NOT_STARTED)) { var status = stage.determineStatus() if (stage.shouldFailOnFailedExpressionEvaluation()) { log.warn("Stage ${stage.id} (${stage.type}) of ${stage.execution.id} " + "is set to fail because of failed expressions.") status = TERMINAL } try { if (status in setOf(RUNNING, NOT_STARTED) || (status.isComplete && !status.isHalt)) { // check to see if this stage has any unplanned synthetic after stages var afterStages = stage.firstAfterStages() if (afterStages.isEmpty()) { stage.withAuth { stage.planAfterStages() } afterStages = stage.firstAfterStages() } if (afterStages.isNotEmpty() && afterStages.any { it.status == NOT_STARTED }) { afterStages .filter { it.status == NOT_STARTED } .forEach { queue.push(StartStage(message, it.id)) } return@withStage } else if (status == NOT_STARTED) { // stage had no synthetic stages or tasks, which is odd but whatever log.warn("Stage ${stage.id} (${stage.type}) of ${stage.execution.id} had no tasks or synthetic stages!") status = SKIPPED } } else if (status.isFailure) { var hasOnFailureStages = false stage.withAuth { hasOnFailureStages = stage.planOnFailureStages() } if (hasOnFailureStages) { stage.firstAfterStages().forEach { queue.push(StartStage(it)) } return@withStage } } stage.status = status stage.endTime = clock.millis() } catch (e: Exception) { log.error("Failed to construct after stages for ${stage.name} ${stage.id}", e) val exceptionDetails = exceptionHandlers.shouldRetry(e, stage.name + ":ConstructAfterStages") stage.context["exception"] = exceptionDetails stage.status = TERMINAL stage.endTime = clock.millis() } stage.includeExpressionEvaluationSummary() repository.storeStage(stage) // When a synthetic stage ends with FAILED_CONTINUE, propagate that status up to the stage's // parent so that no more of the parent's synthetic children will run. if (stage.status == FAILED_CONTINUE && stage.syntheticStageOwner != null && !stage.allowSiblingStagesToContinueOnFailure) { queue.push(message.copy(stageId = stage.parentStageId!!)) } else if (stage.status in listOf(SUCCEEDED, FAILED_CONTINUE, SKIPPED)) { stage.startNext() } else { queue.push(CancelStage(message)) if (stage.syntheticStageOwner == null) { log.debug("Stage has no synthetic owner, completing execution (original message: $message)") queue.push(CompleteExecution(message)) } else { queue.push(message.copy(stageId = stage.parentStageId!!)) } } publisher.publishEvent(StageComplete(this, stage)) trackResult(stage) } } } // TODO: this should be done out of band by responding to the StageComplete event private fun trackResult(stage: Stage) { // We only want to record durations of parent-level stages; not synthetics. if (stage.parentStageId != null) { return } val id = registry.createId("stage.invocations.duration") .withTag("status", stage.status.toString()) .withTag("stageType", stage.type) .let { id -> // TODO rz - Need to check synthetics for their cloudProvider. stage.context["cloudProvider"]?.let { id.withTag("cloudProvider", it.toString()) } ?: id } // If startTime was not set, then assume this was instantaneous. // In practice 0 startTimes can happen if there is // an exception in StartStageHandler or guard causing skipping. // Without a startTime, we cannot record a meaningful time, // and assuming a start of 0 makes the values ridiculously large. val endTime = stage.endTime ?: clock.millis() val startTime = stage.startTime ?: endTime PercentileTimer .get(registry, id) .record(endTime - startTime, TimeUnit.MILLISECONDS) } override val messageType = CompleteStage::class.java /** * Plan any outstanding synthetic after stages. */ private fun Stage.planAfterStages() { var hasPlannedStages = false builder().buildAfterStages(this) { it: Stage -> repository.addStage(it) hasPlannedStages = true } if (hasPlannedStages) { this.execution = repository.retrieve(this.execution.type, this.execution.id) } } /** * Plan any outstanding synthetic on failure stages. */ private fun Stage.planOnFailureStages(): Boolean { // Avoid planning failure stages if _any_ with the same name are already complete val previouslyPlannedAfterStageNames = afterStages().filter { it.status.isComplete }.map { it.name } val graph = StageGraphBuilder.afterStages(this) builder().onFailureStages(this, graph) val onFailureStages = graph.build().toList() onFailureStages.forEachIndexed { index, stage -> if (index > 0) { // all on failure stages should be run linearly graph.connect(onFailureStages.get(index - 1), stage) } } val alreadyPlanned = onFailureStages.any { previouslyPlannedAfterStageNames.contains(it.name) } return if (alreadyPlanned || onFailureStages.isEmpty()) { false } else { removeNotStartedSynthetics() // should be all synthetics (nothing should have been started!) appendAfterStages(onFailureStages) { repository.addStage(it) } true } } private fun Stage.removeNotStartedSynthetics() { syntheticStages() .filter { it.status == NOT_STARTED } .forEach { stage -> execution .stages .filter { it.requisiteStageRefIds.contains(stage.id) } .forEach { it.requisiteStageRefIds = it.requisiteStageRefIds - stage.id repository.addStage(it) } stage.removeNotStartedSynthetics() // should be all synthetics! repository.removeStage(execution, stage.id) } } private fun Stage.determineStatus(): ExecutionStatus { val syntheticStatuses = syntheticStages().map(Stage::getStatus) val taskStatuses = tasks.map(Task::getStatus) val planningStatus = if (hasPlanningFailure()) listOf(failureStatus()) else emptyList() val allStatuses = syntheticStatuses + taskStatuses + planningStatus val afterStageStatuses = afterStages().map(Stage::getStatus) return when { allStatuses.isEmpty() -> NOT_STARTED allStatuses.contains(TERMINAL) -> failureStatus() // handle configured 'if stage fails' options correctly allStatuses.contains(STOPPED) -> STOPPED allStatuses.contains(CANCELED) -> CANCELED allStatuses.contains(FAILED_CONTINUE) -> FAILED_CONTINUE allStatuses.all { it == SUCCEEDED } -> SUCCEEDED afterStageStatuses.contains(NOT_STARTED) -> RUNNING // after stages were planned but not run yet else -> { log.error("Unhandled condition for stage $id of $execution.id, marking as TERMINAL. syntheticStatuses=$syntheticStatuses, taskStatuses=$taskStatuses, planningStatus=$planningStatus, afterStageStatuses=$afterStageStatuses") TERMINAL } } } } private fun Stage.hasPlanningFailure() = context["beforeStagePlanningFailed"] == true
apache-2.0
cabc2aa2bc7c92aa57867e023d8738cb
39.699647
230
0.706199
4.644355
false
false
false
false
loxal/kotlin-javascript-example-bmi-calculator
src/main/kotlin/net/loxal/example/kotlin/bmi_calculator/BMIcalculator.kt
1
6717
/* * Copyright 2015 Alexander Orlov <[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 net.loxal.example.kotlin.bmi_calculator import org.w3c.dom.HTMLDivElement import org.w3c.dom.HTMLElement import org.w3c.dom.HTMLImageElement import org.w3c.dom.HTMLInputElement import kotlin.browser.document class BMIcalculator { private val bmiChart = document.getElementById("bmiChart") as HTMLImageElement private val bmiMarker = document.getElementById("bmiMarker") as HTMLImageElement private val weight = document.getElementById("weight") as HTMLInputElement private val height = document.getElementById("height") as HTMLInputElement private val metric = document.getElementById("metric") as HTMLInputElement private val imperial = document.getElementById("imperial") as HTMLInputElement private val heightUnitLabel = document.getElementById("heightUnitLabel") as HTMLElement private val weightUnitLabel = document.getElementById("weightUnitLabel") as HTMLElement private val bmi = document.getElementById("bmiValue") as HTMLDivElement private val lbInKg = 0.45359237; private val inInCm = 2.54; private var weightInKg: Double = safeParseDouble(weight.value)!! private var heightInCm: Double = safeParseDouble(height.value)!! private var isMetricMeasurement = true private fun initListeners() { weight.onclick = { // TODO consolidate onclick & onkeyup in something as onchange once Kotlin supports it showBMI() } weight.onkeyup = { // TODO consolidate onclick & onkeyup in something as onchange once Kotlin supports it showBMI() } height.onclick = { // TODO consolidate onclick & onkeyup in something as onchange once Kotlin supports it showBMI() } height.onkeyup = { // TODO consolidate onclick & onkeyup in something as onchange once Kotlin supports it showBMI() } imperial.onclick = { calculateImperialBMI() } metric.onclick = { calculateMetricBMI() } } private fun setMetaValues() { if (isMetricMeasurement) { setMetric() } else { convertMetricToImperial() } } private fun changeToMetric() { metric.checked = true isMetricMeasurement = true setMetricLabels() val cmTooPrecise = convertInToCm(safeParseDouble(height.value)!!).toString() val kgTooPrecise = convertLbToKg(safeParseDouble(weight.value)!!).toString() height.value = cmTooPrecise.substringBefore('.') + '.' + cmTooPrecise.substringAfter('.').substring(0, 2) weight.value = kgTooPrecise.substringBefore('.') + '.' + kgTooPrecise.substringAfter('.').substring(0, 2) } private fun changeToImperial() { imperial.checked = true isMetricMeasurement = false setImperialLabels() val inTooPrecise = convertCmToIn(safeParseDouble(height.value)!!).toString() val lbTooPrecise = convertKgToLb(safeParseDouble(weight.value)!!).toString() height.value = inTooPrecise.substringBefore('.') + '.' + inTooPrecise.substringAfter('.').substring(0, 2) weight.value = lbTooPrecise.substringBefore('.') + '.' + lbTooPrecise.substringAfter('.').substring(0, 2) } private fun calculateMetricBMI() { changeToMetric() showBMI() } private fun calculateImperialBMI() { changeToImperial() showBMI() } private fun calculateBMI(): Double { setMetaValues() return weightInKg / Math.pow(heightInCm, 2.0) * 1e4; } private fun showBMI() { val bmiValue: String if (isMetricMeasurement) { bmiValue = calculateBMI().toString().substringBefore('.') + ',' + calculateBMI().toString().substringAfter('.') // TODO l10n is not supported yet } else { bmiValue = calculateBMI().toString() } bmi.textContent = "BMI: ${bmiValue.substring(0, 5)}" // TODO good enough for 99.9% (proper rounding is not supported by Kotlin yet) putBMImarker(safeParseDouble(weight.value)!!, safeParseDouble(height.value)!!) } private fun setMetric() { heightInCm = safeParseDouble(height.value)!! weightInKg = safeParseDouble(weight.value)!! } private fun convertMetricToImperial() { heightInCm = convertInToCm(safeParseDouble(height.value)!!) weightInKg = convertLbToKg(safeParseDouble(weight.value)!!) } private fun convertCmToIn(cm: Double): Double { return cm / inInCm } private fun convertKgToLb(kg: Double): Double { return kg / lbInKg } private fun convertInToCm(inches: Double): Double { return inches * inInCm } private fun convertLbToKg(lb: Double): Double { return lb * lbInKg } private fun kgToXscale(kg: Double): Double { val chartLeftZero = 10 val chartOffsetForScale = 39 val kgStart = 40.0 val xPerKg = 4.116 val visibleWeight = kg - kgStart return (chartLeftZero + chartOffsetForScale) + (visibleWeight * xPerKg) } private fun cmToYscale(cm: Double): Double { val chartGround = bmiChart.height val chartOffsetForScale = 31.5 val cmStart = 148 val yPerCm = 7.62 val visibleHeight = cm - cmStart return (chartGround - chartOffsetForScale) - (visibleHeight * yPerCm) } private fun putBMImarker(kg: Double, cm: Double) { val x = kgToXscale(kg) val y = cmToYscale(cm) bmiMarker.style.cssText = "position: absolute; top: ${y}px; left: ${x}px;" } init { setBMIChartSize() initListeners() showBMI() } private fun setBMIChartSize() { bmiChart.width = 590 bmiChart.height = 480 } private fun setMetricLabels() { heightUnitLabel.textContent = "cm:" weightUnitLabel.textContent = "kg:" } private fun setImperialLabels() { heightUnitLabel.textContent = "in:" weightUnitLabel.textContent = "lb:" } }
apache-2.0
f4f3d9286acf5904cef2a952445debb9
32.59
139
0.655948
4.278344
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/ColorUtils.kt
1
10083
package net.perfectdreams.loritta.morenitta.utils import java.awt.Color import java.util.* /** * Java Code to get a color name from rgb/hex value/awt color * * The part of looking up a color name from the rgb values is edited from * https://gist.github.com/nightlark/6482130#file-gistfile1-java (that has some errors) by Ryan Mast (nightlark) * * @author Xiaoxiao Li */ class ColorUtils { /** * Initialize the color list that we have. */ private fun initColorList(): ArrayList<ColorName> { val colorList = ArrayList<ColorName>() colorList.add(ColorName("AliceBlue", 0xF0, 0xF8, 0xFF)) colorList.add(ColorName("AntiqueWhite", 0xFA, 0xEB, 0xD7)) colorList.add(ColorName("Aqua", 0x00, 0xFF, 0xFF)) colorList.add(ColorName("Aquamarine", 0x7F, 0xFF, 0xD4)) colorList.add(ColorName("Azure", 0xF0, 0xFF, 0xFF)) colorList.add(ColorName("Beige", 0xF5, 0xF5, 0xDC)) colorList.add(ColorName("Bisque", 0xFF, 0xE4, 0xC4)) colorList.add(ColorName("Black", 0x00, 0x00, 0x00)) colorList.add(ColorName("BlanchedAlmond", 0xFF, 0xEB, 0xCD)) colorList.add(ColorName("Blue", 0x00, 0x00, 0xFF)) colorList.add(ColorName("BlueViolet", 0x8A, 0x2B, 0xE2)) colorList.add(ColorName("Brown", 0xA5, 0x2A, 0x2A)) colorList.add(ColorName("BurlyWood", 0xDE, 0xB8, 0x87)) colorList.add(ColorName("CadetBlue", 0x5F, 0x9E, 0xA0)) colorList.add(ColorName("Chartreuse", 0x7F, 0xFF, 0x00)) colorList.add(ColorName("Chocolate", 0xD2, 0x69, 0x1E)) colorList.add(ColorName("Coral", 0xFF, 0x7F, 0x50)) colorList.add(ColorName("CornflowerBlue", 0x64, 0x95, 0xED)) colorList.add(ColorName("Cornsilk", 0xFF, 0xF8, 0xDC)) colorList.add(ColorName("Crimson", 0xDC, 0x14, 0x3C)) colorList.add(ColorName("Cyan", 0x00, 0xFF, 0xFF)) colorList.add(ColorName("DarkBlue", 0x00, 0x00, 0x8B)) colorList.add(ColorName("DarkCyan", 0x00, 0x8B, 0x8B)) colorList.add(ColorName("DarkGoldenRod", 0xB8, 0x86, 0x0B)) colorList.add(ColorName("DarkGray", 0xA9, 0xA9, 0xA9)) colorList.add(ColorName("DarkGreen", 0x00, 0x64, 0x00)) colorList.add(ColorName("DarkKhaki", 0xBD, 0xB7, 0x6B)) colorList.add(ColorName("DarkMagenta", 0x8B, 0x00, 0x8B)) colorList.add(ColorName("DarkOliveGreen", 0x55, 0x6B, 0x2F)) colorList.add(ColorName("DarkOrange", 0xFF, 0x8C, 0x00)) colorList.add(ColorName("DarkOrchid", 0x99, 0x32, 0xCC)) colorList.add(ColorName("DarkRed", 0x8B, 0x00, 0x00)) colorList.add(ColorName("DarkSalmon", 0xE9, 0x96, 0x7A)) colorList.add(ColorName("DarkSeaGreen", 0x8F, 0xBC, 0x8F)) colorList.add(ColorName("DarkSlateBlue", 0x48, 0x3D, 0x8B)) colorList.add(ColorName("DarkSlateGray", 0x2F, 0x4F, 0x4F)) colorList.add(ColorName("DarkTurquoise", 0x00, 0xCE, 0xD1)) colorList.add(ColorName("DarkViolet", 0x94, 0x00, 0xD3)) colorList.add(ColorName("DeepPink", 0xFF, 0x14, 0x93)) colorList.add(ColorName("DeepSkyBlue", 0x00, 0xBF, 0xFF)) colorList.add(ColorName("DimGray", 0x69, 0x69, 0x69)) colorList.add(ColorName("DodgerBlue", 0x1E, 0x90, 0xFF)) colorList.add(ColorName("FireBrick", 0xB2, 0x22, 0x22)) colorList.add(ColorName("FloralWhite", 0xFF, 0xFA, 0xF0)) colorList.add(ColorName("ForestGreen", 0x22, 0x8B, 0x22)) colorList.add(ColorName("Fuchsia", 0xFF, 0x00, 0xFF)) colorList.add(ColorName("Gainsboro", 0xDC, 0xDC, 0xDC)) colorList.add(ColorName("GhostWhite", 0xF8, 0xF8, 0xFF)) colorList.add(ColorName("Gold", 0xFF, 0xD7, 0x00)) colorList.add(ColorName("GoldenRod", 0xDA, 0xA5, 0x20)) colorList.add(ColorName("Gray", 0x80, 0x80, 0x80)) colorList.add(ColorName("Green", 0x00, 0x80, 0x00)) colorList.add(ColorName("GreenYellow", 0xAD, 0xFF, 0x2F)) colorList.add(ColorName("HoneyDew", 0xF0, 0xFF, 0xF0)) colorList.add(ColorName("HotPink", 0xFF, 0x69, 0xB4)) colorList.add(ColorName("IndianRed", 0xCD, 0x5C, 0x5C)) colorList.add(ColorName("Indigo", 0x4B, 0x00, 0x82)) colorList.add(ColorName("Ivory", 0xFF, 0xFF, 0xF0)) colorList.add(ColorName("Khaki", 0xF0, 0xE6, 0x8C)) colorList.add(ColorName("Lavender", 0xE6, 0xE6, 0xFA)) colorList.add(ColorName("LavenderBlush", 0xFF, 0xF0, 0xF5)) colorList.add(ColorName("LawnGreen", 0x7C, 0xFC, 0x00)) colorList.add(ColorName("LemonChiffon", 0xFF, 0xFA, 0xCD)) colorList.add(ColorName("LightBlue", 0xAD, 0xD8, 0xE6)) colorList.add(ColorName("LightCoral", 0xF0, 0x80, 0x80)) colorList.add(ColorName("LightCyan", 0xE0, 0xFF, 0xFF)) colorList.add(ColorName("LightGoldenRodYellow", 0xFA, 0xFA, 0xD2)) colorList.add(ColorName("LightGray", 0xD3, 0xD3, 0xD3)) colorList.add(ColorName("LightGreen", 0x90, 0xEE, 0x90)) colorList.add(ColorName("LightPink", 0xFF, 0xB6, 0xC1)) colorList.add(ColorName("LightSalmon", 0xFF, 0xA0, 0x7A)) colorList.add(ColorName("LightSeaGreen", 0x20, 0xB2, 0xAA)) colorList.add(ColorName("LightSkyBlue", 0x87, 0xCE, 0xFA)) colorList.add(ColorName("LightSlateGray", 0x77, 0x88, 0x99)) colorList.add(ColorName("LightSteelBlue", 0xB0, 0xC4, 0xDE)) colorList.add(ColorName("LightYellow", 0xFF, 0xFF, 0xE0)) colorList.add(ColorName("Lime", 0x00, 0xFF, 0x00)) colorList.add(ColorName("LimeGreen", 0x32, 0xCD, 0x32)) colorList.add(ColorName("Linen", 0xFA, 0xF0, 0xE6)) colorList.add(ColorName("Magenta", 0xFF, 0x00, 0xFF)) colorList.add(ColorName("Maroon", 0x80, 0x00, 0x00)) colorList.add(ColorName("MediumAquaMarine", 0x66, 0xCD, 0xAA)) colorList.add(ColorName("MediumBlue", 0x00, 0x00, 0xCD)) colorList.add(ColorName("MediumOrchid", 0xBA, 0x55, 0xD3)) colorList.add(ColorName("MediumPurple", 0x93, 0x70, 0xDB)) colorList.add(ColorName("MediumSeaGreen", 0x3C, 0xB3, 0x71)) colorList.add(ColorName("MediumSlateBlue", 0x7B, 0x68, 0xEE)) colorList.add(ColorName("MediumSpringGreen", 0x00, 0xFA, 0x9A)) colorList.add(ColorName("MediumTurquoise", 0x48, 0xD1, 0xCC)) colorList.add(ColorName("MediumVioletRed", 0xC7, 0x15, 0x85)) colorList.add(ColorName("MidnightBlue", 0x19, 0x19, 0x70)) colorList.add(ColorName("MintCream", 0xF5, 0xFF, 0xFA)) colorList.add(ColorName("MistyRose", 0xFF, 0xE4, 0xE1)) colorList.add(ColorName("Moccasin", 0xFF, 0xE4, 0xB5)) colorList.add(ColorName("NavajoWhite", 0xFF, 0xDE, 0xAD)) colorList.add(ColorName("Navy", 0x00, 0x00, 0x80)) colorList.add(ColorName("OldLace", 0xFD, 0xF5, 0xE6)) colorList.add(ColorName("Olive", 0x80, 0x80, 0x00)) colorList.add(ColorName("OliveDrab", 0x6B, 0x8E, 0x23)) colorList.add(ColorName("Orange", 0xFF, 0xA5, 0x00)) colorList.add(ColorName("OrangeRed", 0xFF, 0x45, 0x00)) colorList.add(ColorName("Orchid", 0xDA, 0x70, 0xD6)) colorList.add(ColorName("PaleGoldenRod", 0xEE, 0xE8, 0xAA)) colorList.add(ColorName("PaleGreen", 0x98, 0xFB, 0x98)) colorList.add(ColorName("PaleTurquoise", 0xAF, 0xEE, 0xEE)) colorList.add(ColorName("PaleVioletRed", 0xDB, 0x70, 0x93)) colorList.add(ColorName("PapayaWhip", 0xFF, 0xEF, 0xD5)) colorList.add(ColorName("PeachPuff", 0xFF, 0xDA, 0xB9)) colorList.add(ColorName("Peru", 0xCD, 0x85, 0x3F)) colorList.add(ColorName("Pink", 0xFF, 0xC0, 0xCB)) colorList.add(ColorName("Plum", 0xDD, 0xA0, 0xDD)) colorList.add(ColorName("PowderBlue", 0xB0, 0xE0, 0xE6)) colorList.add(ColorName("Purple", 0x80, 0x00, 0x80)) colorList.add(ColorName("Red", 0xFF, 0x00, 0x00)) colorList.add(ColorName("RosyBrown", 0xBC, 0x8F, 0x8F)) colorList.add(ColorName("RoyalBlue", 0x41, 0x69, 0xE1)) colorList.add(ColorName("SaddleBrown", 0x8B, 0x45, 0x13)) colorList.add(ColorName("Salmon", 0xFA, 0x80, 0x72)) colorList.add(ColorName("SandyBrown", 0xF4, 0xA4, 0x60)) colorList.add(ColorName("SeaGreen", 0x2E, 0x8B, 0x57)) colorList.add(ColorName("SeaShell", 0xFF, 0xF5, 0xEE)) colorList.add(ColorName("Sienna", 0xA0, 0x52, 0x2D)) colorList.add(ColorName("Silver", 0xC0, 0xC0, 0xC0)) colorList.add(ColorName("SkyBlue", 0x87, 0xCE, 0xEB)) colorList.add(ColorName("SlateBlue", 0x6A, 0x5A, 0xCD)) colorList.add(ColorName("SlateGray", 0x70, 0x80, 0x90)) colorList.add(ColorName("Snow", 0xFF, 0xFA, 0xFA)) colorList.add(ColorName("SpringGreen", 0x00, 0xFF, 0x7F)) colorList.add(ColorName("SteelBlue", 0x46, 0x82, 0xB4)) colorList.add(ColorName("Tan", 0xD2, 0xB4, 0x8C)) colorList.add(ColorName("Teal", 0x00, 0x80, 0x80)) colorList.add(ColorName("Thistle", 0xD8, 0xBF, 0xD8)) colorList.add(ColorName("Tomato", 0xFF, 0x63, 0x47)) colorList.add(ColorName("Turquoise", 0x40, 0xE0, 0xD0)) colorList.add(ColorName("Violet", 0xEE, 0x82, 0xEE)) colorList.add(ColorName("Wheat", 0xF5, 0xDE, 0xB3)) colorList.add(ColorName("White", 0xFF, 0xFF, 0xFF)) colorList.add(ColorName("WhiteSmoke", 0xF5, 0xF5, 0xF5)) colorList.add(ColorName("Yellow", 0xFF, 0xFF, 0x00)) colorList.add(ColorName("YellowGreen", 0x9A, 0xCD, 0x32)) return colorList } /** * Get the closest color name from our list * * @param r * @param g * @param b * @return */ fun getColorNameFromRgb(r: Int, g: Int, b: Int): String { val colorList = initColorList() var closestMatch: ColorName? = null var minMSE = Integer.MAX_VALUE var mse: Int for (c in colorList) { mse = c.computeMSE(r, g, b) if (mse < minMSE) { minMSE = mse closestMatch = c } } return if (closestMatch != null) { closestMatch.name } else { "No matched color name." } } /** * Convert hexColor to rgb, then call getColorNameFromRgb(r, g, b) * * @param hexColor * @return */ fun getColorNameFromHex(hexColor: Int): String { val r = hexColor and 0xFF0000 shr 16 val g = hexColor and 0xFF00 shr 8 val b = hexColor and 0xFF return getColorNameFromRgb(r, g, b) } fun colorToHex(c: Color): Int { return Integer.decode("0x" + Integer.toHexString(c.rgb).substring(2))!! } fun getColorNameFromColor(color: Color): String { return getColorNameFromRgb(color.red, color.green, color.blue) } /** * SubClass of ColorUtils. In order to lookup color name * * @author Xiaoxiao Li */ inner class ColorName(var name: String, var r: Int, var g: Int, var b: Int) { fun computeMSE(pixR: Int, pixG: Int, pixB: Int): Int { return (((pixR - r) * (pixR - r) + (pixG - g) * (pixG - g) + (pixB - b) * (pixB - b)) / 3).toInt() } } }
agpl-3.0
ffa25086d97687c26b8201c49ed34fb2
43.817778
112
0.709709
2.380312
false
false
false
false
appnexus/mobile-sdk-android
examples/kotlin/SimpleDemo/app/src/main/java/appnexus/example/kotlinsample/NativeActivity.kt
1
3211
package appnexus.example.kotlinsample import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.appnexus.opensdk.* class NativeActivity : AppCompatActivity(),NativeAdRequestListener,NativeAdEventListener { private lateinit var nativeAdRequest: NativeAdRequest private lateinit var nativeAdResponse: NativeAdResponse private lateinit var nativeContainer: View override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_native) nativeContainer = findViewById(R.id.an_native_container) nativeAdRequest = NativeAdRequest(this, "17058950") nativeAdRequest.shouldLoadImage(true) nativeAdRequest.shouldLoadIcon(true) nativeAdRequest.listener = this nativeAdRequest.loadAd() } // NativeAdRequestListener - Start override fun onAdLoaded(response: NativeAdResponse) { log("Native Ad Loaded") nativeAdResponse = response val icon: ImageView = findViewById(R.id.an_icon) val image: ImageView = findViewById(R.id.an_image) val title: TextView = findViewById(R.id.an_title) val sponsoredBy: TextView = findViewById(R.id.an_sponsoredBy) val description: TextView = findViewById(R.id.an_description) val clickThrough: Button = findViewById(R.id.an_clickThrough) icon.setImageBitmap(nativeAdResponse.icon) image.setImageBitmap(nativeAdResponse.image) title.text = nativeAdResponse.title sponsoredBy.text = "Sponsored By: ${nativeAdResponse.sponsoredBy}" description.text = nativeAdResponse.description clickThrough.text = nativeAdResponse.callToAction; NativeAdSDK.unRegisterTracking(nativeContainer) // if re-using the same container for showing multiple ad's need to first unregister, before registering. NativeAdSDK.registerTracking(nativeAdResponse, nativeContainer, mutableListOf(clickThrough) as List<View>?,this) } override fun onAdFailed(errorcode: ResultCode, adResponseinfo:ANAdResponseInfo) { log("Native Ad Failed: " + errorcode.message) } override fun onAdImpression() { } override fun onAdAboutToExpire() { } // NativeAdRequestListener - End // NativeAdEventListener - Start override fun onAdWasClicked() { log("Native Ad Clicked") } override fun onAdWillLeaveApplication() { log("Native Ad will leave application") } override fun onAdWasClicked(clickUrl: String, fallbackURL: String) { log("Native Ad Clicked with URL: $clickUrl ::: fallbackURL: $fallbackURL") } override fun onAdExpired() { } // NativeAdEventListener - End private fun log(msg: String){ Log.d("NativeActivity",msg) Toast.makeText(this.applicationContext, msg, Toast.LENGTH_LONG).show() } override fun onDestroy() { NativeAdSDK.unRegisterTracking(nativeContainer) super.onDestroy() } }
apache-2.0
e3b39d0892f70712a169b2c4b285d30b
32.447917
161
0.715353
4.633478
false
false
false
false
shyiko/ktlint
ktlint-ruleset-test/src/main/kotlin/com/pinterest/ruleset/test/DumpASTRule.kt
1
4109
package com.pinterest.ruleset.test import com.pinterest.ktlint.core.Rule import com.pinterest.ktlint.core.ast.ElementType import com.pinterest.ktlint.core.ast.isRoot import com.pinterest.ktlint.core.ast.lastChildLeafOrSelf import com.pinterest.ktlint.core.ast.lineNumber import com.pinterest.ruleset.test.internal.Color import com.pinterest.ruleset.test.internal.color import java.io.PrintStream import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.psi.tree.IElementType import org.jetbrains.kotlin.lexer.KtTokens public class DumpASTRule @JvmOverloads constructor( private val out: PrintStream = System.err, private val color: Boolean = false ) : Rule("dump") { private companion object { val elementTypeSet = ElementType::class.members.map { it.name }.toSet() } private var lineNumberColumnLength: Int = 0 private var lastNode: ASTNode? = null override fun visit( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, corrected: Boolean) -> Unit ) { if (node.isRoot()) { lineNumberColumnLength = (node.lastChildLeafOrSelf().lineNumber() ?: 1) .let { var v = it; var c = 0; while (v > 0) { c++; v /= 10 }; c } lastNode = node.lastChildLeafOrSelf() } var level = -1 var parent: ASTNode? = node do { level++ parent = parent?.treeParent } while (parent != null) out.println( ( node.lineNumber() ?.let { String.format("%${lineNumberColumnLength}s: ", it).dim() } // should only happen when autoCorrect=true and other rules mutate AST // in a way that changes text length ?: String.format("%${lineNumberColumnLength}s: ", "?").dim() ) + " ".repeat(level).dim() + colorClassName(node.psi.className) + " (".dim() + colorClassName(elementTypeClassName(node.elementType)) + ")".dim() + if (node.getChildren(null).isEmpty()) " \"" + node.text.escape().brighten() + "\"" else "" ) if (lastNode == node) { out.println() out.println( " ".repeat(lineNumberColumnLength) + " format: <line_number:> <node.psi::class> (<node.elementType>) \"<node.text>\"".dim() ) out.println( " ".repeat(lineNumberColumnLength) + " legend: ~ = org.jetbrains.kotlin, c.i.p = com.intellij.psi".dim() ) out.println() } } private fun elementTypeClassName(elementType: IElementType): String { var name = elementType.toString().substringAfterLast(".").toUpperCase() if (name == "FLOAT_CONSTANT" && elementType == KtTokens.FLOAT_LITERAL) { // resolve KtNodeTypes.FLOAT_CONSTANT vs KtTokens.FLOAT_LITERAL(FLOAT_CONSTANT) conflict name = "FLOAT_LITERAL" } if (KtTokens.KEYWORDS.contains(elementType) || KtTokens.SOFT_KEYWORDS.contains(elementType)) { name = "${name}_KEYWORD" } return if (elementTypeSet.contains(name)) name else elementType.className + "." + elementType } private fun colorClassName(className: String): String { val name = className.substringAfterLast(".") return className.substring(0, className.length - name.length).dim() + name } private fun String.brighten() = optColor(Color.YELLOW) private fun String.dim() = optColor(Color.DARK_GRAY) private fun String.optColor(foreground: Color) = if (color) this.color(foreground) else this private val Any.className get() = this.javaClass.name .replace("org.jetbrains.kotlin.", "~.") .replace("com.intellij.psi.", "c.i.p.") private fun String.escape() = this.replace("\\", "\\\\").replace("\n", "\\n").replace("\t", "\\t").replace("\r", "\\r") }
mit
d1accebcb39e50cf4094515fbf5db741
39.683168
107
0.592602
4.334388
false
false
false
false
christophpickl/kpotpourri
release4k/src/test/kotlin/com/github/christophpickl/kpotpourri/release4k/release4k_for_kpot_app.kt
1
4343
package com.github.christophpickl.kpotpourri.release4k import com.github.christophpickl.kpotpourri.common.io.Keyboard import com.github.christophpickl.kpotpourri.common.process.ExecuteContext import com.github.christophpickl.kpotpourri.release4k.Version.VersionParts2.Companion.readVersion2FromStdin import java.io.File //private val relativeKpotPath = "../github2/kpotpourri" // navigate to proper checkout location :) or simply "." private val relativeKpotPath = "." private val liveKpotFolder = File(relativeKpotPath) private val gitUrl = "https://github.com/christophpickl/kpotpourri.git" private val versionTxtFilename = "version.txt" fun main(args: Array<String>) = release4k(workingDirectory = liveKpotFolder) { println() println(""" _ _ _ | | ___ __ ___ | |_ _ __ ___ _ _ _ __ _ __(_) | |/ / '_ \ / _ \| __| '_ \ / _ \| | | | '__| '__| | | <| |_) | (_) | |_| |_) | (_) | |_| | | | | | | |_|\_\ .__/ \___/ \__| .__/ \___/ \__,_|_| |_| |_| |_| |_| """) println() if (File("").canonicalPath.endsWith("release4k")) { throw RuntimeException("Invalid CWD! Execute this main class from 'kpotpourri' root directory, instead of submodule 'release4k' ;)") } // ================================================================================================================= val relativeVersionPath = "$relativeKpotPath/$versionTxtFilename" val currentVersion = readVersionFromTxt(relativeVersionPath).toVersion2() val nextVersion = readVersion2FromStdin(prompt = "Enter next release version", defaultVersion = currentVersion.incrementMinor()) val nextVersionString = nextVersion.niceString val syspropNextVersion = "-Dkpotpourri.version=$nextVersionString" // ================================================================================================================= printHeader("VERIFY NO CHANGES") execute("/usr/bin/git", listOf("status"), ExecuteContext(cwd = liveKpotFolder)) println() if (!Keyboard.readConfirmation(prompt = "Are you sure there are no changes and everything was pushed?!")) { return } // ================================================================================================================= printHeader("RELEASE NOTES") println("Base release directory: ${release4kDirectory.canonicalPath}") println("GitHub URL: $gitUrl") println("Version file: ${File(relativeVersionPath).canonicalPath}") println("Versions: ${currentVersion.niceString} => $nextVersionString") println() // ================================================================================================================= if (!Keyboard.readConfirmation(prompt = "Do you wanna release this?")) { return } // ================================================================================================================= printHeader("CHECKOUT GIT") checkoutGitProject(gitUrl) // ================================================================================================================= printHeader("GRADLE BUILD") // gradlew("clean check checkTodo test build $syspropNextVersion") gradlew(listOf("clean", "check", "test", "build", syspropNextVersion)) // ================================================================================================================= printHeader("CHANGE VERSION") File(gitCheckoutDirectory, versionTxtFilename).writeText(nextVersionString) git(listOf("status")) git(listOf("add", ".")) git(listOf("commit", "-m", "[Auto-Release] Preparing release $nextVersionString")) git(listOf("tag", nextVersionString)) // ================================================================================================================= printHeader("BINTRAY UPLOAD") gradlew(listOf("bintrayUpload", "syspropNextVersion")) git(listOf("push")) git(listOf("push", "origin", "--tags")) // ================================================================================================================= printHeader("PULL LOCAL GIT") execute("/usr/bin/git", listOf("pull"), ExecuteContext(cwd = liveKpotFolder)) execute("/usr/bin/git", listOf("fetch", "-p"), ExecuteContext(cwd = liveKpotFolder)) }
apache-2.0
32007c3243e3899e1096a8fb14099727
48.91954
140
0.496892
5.079532
false
false
false
false
Magneticraft-Team/Magneticraft
ignore/test/block/BlockFeedingTrough.kt
2
5145
@file:Suppress("DEPRECATION", "OverridingDeprecatedMember") package block import com.cout970.magneticraft.block.itemblock.ItemBlockFeedingTrough import com.cout970.magneticraft.misc.block.get import com.cout970.magneticraft.misc.tileentity.getTile import com.cout970.magneticraft.tileentity.TileFeedingTrough import com.cout970.magneticraft.util.vector.isHorizontal import com.cout970.magneticraft.util.vector.toAABBWith import com.teamwizardry.librarianlib.common.base.block.BlockModContainer import net.minecraft.block.material.Material import net.minecraft.block.properties.PropertyBool import net.minecraft.block.properties.PropertyDirection import net.minecraft.block.state.BlockStateContainer import net.minecraft.block.state.IBlockState import net.minecraft.entity.EntityLivingBase import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemBlock import net.minecraft.item.ItemStack import net.minecraft.util.EnumBlockRenderType import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Vec3d import net.minecraft.world.IBlockAccess import net.minecraft.world.World /** * Created by cout970 on 24/06/2016. */ object BlockFeedingTrough : BlockModContainer("feeding_trough", Material.WOOD) { override fun createItemForm(): ItemBlock? { return ItemBlockFeedingTrough(this) } lateinit var FEEDING_TROUGH_IS_CENTER: PropertyBool lateinit var FEEDING_TROUGH_SIDE_POSITION: PropertyDirection val boundingBox = Vec3d.ZERO toAABBWith Vec3d(1.0, 0.75, 1.0) override fun getBoundingBox(state: IBlockState?, source: IBlockAccess?, pos: BlockPos?) = boundingBox override fun createTileEntity(worldIn: World, meta: IBlockState) = if (meta.get(FEEDING_TROUGH_IS_CENTER)) TileFeedingTrough() else null override fun createBlockState(): BlockStateContainer { FEEDING_TROUGH_IS_CENTER = PropertyBool.create("center")!! FEEDING_TROUGH_SIDE_POSITION = PropertyDirection.create("side", { it?.isHorizontal() ?: false })!! return BlockStateContainer(this, FEEDING_TROUGH_IS_CENTER, FEEDING_TROUGH_SIDE_POSITION) } override fun onBlockActivated(worldIn: World, pos: BlockPos, state: IBlockState, playerIn: EntityPlayer?, hand: EnumHand?, heldItem: ItemStack?, side: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): Boolean { val tile = getTileEntity(worldIn, pos, state) if (tile != null) { if (heldItem != null) { val result = tile.insertItem(heldItem) playerIn!!.setHeldItem(hand, result) return true } else { val result = tile.extractItem() playerIn!!.setHeldItem(hand, result) return true } } return false } private fun getTileEntity(worldIn: World, pos: BlockPos, state: IBlockState) = if (state[FEEDING_TROUGH_IS_CENTER]) { worldIn.getTile<TileFeedingTrough>(pos) } else { val dir = state[FEEDING_TROUGH_SIDE_POSITION] worldIn.getTile<TileFeedingTrough>(pos.add(dir.directionVec)) } override fun onBlockPlacedBy(worldIn: World, pos: BlockPos, state: IBlockState, placer: EntityLivingBase, stack: ItemStack?) { super.onBlockPlacedBy(worldIn, pos, state, placer, stack) val dir = placer.adjustedHorizontalFacing val center = state.withProperty(FEEDING_TROUGH_SIDE_POSITION, dir)?.withProperty(FEEDING_TROUGH_IS_CENTER, true) val companion = state.withProperty(FEEDING_TROUGH_SIDE_POSITION, dir.opposite)?.withProperty(FEEDING_TROUGH_IS_CENTER, false) worldIn.setBlockState(pos, center) worldIn.setBlockState(pos.add(dir.directionVec), companion) } override fun breakBlock(worldIn: World, pos: BlockPos, state: IBlockState) { super.breakBlock(worldIn, pos, state) val dir = state[FEEDING_TROUGH_SIDE_POSITION] worldIn.setBlockToAir(pos.add(dir.directionVec)) } override fun getRenderType(state: IBlockState): EnumBlockRenderType { if (!state[FEEDING_TROUGH_IS_CENTER]) { return EnumBlockRenderType.INVISIBLE } return super.getRenderType(state) } override fun isFullBlock(state: IBlockState?) = false override fun isOpaqueCube(state: IBlockState?) = false override fun isFullCube(state: IBlockState?) = false override fun isVisuallyOpaque() = false override fun getMetaFromState(state: IBlockState?): Int { if (state == null) { return 0 } val sideMeta = EnumFacing.HORIZONTALS.indexOf(state[FEEDING_TROUGH_SIDE_POSITION]) shl 1 val centerMeta = if (state[FEEDING_TROUGH_IS_CENTER]) 1 else 0 return sideMeta + centerMeta } override fun getStateFromMeta(meta: Int) = defaultState.run { val side = EnumFacing.HORIZONTALS[meta shr 1] val center = (meta and 1) == 1 withProperty(FEEDING_TROUGH_SIDE_POSITION, side).withProperty(FEEDING_TROUGH_IS_CENTER, center) } }
gpl-2.0
f01339a0aee11a11181fcf22b25f7627
40.837398
217
0.712342
4.169368
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/itemblocks/ItemBlockElectricPoleTransformer.kt
2
2386
package com.cout970.magneticraft.systems.itemblocks import com.cout970.magneticraft.misc.block.get import com.cout970.magneticraft.systems.blocks.BlockBase import net.minecraft.entity.player.EntityPlayer import net.minecraft.init.Blocks import net.minecraft.util.EnumActionResult import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.math.BlockPos import net.minecraft.world.World import com.cout970.magneticraft.features.electric_conductors.Blocks as ConductorBlocks /** * Created by cout970 on 2017/07/03. */ class ItemBlockElectricPoleTransformer(blockBase: BlockBase) : ItemBlockBase(blockBase) { override fun onItemUse(player: EntityPlayer, worldIn: World, pos: BlockPos, hand: EnumHand, facing: EnumFacing, hitX: Float, hitY: Float, hitZ: Float): EnumActionResult { val itemStack = player.getHeldItem(hand) if (itemStack.isEmpty) return EnumActionResult.FAIL val state = worldIn.getBlockState(pos) if (state.block != ConductorBlocks.electricPole) return EnumActionResult.PASS val orientation = state[ConductorBlocks.PROPERTY_POLE_ORIENTATION] ?: return EnumActionResult.PASS val offset = orientation.offsetY val basePos = pos.offset(EnumFacing.UP, offset) val floorPos = basePos.offset(EnumFacing.DOWN, 4) val baseState = worldIn.getBlockState(basePos)[ConductorBlocks.PROPERTY_POLE_ORIENTATION] ?: return EnumActionResult.PASS //@formatter:off ConductorBlocks.air = true worldIn.setBlockState(basePos, Blocks.AIR.defaultState) ConductorBlocks.air = false worldIn.setBlockState(floorPos.offset(EnumFacing.UP, 0), ConductorBlocks.PoleOrientation.DOWN_4.getBlockState(blockBase)) worldIn.setBlockState(floorPos.offset(EnumFacing.UP, 1), ConductorBlocks.PoleOrientation.DOWN_3.getBlockState(blockBase)) worldIn.setBlockState(floorPos.offset(EnumFacing.UP, 2), ConductorBlocks.PoleOrientation.DOWN_2.getBlockState(blockBase)) worldIn.setBlockState(floorPos.offset(EnumFacing.UP, 3), ConductorBlocks.PoleOrientation.DOWN_1.getBlockState(blockBase)) worldIn.setBlockState(floorPos.offset(EnumFacing.UP, 4), baseState.getBlockState(blockBase)) //@formatter:on itemStack.shrink(1) return EnumActionResult.SUCCESS } }
gpl-2.0
f98e92b91b2886fa3ca54bbe211639b4
44.903846
129
0.753143
4.443203
false
false
false
false
ReactiveCircus/FlowBinding
flowbinding-material/src/androidTest/java/reactivecircus/flowbinding/material/NavigationBarViewItemSelectedFlowTest.kt
1
3105
package reactivecircus.flowbinding.material import android.view.MenuItem import androidx.test.filters.LargeTest import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread import com.google.android.material.navigation.NavigationBarView import com.google.common.truth.Truth.assertThat import org.junit.Test import reactivecircus.blueprint.testing.action.selectNavigationBarItem import reactivecircus.flowbinding.material.fixtures.MaterialFragment2 import reactivecircus.flowbinding.material.test.R import reactivecircus.flowbinding.testing.FlowRecorder import reactivecircus.flowbinding.testing.launchTest import reactivecircus.flowbinding.testing.recordWith @LargeTest class NavigationBarViewItemSelectedFlowTest { @Test fun navigationBarViewItemSelections_manual() { launchTest<MaterialFragment2> { val recorder = FlowRecorder<MenuItem>(testScope) val bottomNavigationView = getViewById<NavigationBarView>(R.id.bottomNavigationView) bottomNavigationView.itemSelections().recordWith(recorder) assertThat(recorder.takeValue().itemId) .isEqualTo(R.id.dest1) recorder.assertNoMoreValues() selectNavigationBarItem( R.id.bottomNavigationView, bottomNavigationView.menu.getItem(1).title.toString() ) assertThat(recorder.takeValue().itemId) .isEqualTo(R.id.dest2) recorder.assertNoMoreValues() cancelTestScope() selectNavigationBarItem( R.id.bottomNavigationView, bottomNavigationView.menu.getItem(2).title.toString() ) recorder.assertNoMoreValues() } } @Test fun navigationBarViewItemSelections_programmatic() { launchTest<MaterialFragment2> { val recorder = FlowRecorder<MenuItem>(testScope) val bottomNavigationView = getViewById<NavigationBarView>(R.id.bottomNavigationView) bottomNavigationView.itemSelections().recordWith(recorder) assertThat(recorder.takeValue().itemId) .isEqualTo(R.id.dest1) recorder.assertNoMoreValues() runOnUiThread { bottomNavigationView.selectedItemId = R.id.dest2 } assertThat(recorder.takeValue().itemId) .isEqualTo(R.id.dest2) recorder.assertNoMoreValues() cancelTestScope() runOnUiThread { bottomNavigationView.selectedItemId = R.id.dest3 } recorder.assertNoMoreValues() } } @Test fun navigationBarViewItemSelections_noMenu() { launchTest<MaterialFragment2> { val recorder = FlowRecorder<MenuItem>(testScope) val bottomNavigationView = getViewById<NavigationBarView>(R.id.bottomNavigationView).apply { runOnUiThread { menu.clear() } } bottomNavigationView.itemSelections().recordWith(recorder) recorder.assertNoMoreValues() cancelTestScope() } } }
apache-2.0
0498331627e54135a4e945397523dfe7
35.529412
104
0.68438
5.625
false
true
false
false
facebook/litho
litho-widget-kotlin/src/main/kotlin/com/facebook/litho/widget/collection/CollectionGroupSectionSpec.kt
1
2984
/* * 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.ComponentContext import com.facebook.litho.annotations.Prop import com.facebook.litho.sections.ChangesInfo import com.facebook.litho.sections.Children import com.facebook.litho.sections.SectionContext import com.facebook.litho.sections.annotations.GroupSectionSpec import com.facebook.litho.sections.annotations.OnCreateChildren import com.facebook.litho.sections.annotations.OnDataBound import com.facebook.litho.sections.annotations.OnDataRendered import com.facebook.litho.sections.annotations.OnRefresh import com.facebook.litho.sections.annotations.OnViewportChanged @GroupSectionSpec object CollectionGroupSectionSpec { @JvmStatic @OnCreateChildren fun onCreateChildren(c: SectionContext?, @Prop childrenBuilder: Children.Builder): Children = childrenBuilder.build() @JvmStatic @OnDataBound fun onDataBound( c: SectionContext, @Prop(optional = true) onDataBound: ((ComponentContext) -> Unit)? ) { onDataBound?.invoke(c) } @JvmStatic @OnViewportChanged fun onViewportChanged( c: SectionContext, firstVisibleIndex: Int, lastVisibleIndex: Int, totalCount: Int, firstFullyVisibleIndex: Int, lastFullyVisibleIndex: Int, @Prop(optional = true) onViewportChanged: ((ComponentContext, Int, Int, Int, Int, Int) -> Unit)? ) { onViewportChanged?.invoke( c, firstVisibleIndex, lastVisibleIndex, totalCount, firstFullyVisibleIndex, lastFullyVisibleIndex) } @JvmStatic @OnRefresh fun onRefresh(c: SectionContext, @Prop(optional = true) onPullToRefresh: (() -> Unit)?) { onPullToRefresh?.invoke() } @JvmStatic @OnDataRendered fun onDataRendered( c: SectionContext, isDataChanged: Boolean, isMounted: Boolean, monoTimestampMs: Long, firstVisibleIndex: Int, lastVisibleIndex: Int, changesInfo: ChangesInfo, globalOffset: Int, @Prop(optional = true) onDataRendered: ((ComponentContext, Boolean, Boolean, Long, Int, Int, ChangesInfo, Int) -> Unit)? ) { onDataRendered?.invoke( c, isDataChanged, isMounted, monoTimestampMs, firstVisibleIndex, lastVisibleIndex, changesInfo, globalOffset) } }
apache-2.0
1bf87f25ed1e661fd06208d90a43abc1
28.84
95
0.714812
4.281205
false
false
false
false
wasabeef/recyclerview-animators
animators/src/main/java/jp/wasabeef/recyclerview/animators/FlipInTopXAnimator.kt
1
1618
package jp.wasabeef.recyclerview.animators import android.view.animation.Interpolator import androidx.recyclerview.widget.RecyclerView /** * Copyright (C) 2021 Daichi Furiya / Wasabeef * * 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. */ open class FlipInTopXAnimator : BaseItemAnimator { constructor() constructor(interpolator: Interpolator) { this.interpolator = interpolator } override fun animateRemoveImpl(holder: RecyclerView.ViewHolder) { holder.itemView.animate().apply { rotationX(90f) duration = removeDuration interpolator = interpolator setListener(DefaultRemoveAnimatorListener(holder)) startDelay = getRemoveDelay(holder) }.start() } override fun preAnimateAddImpl(holder: RecyclerView.ViewHolder) { holder.itemView.rotationX = 90f } override fun animateAddImpl(holder: RecyclerView.ViewHolder) { holder.itemView.animate().apply { rotationX(0f) duration = addDuration interpolator = interpolator setListener(DefaultAddAnimatorListener(holder)) startDelay = getAddDelay(holder) }.start() } }
apache-2.0
1daf35a5081c7b3a29b0bf0fe11e28ba
31.36
75
0.74042
4.494444
false
false
false
false
google/horologist
media-sample/src/main/java/com/google/android/horologist/mediasample/ui/app/UampWearApp.kt
1
11211
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.mediasample.ui.app import android.content.Intent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import androidx.wear.compose.material.ScalingLazyListState import androidx.wear.compose.material.Text import androidx.wear.compose.navigation.rememberSwipeDismissableNavHostState import com.google.accompanist.pager.rememberPagerState import com.google.android.horologist.compose.navscaffold.scalingLazyColumnComposable import com.google.android.horologist.media.ui.navigation.MediaNavController.navigateToCollection import com.google.android.horologist.media.ui.navigation.MediaNavController.navigateToCollections import com.google.android.horologist.media.ui.navigation.MediaNavController.navigateToLibrary import com.google.android.horologist.media.ui.navigation.MediaNavController.navigateToPlayer import com.google.android.horologist.media.ui.navigation.MediaNavController.navigateToSettings import com.google.android.horologist.media.ui.navigation.MediaNavController.navigateToVolume import com.google.android.horologist.media.ui.navigation.MediaPlayerScaffold import com.google.android.horologist.mediasample.ui.browse.UampBrowseScreen import com.google.android.horologist.mediasample.ui.browse.UampStreamingBrowseScreen import com.google.android.horologist.mediasample.ui.debug.AudioDebugScreen import com.google.android.horologist.mediasample.ui.debug.MediaInfoTimeText import com.google.android.horologist.mediasample.ui.debug.MediaInfoTimeTextViewModel import com.google.android.horologist.mediasample.ui.debug.SamplesScreen import com.google.android.horologist.mediasample.ui.entity.UampEntityScreen import com.google.android.horologist.mediasample.ui.entity.UampEntityScreenViewModel import com.google.android.horologist.mediasample.ui.entity.UampStreamingPlaylistScreen import com.google.android.horologist.mediasample.ui.entity.UampStreamingPlaylistScreenViewModel import com.google.android.horologist.mediasample.ui.navigation.AudioDebug import com.google.android.horologist.mediasample.ui.navigation.DeveloperOptions import com.google.android.horologist.mediasample.ui.navigation.Samples import com.google.android.horologist.mediasample.ui.player.UampMediaPlayerScreen import com.google.android.horologist.mediasample.ui.playlists.UampPlaylistsScreen import com.google.android.horologist.mediasample.ui.playlists.UampPlaylistsScreenViewModel import com.google.android.horologist.mediasample.ui.settings.DeveloperOptionsScreen import com.google.android.horologist.mediasample.ui.settings.UampSettingsScreen @Composable fun UampWearApp( navController: NavHostController, intent: Intent ) { val appViewModel: MediaPlayerAppViewModel = hiltViewModel() val volumeViewModel: VolumeViewModel = hiltViewModel() val mediaInfoTimeTextViewModel: MediaInfoTimeTextViewModel = hiltViewModel() val pagerState = rememberPagerState(initialPage = 0) val navHostState = rememberSwipeDismissableNavHostState() val appState by appViewModel.appState.collectAsStateWithLifecycle() val timeText: @Composable (Modifier) -> Unit = { modifier -> MediaInfoTimeText( modifier = modifier, mediaInfoTimeTextViewModel = mediaInfoTimeTextViewModel ) } UampTheme { MediaPlayerScaffold( playerScreen = { UampMediaPlayerScreen( modifier = Modifier.fillMaxSize(), mediaPlayerScreenViewModel = hiltViewModel(), volumeViewModel = volumeViewModel, onVolumeClick = { navController.navigateToVolume() } ) }, libraryScreen = { scalingLazyListState -> if (appState.streamingMode == true) { UampStreamingBrowseScreen( onPlaylistsClick = { navController.navigateToCollections() }, onSettingsClick = { navController.navigateToSettings() }, scalingLazyListState = scalingLazyListState ) } else { UampBrowseScreen( uampBrowseScreenViewModel = hiltViewModel(), onDownloadItemClick = { navController.navigateToCollection( it.playlistUiModel.id, it.playlistUiModel.title ) }, onPlaylistsClick = { navController.navigateToCollections() }, onSettingsClick = { navController.navigateToSettings() }, scalingLazyListState = scalingLazyListState ) } }, categoryEntityScreen = { _, name, scalingLazyListState -> if (appState.streamingMode == true) { val viewModel: UampStreamingPlaylistScreenViewModel = hiltViewModel() UampStreamingPlaylistScreen( playlistName = name, viewModel = viewModel, onDownloadItemClick = { navController.navigateToPlayer() }, onShuffleClick = { navController.navigateToPlayer() }, onPlayClick = { navController.navigateToPlayer() }, scalingLazyListState = scalingLazyListState ) } else { val uampEntityScreenViewModel: UampEntityScreenViewModel = hiltViewModel() UampEntityScreen( playlistName = name, uampEntityScreenViewModel = uampEntityScreenViewModel, onDownloadItemClick = { navController.navigateToPlayer() }, onShuffleClick = { navController.navigateToPlayer() }, onPlayClick = { navController.navigateToPlayer() }, onErrorDialogCancelClick = { navController.popBackStack() }, scalingLazyListState = scalingLazyListState ) } }, mediaEntityScreen = { _ -> Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text("Media XXX") } }, playlistsScreen = { scalingLazyListState -> val uampPlaylistsScreenViewModel: UampPlaylistsScreenViewModel = hiltViewModel() UampPlaylistsScreen( uampPlaylistsScreenViewModel = uampPlaylistsScreenViewModel, onPlaylistItemClick = { playlistUiModel -> navController.navigateToCollection( playlistUiModel.id, playlistUiModel.title ) }, onErrorDialogCancelClick = { navController.popBackStack() }, scalingLazyListState = scalingLazyListState ) }, settingsScreen = { state -> UampSettingsScreen( state = state, settingsScreenViewModel = hiltViewModel(), navController = navController ) }, navHostState = navHostState, pagerState = pagerState, snackbarViewModel = hiltViewModel<SnackbarViewModel>(), volumeViewModel = hiltViewModel<VolumeViewModel>(), timeText = timeText, deepLinkPrefix = appViewModel.deepLinkPrefix, navController = navController, additionalNavRoutes = { scalingLazyColumnComposable( route = AudioDebug.navRoute, arguments = AudioDebug.arguments, deepLinks = AudioDebug.deepLinks(appViewModel.deepLinkPrefix), scrollStateBuilder = { ScalingLazyListState() } ) { AudioDebugScreen( state = it.scrollableState, audioDebugScreenViewModel = hiltViewModel() ) } scalingLazyColumnComposable( route = Samples.navRoute, arguments = Samples.arguments, deepLinks = Samples.deepLinks(appViewModel.deepLinkPrefix), scrollStateBuilder = { ScalingLazyListState() } ) { SamplesScreen( state = it.scrollableState, samplesScreenViewModel = hiltViewModel(), navController = navController ) } scalingLazyColumnComposable( route = DeveloperOptions.navRoute, arguments = DeveloperOptions.arguments, deepLinks = DeveloperOptions.deepLinks(appViewModel.deepLinkPrefix), scrollStateBuilder = { ScalingLazyListState() } ) { DeveloperOptionsScreen( state = it.scrollableState, developerOptionsScreenViewModel = hiltViewModel(), navController = navController ) } } ) } LaunchedEffect(Unit) { val collectionId = intent.getAndRemoveKey(MediaActivity.CollectionKey) val mediaId = intent.getAndRemoveKey(MediaActivity.MediaIdKey) if (collectionId != null) { appViewModel.playItems(mediaId, collectionId) } else { appViewModel.startupSetup(navigateToLibrary = { navController.navigateToLibrary() }) } } } private fun Intent.getAndRemoveKey(key: String): String? = getStringExtra(key).also { removeExtra(key) }
apache-2.0
4b70a5eea29628ac1ceefec954303468
45.7125
97
0.626171
6.004821
false
false
false
false
xfournet/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/JavaAbstractUElement.kt
1
5129
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.* import org.jetbrains.uast.* import org.jetbrains.uast.java.expressions.JavaUExpressionList import org.jetbrains.uast.java.internal.JavaUElementWithComments import org.jetbrains.uast.java.kinds.JavaSpecialExpressionKinds abstract class JavaAbstractUElement(givenParent: UElement?) : JavaUElementWithComments, JvmDeclarationUElement { @Suppress("unused") // Used in Kotlin 1.2, to be removed in 2018.1 @Deprecated("use JavaAbstractUElement(givenParent)", ReplaceWith("JavaAbstractUElement(givenParent)")) constructor() : this(null) override fun equals(other: Any?): Boolean { if (other !is UElement || other.javaClass != this.javaClass) return false return if (this.psi != null) this.psi == other.psi else this === other } override fun hashCode() = psi?.hashCode() ?: System.identityHashCode(this) override fun asSourceString(): String { return this.psi?.text ?: super<JavaUElementWithComments>.asSourceString() } override fun toString() = asRenderString() override val uastParent: UElement? by lz { givenParent ?: convertParent() } protected open fun convertParent(): UElement? = getPsiParentForLazyConversion() ?.let { JavaConverter.unwrapElements(it).toUElement() } ?.let { unwrapSwitch(it) } ?.also { if (it === this) throw IllegalStateException("lazy parent loop for $this") if (it.psi != null && it.psi === this.psi) throw IllegalStateException("lazy parent loop: psi ${this.psi}(${this.psi?.javaClass}) for $this of ${this.javaClass}") } protected open fun getPsiParentForLazyConversion() = this.psi?.parent //explicitly overridden in abstract class to be binary compatible with Kotlin override val comments: List<UComment> get() = super<JavaUElementWithComments>.comments override val sourcePsi: PsiElement? get() = super<JavaUElementWithComments>.sourcePsi override val javaPsi: PsiElement? get() = super<JavaUElementWithComments>.javaPsi } private fun JavaAbstractUElement.unwrapSwitch(uParent: UElement): UElement { when (uParent) { is JavaUCodeBlockExpression -> { val codeBlockParent = uParent.uastParent if (codeBlockParent is JavaUExpressionList && codeBlockParent.kind == JavaSpecialExpressionKinds.SWITCH) { if (branchHasElement(psi, codeBlockParent.psi) { it is PsiSwitchLabelStatement }) { return codeBlockParent } val uSwitchExpression = codeBlockParent.uastParent as? JavaUSwitchExpression ?: return uParent val psiElement = psi ?: return uParent return findUSwitchClauseBody(uSwitchExpression, psiElement) ?: return codeBlockParent } if (codeBlockParent is JavaUSwitchExpression) { return unwrapSwitch(codeBlockParent) } return uParent } is USwitchExpression -> { val parentPsi = uParent.psi as PsiSwitchStatement return if (this === uParent.body || branchHasElement(psi, parentPsi) { it === parentPsi.expression }) uParent else uParent.body } else -> return uParent } } private inline fun branchHasElement(child: PsiElement?, parent: PsiElement?, predicate: (PsiElement) -> Boolean): Boolean { var current: PsiElement? = child; while (current != null && current != parent) { if (predicate(current)) return true current = current.parent } return false } abstract class JavaAbstractUExpression(givenParent: UElement?) : JavaAbstractUElement(givenParent), UExpression { @Suppress("unused") // Used in Kotlin 1.2, to be removed in 2018.1 @Deprecated("use JavaAbstractUExpression(givenParent)", ReplaceWith("JavaAbstractUExpression(givenParent)")) constructor() : this(null) override fun evaluate(): Any? { val project = psi?.project ?: return null return JavaPsiFacade.getInstance(project).constantEvaluationHelper.computeConstantExpression(psi) } override val annotations: List<UAnnotation> get() = emptyList() override fun getExpressionType(): PsiType? { val expression = psi as? PsiExpression ?: return null return expression.type } override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let { when (it) { is PsiResourceExpression -> it.parent else -> it } } override fun convertParent(): UElement? = super.convertParent().let { uParent -> when (uParent) { is UAnonymousClass -> uParent.uastParent else -> uParent } } }
apache-2.0
cb5ce9271a3aefc92f33b93da5469296
35.899281
129
0.718074
4.838679
false
false
false
false
petrbalat/jlib
src/main/java/cz/softdeluxe/jlib/hibernate/IntArrayUserType.kt
1
1582
package cz.softdeluxe.jlib.hibernate import org.hibernate.engine.spi.SessionImplementor import org.hibernate.usertype.UserType import java.io.Serializable import java.sql.PreparedStatement import java.sql.ResultSet const val INT_ARRAY_TYPE = "cz.softdeluxe.jlib.hibernate.IntArrayUserType" /** * podpora ukládní pole integerů pro hibernate * * @author balat */ @Suppress("unused") class IntArrayUserType : UserType { override fun hashCode(x: Any?): Int = x?.hashCode() ?: 0 override fun deepCopy(value: Any?): Any? = value override fun replace(original: Any?, target: Any?, owner: Any?): Any? = original override fun equals(x: Any?, y: Any?): Boolean = x == y override fun returnedClass(): Class<*> = IntArray::class.java override fun assemble(cached: Serializable?, owner: Any?): Any? = cached override fun disassemble(value: Any?): Serializable? = value as Serializable? override fun nullSafeSet(statement: PreparedStatement?, value: Any?, index: Int, session: SessionImplementor?) { val connection = statement?.connection val integers = value as Array<Int> val array = connection?.createArrayOf("integer", integers) statement?.setArray(index, array) } override fun nullSafeGet(rs: ResultSet, names: Array<out String>, session: SessionImplementor?, owner: Any?): Array<Int> { val array = rs.getArray(names[0]) return array?.array as Array<Int> } override fun isMutable(): Boolean = false override fun sqlTypes(): IntArray = intArrayOf(java.sql.Types.ARRAY) }
apache-2.0
52b43e723507d2acef4862512c9cc3ec
31.244898
126
0.704243
4.059126
false
false
false
false
mmorihiro/larger-circle
core/src/mmorihiro/matchland/controller/appwarp/ClientHolder.kt
2
1491
package mmorihiro.matchland.controller.appwarp import com.shephertz.app42.gaming.multiplayer.client.WarpClient object ClientHolder { init { WarpClient.initialize( "37e334f70df6e1984fc390d2a52939f75f8e546584c20ef3a31b87efec76d11f", "ef2760dcfdbbff89c6d081934e985c26cc05e16dc026146b972ca1a1ad3fc9fc") } val client = WarpClient.getInstance()!! private lateinit var connectionListener: ConnectionListener private lateinit var roomListener: RoomListener private lateinit var zoneListener: ZoneListener private lateinit var notificationListener: NotificationListener private var isAdded = false fun addListeners(controller: WarpController) { if (isAdded) { connectionListener.controller = controller roomListener.controller = controller zoneListener.controller = controller notificationListener.controller = controller } else { connectionListener = ConnectionListener(controller) roomListener = RoomListener(controller) zoneListener = ZoneListener(controller) notificationListener = NotificationListener(controller) client.addConnectionRequestListener(connectionListener) client.addRoomRequestListener(roomListener) client.addZoneRequestListener(zoneListener) client.addNotificationListener(notificationListener) isAdded = true } } }
apache-2.0
b1142b9cf4d367c6d5f9a9b8c501ac1c
39.324324
83
0.714956
4.872549
false
false
false
false
ntemplon/legends-of-omterra
core/src/com/jupiter/europa/entity/Party.kt
1
6029
/* * The MIT License * * Copyright 2015 Nathan Templon. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.jupiter.europa.entity import com.badlogic.gdx.graphics.g2d.Sprite import com.badlogic.gdx.utils.Json import com.badlogic.gdx.utils.Json.Serializable import com.badlogic.gdx.utils.JsonValue import com.jupiter.europa.EuropaGame import com.jupiter.europa.entity.component.* import com.jupiter.europa.entity.effects.BasicAbilitiesEffect import com.jupiter.europa.entity.messaging.RequestEffectAddMessage import com.jupiter.europa.entity.stats.AttributeSet import com.jupiter.europa.entity.stats.SkillSet import com.jupiter.europa.entity.stats.SkillSet.Skills import com.jupiter.europa.entity.stats.characterclass.CharacterClass import com.jupiter.europa.entity.stats.race.Race import com.jupiter.europa.geometry.Size import com.jupiter.europa.io.FileLocations import java.awt.Point import java.util.ArrayList import java.util.Collections import java.util.HashMap import java.util.HashSet /** * @author Nathan Templon */ public class Party : Serializable { // Fields private val player1: EuropaEntity? = null private val activePartyMembers = ArrayList<EuropaEntity>() private var partyMembers: MutableMap<String, EuropaEntity> = hashMapOf() // Properties public fun getActivePartyMembers(): Array<EuropaEntity> { return this.activePartyMembers.toArray<EuropaEntity>(arrayOfNulls<EuropaEntity>(this.activePartyMembers.size())) } // Public Methods public fun addPlayer(entity: EuropaEntity) { this.partyMembers.put(Mappers.name.get(entity).name, entity) } public fun selectPlayer(entity: EuropaEntity) { this.activePartyMembers.add(entity) } // Serializable (Json) implementation override fun write(json: Json) { json.writeValue(PARTY_MEMBERS_KEY, this.partyMembers, javaClass<HashMap<Any, Any>>()) json.writeArrayStart(ACTIVE_PARTY_MEMBERS_KEY) for (entity in this.getActivePartyMembers()) { json.writeValue(Mappers.name.get(entity).name) } json.writeArrayEnd() } override fun read(json: Json, jsonData: JsonValue) { if (jsonData.has(PARTY_MEMBERS_KEY)) { this.partyMembers = json.fromJson(javaClass<HashMap<String, EuropaEntity>>(), jsonData.get(PARTY_MEMBERS_KEY).prettyPrint(EuropaGame.PRINT_SETTINGS)) } val members = jsonData.get(ACTIVE_PARTY_MEMBERS_KEY) for (i in 0..members.size - 1) { this.activePartyMembers.add(this.partyMembers.get(members.getString(i))) } } companion object { // Constants public val PARTY_MEMBERS_KEY: String = "party-members" public val ACTIVE_PARTY_MEMBERS_KEY: String = "active-party-members" // Static Methods public fun createPlayer(name: String, charClass: Class<out CharacterClass>, race: Race, attributes: AttributeSet): EuropaEntity { // NOTE: Order of component creation is important! val entity = EuropaEntity() entity.add(NameComponent(name)) // Effects val effectsComponent = EffectsComponent() entity.add(effectsComponent) EuropaGame.game.messageSystem.publish(RequestEffectAddMessage(entity, BasicAbilitiesEffect())) entity.add(RaceComponent(race)) val classComponent = CharacterClassComponent(charClass, entity) classComponent.characterClass.featPool.increaseCapacity(race.firstLevelFeats) // First level bonus feats val textureSetName = race.textureString + "-" + classComponent.characterClass.textureSetName entity.add(MovementResourceComponent(FileLocations.CHARACTER_SPRITES, textureSetName)) entity.add(PositionComponent(null, Point(19, 25), 0)) entity.add(SizeComponent(Size(1, 1))) entity.add(CollisionComponent(Mappers.position.get(entity).tilePosition, Mappers.size.get(entity).size)) entity.add(WalkComponent()) entity.add(RenderComponent(Sprite(Mappers.moveTexture.get(entity).frontStandTexture))) entity.add(AttributesComponent(attributes).applyRace(race)) val res = ResourceComponent() entity.add(res) // Skills val classSkills = HashSet<Skills>() classSkills.addAll(classComponent.characterClass.classSkills) classSkills.addAll(race.classSkills) val sorted = ArrayList(classSkills) Collections.sort(sorted) entity.add(SkillsComponent(SkillSet(), sorted)) // Abilities val abilities = AbilityComponent() entity.add(abilities) entity.add(classComponent) entity.initializeComponents() // Final Initialization classComponent.characterClass.onFirstCreation() res.onCreateNew() return entity } } }
mit
0ec5a07dbef67c206a669c62b8404964
36.68125
161
0.70476
4.469236
false
false
false
false
square/duktape-android
samples/world-clock/presenters/src/jsMain/kotlin/app/cash/zipline/samples/worldclock/TimeFormatter.kt
1
1756
/* * Copyright (C) 2022 Block, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline.samples.worldclock import kotlin.js.Date class TimeFormatter { fun formatLocalTime( now: dynamic = Date(), millis: Boolean = false, ): String { val originalHours = now.getHours() now.setHours(originalHours - 4) // This sample doesn't implement DST. val nyc = formatDate(now, millis) return """ |Time in NYC |$nyc """.trimMargin() } fun formatWorldTime( now: dynamic = Date(), millis: Boolean = false, ): String { val originalHours = now.getHours() now.setHours(originalHours + 2) val barcelona = formatDate(now, millis) now.setHours(originalHours - 4) val nyc = formatDate(now, millis) now.setHours(originalHours - 7) val sf = formatDate(now, millis) return """ |Barcelona |$barcelona | |NYC |$nyc | |SF |$sf """.trimMargin() } private fun formatDate( date: dynamic, millis: Boolean = false, ): String { val limit = when { millis -> 23 else -> 19 } val string = date.toISOString() as String return string.slice(11 until limit) } }
apache-2.0
14c5cde21f1113e7dede1aec9fdc0771
22.72973
75
0.640661
3.87638
false
false
false
false
openhab/openhab.android
mobile/src/main/java/org/openhab/habdroid/util/ItemClient.kt
1
3822
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.util import android.util.Log import java.io.IOException import java.io.StringReader import javax.xml.parsers.DocumentBuilderFactory import javax.xml.parsers.ParserConfigurationException import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import org.openhab.habdroid.core.connection.Connection import org.openhab.habdroid.model.Item import org.openhab.habdroid.model.toItem import org.xml.sax.InputSource import org.xml.sax.SAXException object ItemClient { private val TAG = ItemClient::class.java.simpleName suspend fun loadItems(connection: Connection): List<Item>? { val response = connection.httpClient.get("rest/items") val contentType = response.response.contentType() val content = response.asText().response if (contentType?.type == "application" && contentType.subtype == "json") { // JSON return try { JSONArray(content).map { it.toItem() } } catch (e: JSONException) { Log.e(TAG, "Failed parsing JSON result for items", e) null } } else { // XML return try { val dbf = DocumentBuilderFactory.newInstance() val builder = dbf.newDocumentBuilder() val document = builder.parse(InputSource(StringReader(content))) val nodes = document.childNodes val items = ArrayList<Item>(nodes.length) for (i in 0 until nodes.length) { nodes.item(i).toItem()?.let { items.add(it) } } items } catch (e: ParserConfigurationException) { Log.e(TAG, "Failed parsing XML result for items", e) null } catch (e: SAXException) { Log.e(TAG, "Failed parsing XML result for items", e) null } catch (e: IOException) { Log.e(TAG, "Failed parsing XML result for items", e) null } } } suspend fun loadItem(connection: Connection, itemName: String): Item? { val response = connection.httpClient.get("rest/items/$itemName") val contentType = response.response.contentType() val content = response.asText().response if (contentType?.type == "application" && contentType.subtype == "json") { // JSON return try { JSONObject(content).toItem() } catch (e: JSONException) { Log.e(TAG, "Failed parsing JSON result for item $itemName", e) null } } else { // XML return try { val dbf = DocumentBuilderFactory.newInstance() val builder = dbf.newDocumentBuilder() val document = builder.parse(InputSource(StringReader(content))) document.toItem() } catch (e: ParserConfigurationException) { Log.e(TAG, "Failed parsing XML result for item $itemName", e) null } catch (e: SAXException) { Log.e(TAG, "Failed parsing XML result for item $itemName", e) null } catch (e: IOException) { Log.e(TAG, "Failed parsing XML result for item $itemName", e) null } } } }
epl-1.0
b172e8e4d7a12dc97113d50ff06dfa1e
36.106796
82
0.583987
4.718519
false
false
false
false
carlphilipp/stock-tracker-android
src/fr/cph/stock/android/web/Md5.kt
1
1311
/** * Copyright 2017 Carl-Philipp Harmant * * * 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 fr.cph.stock.android.web import java.security.MessageDigest class Md5(private val password: String) { val hexInString: String get() { val md = MessageDigest.getInstance("MD5") md.update(password.toByteArray()) val hexString = StringBuilder() val byteData: ByteArray = md!!.digest() byteData.forEach { byte -> run { val hex = Integer.toHexString(0xff and byte.toInt()) if (hex.length == 1) hexString.append('0') hexString.append(hex) } } return hexString.toString() } }
apache-2.0
977cba8d5a1890aad59796e755d499e9
30.214286
75
0.61251
4.505155
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/ui/FixedTextView.kt
1
12549
/* * Copyright (c) 2020 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * This file is part of FairEmail. * * FairEmail 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. * * FairEmail 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 FairEmail. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2018-2020 by Marcel Bokhorst (M66B) * * Source: https://github.com/M66B/FairEmail/blob/75fe7d0ec92a9874a98c22b61eeb8e6a8906a9ea/app/src/main/java/eu/faircode/email/FixedTextView.java * */ package com.ichi2.ui import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.os.Build import android.util.AttributeSet import android.view.KeyEvent import android.view.MotionEvent import androidx.appcompat.widget.AppCompatTextView import timber.log.Timber class FixedTextView : AppCompatTextView { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { try { super.onMeasure(widthMeasureSpec, heightMeasureSpec) } catch (ex: Throwable) { Timber.w(ex) /* java.lang.ArrayIndexOutOfBoundsException: length=...; index=... at android.text.TextLine.measure(TextLine.java:316) at android.text.TextLine.metrics(TextLine.java:271) at android.text.Layout.measurePara(Layout.java:2056) at android.text.Layout.getDesiredWidth(Layout.java:164) at android.widget.TextView.onMeasure(TextView.java:8291) at androidx.appcompat.widget.AppCompatTextView.onMeasure(SourceFile:554) at android.view.View.measure(View.java:22360) */ setMeasuredDimension(0, 0) } } override fun onPreDraw(): Boolean { return try { super.onPreDraw() } catch (ex: Throwable) { Timber.w(ex) /* java.lang.ArrayIndexOutOfBoundsException: length=54; index=54 at android.text.TextLine.measure(TextLine.java:316) at android.text.TextLine.metrics(TextLine.java:271) at android.text.Layout.getLineExtent(Layout.java:1374) at android.text.Layout.getLineStartPos(Layout.java:700) at android.text.Layout.getHorizontal(Layout.java:1175) at android.text.Layout.getHorizontal(Layout.java:1144) at android.text.Layout.getPrimaryHorizontal(Layout.java:1115) at android.widget.TextView.bringPointIntoView(TextView.java:8944) at android.widget.TextView.onPreDraw(TextView.java:6475) */ true } } override fun onDraw(canvas: Canvas) { try { super.onDraw(canvas) } catch (ex: Throwable) { Timber.w(ex) /* java.lang.ArrayIndexOutOfBoundsException: length=74; index=74 at android.text.TextLine.draw(TextLine.java:241) at android.text.Layout.drawText(Layout.java:545) at android.text.Layout.draw(Layout.java:289) at android.widget.TextView.onDraw(TextView.java:6972) at android.view.View.draw(View.java:19380) */ } } override fun dispatchTouchEvent(event: MotionEvent): Boolean { // https://issuetracker.google.com/issues/37068143 if (event.actionMasked == MotionEvent.ACTION_DOWN && Build.VERSION.RELEASE == "6.0" && hasSelection()) { // Remove selection val text = text setText(null) setText(text) } return super.dispatchTouchEvent(event) } override fun onTouchEvent(event: MotionEvent): Boolean { return try { super.onTouchEvent(event) } catch (ex: Throwable) { Timber.w(ex) false /* java.lang.IllegalArgumentException at com.android.internal.util.Preconditions.checkArgument(Preconditions.java:33) at android.widget.SelectionActionModeHelper$TextClassificationHelper.init(SelectionActionModeHelper.java:640) at android.widget.SelectionActionModeHelper.resetTextClassificationHelper(SelectionActionModeHelper.java:203) at android.widget.SelectionActionModeHelper.invalidateActionModeAsync(SelectionActionModeHelper.java:104) at android.widget.Editor.invalidateActionModeAsync(Editor.java:2028) at android.widget.Editor.showFloatingToolbar(Editor.java:1419) at android.widget.Editor.updateFloatingToolbarVisibility(Editor.java:1397) at android.widget.Editor.onTouchEvent(Editor.java:1367) at android.widget.TextView.onTouchEvent(TextView.java:9701) */ } } override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) { try { super.onFocusChanged(focused, direction, previouslyFocusedRect) } catch (ex: Throwable) { /* java.lang.ClassCastException: android.text.SpannedString cannot be cast to android.text.Spannable at android.widget.Editor.onFocusChanged(Editor.java:1058) at android.widget.TextView.onFocusChanged(TextView.java:9262) at android.view.View.handleFocusGainInternal(View.java:5388) at android.view.View.requestFocusNoSearch(View.java:8131) at android.view.View.requestFocus(View.java:8110) at android.view.View.requestFocus(View.java:8077) at android.view.View.requestFocus(View.java:8056) at android.view.View.onTouchEvent(View.java:10359) at android.widget.TextView.onTouchEvent(TextView.java:9580) at android.view.View.dispatchTouchEvent(View.java:8981) */ Timber.w(ex) } } override fun performLongClick(): Boolean { return try { super.performLongClick() } catch (ex: Throwable) { /* java.lang.IllegalStateException: Drag shadow dimensions must be positive at android.view.View.startDragAndDrop(View.java:27316) at android.widget.Editor.startDragAndDrop(Editor.java:1340) at android.widget.Editor.performLongClick(Editor.java:1374) at android.widget.TextView.performLongClick(TextView.java:13544) at android.view.View.performLongClick(View.java:7928) at android.view.View$CheckForLongPress.run(View.java:29321) */ /* java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.Editor$SelectionModifierCursorController.getMinTouchOffset()' on a null object reference at android.widget.Editor.touchPositionIsInSelection(Unknown:36) at android.widget.Editor.performLongClick(Unknown:72) at android.widget.TextView.performLongClick(Unknown:24) */ Timber.w(ex) false } } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { return try { super.onKeyDown(keyCode, event) } catch (ex: Throwable) { /* java.lang.IllegalArgumentException at com.android.internal.util.Preconditions.checkArgument(Preconditions.java:33) at android.widget.SelectionActionModeHelper$TextClassificationHelper.init(SelectionActionModeHelper.java:641) at android.widget.SelectionActionModeHelper.resetTextClassificationHelper(SelectionActionModeHelper.java:204) at android.widget.SelectionActionModeHelper.startActionModeAsync(SelectionActionModeHelper.java:88) at android.widget.Editor.startSelectionActionModeAsync(Editor.java:2021) at android.widget.Editor.refreshTextActionMode(Editor.java:1966) at android.widget.TextView.spanChange(TextView.java:9525) at android.widget.TextView$ChangeWatcher.onSpanChanged(TextView.java:11973) at android.text.SpannableStringBuilder.sendSpanChanged(SpannableStringBuilder.java:1292) at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:748) at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:672) at android.text.Selection.extendSelection(Selection.java:102) at android.text.Selection.extendLeft(Selection.java:324) at android.text.method.ArrowKeyMovementMethod.left(ArrowKeyMovementMethod.java:72) at android.text.method.BaseMovementMethod.handleMovementKey(BaseMovementMethod.java:165) at android.text.method.ArrowKeyMovementMethod.handleMovementKey(ArrowKeyMovementMethod.java:65) at android.text.method.BaseMovementMethod.onKeyDown(BaseMovementMethod.java:42) at android.widget.TextView.doKeyDown(TextView.java:7367) at android.widget.TextView.onKeyDown(TextView.java:7117) at android.view.KeyEvent.dispatch(KeyEvent.java:2707) */ Timber.w(ex) false } } override fun setText(text: CharSequence?, type: BufferType) { try { super.setText(text, type) } catch (ex: Throwable) { Timber.w(ex) /* java.lang.IndexOutOfBoundsException: at android.text.PackedIntVector.getValue (PackedIntVector.java:71) at android.text.DynamicLayout.getLineTop (DynamicLayout.java:602) at android.text.Layout.getLineBottom (Layout.java:1260) at android.widget.TextView.invalidateRegion (TextView.java:5379) at android.widget.TextView.invalidateCursor (TextView.java:5348) at android.widget.TextView.spanChange (TextView.java:8351) at android.widget.TextView$ChangeWatcher.onSpanAdded (TextView.java:10550) at android.text.SpannableStringInternal.sendSpanAdded (SpannableStringInternal.java:315) at android.text.SpannableStringInternal.setSpan (SpannableStringInternal.java:138) at android.text.SpannableString.setSpan (SpannableString.java:46) at android.text.Selection.setSelection (Selection.java:76) at android.text.Selection.setSelection (Selection.java:87) at android.text.method.ArrowKeyMovementMethod.initialize (ArrowKeyMovementMethod.java:336) at android.widget.TextView.setText (TextView.java:4555) at android.widget.TextView.setText (TextView.java:4424) at android.widget.TextView.setText (TextView.java:4379) */ } } }
gpl-3.0
ecdb25fa13303422c9c55e248c2555e6
49.805668
189
0.654953
4.525424
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/AbstractCreateNoteFragment.kt
1
2306
package de.westnordost.streetcomplete.quests import android.content.res.Configuration import android.os.Bundle import com.google.android.material.bottomsheet.BottomSheetBehavior import android.view.View import android.widget.EditText import androidx.fragment.app.add import androidx.fragment.app.commit import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.ktx.popIn import de.westnordost.streetcomplete.ktx.popOut import de.westnordost.streetcomplete.quests.note_discussion.AttachPhotoFragment import de.westnordost.streetcomplete.util.TextChangedWatcher /** Abstract base class for a bottom sheet that lets the user create a note */ abstract class AbstractCreateNoteFragment : AbstractBottomSheetFragment() { protected abstract val noteInput: EditText protected abstract val okButton: View private val attachPhotoFragment: AttachPhotoFragment? get() = childFragmentManager.findFragmentById(R.id.attachPhotoFragment) as AttachPhotoFragment? private val noteText get() = noteInput.text?.toString().orEmpty().trim() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) { BottomSheetBehavior.from(bottomSheet).state = BottomSheetBehavior.STATE_EXPANDED } if (savedInstanceState == null) { childFragmentManager.commit { add<AttachPhotoFragment>(R.id.attachPhotoFragment) } } noteInput.addTextChangedListener(TextChangedWatcher { updateOkButtonEnablement() }) okButton.setOnClickListener { onClickOk() } updateOkButtonEnablement() } private fun onClickOk() { onComposedNote(noteText, attachPhotoFragment?.imagePaths.orEmpty()) } override fun onDiscard() { attachPhotoFragment?.deleteImages() } override fun isRejectingClose() = noteText.isNotEmpty() || attachPhotoFragment?.imagePaths?.isNotEmpty() == true private fun updateOkButtonEnablement() { if (noteText.isNotEmpty()) { okButton.popIn() } else { okButton.popOut() } } protected abstract fun onComposedNote(text: String, imagePaths: List<String>) }
gpl-3.0
369bb6ff368e505300134e2a1958c30b
34.476923
103
0.741544
5.057018
false
false
false
false
sksamuel/elasticsearch-river-neo4j
streamops-session/streamops-session-pulsar/src/main/kotlin/com/octaldata/session/pulsar/PulsarSession.kt
1
1493
package com.octaldata.session.pulsar import com.octaldata.domain.DeploymentConnectionConfig import com.octaldata.domain.DeploymentId import com.octaldata.domain.DeploymentName import com.octaldata.session.AclOps import com.octaldata.session.BookiesOps import com.octaldata.session.ConsumerOps import com.octaldata.session.DeploymentOps import com.octaldata.session.FunctionOps import com.octaldata.session.NamespaceOps import com.octaldata.session.NoopConsumerOps import com.octaldata.session.RecordOps import com.octaldata.session.Session import com.octaldata.session.SubscriptionOps import com.octaldata.session.TenantOps import com.octaldata.session.TopicOps class PulsarSession( private val id: DeploymentId, private val name: DeploymentName, private val config: DeploymentConnectionConfig.Pulsar ) : Session { override fun consumers(): ConsumerOps = NoopConsumerOps override fun deployment(): DeploymentOps = PulsarDeploymentOps(id, name, config) override fun records(): RecordOps = PulsarRecordOps(id, name, config) override fun topics(): TopicOps = PulsarTopicOps(config) override fun acl(): AclOps = TODO() override fun namespaces(): NamespaceOps = PulsarNamespaceOps(config) override fun tenants(): TenantOps = PulsarTenantOps(config) override fun functions(): FunctionOps = PulsarFunctionOps(config) override fun subscriptions(): SubscriptionOps = PulsarSubscriptionOps(config) override fun bookies(): BookiesOps = PulsarBookiesOps(config) }
apache-2.0
9ae453cbb4022ba1c3b62999a76ebc4f
41.685714
83
0.814468
4.217514
false
true
false
false
pdvrieze/ProcessManager
PE-common/src/commonMain/kotlin/nl/adaptivity/diagram/ItemCache.kt
1
8029
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.diagram /** * A cache implementation that allows drawing strategy related items to be stored. * This cache assumes that the strategy count is very low (1 or 2) and the item count * does not really change (and is low). * @author Paul de Vrieze */ class ItemCache { private var strategies = arrayOfNulls<DrawingStrategy<*, *, *>>(0) private var pens = arrayOf<Array<Pen<*>?>?>(arrayOfNulls(1)) private var paths = arrayOf<Array<DiagramPath<*>?>?>(arrayOfNulls(1)) private var pathLists = arrayOf<Array<List<*>?>?>(arrayOfNulls(1)) @Suppress("unused") fun <S : DrawingStrategy<S, PEN_T, PATH_T>, PEN_T : Pen<PEN_T>, PATH_T : DiagramPath<PATH_T>> setPen(strategy: S, index: Int, pen: PEN_T) { setPen(ensureStrategyIndex(strategy), index, pen) } private fun <PEN_T : Pen<PEN_T>> setPen(strategyIdx: Int, penIdx: Int, pen: PEN_T) { pens = pens.ensureArrayLength(strategyIdx + 1) val strategyPens = pens[strategyIdx].ensureArrayLength(penIdx + 1) strategyPens[penIdx] = pen pens[strategyIdx] = strategyPens } fun <S : DrawingStrategy<S, PEN_T, PATH_T>, PEN_T : Pen<PEN_T>, PATH_T : DiagramPath<PATH_T>> setPath(strategy: S, index: Int, path: PATH_T) { setPath(ensureStrategyIndex(strategy), index, path) } private fun <PATH_T : DiagramPath<PATH_T>> setPath(strategyIdx: Int, pathIdx: Int, path: PATH_T) { if (strategyIdx < 0) { setPath(strategies.size, pathIdx, path) } else { paths = paths.ensureArrayLength(strategyIdx + 1) val sPaths = paths[strategyIdx].ensureArrayLength(pathIdx + 1) sPaths[pathIdx] = path paths[strategyIdx] = sPaths } } @Suppress("unused") fun <S : DrawingStrategy<S, PEN_T, PATH_T>, PEN_T : Pen<PEN_T>, PATH_T : DiagramPath<PATH_T>> setPathList(strategy: S, index: Int, pathList: List<PATH_T>) { setPathList(ensureStrategyIndex(strategy), index, pathList) } private fun <PATH_T : DiagramPath<PATH_T>> setPathList(strategyIdx: Int, pathListIdx: Int, pathList: List<PATH_T>) { if (strategyIdx < 0) { setPathList(strategies.size, pathListIdx, pathList) } else { pathLists = pathLists.ensureArrayLength(strategyIdx + 1) val sPathLists = pathLists[strategyIdx].ensureArrayLength(pathListIdx + 1) pathLists[strategyIdx] = sPathLists sPathLists[pathListIdx] = pathList as List<*> } } private inline fun <reified V> Array<V?>?.ensureArrayLength(length: Int) = when { this == null -> arrayOfNulls(length) else -> this.ensureArrayLengthNotNull(length) } private fun <V> Array<V?>.ensureArrayLengthNotNull(length: Int): Array<V?> { return when { size < length -> this.copyOf(length) else -> this } } // // private static <V> V[][] ensureArraysLength(V[][] array, int length) { // if (array.length<=length) { // @SuppressWarnings("unchecked") // V[][] newArray = (V[][]) Array.newInstance(array.getClass(), length, 0); // System.arraycopy(array, 0, newArray, 0, array.length); // return newArray; // } // return array; // } private fun <S : DrawingStrategy<S, PEN_T, PATH_T>, PEN_T : Pen<PEN_T>, PATH_T : DiagramPath<PATH_T>> getStrategyIndex(strategy: S): Int { return strategies.indexOfFirst { it === strategy } } private fun <S : DrawingStrategy<S, PEN_T, PATH_T>, PEN_T : Pen<PEN_T>, PATH_T : DiagramPath<PATH_T>> ensureStrategyIndex(strategy: S): Int { var strategyIdx = getStrategyIndex(strategy) if (strategyIdx < 0) { strategyIdx = strategies.size val newStrategies = strategies.ensureArrayLengthNotNull(strategyIdx + 1) newStrategies[strategyIdx] = strategy strategies = newStrategies } return strategyIdx } fun <S : DrawingStrategy<S, PEN_T, PATH_T>, PEN_T : Pen<PEN_T>, PATH_T : DiagramPath<PATH_T>> getPen(strategy: S, index: Int, alternate: PEN_T.() -> Unit): PEN_T { val strategyIdx = getStrategyIndex(strategy) return getPen(strategyIdx, index) ?: strategy.newPen().apply { alternate(); setPen(strategyIdx, index, this) } } fun <S : DrawingStrategy<S, PEN_T, PATH_T>, PEN_T : Pen<PEN_T>, PATH_T : DiagramPath<PATH_T>> getPen(strategy: S, index: Int): PEN_T? { val strategyIdx = getStrategyIndex(strategy) return getPen(strategyIdx, index) } private fun <PEN_T : Pen<PEN_T>> getPen(strategyIdx: Int, penIdx: Int): PEN_T? { if (strategyIdx < 0 || strategyIdx >= pens.size || penIdx >= pens[strategyIdx]!!.size) { return null } @Suppress("UNCHECKED_CAST") return pens[strategyIdx]!![penIdx] as PEN_T? } fun <S : DrawingStrategy<S, PEN_T, PATH_T>, PEN_T : Pen<PEN_T>, PATH_T : DiagramPath<PATH_T>> getPath(strategy: S, index: Int, alternate: PATH_T.() -> Unit): PATH_T { val strategyIdx = getStrategyIndex(strategy) return getPath(strategy, index) ?: strategy.newPath().apply { alternate(); setPath(strategyIdx, index, this) } } fun <S : DrawingStrategy<S, PEN_T, PATH_T>, PEN_T : Pen<PEN_T>, PATH_T : DiagramPath<PATH_T>> getPath(strategy: S, index: Int): PATH_T? { val strategyIdx = getStrategyIndex(strategy) return getPath<PATH_T>(strategyIdx, index) } private fun <PATH_T : DiagramPath<PATH_T>> getPath(strategyIdx: Int, pathIdx: Int): PATH_T? { if (strategyIdx < 0 || strategyIdx >= paths.size || pathIdx >= paths[strategyIdx]!!.size) { return null } @Suppress("UNCHECKED_CAST") return paths[strategyIdx]!![pathIdx] as PATH_T? } fun <S : DrawingStrategy<S, PEN_T, PATH_T>, PEN_T : Pen<PEN_T>, PATH_T : DiagramPath<PATH_T>> getPathList(strategy: S, index: Int, alternate: (S) -> List<PATH_T>): List<PATH_T> { val strategyIdx = getStrategyIndex(strategy) return getPathList(strategyIdx, index) ?: alternate(strategy).apply { setPathList(strategyIdx, index, this) } } @Suppress("unused") fun <S : DrawingStrategy<S, PEN_T, PATH_T>, PEN_T : Pen<PEN_T>, PATH_T : DiagramPath<PATH_T>> getPathList(strategy: S, index: Int): List<PATH_T>? { val strategyIdx = getStrategyIndex(strategy) return getPathList(strategyIdx, index) } private fun <PATH_T : DiagramPath<PATH_T>> getPathList(strategyIdx: Int, pathListIdx: Int): List<PATH_T>? { if (strategyIdx < 0 || strategyIdx >= pathLists.size || pathListIdx >= pathLists[strategyIdx]!!.size) { return null } @Suppress("UNCHECKED_CAST") return pathLists[strategyIdx]!![pathListIdx] as List<PATH_T>? } /** * Clear all the paths at the given index. * @param index The index of the paths to clear */ fun clearPath(index: Int) { for (lists in paths) { if (lists != null && lists.size > index) { lists[index] = null } } } }
lgpl-3.0
613ea39383c4331430f732b19c704b13
36.694836
120
0.616017
3.71541
false
false
false
false
huhanpan/smart
app/src/main/java/com/etong/smart/Main/ActivityDetailAdapter.kt
1
10184
package com.etong.smart.Main import android.content.Intent import android.support.v4.app.ActivityOptionsCompat import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.PopupMenu import android.support.v7.widget.RecyclerView import android.text.Html import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import com.etong.smart.Data.Discuss import com.etong.smart.Main.LeftDrawer.ReviewImageActivity import com.etong.smart.Other.* import com.etong.smart.R import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.end_view.view.* import kotlinx.android.synthetic.main.item_activity_detail.view.* import kotlinx.android.synthetic.main.item_activity_detail_comment.view.* import kotlinx.android.synthetic.main.item_activity_detail_image.view.* import kotlinx.android.synthetic.main.item_activity_detail_sub_comment.view.* import java.util.* class ActivityDetailAdapter(val activityActivity: ActivityDetailActivity, val dataList: ArrayList<AdapterData>, val mListener: ChangeListener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { companion object { val Detail_type = 0 val Comment_type = 1 val Sub_comment_type = 2 val More_sub_comment_type = 3 val EndView_type = 4 val NullView_tyep = 5 } data class AdapterData(val type: Int, val Data: Any? = null) interface ChangeListener { fun reply(item: Discuss, position: Int) fun getMore(item: Discuss) fun getSubMore(item: Discuss, position: Int) fun removeDiscuss() } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { when (viewType) { Detail_type -> return DetailViewHolder(InflateView(parent, R.layout.item_activity_detail)) Comment_type -> return CommentViewHolder(InflateView(parent, R.layout.item_activity_detail_comment)) Sub_comment_type -> return SubCommentViewHolder(InflateView(parent, R.layout.item_activity_detail_sub_comment)) More_sub_comment_type -> return MoreViewHoler(InflateView(parent, R.layout.item_activity_detail_more_comment)) else -> return EndViewHolder(InflateView(parent, R.layout.end_view)) } } private fun InflateView(parent: ViewGroup?, layout: Int) = LayoutInflater.from(parent?.context).inflate(layout, parent, false) override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { when (holder) { is DetailViewHolder -> { holder.bindView(dataList[position].Data as RxServie.ActivityDetailBean) } is CommentViewHolder -> { holder.bindView(dataList[position].Data as Discuss, position) } is SubCommentViewHolder -> { holder.bindView(dataList[position].Data as Discuss) } is EndViewHolder -> { holder.bindView(dataList[position].type) } is MoreViewHoler -> { holder.bindView(dataList[position - 1].Data as Discuss, position) } } if (itemCount != 1 && position == itemCount - 1 && dataList[position].type != EndView_type) { for (i in position.downTo(0)) { if (dataList[i].type == Comment_type) { mListener.getMore(dataList[i].Data as Discuss) return } } } } override fun getItemViewType(position: Int): Int { return dataList[position].type } override fun getItemCount() = dataList.count() inner class DetailViewHolder(val item: View) : RecyclerView.ViewHolder(item) { fun bindView(data: RxServie.ActivityDetailBean) { with(data) { itemView.tv_name.text = name itemView.tv_create_date.text = create_date?.split(" ")?.get(0) itemView.tv_content.text = content itemView.tv_activity_time.text = start_date?.split(" ")?.get(0) + " ~ " + end_date?.split(" ")?.get(0) Picasso.with(item.context).load(Service.QiniuUrl + header_img).placeholder(R.drawable.user_place).into(itemView.user_icon) itemView.recyclerView_images.layoutManager = GridLayoutManager(item.context, 3) itemView.recyclerView_images.adapter = DetailImageAdapter(activityActivity, img_url?.split(";")) itemView.tv_num.text = discuss_count } } } inner class CommentViewHolder(val item: View) : RecyclerView.ViewHolder(item) { fun bindView(discuss: Discuss, position: Int) { with(discuss) { itemView.user_name.text = name itemView.tv_time.text = create_date?.toDate() itemView.tv_comment_content.text = content // itemView.comment_spaceview.visibility = if (discuss_content_count == "0" && position != itemCount - 2) View.VISIBLE else View.GONE itemView.comment_spaceview.visibility = View.GONE Picasso.with(item.context).load(Service.QiniuUrl + header_img).placeholder(R.drawable.user_place).into(itemView.discuss_user_icon) itemView.btn_comment.setOnClickListener { mListener.reply(discuss, position) } item.setOnLongClickListener { val menu = PopupMenu(activityActivity, it, Gravity.TOP) menu.inflate(R.menu.remove_disucss) menu.setOnMenuItemClickListener { RxServie.removeDiscuss(id, { if (it) { mListener.removeDiscuss() } else { "删除评论失败!".showToast() } }) true } if (discuss.name == Storage.readUserInfo().nickname) menu.show() true } } } } inner class SubCommentViewHolder(val item: View) : RecyclerView.ViewHolder(item) { fun bindView(discuss: Discuss) { val text = "<font color='#297EF5'>${discuss.name}:</font>${discuss.content}" itemView.tv_sub_discuss_content.text = Html.fromHtml(text) item.setOnLongClickListener { val menu = PopupMenu(activityActivity, it, Gravity.CENTER + Gravity.TOP) menu.inflate(R.menu.remove_disucss) menu.setOnMenuItemClickListener { RxServie.removeDiscuss(discuss.id, { if (it) { mListener.removeDiscuss() } else { "删除评论失败!".showToast() } }) true } if (discuss.name == Storage.readUserInfo().nickname) menu.show() true } } } inner class MoreViewHoler(val item: View) : RecyclerView.ViewHolder(item) { fun bindView(discuss: Discuss, position: Int) { itemView.setOnClickListener { mListener.getSubMore(discuss, position) } } } class EndViewHolder(val item: View) : RecyclerView.ViewHolder(item) { fun bindView(type: Int) { when (type) { EndView_type -> { itemView.endView.visibility = View.VISIBLE itemView.nullView.visibility = View.GONE } NullView_tyep -> { itemView.endView.visibility = View.GONE itemView.nullView.visibility = View.VISIBLE } } } } class DetailImageAdapter(val activityActivity: ActivityDetailActivity, val data: List<String>?) : RecyclerView.Adapter<DetailImageAdapter.ImageViewHolder>() { override fun getItemCount(): Int { return if (data != null) data.size - 1 else 0 } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ImageViewHolder { val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_activity_detail_image, parent, false) return ImageViewHolder(view) } override fun onBindViewHolder(holder: ImageViewHolder?, position: Int) { if (data != null) holder?.setView(data[position], position) } inner class ImageViewHolder(val item: View) : RecyclerView.ViewHolder(item) { fun setView(url: String, position: Int) { val space = (item.context.resources.displayMetrics.density * 10).toInt() val w = (activityActivity.resources.displayMetrics.widthPixels / 3.0).toInt() val layout = FrameLayout.LayoutParams(w, w) itemView.imageView.layoutParams = layout if (position < 3) { if (position % 3 == 2) itemView.frameLayout.setPadding(space, 0, space, 0) else itemView.frameLayout.setPadding(space, 0, 0, 0) } else { if (position % 3 == 2) itemView.frameLayout.setPadding(space, space, space, 0) else itemView.frameLayout.setPadding(space, space, 0, 0) } itemView.imageView.setOnClickListener { val option = ActivityOptionsCompat.makeSceneTransitionAnimation(activityActivity, it, "ImageView") val intent = Intent(activityActivity, ReviewImageActivity::class.java) intent.putExtra("image_url", url) activityActivity.startActivity(intent, option.toBundle()) } Picasso.with(item.context).load(Service.QiniuUrl + url).into(itemView.imageView) } } } }
gpl-2.0
a5e7780efc01c43b4dcbc8a8fa2b8e10
42.592275
194
0.587633
4.654445
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/provider/CollectionProvider.kt
1
2860
package com.boardgamegeek.provider import android.net.Uri import android.provider.BaseColumns._ID import com.boardgamegeek.entities.CollectionItemEntity import com.boardgamegeek.provider.BggContract.* import com.boardgamegeek.provider.BggContract.Collection import com.boardgamegeek.provider.BggContract.Companion.PATH_COLLECTION import com.boardgamegeek.provider.BggContract.Companion.QUERY_KEY_GROUP_BY import com.boardgamegeek.provider.BggContract.Companion.QUERY_KEY_HAVING import com.boardgamegeek.provider.BggContract.GameSuggestedPlayerCountPollPollResults.Columns.RECOMMENDATION import com.boardgamegeek.provider.BggDatabase.Tables class CollectionProvider : BasicProvider() { override fun getType(uri: Uri) = Collection.CONTENT_TYPE override val path = PATH_COLLECTION override val table = Tables.COLLECTION override val defaultSortOrder = Collection.DEFAULT_SORT override fun buildExpandedSelection(uri: Uri, projection: Array<String>?): SelectionBuilder { val builder = SelectionBuilder() .table(Tables.COLLECTION_JOIN_GAMES) .mapToTable(_ID, Tables.COLLECTION) .mapToTable(Collection.Columns.GAME_ID, Tables.COLLECTION) .mapToTable(Collection.Columns.UPDATED, Tables.COLLECTION) .mapToTable(Collection.Columns.UPDATED_LIST, Tables.COLLECTION) .mapToTable(Collection.Columns.PRIVATE_INFO_QUANTITY, Tables.COLLECTION) .mapIfNull(Games.Columns.GAME_RANK, CollectionItemEntity.RANK_UNKNOWN.toString()) // TODO move upstream or is this even necessary? .map(Plays.Columns.MAX_DATE, "(SELECT MAX(${Plays.Columns.DATE}) FROM ${Tables.PLAYS} WHERE ${Tables.PLAYS}.${Plays.Columns.OBJECT_ID}=${Tables.GAMES}.${Games.Columns.GAME_ID})") var groupBy = uri.getQueryParameter(QUERY_KEY_GROUP_BY).orEmpty() val having = uri.getQueryParameter(QUERY_KEY_HAVING).orEmpty() for (column in projection.orEmpty()) { if (column.startsWith(Games.Columns.PLAYER_COUNT_RECOMMENDATION_PREFIX)) { val playerCount = Games.getRecommendedPlayerCountFromColumn(column) if (!playerCount.isNullOrBlank()) { builder.map( Games.createRecommendedPlayerCountColumn(playerCount), "(SELECT $RECOMMENDATION FROM ${Tables.GAME_SUGGESTED_PLAYER_COUNT_POLL_RESULTS} AS x WHERE ${Tables.COLLECTION}.${Games.Columns.GAME_ID}=x.${Games.Columns.GAME_ID} AND x.player_count=$playerCount)" ) } if (groupBy.isEmpty()) groupBy = Games.Columns.GAME_ID } } if (having.isNotEmpty() && groupBy.isEmpty()) groupBy = Games.Columns.GAME_ID if (groupBy.isNotEmpty()) builder.groupBy(groupBy) builder.having(having) return builder } }
gpl-3.0
30ba22a9f3bf745d8f51a2a47d20f6c4
54
222
0.707343
4.627832
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/readers/DataProviderReader.kt
1
3776
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers import com.google.cloud.spanner.Struct import kotlinx.coroutines.flow.singleOrNull import org.wfanet.measurement.common.identity.ExternalId import org.wfanet.measurement.gcloud.spanner.AsyncDatabaseClient import org.wfanet.measurement.gcloud.spanner.appendClause import org.wfanet.measurement.gcloud.spanner.getBytesAsByteString import org.wfanet.measurement.gcloud.spanner.getProtoEnum import org.wfanet.measurement.gcloud.spanner.getProtoMessage import org.wfanet.measurement.internal.kingdom.Certificate import org.wfanet.measurement.internal.kingdom.DataProvider class DataProviderReader : SpannerReader<DataProviderReader.Result>() { data class Result(val dataProvider: DataProvider, val dataProviderId: Long) override val baseSql: String = """ SELECT DataProviders.DataProviderId, DataProviders.ExternalDataProviderId, DataProviders.DataProviderDetails, DataProviders.DataProviderDetailsJson, DataProviderCertificates.ExternalDataProviderCertificateId, Certificates.CertificateId, Certificates.SubjectKeyIdentifier, Certificates.NotValidBefore, Certificates.NotValidAfter, Certificates.RevocationState, Certificates.CertificateDetails FROM DataProviders JOIN DataProviderCertificates USING (DataProviderId) JOIN Certificates USING (CertificateId) """ .trimIndent() override suspend fun translate(struct: Struct): Result = Result(buildDataProvider(struct), struct.getLong("DataProviderId")) suspend fun readByExternalDataProviderId( readContext: AsyncDatabaseClient.ReadContext, externalDataProviderId: ExternalId, ): Result? { return fillStatementBuilder { appendClause("WHERE ExternalDataProviderId = @externalDataProviderId") bind("externalDataProviderId").to(externalDataProviderId.value) appendClause("LIMIT 1") } .execute(readContext) .singleOrNull() } private fun buildDataProvider(struct: Struct): DataProvider = DataProvider.newBuilder() .apply { externalDataProviderId = struct.getLong("ExternalDataProviderId") details = struct.getProtoMessage("DataProviderDetails", DataProvider.Details.parser()) certificate = buildCertificate(struct) } .build() // TODO(uakyol) : Move this function to CertificateReader when it is implemented. private fun buildCertificate(struct: Struct): Certificate = Certificate.newBuilder() .apply { externalDataProviderId = struct.getLong("ExternalDataProviderId") externalCertificateId = struct.getLong("ExternalDataProviderCertificateId") subjectKeyIdentifier = struct.getBytesAsByteString("SubjectKeyIdentifier") notValidBefore = struct.getTimestamp("NotValidBefore").toProto() notValidAfter = struct.getTimestamp("NotValidAfter").toProto() revocationState = struct.getProtoEnum("RevocationState", Certificate.RevocationState::forNumber) details = struct.getProtoMessage("CertificateDetails", Certificate.Details.parser()) } .build() }
apache-2.0
ccd854426047552f69dc18579ab95a37
40.955556
94
0.761917
4.955381
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/Commonx.kt
1
1987
/* * Copyright (c) 2016. Sunghyouk Bae <[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. * */ @file:JvmName("Commonx") package debop4k.core private val log = loggerOf("Commonx") /** * var 로 선언된 필드 중 non null 수형에 대해 초기화 값을 지정하고자 할 때 사용합니다. * 특히 ```@Autowired```, ```@Inject``` var 수형에 사용하기 좋다. * @see lateinit * @see Delegates.nonNull */ fun <T> uninitialized(): T = null as T /** 두 인스턴스가 같은가? */ fun areEquals(a: Any?, b: Any?): Boolean { return (a === b) || (a != null && a == b) } infix inline fun <T> T.initializedBy(initializer: (T) -> Unit): T { initializer(this) return this } infix inline fun <T> T.initializeWith(initialize: T.() -> Unit): T { this.initialize() return this } infix inline fun <T> T.with(block: T.() -> Unit): T { this.block() return this } infix inline fun <T : Any, R : Any> T?.whenNotNull(thenDo: (T) -> R?): R? = if (this == null) null else thenDo(this) infix inline fun <T : Any, R : Any> T?.withNotNull(thenDo: T.() -> R?): R? = if (this == null) null else this.thenDo() fun <T : Any, R : Any> Collection<T?>.whenAllNotNull(block: (Collection<T>) -> R) { if (this.all { it != null }) { block(this.filterNotNull()) } } fun <T : Any, R : Any> Collection<T?>.whenAnyNotNull(block: (Collection<T>) -> R) { if (this.any { it != null }) { block(this.filterNotNull()) } }
apache-2.0
987cb554bd65ddfcb32b2d20e19756fd
25.985714
83
0.642139
3.086601
false
false
false
false
minjaesong/terran-basic-java-vm
src/net/torvald/terrarum/virtualcomputer/terranvmadapter/LCDFont.kt
1
1081
package net.torvald.terrarum.virtualcomputer.terranvmadapter import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.graphics.g2d.GlyphLayout import net.torvald.terrarumsansbitmap.gdx.TextureRegionPack /** * Created by minjaesong on 2017-11-18. */ class LCDFont: BitmapFont() { internal val W = 12 internal val H = 16 internal val fontSheet = TextureRegionPack(Gdx.files.internal("assets/lcd.tga"), W, H) init { setOwnsTexture(true) } override fun draw(batch: Batch, str: CharSequence, x: Float, y: Float): GlyphLayout? { str.forEachIndexed { index, c -> batch.draw( fontSheet.get(c.toInt() % 16, c.toInt() / 16), x + W * index, y ) } return null } override fun getLineHeight() = H.toFloat() override fun getCapHeight() = getLineHeight() override fun getXHeight() = getLineHeight() override fun dispose() { fontSheet.dispose() } }
mit
295ec697847fb2c1c02c756a758d21b9
24.761905
90
0.643848
3.740484
false
false
false
false
mgolokhov/dodroid
app/src/main/java/doit/study/droid/quiz/ui/QuizMainFragment.kt
1
3218
package doit.study.droid.quiz.ui import android.graphics.Color import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import doit.study.droid.app.App import doit.study.droid.databinding.FragmentQuizMainBinding import doit.study.droid.utils.lazyAndroid import javax.inject.Inject import timber.log.Timber class QuizMainFragment : Fragment() { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private val viewModel: QuizMainViewModel by lazyAndroid { ViewModelProviders.of(this, viewModelFactory)[QuizMainViewModel::class.java] } private lateinit var viewDataBinding: FragmentQuizMainBinding private val handler = Handler() override fun onCreate(savedInstanceState: Bundle?) { App.dagger.inject(this) super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewDataBinding = FragmentQuizMainBinding.inflate(inflater, container, false) return viewDataBinding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewDataBinding.apply { lifecycleOwner = viewLifecycleOwner } setupPagerAdapter() setupActionBarTitle() setupResultPage() setupNavigationToResultPage() viewDataBinding.titlePagerTabStrip.tabIndicatorColor = Color.BLACK } override fun onStop() { super.onStop() handler.removeCallbacksAndMessages(null) } private fun setupNavigationToResultPage() { viewModel.swipeToResultPageEvent.observe(viewLifecycleOwner, Observer { it.getContentIfNotHandled()?.let { handler.postDelayed({ viewDataBinding.viewPager.setCurrentItem(it, true) }, DELAY_NAV_TO_RESULT_PAGE_MS) } }) } private fun setupResultPage() { viewModel.addResultPageEvent.observe(viewLifecycleOwner, Observer { it.getContentIfNotHandled()?.let { viewDataBinding.viewPager.adapter?.notifyDataSetChanged() } }) } private fun setupActionBarTitle() { viewModel.actionBarTitle.observe(viewLifecycleOwner, Observer { activity?.title = it }) } private fun setupPagerAdapter() { viewModel.items.observe(viewLifecycleOwner, Observer { Timber.d("$this result: $it") if (it.isNotEmpty()) { viewDataBinding.viewPager.apply { adapter = QuizPagerAdapter(childFragmentManager, viewModel) adapter?.notifyDataSetChanged() } } }) } companion object { fun newInstance(): QuizMainFragment = QuizMainFragment() private const val DELAY_NAV_TO_RESULT_PAGE_MS = 2_000L } }
mit
b2872e686df96ecdeaee93a7e6e6ce95
30.861386
85
0.676196
5.284072
false
false
false
false
danrien/projectBlueWater
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/service/receivers/devices/remote/connected/MediaSessionBroadcaster.kt
1
5686
package com.lasthopesoftware.bluewater.client.playback.service.receivers.devices.remote.connected import android.content.Context import android.graphics.Bitmap import android.media.MediaMetadata import android.media.session.PlaybackState import android.os.Build import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import androidx.annotation.RequiresApi import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.FilePropertyHelpers import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.KnownFileProperties import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.ScopedCachedFilePropertiesProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.image.ProvideImages import com.lasthopesoftware.bluewater.client.playback.service.receivers.devices.remote.IRemoteBroadcaster import com.lasthopesoftware.bluewater.client.playback.service.receivers.devices.remote.connected.MediaSessionBroadcaster import com.lasthopesoftware.bluewater.shared.promises.extensions.LoopedInPromise.Companion.response import org.slf4j.LoggerFactory @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) class MediaSessionBroadcaster( private val context: Context, private val scopedCachedFilePropertiesProvider: ScopedCachedFilePropertiesProvider, private val imageProvider: ProvideImages, private val mediaSession: MediaSessionCompat ) : IRemoteBroadcaster { @Volatile private var playbackState = PlaybackStateCompat.STATE_STOPPED @Volatile private var trackPosition: Long = -1 @Volatile private var mediaMetadata = MediaMetadataCompat.Builder().build() @Volatile private var capabilities = standardCapabilities private var remoteClientBitmap: Bitmap? = null @Volatile private var isPlaying = false override fun setPlaying() { isPlaying = true val builder = PlaybackStateCompat.Builder() capabilities = PlaybackStateCompat.ACTION_PAUSE or standardCapabilities builder.setActions(capabilities) playbackState = PlaybackStateCompat.STATE_PLAYING builder.setState(playbackState, trackPosition, playbackSpeed) mediaSession.setPlaybackState(builder.build()) } override fun setPaused() { isPlaying = false val builder = PlaybackStateCompat.Builder() capabilities = PlaybackState.ACTION_PLAY or standardCapabilities builder.setActions(capabilities) playbackState = PlaybackState.STATE_PAUSED builder.setState(playbackState, trackPosition, playbackSpeed) mediaSession.setPlaybackState(builder.build()) } override fun setStopped() { isPlaying = false val builder = PlaybackStateCompat.Builder() capabilities = PlaybackState.ACTION_PLAY or standardCapabilities builder.setActions(capabilities) playbackState = PlaybackState.STATE_STOPPED builder.setState( playbackState, trackPosition, playbackSpeed ) mediaSession.setPlaybackState(builder.build()) updateClientBitmap(null) } override fun updateNowPlaying(serviceFile: ServiceFile) { scopedCachedFilePropertiesProvider .promiseFileProperties(serviceFile) .eventually(response({ fileProperties -> val artist = fileProperties[KnownFileProperties.ARTIST] val name = fileProperties[KnownFileProperties.NAME] val album = fileProperties[KnownFileProperties.ALBUM] val duration = FilePropertyHelpers.parseDurationIntoMilliseconds(fileProperties) .toLong() val metadataBuilder = MediaMetadataCompat.Builder(mediaMetadata) metadataBuilder.putString(MediaMetadata.METADATA_KEY_ARTIST, artist) metadataBuilder.putString(MediaMetadata.METADATA_KEY_ALBUM, album) metadataBuilder.putString(MediaMetadata.METADATA_KEY_TITLE, name) metadataBuilder.putLong(MediaMetadata.METADATA_KEY_DURATION, duration) val trackNumberString = fileProperties[KnownFileProperties.TRACK] val trackNumber = trackNumberString?.toLong() if (trackNumber != null) { metadataBuilder.putLong(MediaMetadata.METADATA_KEY_TRACK_NUMBER, trackNumber) } mediaSession.setMetadata(metadataBuilder.build().also { mediaMetadata = it }) }, context)) imageProvider .promiseFileBitmap(serviceFile) .eventually(response(::updateClientBitmap, context)) .excuse { e -> logger.warn( "There was an error getting the image for the file with id `" + serviceFile.key + "`", e ) } } override fun updateTrackPosition(trackPosition: Long) { val builder = PlaybackStateCompat.Builder() builder.setActions(capabilities) builder.setState( playbackState, trackPosition.also { this.trackPosition = it }, playbackSpeed ) mediaSession.setPlaybackState(builder.build()) } @Synchronized private fun updateClientBitmap(bitmap: Bitmap?) { if (remoteClientBitmap == bitmap) return val metadataBuilder = MediaMetadataCompat.Builder(mediaMetadata) metadataBuilder.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, bitmap) mediaSession.setMetadata(metadataBuilder.build().also { mediaMetadata = it }) remoteClientBitmap = bitmap } companion object { private val logger by lazy { LoggerFactory.getLogger(MediaSessionBroadcaster::class.java) } private const val playbackSpeed = 1.0f private const val standardCapabilities = PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_SKIP_TO_NEXT or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or PlaybackStateCompat.ACTION_STOP or PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID or PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH } }
lgpl-3.0
cca9bbdc0c9a5cfe0ae02ae399f9a33e
37.161074
120
0.807246
4.466614
false
false
false
false
soniccat/android-taskmanager
quizlet_repository/src/main/java/com/example/alexeyglushkov/quizletservice/QuizletRepository.kt
1
6870
package com.example.alexeyglushkov.quizletservice import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import com.aglushkov.modelcore.resource.Resource import com.aglushkov.repository.RepositoryCommandHolder import com.aglushkov.repository.command.CancellableRepositoryCommand import com.aglushkov.repository.command.DisposableRepositoryCommand import com.aglushkov.repository.command.RepositoryCommand import com.aglushkov.repository.livedata.NonNullMutableLiveData import com.aglushkov.repository.livedata.ResourceLiveDataProvider import com.example.alexeyglushkov.authtaskmanager.BaseServiceTask import com.example.alexeyglushkov.cachemanager.Storage import com.example.alexeyglushkov.cachemanager.clients.* import com.example.alexeyglushkov.quizletservice.entities.QuizletSet import com.example.alexeyglushkov.quizletservice.entities.QuizletTerm import com.example.alexeyglushkov.streamlib.progress.ProgressListener import io.reactivex.Single import io.reactivex.internal.functions.Functions import kotlinx.coroutines.* import java.lang.Exception import kotlin.collections.ArrayList // TODO: base class for repository with service and cache class QuizletRepository(private val service: QuizletService, storage: Storage) : ResourceLiveDataProvider<List<QuizletSet>> { private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private val cache: ScopeCache private val commandHolder = RepositoryCommandHolder<Long>() init { cache = ScopeCacheAdapter(SimpleCache(storage, 0), scope) } //// Actions fun loadSets(progressListener: ProgressListener): RepositoryCommand<Resource<List<QuizletSet>>, Long> { val job = scope.launch { loadSetsInternal(progressListener) } return commandHolder.putCommand(CancellableRepositoryCommand(LOAD_SETS_COMMAND_ID, job, setsLiveData)) } @Throws suspend private fun loadSetsInternal(progressListener: ProgressListener) { val previousState = setsLiveData.value!! setsLiveData.value = setsLiveData.value!!.toLoading() try { val sets = service.loadSets(progressListener) cache.putValue("quizlet_sets", sets) setsLiveData.value = setsLiveData.value!!.toLoaded(sets) } catch (e: Exception) { if (e is CancellationException) { setsLiveData.value = setsLiveData.value!!.toError(e, true, previousState.data(), previousState.canLoadNextPage) } else { setsLiveData.value = previousState } throw e } } fun restoreOrLoad(progressListener: ProgressListener): RepositoryCommand<Resource<List<QuizletSet>>, Long> { val job = scope.launch { restoreOrLoadInternal(progressListener) } return commandHolder.putCommand(CancellableRepositoryCommand(LOAD_SETS_COMMAND_ID, job, setsLiveData)) } private suspend fun restoreOrLoadInternal(progressListener: ProgressListener) { val previousState: Resource<List<QuizletSet>> = setsLiveData.value!! setsLiveData.setValue(previousState.toLoading()) var sets: List<QuizletSet>? = null try { try { sets = cache.getCachedValue<List<QuizletSet>>("quizlet_sets") } catch (e: Exception) { // ignore } if (sets != null) { setsLiveData.setValue(setsLiveData.value!!.toLoaded(sets)) } else { setsLiveData.setValue(previousState) if (service.account?.isAuthorized ?: false) { loadSetsInternal(progressListener) } else { throw Exception("restoreOrLoadInternal: Account isn't aurthoized to loadSetsInternal") } } } catch (e: Exception) { if (e is CancellationException) { setsLiveData.setValue(previousState) } } } //// Setters / Getters // Getters override val liveData: LiveData<Resource<List<QuizletSet>>> get() = setsLiveData fun getTermListLiveData(setId: Long): MutableLiveData<Resource<List<QuizletTerm>>> { val liveDataId = LOAD_TERMS_COMMAND_PREFIX + setId var liveData = commandHolder.getLiveData<MutableLiveData<Resource<List<QuizletTerm>>>>(liveDataId) if (liveData == null) { liveData = QuizletTermAdapter(setId).liveData commandHolder.putLiveData(liveDataId, liveData) } return liveData } private val setsLiveData: NonNullMutableLiveData<Resource<List<QuizletSet>>> get() { var liveData = commandHolder.getLiveData<NonNullMutableLiveData<Resource<List<QuizletSet>>>>(LOAD_SETS_COMMAND_ID) if (liveData == null) { liveData = NonNullMutableLiveData(Resource.Uninitialized<List<QuizletSet>>() as Resource<List<QuizletSet>>) commandHolder.putLiveData(LOAD_SETS_COMMAND_ID, liveData) } return liveData } // Inner Classes // QuizletSet liveData to QuizletTerm liveData private inner class QuizletTermAdapter(private val setId: Long) : ResourceLiveDataProvider<List<QuizletTerm>> { override val liveData: MutableLiveData<Resource<List<QuizletTerm>>> get() { val mediatorLiveData = MediatorLiveData<Resource<List<QuizletTerm>>>() mediatorLiveData.setValue(Resource.Uninitialized()) mediatorLiveData.addSource<Resource<List<QuizletSet>>>([email protected], object : Observer<Resource<List<QuizletSet>>> { override fun onChanged(listResource: Resource<List<QuizletSet>>) { mediatorLiveData.setValue(buildFinalResource(listResource)) } }) return mediatorLiveData } private fun buildFinalResource(listResource: Resource<List<QuizletSet>>): Resource<List<QuizletTerm>> { val terms: MutableList<QuizletTerm> = ArrayList() val data = listResource.data() if (data != null) { for (set in data) { for (term in set.terms) { val setId = term.setId if (this.setId == Companion.NO_ID || setId == this.setId) { terms.add(term) } } } } return listResource.copyWith(terms) } } companion object { private const val LOAD_SETS_COMMAND_ID: Long = 0 private const val LOAD_TERMS_COMMAND_PREFIX: Long = 2 // it's 2 to support -1 set id private const val NO_ID: Long = -1 } }
mit
7d49bce64770841685d8fed7d4e357f8
42.487342
151
0.66361
4.844852
false
false
false
false
cwoolner/flex-poker
src/test/kotlin/com/flexpoker/table/command/service/DefaultHandEvaluatorServiceTest.kt
1
35273
package com.flexpoker.table.command.service import com.flexpoker.table.command.Card import com.flexpoker.table.command.CardRank import com.flexpoker.table.command.CardSuit import com.flexpoker.table.command.FlopCards import com.flexpoker.table.command.HandRanking import com.flexpoker.table.command.PocketCards import com.flexpoker.table.command.RiverCard import com.flexpoker.table.command.TurnCard import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.util.ArrayList import java.util.UUID class DefaultHandEvaluatorServiceTest { private val bso = DefaultHandEvaluatorService() @Test fun testDeterminePossibleHands() { testDeterminePossibleHandsStraightFlushOnBoard() testDeterminePossibleHandsFourOfAKindOnBoard() testDeterminePossibleHandsFullHouseOnBoard() testDeterminePossibleHandsFlushOnBoard() testDeterminePossibleHandsStraightOnBoard() testDeterminePossibleHandsThreeOfAKindOnBoard() testDeterminePossibleHandsTwoPairOnBoard() testDeterminePossibleHandsOnePairOnBoard() testDeterminePossibleHandsScenario1() testDeterminePossibleHandsScenario2() testDeterminePossibleHandsScenario3() testDeterminePossibleHandsScenario4() testDeterminePossibleHandsScenario5() } @Test fun testDetermineHandEvaluation() { testDetermineHandEvaluationScenario1() testDetermineHandEvaluationScenario2() testDetermineHandEvaluationScenario3() testDetermineHandEvaluationScenario4() } private fun testDetermineHandEvaluationScenario1() { val card1 = Card(0, CardRank.FOUR, CardSuit.SPADES) val card2 = Card(0, CardRank.JACK, CardSuit.SPADES) val card3 = Card(0, CardRank.EIGHT, CardSuit.HEARTS) val card4 = Card(0, CardRank.FOUR, CardSuit.HEARTS) val card5 = Card(0, CardRank.QUEEN, CardSuit.HEARTS) val flopCards = FlopCards(card1, card3, card4) val turnCard = TurnCard(card5) val riverCard = RiverCard(card2) val possibleHandRankings = bso.determinePossibleHands(flopCards, turnCard, riverCard) val id1 = UUID.randomUUID() val id2 = UUID.randomUUID() val id3 = UUID.randomUUID() val id4 = UUID.randomUUID() val id5 = UUID.randomUUID() val id6 = UUID.randomUUID() val id8 = UUID.randomUUID() val pocketCardsList = ArrayList<PocketCards>() val pocketCards1 = PocketCards( Card(0, CardRank.NINE, CardSuit.HEARTS), Card(0, CardRank.ACE, CardSuit.CLUBS) ) val pocketCards2 = PocketCards( Card(0, CardRank.QUEEN, CardSuit.HEARTS), Card(0, CardRank.ACE, CardSuit.CLUBS) ) val pocketCards3 = PocketCards( Card(0, CardRank.TWO, CardSuit.HEARTS), Card(0, CardRank.ACE, CardSuit.HEARTS) ) val pocketCards4 = PocketCards( Card(0, CardRank.FOUR, CardSuit.CLUBS), Card(0, CardRank.FOUR, CardSuit.DIAMONDS) ) val pocketCards5 = PocketCards( Card(0, CardRank.FIVE, CardSuit.CLUBS), Card(0, CardRank.FOUR, CardSuit.DIAMONDS) ) val pocketCards6 = PocketCards( Card(0, CardRank.FOUR, CardSuit.CLUBS), Card(0, CardRank.EIGHT, CardSuit.CLUBS) ) val pocketCards8 = PocketCards( Card(0, CardRank.QUEEN, CardSuit.CLUBS), Card(0, CardRank.QUEEN, CardSuit.DIAMONDS) ) pocketCardsList.add(pocketCards1) pocketCardsList.add(pocketCards2) pocketCardsList.add(pocketCards3) pocketCardsList.add(pocketCards4) pocketCardsList.add(pocketCards5) pocketCardsList.add(pocketCards6) pocketCardsList.add(pocketCards8) val handEvaluations = bso.determineHandEvaluation( flopCards, turnCard, riverCard, pocketCardsList, possibleHandRankings ) val handEvaluation1 = handEvaluations[pocketCards1] val handEvaluation2 = handEvaluations[pocketCards2] val handEvaluation3 = handEvaluations[pocketCards3] val handEvaluation4 = handEvaluations[pocketCards4] val handEvaluation5 = handEvaluations[pocketCards5] val handEvaluation6 = handEvaluations[pocketCards6] val handEvaluation8 = handEvaluations[pocketCards8] handEvaluation1!!.playerId = id1 handEvaluation2!!.playerId = id2 handEvaluation3!!.playerId = id3 handEvaluation4!!.playerId = id4 handEvaluation5!!.playerId = id5 handEvaluation6!!.playerId = id6 handEvaluation8!!.playerId = id8 assertEquals(HandRanking.ONE_PAIR, handEvaluation1.handRanking) assertEquals(CardRank.FOUR, handEvaluation1.primaryCardRank) assertEquals(CardRank.ACE, handEvaluation1.firstKicker) assertEquals(CardRank.QUEEN, handEvaluation1.secondKicker) assertEquals(CardRank.JACK, handEvaluation1.thirdKicker) assertEquals(id1, handEvaluation1.playerId) assertEquals(HandRanking.TWO_PAIR, handEvaluation2.handRanking) assertEquals(CardRank.QUEEN, handEvaluation2.primaryCardRank) assertEquals(CardRank.FOUR, handEvaluation2.secondaryCardRank) assertEquals(CardRank.ACE, handEvaluation2.firstKicker) assertEquals(id2, handEvaluation2.playerId) assertEquals(HandRanking.FLUSH, handEvaluation3.handRanking) assertEquals(CardRank.ACE, handEvaluation3.primaryCardRank) assertEquals(CardRank.QUEEN, handEvaluation3.firstKicker) assertEquals(CardRank.EIGHT, handEvaluation3.secondKicker) assertEquals(CardRank.FOUR, handEvaluation3.thirdKicker) assertEquals(CardRank.TWO, handEvaluation3.fourthKicker) assertEquals(id3, handEvaluation3.playerId) assertEquals(HandRanking.FOUR_OF_A_KIND, handEvaluation4.handRanking) assertEquals(CardRank.FOUR, handEvaluation4.primaryCardRank) assertEquals(CardRank.QUEEN, handEvaluation4.firstKicker) assertEquals(id4, handEvaluation4.playerId) assertEquals(HandRanking.THREE_OF_A_KIND, handEvaluation5.handRanking) assertEquals(CardRank.FOUR, handEvaluation5.primaryCardRank) assertEquals(CardRank.QUEEN, handEvaluation5.firstKicker) assertEquals(CardRank.JACK, handEvaluation5.secondKicker) assertEquals(id5, handEvaluation5.playerId) assertEquals(HandRanking.FULL_HOUSE, handEvaluation6.handRanking) assertEquals(CardRank.FOUR, handEvaluation6.primaryCardRank) assertEquals(CardRank.EIGHT, handEvaluation6.secondaryCardRank) assertEquals(id6, handEvaluation6.playerId) assertEquals(HandRanking.FULL_HOUSE, handEvaluation8.handRanking) assertEquals(CardRank.QUEEN, handEvaluation8.primaryCardRank) assertEquals(CardRank.FOUR, handEvaluation8.secondaryCardRank) assertEquals(id8, handEvaluation8.playerId) } private fun testDetermineHandEvaluationScenario2() { val card1 = Card(0, CardRank.KING, CardSuit.HEARTS) val card2 = Card(0, CardRank.JACK, CardSuit.HEARTS) val card3 = Card(0, CardRank.NINE, CardSuit.HEARTS) val card4 = Card(0, CardRank.TEN, CardSuit.HEARTS) val card5 = Card(0, CardRank.QUEEN, CardSuit.HEARTS) val flopCards = FlopCards(card1, card3, card4) val turnCard = TurnCard(card5) val riverCard = RiverCard(card2) val possibleHandRankings = bso.determinePossibleHands(flopCards, turnCard, riverCard) val id1 = UUID.randomUUID() val id2 = UUID.randomUUID() val id3 = UUID.randomUUID() val pocketCardsList = ArrayList<PocketCards>() val pocketCards1 = PocketCards( Card(0, CardRank.EIGHT, CardSuit.HEARTS), Card(0, CardRank.ACE, CardSuit.CLUBS) ) val pocketCards2 = PocketCards( Card(0, CardRank.QUEEN, CardSuit.SPADES), Card(0, CardRank.ACE, CardSuit.HEARTS) ) val pocketCards3 = PocketCards( Card(0, CardRank.QUEEN, CardSuit.SPADES), Card(0, CardRank.ACE, CardSuit.DIAMONDS) ) pocketCardsList.add(pocketCards1) pocketCardsList.add(pocketCards2) pocketCardsList.add(pocketCards3) val handEvaluations = bso.determineHandEvaluation( flopCards, turnCard, riverCard, pocketCardsList, possibleHandRankings ) val handEvaluation1 = handEvaluations[pocketCards1] val handEvaluation2 = handEvaluations[pocketCards2] val handEvaluation3 = handEvaluations[pocketCards3] handEvaluation1!!.playerId = id1 handEvaluation2!!.playerId = id2 handEvaluation3!!.playerId = id3 assertEquals(HandRanking.STRAIGHT_FLUSH, handEvaluation1.handRanking) assertEquals(CardRank.KING, handEvaluation1.primaryCardRank) assertEquals(id1, handEvaluation1.playerId) assertEquals(HandRanking.STRAIGHT_FLUSH, handEvaluation2.handRanking) assertEquals(CardRank.ACE, handEvaluation2.primaryCardRank) assertEquals(id2, handEvaluation2.playerId) assertEquals(HandRanking.STRAIGHT_FLUSH, handEvaluation3.handRanking) assertEquals(CardRank.KING, handEvaluation3.primaryCardRank) assertEquals(id3, handEvaluation3.playerId) } private fun testDetermineHandEvaluationScenario3() { val card1 = Card(0, CardRank.ACE, CardSuit.CLUBS) val card2 = Card(0, CardRank.TWO, CardSuit.CLUBS) val card3 = Card(0, CardRank.THREE, CardSuit.CLUBS) val card4 = Card(0, CardRank.FOUR, CardSuit.CLUBS) val card5 = Card(0, CardRank.SIX, CardSuit.HEARTS) val flopCards = FlopCards(card1, card3, card4) val turnCard = TurnCard(card5) val riverCard = RiverCard(card2) val possibleHandRankings = bso.determinePossibleHands(flopCards, turnCard, riverCard) val id1 = UUID.randomUUID() val id2 = UUID.randomUUID() val id3 = UUID.randomUUID() val pocketCardsList = ArrayList<PocketCards>() val pocketCards1 = PocketCards( Card(0, CardRank.FIVE, CardSuit.CLUBS), Card(0, CardRank.ACE, CardSuit.CLUBS) ) val pocketCards2 = PocketCards( Card(0, CardRank.FIVE, CardSuit.SPADES), Card(0, CardRank.ACE, CardSuit.HEARTS) ) val pocketCards3 = PocketCards( Card(0, CardRank.QUEEN, CardSuit.SPADES), Card(0, CardRank.ACE, CardSuit.DIAMONDS) ) pocketCardsList.add(pocketCards1) pocketCardsList.add(pocketCards2) pocketCardsList.add(pocketCards3) val handEvaluations = bso.determineHandEvaluation( flopCards, turnCard, riverCard, pocketCardsList, possibleHandRankings ) val handEvaluation1 = handEvaluations[pocketCards1] val handEvaluation2 = handEvaluations[pocketCards2] val handEvaluation3 = handEvaluations[pocketCards3] handEvaluation1!!.playerId = id1 handEvaluation2!!.playerId = id2 handEvaluation3!!.playerId = id3 assertEquals(HandRanking.STRAIGHT_FLUSH, handEvaluation1.handRanking) assertEquals(CardRank.FIVE, handEvaluation1.primaryCardRank) assertEquals(id1, handEvaluation1.playerId) assertEquals(HandRanking.STRAIGHT, handEvaluation2.handRanking) assertEquals(CardRank.SIX, handEvaluation2.primaryCardRank) assertEquals(id2, handEvaluation2.playerId) assertEquals(HandRanking.ONE_PAIR, handEvaluation3.handRanking) assertEquals(CardRank.ACE, handEvaluation3.primaryCardRank) assertEquals(CardRank.QUEEN, handEvaluation3.firstKicker) assertEquals(CardRank.SIX, handEvaluation3.secondKicker) assertEquals(CardRank.FOUR, handEvaluation3.thirdKicker) assertEquals(id3, handEvaluation3.playerId) } private fun testDetermineHandEvaluationScenario4() { val card1 = Card(0, CardRank.KING, CardSuit.SPADES) val card2 = Card(0, CardRank.TWO, CardSuit.DIAMONDS) val card3 = Card(0, CardRank.QUEEN, CardSuit.CLUBS) val card4 = Card(0, CardRank.FOUR, CardSuit.CLUBS) val card5 = Card(0, CardRank.SIX, CardSuit.HEARTS) val flopCards = FlopCards(card1, card3, card4) val turnCard = TurnCard(card5) val riverCard = RiverCard(card2) val possibleHandRankings = bso.determinePossibleHands(flopCards, turnCard, riverCard) val id1 = UUID.randomUUID() val id2 = UUID.randomUUID() val pocketCardsList = ArrayList<PocketCards>() val pocketCards1 = PocketCards( Card(0, CardRank.FIVE, CardSuit.CLUBS), Card(0, CardRank.ACE, CardSuit.CLUBS) ) val pocketCards2 = PocketCards( Card(0, CardRank.THREE, CardSuit.SPADES), Card(0, CardRank.SEVEN, CardSuit.HEARTS) ) pocketCardsList.add(pocketCards1) pocketCardsList.add(pocketCards2) val handEvaluations = bso.determineHandEvaluation( flopCards, turnCard, riverCard, pocketCardsList, possibleHandRankings ) val handEvaluation1 = handEvaluations[pocketCards1] val handEvaluation2 = handEvaluations[pocketCards2] handEvaluation1!!.playerId = id1 handEvaluation2!!.playerId = id2 assertEquals(HandRanking.HIGH_CARD, handEvaluation1.handRanking) assertEquals(CardRank.ACE, handEvaluation1.primaryCardRank) assertEquals(CardRank.KING, handEvaluation1.firstKicker) assertEquals(CardRank.QUEEN, handEvaluation1.secondKicker) assertEquals(CardRank.SIX, handEvaluation1.thirdKicker) assertEquals(CardRank.FIVE, handEvaluation1.fourthKicker) assertEquals(id1, handEvaluation1.playerId) assertEquals(HandRanking.HIGH_CARD, handEvaluation2.handRanking) assertEquals(CardRank.KING, handEvaluation2.primaryCardRank) assertEquals(CardRank.QUEEN, handEvaluation2.firstKicker) assertEquals(CardRank.SEVEN, handEvaluation2.secondKicker) assertEquals(CardRank.SIX, handEvaluation2.thirdKicker) assertEquals(CardRank.FOUR, handEvaluation2.fourthKicker) assertEquals(id2, handEvaluation2.playerId) } private fun testDeterminePossibleHandsScenario1() { val card1 = Card(0, CardRank.ACE, CardSuit.HEARTS) val card2 = Card(0, CardRank.TWO, CardSuit.DIAMONDS) val card3 = Card(0, CardRank.SEVEN, CardSuit.CLUBS) val card4 = Card(0, CardRank.EIGHT, CardSuit.SPADES) val card5 = Card(0, CardRank.KING, CardSuit.HEARTS) val flopCards = FlopCards(card1, card3, card4) val turnCard = TurnCard(card5) val riverCard = RiverCard(card2) val handRankings = bso.determinePossibleHands(flopCards, turnCard, riverCard) assertEquals(4, handRankings.size) assertEquals(HandRanking.HIGH_CARD, handRankings[0]) assertEquals(HandRanking.ONE_PAIR, handRankings[1]) assertEquals(HandRanking.TWO_PAIR, handRankings[2]) assertEquals(HandRanking.THREE_OF_A_KIND, handRankings[3]) } private fun testDeterminePossibleHandsScenario2() { val card1 = Card(0, CardRank.ACE, CardSuit.HEARTS) val card2 = Card(0, CardRank.KING, CardSuit.HEARTS) val card3 = Card(0, CardRank.SEVEN, CardSuit.CLUBS) val card4 = Card(0, CardRank.EIGHT, CardSuit.SPADES) val card5 = Card(0, CardRank.QUEEN, CardSuit.HEARTS) val flopCards = FlopCards(card1, card3, card4) val turnCard = TurnCard(card5) val riverCard = RiverCard(card2) val handRankings = bso.determinePossibleHands(flopCards, turnCard, riverCard) assertEquals(7, handRankings.size) assertEquals(HandRanking.HIGH_CARD, handRankings[0]) assertEquals(HandRanking.ONE_PAIR, handRankings[1]) assertEquals(HandRanking.TWO_PAIR, handRankings[2]) assertEquals(HandRanking.THREE_OF_A_KIND, handRankings[3]) assertEquals(HandRanking.STRAIGHT, handRankings[4]) assertEquals(HandRanking.FLUSH, handRankings[5]) assertEquals(HandRanking.STRAIGHT_FLUSH, handRankings[6]) } private fun testDeterminePossibleHandsScenario3() { val card1 = Card(0, CardRank.THREE, CardSuit.CLUBS) val card2 = Card(0, CardRank.NINE, CardSuit.SPADES) val card3 = Card(0, CardRank.TWO, CardSuit.CLUBS) val card4 = Card(0, CardRank.SIX, CardSuit.CLUBS) val card5 = Card(0, CardRank.THREE, CardSuit.HEARTS) val flopCards = FlopCards(card1, card3, card4) val turnCard = TurnCard(card5) val riverCard = RiverCard(card2) val handRankings = bso.determinePossibleHands(flopCards, turnCard, riverCard) assertEquals(8, handRankings.size) assertEquals(HandRanking.ONE_PAIR, handRankings[0]) assertEquals(HandRanking.TWO_PAIR, handRankings[1]) assertEquals(HandRanking.THREE_OF_A_KIND, handRankings[2]) assertEquals(HandRanking.STRAIGHT, handRankings[3]) assertEquals(HandRanking.FLUSH, handRankings[4]) assertEquals(HandRanking.FULL_HOUSE, handRankings[5]) assertEquals(HandRanking.FOUR_OF_A_KIND, handRankings[6]) assertEquals(HandRanking.STRAIGHT_FLUSH, handRankings[7]) } private fun testDeterminePossibleHandsScenario4() { val card1 = Card(0, CardRank.TEN, CardSuit.CLUBS) val card2 = Card(0, CardRank.SIX, CardSuit.HEARTS) val card3 = Card(0, CardRank.JACK, CardSuit.DIAMONDS) val card4 = Card(0, CardRank.NINE, CardSuit.CLUBS) val card5 = Card(0, CardRank.THREE, CardSuit.CLUBS) val flopCards = FlopCards(card1, card3, card4) val turnCard = TurnCard(card5) val riverCard = RiverCard(card2) val handRankings = bso.determinePossibleHands(flopCards, turnCard, riverCard) assertEquals(6, handRankings.size) assertEquals(HandRanking.HIGH_CARD, handRankings[0]) assertEquals(HandRanking.ONE_PAIR, handRankings[1]) assertEquals(HandRanking.TWO_PAIR, handRankings[2]) assertEquals(HandRanking.THREE_OF_A_KIND, handRankings[3]) assertEquals(HandRanking.STRAIGHT, handRankings[4]) assertEquals(HandRanking.FLUSH, handRankings[5]) } private fun testDeterminePossibleHandsScenario5() { val card1 = Card(0, CardRank.EIGHT, CardSuit.CLUBS) val card2 = Card(0, CardRank.FOUR, CardSuit.DIAMONDS) val card3 = Card(0, CardRank.ACE, CardSuit.DIAMONDS) val card4 = Card(0, CardRank.EIGHT, CardSuit.DIAMONDS) val card5 = Card(0, CardRank.FIVE, CardSuit.DIAMONDS) val flopCards = FlopCards(card1, card3, card4) val turnCard = TurnCard(card5) val riverCard = RiverCard(card2) val handRankings = bso.determinePossibleHands(flopCards, turnCard, riverCard) assertEquals(8, handRankings.size) assertEquals(HandRanking.ONE_PAIR, handRankings[0]) assertEquals(HandRanking.TWO_PAIR, handRankings[1]) assertEquals(HandRanking.THREE_OF_A_KIND, handRankings[2]) assertEquals(HandRanking.STRAIGHT, handRankings[3]) assertEquals(HandRanking.FLUSH, handRankings[4]) assertEquals(HandRanking.FULL_HOUSE, handRankings[5]) assertEquals(HandRanking.FOUR_OF_A_KIND, handRankings[6]) assertEquals(HandRanking.STRAIGHT_FLUSH, handRankings[7]) } private fun testDeterminePossibleHandsStraightFlushOnBoard() { verifyStraightFlushOnBoardHelper(CardRank.FIVE) verifyStraightFlushOnBoardHelper(CardRank.SIX) verifyStraightFlushOnBoardHelper(CardRank.SEVEN) verifyStraightFlushOnBoardHelper(CardRank.EIGHT) verifyStraightFlushOnBoardHelper(CardRank.NINE) verifyStraightFlushOnBoardHelper(CardRank.TEN) verifyStraightFlushOnBoardHelper(CardRank.JACK) verifyStraightFlushOnBoardHelper(CardRank.QUEEN) verifyStraightFlushOnBoardHelper(CardRank.KING) verifyStraightFlushOnBoardHelper(CardRank.ACE) } private fun testDeterminePossibleHandsFourOfAKindOnBoard() { verifyFourOfAKindOnBoardHelper(CardRank.TWO) verifyFourOfAKindOnBoardHelper(CardRank.THREE) verifyFourOfAKindOnBoardHelper(CardRank.FOUR) verifyFourOfAKindOnBoardHelper(CardRank.FIVE) verifyStraightFlushOnBoardHelper(CardRank.SIX) verifyFourOfAKindOnBoardHelper(CardRank.SEVEN) verifyFourOfAKindOnBoardHelper(CardRank.EIGHT) verifyStraightFlushOnBoardHelper(CardRank.NINE) verifyFourOfAKindOnBoardHelper(CardRank.TEN) verifyFourOfAKindOnBoardHelper(CardRank.JACK) verifyFourOfAKindOnBoardHelper(CardRank.QUEEN) verifyStraightFlushOnBoardHelper(CardRank.KING) verifyFourOfAKindOnBoardHelper(CardRank.ACE) } private fun testDeterminePossibleHandsFullHouseOnBoard() { verifyFullHouseOnBoardHelper(CardRank.TWO, CardRank.ACE) verifyFullHouseOnBoardHelper(CardRank.ACE, CardRank.TWO) verifyFullHouseOnBoardHelper(CardRank.KING, CardRank.ACE) verifyFullHouseOnBoardHelper(CardRank.ACE, CardRank.KING) verifyFullHouseOnBoardHelper(CardRank.KING, CardRank.QUEEN) verifyFullHouseOnBoardHelper(CardRank.EIGHT, CardRank.SEVEN) } private fun testDeterminePossibleHandsFlushOnBoard() { var card1 = Card(0, CardRank.ACE, CardSuit.HEARTS) var card2 = Card(0, CardRank.TWO, CardSuit.HEARTS) var card3 = Card(0, CardRank.SIX, CardSuit.HEARTS) var card4 = Card(0, CardRank.SEVEN, CardSuit.HEARTS) var card5 = Card(0, CardRank.KING, CardSuit.HEARTS) var flopCards = FlopCards(card1, card2, card3) var turnCard = TurnCard(card4) var riverCard = RiverCard(card5) var handRankings: List<HandRanking?> = bso.determinePossibleHands(flopCards, turnCard, riverCard) assertEquals(1, handRankings.size) assertEquals(HandRanking.FLUSH, handRankings[0]) card1 = Card(0, CardRank.THREE, CardSuit.SPADES) card2 = Card(0, CardRank.TWO, CardSuit.SPADES) card3 = Card(0, CardRank.EIGHT, CardSuit.SPADES) card4 = Card(0, CardRank.NINE, CardSuit.SPADES) card5 = Card(0, CardRank.KING, CardSuit.SPADES) flopCards = FlopCards(card1, card2, card3) turnCard = TurnCard(card4) riverCard = RiverCard(card5) handRankings = bso.determinePossibleHands(flopCards, turnCard, riverCard) assertEquals(1, handRankings.size) assertEquals(HandRanking.FLUSH, handRankings[0]) } private fun testDeterminePossibleHandsStraightOnBoard() { verifyStraightOnBoardHelper(CardRank.FIVE) verifyStraightOnBoardHelper(CardRank.SIX) verifyStraightOnBoardHelper(CardRank.SEVEN) verifyStraightOnBoardHelper(CardRank.EIGHT) verifyStraightOnBoardHelper(CardRank.NINE) verifyStraightOnBoardHelper(CardRank.TEN) verifyStraightOnBoardHelper(CardRank.JACK) verifyStraightOnBoardHelper(CardRank.QUEEN) verifyStraightOnBoardHelper(CardRank.KING) verifyStraightOnBoardHelper(CardRank.ACE) } private fun testDeterminePossibleHandsThreeOfAKindOnBoard() { verifyThreeOfAKindOnBoardHelper(CardRank.TWO) verifyThreeOfAKindOnBoardHelper(CardRank.THREE) verifyThreeOfAKindOnBoardHelper(CardRank.FOUR) verifyThreeOfAKindOnBoardHelper(CardRank.FIVE) verifyThreeOfAKindOnBoardHelper(CardRank.SIX) verifyThreeOfAKindOnBoardHelper(CardRank.SEVEN) verifyThreeOfAKindOnBoardHelper(CardRank.EIGHT) verifyThreeOfAKindOnBoardHelper(CardRank.NINE) verifyThreeOfAKindOnBoardHelper(CardRank.TEN) verifyThreeOfAKindOnBoardHelper(CardRank.JACK) verifyThreeOfAKindOnBoardHelper(CardRank.QUEEN) verifyThreeOfAKindOnBoardHelper(CardRank.KING) verifyThreeOfAKindOnBoardHelper(CardRank.ACE) } private fun testDeterminePossibleHandsTwoPairOnBoard() { verifyTwoPairOnBoardHelper(CardRank.TWO, CardRank.KING) verifyTwoPairOnBoardHelper(CardRank.THREE, CardRank.ACE) verifyTwoPairOnBoardHelper(CardRank.FOUR, CardRank.SEVEN) verifyTwoPairOnBoardHelper(CardRank.FIVE, CardRank.EIGHT) verifyTwoPairOnBoardHelper(CardRank.SIX, CardRank.ACE) verifyTwoPairOnBoardHelper(CardRank.SEVEN, CardRank.TWO) verifyTwoPairOnBoardHelper(CardRank.EIGHT, CardRank.NINE) verifyTwoPairOnBoardHelper(CardRank.NINE, CardRank.TEN) verifyTwoPairOnBoardHelper(CardRank.TEN, CardRank.JACK) verifyTwoPairOnBoardHelper(CardRank.JACK, CardRank.THREE) verifyTwoPairOnBoardHelper(CardRank.QUEEN, CardRank.KING) verifyTwoPairOnBoardHelper(CardRank.KING, CardRank.SIX) verifyTwoPairOnBoardHelper(CardRank.ACE, CardRank.KING) } private fun testDeterminePossibleHandsOnePairOnBoard() { verifyOnePairOnBoardHelper(CardRank.TWO) verifyOnePairOnBoardHelper(CardRank.THREE) verifyOnePairOnBoardHelper(CardRank.FOUR) verifyOnePairOnBoardHelper(CardRank.FIVE) verifyOnePairOnBoardHelper(CardRank.SIX) verifyOnePairOnBoardHelper(CardRank.SEVEN) verifyOnePairOnBoardHelper(CardRank.EIGHT) verifyOnePairOnBoardHelper(CardRank.NINE) verifyOnePairOnBoardHelper(CardRank.TEN) verifyOnePairOnBoardHelper(CardRank.JACK) verifyOnePairOnBoardHelper(CardRank.QUEEN) verifyOnePairOnBoardHelper(CardRank.KING) verifyOnePairOnBoardHelper(CardRank.ACE) } private fun verifyStraightFlushOnBoardHelper(cardRank: CardRank) { val commonCards = createStraightFlush(cardRank) val handRankings = bso.determinePossibleHands( commonCards.flopCards, commonCards.turnCard, commonCards.riverCard ) assertEquals(1, handRankings.size) assertEquals(HandRanking.STRAIGHT_FLUSH, handRankings[0]) } private fun verifyFourOfAKindOnBoardHelper(cardRank: CardRank) { val commonCards = createFourOfAKind(cardRank) val handRankings = bso.determinePossibleHands( commonCards.flopCards, commonCards.turnCard, commonCards.riverCard ) assertEquals(1, handRankings.size) assertEquals(HandRanking.FOUR_OF_A_KIND, handRankings[0]) } private fun verifyFullHouseOnBoardHelper(primaryCardRank: CardRank, secondaryCardRank: CardRank) { val commonCards = createFullHouse(primaryCardRank, secondaryCardRank) val handRankings = bso.determinePossibleHands( commonCards.flopCards, commonCards.turnCard, commonCards.riverCard ) assertEquals(2, handRankings.size) assertEquals(HandRanking.FULL_HOUSE, handRankings[0]) assertEquals(HandRanking.FOUR_OF_A_KIND, handRankings[1]) } private fun verifyStraightOnBoardHelper(cardRank: CardRank) { val commonCards = createStraight(cardRank) val handRankings = bso.determinePossibleHands( commonCards.flopCards, commonCards.turnCard, commonCards.riverCard ) assertEquals(1, handRankings.size) assertEquals(HandRanking.STRAIGHT, handRankings[0]) } private fun verifyThreeOfAKindOnBoardHelper(cardRank: CardRank) { val commonCards = createThreeOfAKind(cardRank) val handRankings = bso.determinePossibleHands( commonCards.flopCards, commonCards.turnCard, commonCards.riverCard ) assertEquals(3, handRankings.size) assertEquals(HandRanking.THREE_OF_A_KIND, handRankings[0]) assertEquals(HandRanking.FULL_HOUSE, handRankings[1]) assertEquals(HandRanking.FOUR_OF_A_KIND, handRankings[2]) } private fun verifyTwoPairOnBoardHelper(primaryCardRank: CardRank, secondaryCardRank: CardRank) { val commonCards = createTwoPair(primaryCardRank, secondaryCardRank) val handRankings = bso.determinePossibleHands( commonCards.flopCards, commonCards.turnCard, commonCards.riverCard ) assertEquals(3, handRankings.size) assertEquals(HandRanking.TWO_PAIR, handRankings[0]) assertEquals(HandRanking.FULL_HOUSE, handRankings[1]) assertEquals(HandRanking.FOUR_OF_A_KIND, handRankings[2]) } private fun verifyOnePairOnBoardHelper(cardRank: CardRank) { val commonCards = createOnePair(cardRank) val handRankings = bso.determinePossibleHands( commonCards.flopCards, commonCards.turnCard, commonCards.riverCard ) assertEquals(5, handRankings.size) assertEquals(HandRanking.ONE_PAIR, handRankings[0]) assertEquals(HandRanking.TWO_PAIR, handRankings[1]) assertEquals(HandRanking.THREE_OF_A_KIND, handRankings[2]) assertEquals(HandRanking.FULL_HOUSE, handRankings[3]) assertEquals(HandRanking.FOUR_OF_A_KIND, handRankings[4]) } private fun createThreeOfAKind(cardRank: CardRank): CommonCards { val card1 = Card(0, cardRank, CardSuit.CLUBS) val card4 = Card(0, cardRank, CardSuit.SPADES) val card2 = Card(0, cardRank, CardSuit.DIAMONDS) val card3: Card val card5: Card if (cardRank.ordinal < 7) { card3 = Card(0, CardRank.KING, CardSuit.HEARTS) card5 = Card(0, CardRank.QUEEN, CardSuit.HEARTS) } else { card3 = Card(0, CardRank.TWO, CardSuit.HEARTS) card5 = Card(0, CardRank.SIX, CardSuit.HEARTS) } val flopCards = FlopCards(card2, card4, card5) val turnCard = TurnCard(card3) val riverCard = RiverCard(card1) return CommonCards(flopCards, turnCard, riverCard) } private fun createTwoPair(primaryCardRank: CardRank, secondaryCardRank: CardRank): CommonCards { val card1 = Card(0, primaryCardRank, CardSuit.CLUBS) val card4 = Card(0, primaryCardRank, CardSuit.SPADES) val card2 = Card(0, secondaryCardRank, CardSuit.HEARTS) val card3 = Card(0, secondaryCardRank, CardSuit.SPADES) val card5: Card card5 = if (primaryCardRank.ordinal < 7) { if (secondaryCardRank == CardRank.KING) { Card(0, CardRank.QUEEN, CardSuit.HEARTS) } else { Card(0, CardRank.KING, CardSuit.HEARTS) } } else { if (secondaryCardRank == CardRank.THREE) { Card(0, CardRank.TWO, CardSuit.HEARTS) } else { Card(0, CardRank.THREE, CardSuit.HEARTS) } } val flopCards = FlopCards(card2, card4, card5) val turnCard = TurnCard(card3) val riverCard = RiverCard(card1) return CommonCards(flopCards, turnCard, riverCard) } private fun createOnePair(cardRank: CardRank): CommonCards { val card1 = Card(0, cardRank, CardSuit.CLUBS) val card4 = Card(0, cardRank, CardSuit.SPADES) val card2: Card val card3: Card val card5: Card if (cardRank == CardRank.TWO) { card2 = Card(0, CardRank.ACE, CardSuit.CLUBS) card3 = Card(0, CardRank.SEVEN, CardSuit.DIAMONDS) card5 = Card(0, CardRank.QUEEN, CardSuit.HEARTS) } else if (cardRank == CardRank.SEVEN) { card2 = Card(0, CardRank.TWO, CardSuit.CLUBS) card3 = Card(0, CardRank.ACE, CardSuit.DIAMONDS) card5 = Card(0, CardRank.QUEEN, CardSuit.HEARTS) } else if (cardRank == CardRank.QUEEN) { card2 = Card(0, CardRank.TWO, CardSuit.CLUBS) card3 = Card(0, CardRank.SEVEN, CardSuit.DIAMONDS) card5 = Card(0, CardRank.KING, CardSuit.HEARTS) } else { card2 = Card(0, CardRank.TWO, CardSuit.CLUBS) card3 = Card(0, CardRank.SEVEN, CardSuit.DIAMONDS) card5 = Card(0, CardRank.QUEEN, CardSuit.HEARTS) } val flopCards = FlopCards(card2, card4, card5) val turnCard = TurnCard(card3) val riverCard = RiverCard(card1) return CommonCards(flopCards, turnCard, riverCard) } private fun createStraight(cardRank: CardRank): CommonCards { val cardRanks = CardRank.values() val card1: Card // if 5, make the first one an ace for the wheel card1 = if (cardRank.ordinal == 3) { Card(0, CardRank.ACE, CardSuit.HEARTS) } else { Card(0, cardRanks[cardRank.ordinal - 4], CardSuit.HEARTS) } val card2 = Card(0, cardRanks[cardRank.ordinal - 3], CardSuit.CLUBS) val card3 = Card(0, cardRanks[cardRank.ordinal - 2], CardSuit.DIAMONDS) val card4 = Card(0, cardRanks[cardRank.ordinal - 1], CardSuit.SPADES) val card5 = Card(0, cardRank, CardSuit.HEARTS) val flopCards = FlopCards(card2, card4, card5) val turnCard = TurnCard(card3) val riverCard = RiverCard(card1) return CommonCards(flopCards, turnCard, riverCard) } private fun createStraightFlush(cardRank: CardRank): CommonCards { val cardRanks = CardRank.values() val card1: Card // if 5, make the first one an ace for the wheel card1 = if (cardRank.ordinal == 3) { Card(0, CardRank.ACE, CardSuit.HEARTS) } else { Card(0, cardRanks[cardRank.ordinal - 4], CardSuit.HEARTS) } val card2 = Card(0, cardRanks[cardRank.ordinal - 3], CardSuit.HEARTS) val card3 = Card(0, cardRanks[cardRank.ordinal - 2], CardSuit.HEARTS) val card4 = Card(0, cardRanks[cardRank.ordinal - 1], CardSuit.HEARTS) val card5 = Card(0, cardRank, CardSuit.HEARTS) val flopCards = FlopCards(card1, card3, card4) val turnCard = TurnCard(card5) val riverCard = RiverCard(card2) return CommonCards(flopCards, turnCard, riverCard) } private fun createFourOfAKind(cardRank: CardRank): CommonCards { val card1 = Card(0, cardRank, CardSuit.HEARTS) val card2 = Card(0, cardRank, CardSuit.CLUBS) val card3 = Card(0, cardRank, CardSuit.DIAMONDS) val card4 = Card(0, cardRank, CardSuit.SPADES) val card5: Card card5 = if (cardRank === CardRank.EIGHT) { Card(0, CardRank.THREE, CardSuit.HEARTS) } else { Card(0, cardRank, CardSuit.HEARTS) } val flopCards = FlopCards(card1, card3, card4) val turnCard = TurnCard(card5) val riverCard = RiverCard(card2) return CommonCards(flopCards, turnCard, riverCard) } private fun createFullHouse( primaryCardRank: CardRank, secondaryCardRank: CardRank ): CommonCards { val card1 = Card(0, primaryCardRank, CardSuit.HEARTS) val card2 = Card(0, secondaryCardRank, CardSuit.CLUBS) val card3 = Card(0, secondaryCardRank, CardSuit.DIAMONDS) val card4 = Card(0, primaryCardRank, CardSuit.SPADES) val card5 = Card(0, primaryCardRank, CardSuit.HEARTS) val flopCards = FlopCards(card1, card3, card4) val turnCard = TurnCard(card5) val riverCard = RiverCard(card2) return CommonCards(flopCards, turnCard, riverCard) } }
gpl-2.0
62aa8b77a76351105c67f466beae41b8
47.188525
105
0.695943
3.862148
false
true
false
false
nemerosa/ontrack
ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/settings/AutoVersioningSettingsProvider.kt
1
1701
package net.nemerosa.ontrack.extension.av.settings import net.nemerosa.ontrack.model.settings.SettingsProvider import net.nemerosa.ontrack.model.support.SettingsRepository import net.nemerosa.ontrack.model.support.getBoolean import org.springframework.stereotype.Component import java.time.Duration @Component class AutoVersioningSettingsProvider( private val settingsRepository: SettingsRepository, ) : SettingsProvider<AutoVersioningSettings> { override fun getSettings() = AutoVersioningSettings( enabled = settingsRepository.getBoolean( AutoVersioningSettings::enabled, AutoVersioningSettings.DEFAULT_ENABLED ), auditRetentionDuration = settingsRepository.getString( AutoVersioningSettings::class.java, AutoVersioningSettings::auditRetentionDuration.name, "" ) ?.takeIf { it.isNotBlank() } ?.let { Duration.parse(it) } ?: AutoVersioningSettings.DEFAULT_AUDIT_RETENTION_DURATION, auditCleanupDuration = settingsRepository.getString( AutoVersioningSettings::class.java, AutoVersioningSettings::auditCleanupDuration.name, "" ) ?.takeIf { it.isNotBlank() } ?.let { Duration.parse(it) } ?: AutoVersioningSettings.DEFAULT_AUDIT_CLEANUP_DURATION, buildLinks = settingsRepository.getBoolean( AutoVersioningSettings::class.java, AutoVersioningSettings::buildLinks.name, AutoVersioningSettings.DEFAULT_BUILD_LINKS ) ) override fun getSettingsClass(): Class<AutoVersioningSettings> = AutoVersioningSettings::class.java }
mit
2eb54a92eb39c790a6f06b6ebd6108bd
38.581395
103
0.697825
5.434505
false
false
false
false
softelnet/sponge
sponge-kotlin/src/test/kotlin/examples/KnowledgeBaseAutoEnable.kt
1
2515
/* * Sponge Knowledge Base * Auto-enable */ package org.openksavi.sponge.kotlin.examples import org.openksavi.sponge.event.Event import org.openksavi.sponge.kotlin.KAction import org.openksavi.sponge.kotlin.KCorrelator import org.openksavi.sponge.kotlin.KFilter import org.openksavi.sponge.kotlin.KKnowledgeBase import org.openksavi.sponge.kotlin.KRule import org.openksavi.sponge.kotlin.KTrigger import java.util.concurrent.atomic.AtomicInteger class KnowledgeBaseAutoEnable : KKnowledgeBase() { override fun onInit() { // Variables for assertions only sponge.setVariable("counter", AtomicInteger(0)) } class AutoAction : KAction() { fun onCall(): Any? { logger.debug("Running") sponge.getVariable<AtomicInteger>("counter").incrementAndGet() return null } } class AutoFilter : KFilter() { override fun onConfigure() { withEvent("e1") } override fun onAccept(event: Event): Boolean { logger.debug("Received event: {}", event.name) sponge.getVariable<AtomicInteger>("counter").incrementAndGet() return true } } class AutoTrigger : KTrigger() { override fun onConfigure() { withEvent("e1") } override fun onRun(event: Event) { logger.debug("Received event: {}", event.name) sponge.getVariable<AtomicInteger>("counter").incrementAndGet() } } class AutoRule : KRule() { override fun onConfigure() { withEvents("e1", "e2") } override fun onRun(event: Event) { logger.debug("Running for sequence: {}", eventSequence) sponge.getVariable<AtomicInteger>("counter").incrementAndGet() } } class AutoCorrelator : KCorrelator() { override fun onConfigure() { withEvents("e1", "e2") } override fun onAcceptAsFirst(event: Event) = event.name == "e1" override fun onEvent(event: Event) { logger.debug("Received event: {}", event.name) if (event.name == "e2") { sponge.getVariable<AtomicInteger>("counter").incrementAndGet() finish() } } } override fun onStartup() { sponge.call("AutoAction") sponge.event("e1").send() sponge.event("e2").send() } }
apache-2.0
53117ac6a1f47fc51d2f7a79854946c9
27.940476
78
0.580915
4.589416
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/components/floatingbottombar/ExpandableItemViewController.kt
1
10997
package com.pennapps.labs.pennmobile.components.floatingbottombar import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.res.ColorStateList import android.graphics.Typeface import android.graphics.drawable.Drawable import android.os.Build import android.text.Spannable import android.text.SpannableString import android.text.style.StyleSpan import android.util.DisplayMetrics import android.view.Gravity import android.view.View import android.widget.FrameLayout import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.annotation.FloatRange import androidx.annotation.Px import androidx.annotation.VisibleForTesting import androidx.appcompat.widget.AppCompatImageView import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintSet import androidx.core.content.ContextCompat import androidx.core.view.AccessibilityDelegateCompat import androidx.core.view.ViewCompat.setAccessibilityDelegate import androidx.core.view.accessibility.AccessibilityNodeInfoCompat import com.google.android.material.textview.MaterialTextView import com.pennapps.labs.pennmobile.R import com.pennapps.labs.pennmobile.components.floatingbottombar.utils.DrawableHelper import com.pennapps.labs.pennmobile.components.floatingbottombar.utils.createChain internal open class ExpandableItemViewController( internal val menuItem: ExpandableBottomBarMenuItem, private val itemView: View, private val textView: TextView, private val iconView: ImageView, private val backgroundCornerRadius: Float, private val backgroundOpacity: Float, private val imageView: ImageView, private val highlight: ImageView ) { fun setAccessibleWith( prev: ExpandableItemViewController?, next: ExpandableItemViewController? ) { setAccessibilityDelegate(itemView, object : AccessibilityDelegateCompat() { override fun onInitializeAccessibilityNodeInfo( host: View?, info: AccessibilityNodeInfoCompat? ) { info?.setTraversalAfter(prev?.itemView) info?.setTraversalBefore(next?.itemView) super.onInitializeAccessibilityNodeInfo(host, info) } }) } fun deselect() { itemView.background = null textView.visibility = View.INVISIBLE textView.isSelected = false iconView.isSelected = false itemView.isSelected = false imageView.visibility = View.GONE highlight.visibility = View.INVISIBLE } fun select() { textView.visibility = View.VISIBLE textView.isSelected = true iconView.isSelected = true itemView.isSelected = true imageView.visibility = View.VISIBLE highlight.visibility = View.VISIBLE //itemView.background = createHighlightedMenuShape() } @VisibleForTesting internal open fun createHighlightedMenuShape(): Drawable { return DrawableHelper.createShapeDrawable( menuItem.activeColor, backgroundCornerRadius, backgroundOpacity ) } fun attachTo( parent: ConstraintLayout, previousIconId: Int, nextIconId: Int, menuItemHorizontalMarginLeft: Int, menuItemHorizontalMarginRight: Int, menuItemVerticalMarginTop: Int, menuItemVerticalMarginBottom: Int ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { textView.setTextAppearance(R.style.fontBottomBar) } val activity = parent.context as Activity val displayMetrics = DisplayMetrics() activity.windowManager.defaultDisplay.getMetrics(displayMetrics) var width = displayMetrics.widthPixels var height = displayMetrics.heightPixels val lp = ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.MATCH_CONSTRAINT, ConstraintLayout.LayoutParams.MATCH_PARENT ) lp.setMargins( menuItemHorizontalMarginLeft, menuItemVerticalMarginTop, menuItemHorizontalMarginRight, menuItemVerticalMarginBottom ) parent.addView(itemView, lp) val cl = ConstraintSet() cl.clone(parent) cl.connect(itemView.id, ConstraintSet.TOP, parent.id, ConstraintSet.TOP) cl.connect(itemView.id, ConstraintSet.BOTTOM, parent.id, ConstraintSet.BOTTOM) if (previousIconId == itemView.id) { cl.connect(itemView.id, ConstraintSet.START, parent.id, ConstraintSet.START) } else { cl.connect(itemView.id, ConstraintSet.START, previousIconId, ConstraintSet.END) cl.createChain(previousIconId, itemView.id, ConstraintSet.CHAIN_PACKED) } if (nextIconId == itemView.id) { cl.connect(itemView.id, ConstraintSet.END, parent.id, ConstraintSet.END) } else { cl.connect(itemView.id, ConstraintSet.END, nextIconId, ConstraintSet.START) cl.createChain(itemView.id, nextIconId, ConstraintSet.CHAIN_PACKED) } cl.applyTo(parent) } class Builder(private val menuItem: ExpandableBottomBarMenuItem) { @Px private var itemVerticalPadding: Int = 0 @Px private var itemHorizontalPadding: Int = 0 @Px @SuppressLint("SupportAnnotationUsage") private var backgroundCornerRadius: Float = 0.0f @FloatRange(from = 0.0, to = 1.0) private var backgroundOpacity: Float = 1.0f private lateinit var backgroundColorSelector: ColorStateList private lateinit var onItemClickListener: (View) -> Unit fun itemMargins( @Px itemHorizontalPadding: Int, @Px itemVerticalPadding: Int ): Builder { this.itemVerticalPadding = itemVerticalPadding this.itemHorizontalPadding = itemHorizontalPadding return this } fun itemBackground( backgroundCornerRadius: Float, @FloatRange(from = 0.0, to = 1.0) backgroundOpacity: Float ): Builder { this.backgroundCornerRadius = backgroundCornerRadius this.backgroundOpacity = backgroundOpacity return this } fun itemsColors(backgroundColorSelector: ColorStateList): Builder { this.backgroundColorSelector = backgroundColorSelector return this } fun onItemClickListener(onItemClickListener: (View) -> Unit): Builder { this.onItemClickListener = onItemClickListener return this } fun build(context: Context): ExpandableItemViewController { val itemView = LinearLayout(context).apply { id = menuItem.itemId orientation = LinearLayout.VERTICAL setPadding( itemHorizontalPadding, itemVerticalPadding, itemHorizontalPadding, itemVerticalPadding ) contentDescription = context.resources.getString( R.string.accessibility_item_description, menuItem.text ) isFocusable = true gravity = Gravity.BOTTOM } val iconView = AppCompatImageView(context).apply { setImageDrawable( DrawableHelper.createDrawable( context, menuItem.iconId, backgroundColorSelector ) ) } val textView = MaterialTextView(context).apply { val rawText = SpannableString(menuItem.text) rawText.setSpan( StyleSpan(Typeface.NORMAL), 0, rawText.length, Spannable.SPAN_PARAGRAPH ) text = rawText gravity = Gravity.CENTER visibility = View.INVISIBLE textSize = 11.5F setTextColor(backgroundColorSelector) } val itemLayoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ).apply { gravity = Gravity.CENTER setMargins(0, 0, 0, 0) } val textLayoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ).apply { gravity = Gravity.CENTER setMargins(0, 24, 0, 12) } val indicatorLayoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ).apply { gravity = Gravity.CENTER setMargins(0, 0, 0, 0) } val imageView = ImageView(context).apply { val indicator = ContextCompat .getDrawable(context, R.drawable.ic_bottom_bar_indicator) setImageDrawable(indicator) visibility = View.GONE } with(itemView) { addView(iconView, itemLayoutParams) addView(textView, textLayoutParams) addView(imageView, indicatorLayoutParams) setOnClickListener(onItemClickListener) } val highlight = ImageView(context).apply { val indicator = ContextCompat .getDrawable(context, R.drawable.ic_bottom_bar_highlight) setImageDrawable(indicator) visibility = View.GONE } val highlightLayoutParams = FrameLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM ).apply { setMargins(0, 0, 0, 0) } val frameView = FrameLayout(context).apply { id = menuItem.itemId isFocusable = true addView(itemView) addView(highlight, highlightLayoutParams) } return ExpandableItemViewController( menuItem, frameView, textView, iconView, backgroundCornerRadius, backgroundOpacity, imageView, highlight ) } } }
mit
1d26f20774514aeb0627102a4106845f
35.293729
91
0.611258
5.827769
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/search/SearchActivity.kt
1
1956
package org.wikipedia.search import android.content.Context import android.content.Intent import org.wikipedia.Constants import org.wikipedia.Constants.InvokeSource import org.wikipedia.WikipediaApp import org.wikipedia.activity.SingleFragmentActivity import org.wikipedia.analytics.IntentFunnel import org.wikipedia.util.log.L class SearchActivity : SingleFragmentActivity<SearchFragment>() { public override fun createFragment(): SearchFragment { var source = intent.getSerializableExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE) as InvokeSource? if (source == null) { when { Intent.ACTION_SEND == intent.action -> { source = InvokeSource.INTENT_SHARE } Intent.ACTION_PROCESS_TEXT == intent.action -> { source = InvokeSource.INTENT_PROCESS_TEXT } else -> { source = InvokeSource.INTENT_UNKNOWN L.logRemoteErrorIfProd(RuntimeException("Unknown intent when launching SearchActivity: " + intent.action.orEmpty())) } } } return SearchFragment.newInstance(source, intent.getStringExtra(QUERY_EXTRA), intent.getBooleanExtra(EXTRA_RETURN_LINK, false)) } companion object { const val QUERY_EXTRA = "query" const val EXTRA_RETURN_LINK = "returnLink" const val EXTRA_RETURN_LINK_TITLE = "returnLinkTitle" const val RESULT_LINK_SUCCESS = 1 fun newIntent(context: Context, source: InvokeSource, query: String?, returnLink: Boolean = false): Intent { if (source == InvokeSource.WIDGET) { IntentFunnel(WikipediaApp.instance).logSearchWidgetTap() } return Intent(context, SearchActivity::class.java) .putExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE, source) .putExtra(QUERY_EXTRA, query) .putExtra(EXTRA_RETURN_LINK, returnLink) } } }
apache-2.0
6a73bedfd981de57fe8f6da3616bcac2
43.454545
136
0.661043
4.877805
false
false
false
false
Popalay/Cardme
presentation/src/main/kotlin/com/popalay/cardme/presentation/screens/trash/TrashActivity.kt
1
2320
package com.popalay.cardme.presentation.screens.trash import android.arch.lifecycle.ViewModelProvider import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.MotionEvent import android.view.View import com.popalay.cardme.R import com.popalay.cardme.databinding.ActivityTrashBinding import com.popalay.cardme.presentation.base.RightSlidingActivity import com.popalay.cardme.utils.extensions.getDataBinding import com.popalay.cardme.utils.extensions.getViewModel import com.popalay.cardme.utils.extensions.onItemTouch import com.popalay.cardme.utils.recycler.SpacingItemDecoration import javax.inject.Inject class TrashActivity : RightSlidingActivity() { companion object { fun getIntent(context: Context) = Intent(context, TrashActivity::class.java) } @Inject lateinit var factory: ViewModelProvider.Factory private lateinit var b: ActivityTrashBinding private var isCardTouched: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) b = getDataBinding<ActivityTrashBinding>(R.layout.activity_trash) b.vm = getViewModel<TrashViewModel>(factory) initUI() } override fun getRootView(): View = b.root override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.trash_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_empty_trash -> b.vm?.emptyTrashClick?.accept(true) } return super.onOptionsItemSelected(item) } override fun canSlideRight() = !isCardTouched private fun initUI() { setSupportActionBar(b.toolbar) b.listCards.addItemDecoration(SpacingItemDecoration.create { dividerSize = resources.getDimension(R.dimen.normal).toInt() showBetween = true showOnSides = true }) b.listCards.onItemTouch { when (it.action) { MotionEvent.ACTION_MOVE, MotionEvent.ACTION_DOWN -> isCardTouched = true MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> isCardTouched = false } } } }
apache-2.0
a00fab370fa0ab715d2e0d43bb685f35
30.794521
89
0.71681
4.54902
false
false
false
false