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
JavaEden/Orchid-Core
OrchidCore/src/main/kotlin/com/eden/orchid/api/resources/resource/FileResource.kt
2
3104
package com.eden.orchid.api.resources.resource import com.eden.orchid.api.theme.pages.OrchidReference import com.eden.orchid.utilities.asInputStream import org.apache.commons.io.IOUtils import java.io.File import java.io.FileInputStream import java.io.IOException import java.io.InputStream import java.nio.file.Files import java.nio.file.Path /** * A Resource type that provides a content to a template from a resource file on disk. When used with * renderTemplate() or renderString(), this resource will supply the `page.content` variable to the template renderer as * the file contents after having the embedded data removed, and any embedded data will be available in the renderer * through the `page` variable. When used with renderRaw(), the raw contents (after having the embedded data removed) * will be written directly instead. */ class FileResource( reference: OrchidReference, val file: File ) : OrchidResource(reference) { override fun getContentStream(): InputStream { return try { FileInputStream(file) } catch (e: Exception) { e.printStackTrace() "".asInputStream() } } override fun canUpdate(): Boolean { return true } override fun canDelete(): Boolean { return true } @Throws(IOException::class) override fun update(newContent: InputStream) { Files.write(file.toPath(), IOUtils.toByteArray(newContent)) } @Throws(IOException::class) override fun delete() { file.delete() } companion object { fun pathFromFile(file: File, basePath: Path): String { return pathFromFile( file, basePath.toFile() ) } fun pathFromFile(file: File, baseFile: File): String { return pathFromFile( file, baseFile.absolutePath ) } fun pathFromFile( file: File, basePath: String ): String { var baseFilePath = basePath var filePath = file.path // normalise Windows-style backslashes to common forward slashes baseFilePath = baseFilePath.replace("\\\\".toRegex(), "/") filePath = filePath.replace("\\\\".toRegex(), "/") // Remove the common base path from the actual file path if (filePath.startsWith(baseFilePath)) { filePath = filePath.replace(baseFilePath.toRegex(), "") } if (filePath.startsWith("/")) { filePath = filePath.removePrefix("/") } // if the path is not a child of the base path (i.e. still has relative path segments), strip those away. The // resolved "path" of this resource will be the portion after those relative segments. filePath = filePath.split("/".toRegex()).toTypedArray() .filter { it: String -> !(it == ".." || it == ".") } .joinToString("/", "", "", -1, "", null) return filePath } } }
mit
a249fe95c2fe6cf488cfb17ed4759134
32.376344
121
0.605026
4.903633
false
false
false
false
jk1/intellij-community
community-guitests/testSrc/com/intellij/ide/projectWizard/kotlin/createProject/CreateJavaProjectAndConfigureKotlinGuiTest.kt
3
2673
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.projectWizard.kotlin.createProject import com.intellij.ide.projectWizard.kotlin.model.* import com.intellij.testGuiFramework.util.scenarios.projectStructureDialogScenarios import org.junit.Ignore import org.junit.Test class CreateJavaProjectAndConfigureKotlinGuiTest : KotlinGuiTestCase() { @Test @JvmName("kotlin_cfg_jvm_with_lib") fun configureKotlinJvmWithLibInJavaProject() { createJavaProject(projectFolder) configureKotlinJvm(libInPlugin = false) checkKotlinLibInProject( projectPath = projectFolder, kotlinKind = KotlinKind.JVM, kotlinVersion = KotlinTestProperties.kotlin_artifact_version) projectStructureDialogScenarios.checkKotlinLibsInStructureFromProject( projectPath = projectFolder, kotlinKind = KotlinKind.JVM) } @Test @JvmName("kotlin_cfg_jvm_no_lib") fun configureKotlinJvmInJavaProject() { createJavaProject(projectFolder) configureKotlinJvm(libInPlugin = true) projectStructureDialogScenarios.checkKotlinLibsInStructureFromPlugin( kotlinKind = KotlinKind.JVM, kotlinVersion = KotlinTestProperties.kotlin_artifact_version) } @Test @JvmName("kotlin_cfg_js_with_lib") fun configureKotlinJSWithLibInJavaProject() { createJavaProject(projectFolder) configureKotlinJs(libInPlugin = false) checkKotlinLibInProject( projectPath = projectFolder, kotlinKind = KotlinKind.JS, kotlinVersion = KotlinTestProperties.kotlin_artifact_version) projectStructureDialogScenarios.checkKotlinLibsInStructureFromProject( projectPath = projectFolder, kotlinKind = KotlinKind.JS) } @Test @JvmName("kotlin_cfg_js_no_lib") fun configureKotlinJSInJavaProject() { createJavaProject(projectFolder) configureKotlinJs(libInPlugin = true) projectStructureDialogScenarios.checkKotlinLibsInStructureFromPlugin( kotlinKind = KotlinKind.JS, kotlinVersion = KotlinTestProperties.kotlin_artifact_version) } @Test @Ignore @JvmName("kotlin_cfg_js_no_lib_from_file") fun configureKotlinJSInJavaProjectFromKotlinFile() { createJavaProject(projectFolder) // createKotlinFile( // projectName = projectFolder.name, // fileName = "K1") // ideFrame { popupClick("org.jetbrains.kotlin.idea.configuration.KotlinGradleModuleConfigurator@4aae5ef8") // } // configureKotlinJs(libInPlugin = true) // checkKotlinLibsInStructureFromPlugin( // projectType = KotlinKind.JS, // errors = collector) } }
apache-2.0
cbfa8e77fd7f389ad723507ebd0b69fc
34.653333
140
0.759446
4.346341
false
true
false
false
NiciDieNase/chaosflix
touch/src/androidTest/java/de/nicidienase/chaosflix/PersistenceTest.kt
1
972
package de.nicidienase.chaosflix import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import de.nicidienase.chaosflix.common.ChaosflixDatabase import de.nicidienase.chaosflix.common.userdata.entities.progress.PlaybackProgress import java.util.Date import org.junit.Test import org.junit.runner.RunWith /** * Created by felix on 31.10.17. */ @RunWith(AndroidJUnit4::class) class PersistenceTest { @Test fun test1() { val context = InstrumentationRegistry.getInstrumentation().context val dummyGuid = "asasdlfkjsd" val playbackProgressDao = ChaosflixDatabase.getInstance(context).playbackProgressDao() val watchDate = Date().time playbackProgressDao.saveProgress(PlaybackProgress(23, dummyGuid, 1337, watchDate)) playbackProgressDao.getProgressForEvent(dummyGuid) .observeForever { assert(it?.id == 23L && it.progress == 1337L) } } }
mit
6572189e62008bb7d7fe092e3908c62b
33.714286
94
0.752058
4.226087
false
true
false
false
himikof/intellij-rust
src/main/kotlin/org/rust/lang/core/types/Extensions.kt
1
2997
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.types import com.intellij.openapi.util.Computable import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import org.rust.ide.utils.recursionGuard import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.types.infer.* import org.rust.lang.core.types.ty.Ty import org.rust.lang.core.types.ty.TyReference import org.rust.lang.core.types.ty.TyUnknown val RsTypeReference.type: Ty get() = recursionGuard(this, Computable { inferTypeReferenceType(this) }) ?: TyUnknown val RsTypeElement.lifetimeElidable: Boolean get() { val typeOwner = owner.parent return typeOwner !is RsFieldDecl && typeOwner !is RsTupleFieldDecl && typeOwner !is RsTypeAlias } val RsTypeBearingItemElement.type: Ty get() = CachedValuesManager.getCachedValue(this, CachedValueProvider { val type = recursionGuard(this, Computable { inferDeclarationType(this) }) ?: TyUnknown CachedValueProvider.Result.create(type, PsiModificationTracker.MODIFICATION_COUNT) }) val RsFunction.inferenceContext: RsInferenceContext get() = CachedValuesManager.getCachedValue(this, CachedValueProvider { CachedValueProvider.Result.create(inferTypesIn(this), PsiModificationTracker.MODIFICATION_COUNT) }) val RsPatBinding.type: Ty get() = this.parentOfType<RsFunction>()?.inferenceContext?.getBindingType(this) ?: TyUnknown val RsExpr.type: Ty get() = this.parentOfType<RsFunction>()?.inferenceContext?.getExprType(this) ?: inferOutOfFnExpressionType(this) val RsExpr.declaration: RsCompositeElement? get() = when (this) { is RsPathExpr -> path.reference.resolve() else -> null } private val DEFAULT_MUTABILITY = true val RsExpr.isMutable: Boolean get() { return when (this) { is RsPathExpr -> { val declaration = path.reference.resolve() ?: return DEFAULT_MUTABILITY if (declaration is RsSelfParameter) return declaration.isMut if (declaration is RsPatBinding && declaration.isMut) return true if (declaration is RsConstant) return declaration.isMut val type = this.type if (type is TyReference) return type.mutable val letExpr = declaration.parentOfType<RsLetDecl>() if (letExpr != null && letExpr.eq == null) return true if (type is TyUnknown) return DEFAULT_MUTABILITY if (declaration is RsEnumVariant) return true false } // is RsFieldExpr -> (expr.type as? TyReference)?.mutable ?: DEFAULT_MUTABILITY // <- this one brings false positives without additional analysis is RsUnaryExpr -> mul != null || (expr != null && expr?.isMutable ?: DEFAULT_MUTABILITY) else -> DEFAULT_MUTABILITY } }
mit
1c55abb7cea8e6689884deba0899c9e1
37.423077
149
0.712045
4.44
false
false
false
false
daviddenton/k2
src/main/kotlin/io/github/daviddenton/k2/contract/Binding.kt
1
2180
package io.github.daviddenton.k2.contract import io.github.daviddenton.k2.http.Method import io.github.daviddenton.k2.http.Request import io.github.daviddenton.k2.util.then import io.netty.handler.codec.http.QueryStringEncoder sealed class Binding(val parameter: NamedParameter<*, *>) : (RequestBuilder) -> RequestBuilder class QueryBinding(parameter: NamedParameter<*, *>, private val value: String) : Binding(parameter) { override fun invoke(requestBuild: RequestBuilder): RequestBuilder = requestBuild.copy(queries = requestBuild.queries.plus( parameter.name to listOf(value).plus(requestBuild.queries[parameter.name] ?: emptyList()))) } class PathBinding(parameter: NamedParameter<*, *>, private val value: String) : Binding(parameter) { override fun invoke(requestBuild: RequestBuilder) = requestBuild.copy(uriParts = requestBuild.uriParts.plus(value)) } open class RequestBinding(parameter: NamedParameter<*, *>, private val into: (Request) -> Request) : Binding(parameter) { override fun invoke(requestBuild: RequestBuilder) = requestBuild.copy(fn = requestBuild.fn.then(into)) } class FormFieldBinding(parameter: NamedParameter<*, *>, private val value: String) : RequestBinding(parameter, { it }) { operator fun invoke(form: Form): Form = form + (parameter.name to value) } class HeaderBinding(parameter: NamedParameter<*, *>, private val value: String) : RequestBinding(parameter, { it.header(parameter.name to value) }) data class RequestBuilder(val method: Method, val uriParts: Iterable<String> = listOf(), val queries: Map<String, List<String>> = emptyMap(), val headers: Map<String, Set<String>> = emptyMap(), val fn: (Request) -> Request) { fun build(): Request { val baseUri = uriParts.joinToString { "/" } val uri = queries.toList().fold(QueryStringEncoder(if (baseUri.isEmpty()) "/" else baseUri), { memo, q -> q.second.forEach { v -> memo.addParam(q.first, v) } memo }).toString() return fn(Request(method, uri, "", headers)) } }
apache-2.0
6afc5d24804b90b5862b675192168620
45.382979
121
0.675688
4.113208
false
false
false
false
ayatk/biblio
app/src/main/kotlin/com/ayatk/biblio/ui/search/SearchActivity.kt
1
5643
/* * Copyright (c) 2016-2018 ayatk. * * 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.ayatk.biblio.ui.search import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.widget.SearchView import androidx.core.view.GravityCompat import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.databinding.DataBindingUtil import androidx.drawerlayout.widget.DrawerLayout import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.RecyclerView import com.ayatk.biblio.R import com.ayatk.biblio.databinding.ActivitySearchBinding import com.ayatk.biblio.di.ViewModelFactory import com.ayatk.biblio.model.Novel import com.ayatk.biblio.ui.search.item.SearchResultItem import com.ayatk.biblio.ui.util.helper.navigateToDetail import com.ayatk.biblio.ui.util.init import com.ayatk.biblio.ui.util.initBackToolbar import com.ayatk.biblio.util.Result import com.ayatk.biblio.util.ext.observe import com.xwray.groupie.GroupAdapter import com.xwray.groupie.ViewHolder import dagger.android.support.DaggerAppCompatActivity import timber.log.Timber import javax.inject.Inject class SearchActivity : DaggerAppCompatActivity() { @Inject lateinit var viewModelFactory: ViewModelFactory private val viewModel: SearchViewModel by lazy { ViewModelProvider(this, viewModelFactory).get(SearchViewModel::class.java) } private val binding: ActivitySearchBinding by lazy { DataBindingUtil.setContentView(this, R.layout.activity_search) } private lateinit var searchView: SearchView private val groupAdapter = GroupAdapter<ViewHolder>() private val onItemClickListener = { novel: Novel -> navigateToDetail(novel) } private val onDownloadClickListener: (Novel) -> Unit = { novel: Novel -> viewModel.saveNovel(novel) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) overridePendingTransition(R.anim.activity_fade_enter, R.anim.activity_fade_exit) binding.lifecycleOwner = this binding.viewModel = viewModel initBackToolbar(binding.toolbar) val scrollListener = object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { if (newState == RecyclerView.SCROLL_STATE_DRAGGING) { searchView.clearFocus() } } } binding.searchResult.init(groupAdapter, scrollListener) binding.drawerLayout.addDrawerListener( object : ActionBarDrawerToggle( this, binding.drawerLayout, R.string.drawer_open, R.string.drawer_close ) { override fun onDrawerStateChanged(newState: Int) { super.onDrawerStateChanged(newState) Timber.d(newState.toString()) if (newState != DrawerLayout.STATE_IDLE) { searchView.clearFocus() } } } ) viewModel.result.observe(this) { result -> when (result) { is Result.Success -> { val novels = result.data groupAdapter.update(novels.map { SearchResultItem(it, onItemClickListener, onDownloadClickListener) }) if (binding.searchResult.isGone) { binding.searchResult.isVisible = novels.isNotEmpty() } } is Result.Failure -> Timber.e(result.e) } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.menu_search, menu) val menuItem = menu.findItem(R.id.action_search) menuItem.setOnActionExpandListener( object : MenuItem.OnActionExpandListener { override fun onMenuItemActionExpand(item: MenuItem): Boolean = true override fun onMenuItemActionCollapse(item: MenuItem): Boolean { onBackPressed() return false } } ) menuItem.expandActionView() searchView = menuItem.actionView as SearchView searchView.setOnQueryTextListener( object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean = onQueryTextChange(query) override fun onQueryTextChange(newText: String): Boolean { viewModel.setQuery(newText) return false } } ) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.action_filter) { searchView.clearFocus() binding.drawerLayout.openDrawer(GravityCompat.END) return true } return super.onOptionsItemSelected(item) } override fun finish() { super.finish() overridePendingTransition(0, R.anim.activity_fade_exit) } override fun onBackPressed() { if (binding.drawerLayout.isDrawerOpen(GravityCompat.END)) { binding.drawerLayout.closeDrawer(GravityCompat.END) } else { finish() } } companion object { fun createIntent(context: Context): Intent = Intent(context, SearchActivity::class.java) } }
apache-2.0
99168cb3f0e41b9a308e69e6fbdfbb03
30.881356
92
0.722842
4.667494
false
false
false
false
octarine-noise/BetterFoliage
src/main/kotlin/mods/betterfoliage/client/render/RenderLog.kt
1
3118
package mods.betterfoliage.client.render import mods.betterfoliage.BetterFoliageMod import mods.betterfoliage.client.chunk.ChunkOverlayManager import mods.betterfoliage.client.config.Config import mods.betterfoliage.client.render.column.AbstractRenderColumn import mods.betterfoliage.client.render.column.ColumnRenderLayer import mods.betterfoliage.client.render.column.ColumnTextureInfo import mods.betterfoliage.client.render.column.SimpleColumnInfo import mods.octarinecore.client.render.BlockContext import mods.octarinecore.client.resource.* import mods.octarinecore.common.config.ConfigurableBlockMatcher import mods.octarinecore.common.config.ModelTextureList import mods.octarinecore.tryDefault import net.minecraft.block.BlockLog import net.minecraft.block.state.IBlockState import net.minecraft.util.EnumFacing.Axis import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.fml.relauncher.SideOnly class RenderLog : AbstractRenderColumn(BetterFoliageMod.MOD_ID) { override val addToCutout: Boolean get() = false override fun isEligible(ctx: BlockContext) = Config.enabled && Config.roundLogs.enabled && Config.blocks.logClasses.matchesClass(ctx.block) override val overlayLayer = RoundLogOverlayLayer() override val connectPerpendicular: Boolean get() = Config.roundLogs.connectPerpendicular override val radiusSmall: Double get() = Config.roundLogs.radiusSmall override val radiusLarge: Double get() = Config.roundLogs.radiusLarge init { ChunkOverlayManager.layers.add(overlayLayer) } } class RoundLogOverlayLayer : ColumnRenderLayer() { override val registry: ModelRenderRegistry<ColumnTextureInfo> get() = LogRegistry override val blockPredicate = { state: IBlockState -> Config.blocks.logClasses.matchesClass(state.block) } override val surroundPredicate = { state: IBlockState -> state.isOpaqueCube && !Config.blocks.logClasses.matchesClass(state.block) } override val connectSolids: Boolean get() = Config.roundLogs.connectSolids override val lenientConnect: Boolean get() = Config.roundLogs.lenientConnect override val defaultToY: Boolean get() = Config.roundLogs.defaultY } @SideOnly(Side.CLIENT) object LogRegistry : ModelRenderRegistryRoot<ColumnTextureInfo>() object StandardLogRegistry : ModelRenderRegistryConfigurable<ColumnTextureInfo>() { override val logger = BetterFoliageMod.logDetail override val matchClasses: ConfigurableBlockMatcher get() = Config.blocks.logClasses override val modelTextures: List<ModelTextureList> get() = Config.blocks.logModels.list override fun processModel(state: IBlockState, textures: List<String>) = SimpleColumnInfo.Key(logger, getAxis(state), textures) fun getAxis(state: IBlockState): Axis? { val axis = tryDefault(null) { state.getValue(BlockLog.LOG_AXIS).toString() } ?: state.properties.entries.find { it.key.getName().toLowerCase() == "axis" }?.value?.toString() return when (axis) { "x" -> Axis.X "y" -> Axis.Y "z" -> Axis.Z else -> null } } }
mit
ca809fec4c8bcae838c2e069ba5e1b93
45.552239
136
0.771969
4.271233
false
true
false
false
mdanielwork/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequestExecutor.kt
2
11039
// 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 org.jetbrains.plugins.github.api import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.util.EventDispatcher import com.intellij.util.ThrowableConvertor import com.intellij.util.io.HttpRequests import com.intellij.util.io.HttpSecurityUtil import com.intellij.util.io.RequestBuilder import org.jetbrains.annotations.CalledInAny import org.jetbrains.annotations.CalledInBackground import org.jetbrains.annotations.TestOnly import org.jetbrains.plugins.github.api.data.GithubErrorMessage import org.jetbrains.plugins.github.exceptions.* import org.jetbrains.plugins.github.util.GithubSettings import java.io.IOException import java.io.InputStream import java.io.InputStreamReader import java.io.Reader import java.net.HttpURLConnection import java.util.* import java.util.function.Supplier import java.util.zip.GZIPInputStream /** * Executes API requests taking care of authentication, headers, proxies, timeouts, etc. */ sealed class GithubApiRequestExecutor { protected val authDataChangedEventDispatcher = EventDispatcher.create(AuthDataChangeListener::class.java) @CalledInBackground @Throws(IOException::class, ProcessCanceledException::class) abstract fun <T> execute(indicator: ProgressIndicator, request: GithubApiRequest<T>): T @TestOnly @CalledInBackground @Throws(IOException::class, ProcessCanceledException::class) fun <T> execute(request: GithubApiRequest<T>): T = execute(EmptyProgressIndicator(), request) fun addListener(listener: AuthDataChangeListener, disposable: Disposable) = authDataChangedEventDispatcher.addListener(listener, disposable) fun addListener(disposable: Disposable, listener: () -> Unit) = authDataChangedEventDispatcher.addListener(object : AuthDataChangeListener { override fun authDataChanged() { listener() } }, disposable) class WithTokenAuth internal constructor(githubSettings: GithubSettings, token: String, private val useProxy: Boolean) : Base(githubSettings) { @Volatile internal var token: String = token set(value) { field = value authDataChangedEventDispatcher.multicaster.authDataChanged() } @Throws(IOException::class, ProcessCanceledException::class) override fun <T> execute(indicator: ProgressIndicator, request: GithubApiRequest<T>): T { indicator.checkCanceled() return createRequestBuilder(request) .tuner { connection -> request.additionalHeaders.forEach(connection::addRequestProperty) connection.addRequestProperty(HttpSecurityUtil.AUTHORIZATION_HEADER_NAME, "Token $token") } .useProxy(useProxy) .execute(request, indicator) } } class WithBasicAuth internal constructor(githubSettings: GithubSettings, private val login: String, private val password: CharArray, private val twoFactorCodeSupplier: Supplier<String?>) : Base(githubSettings) { private var twoFactorCode: String? = null @Throws(IOException::class, ProcessCanceledException::class) override fun <T> execute(indicator: ProgressIndicator, request: GithubApiRequest<T>): T { indicator.checkCanceled() val basicHeaderValue = HttpSecurityUtil.createBasicAuthHeaderValue(login, password) return executeWithBasicHeader(indicator, request, basicHeaderValue) } private fun <T> executeWithBasicHeader(indicator: ProgressIndicator, request: GithubApiRequest<T>, header: String): T { indicator.checkCanceled() return try { createRequestBuilder(request) .tuner { connection -> request.additionalHeaders.forEach(connection::addRequestProperty) connection.addRequestProperty(HttpSecurityUtil.AUTHORIZATION_HEADER_NAME, "Basic $header") twoFactorCode?.let { connection.addRequestProperty(OTP_HEADER_NAME, it) } } .execute(request, indicator) } catch (e: GithubTwoFactorAuthenticationException) { twoFactorCode = twoFactorCodeSupplier.get() ?: throw e executeWithBasicHeader(indicator, request, header) } } } abstract class Base(private val githubSettings: GithubSettings) : GithubApiRequestExecutor() { protected fun <T> RequestBuilder.execute(request: GithubApiRequest<T>, indicator: ProgressIndicator): T { indicator.checkCanceled() try { LOG.debug("Request: ${request.url} ${request.operationName} : Connecting") return connect { val connection = it.connection as HttpURLConnection if (request is GithubApiRequest.WithBody) { LOG.debug("Request: ${connection.requestMethod} ${connection.url} with body:\n${request.body} : Connected") request.body?.let { body -> it.write(body) } } else { LOG.debug("Request: ${connection.requestMethod} ${connection.url} : Connected") } checkResponseCode(connection) indicator.checkCanceled() val result = request.extractResult(createResponse(it, indicator)) LOG.debug("Request: ${connection.requestMethod} ${connection.url} : Result extracted") result } } catch (e: GithubStatusCodeException) { @Suppress("UNCHECKED_CAST") if (request is GithubApiRequest.Get.Optional<*> && e.statusCode == HttpURLConnection.HTTP_NOT_FOUND) return null as T else throw e } catch (e: GithubConfusingException) { if (request.operationName != null) { val errorText = "Can't ${request.operationName}" e.setDetails(errorText) LOG.debug(errorText, e) } throw e } } protected fun createRequestBuilder(request: GithubApiRequest<*>): RequestBuilder { return when (request) { is GithubApiRequest.Get -> HttpRequests.request(request.url) is GithubApiRequest.Post -> HttpRequests.post(request.url, request.bodyMimeType) is GithubApiRequest.Put -> HttpRequests.put(request.url, request.bodyMimeType) is GithubApiRequest.Patch -> HttpRequests.patch(request.url, request.bodyMimeType) is GithubApiRequest.Head -> HttpRequests.head(request.url) is GithubApiRequest.Delete -> HttpRequests.delete(request.url) else -> throw UnsupportedOperationException("${request.javaClass} is not supported") } .connectTimeout(githubSettings.connectionTimeout) .userAgent("Intellij IDEA Github Plugin") .throwStatusCodeException(false) .forceHttps(true) .accept(request.acceptMimeType) } @Throws(IOException::class) private fun checkResponseCode(connection: HttpURLConnection) { if (connection.responseCode < 400) return val statusLine = "${connection.responseCode} ${connection.responseMessage}" val errorText = getErrorText(connection) LOG.debug("Request: ${connection.requestMethod} ${connection.url} : Error ${statusLine} body:\n${errorText}") val jsonError = getJsonError(connection, errorText) jsonError ?: LOG.debug("Request: ${connection.requestMethod} ${connection.url} : Unable to parse JSON error") throw when (connection.responseCode) { HttpURLConnection.HTTP_UNAUTHORIZED, HttpURLConnection.HTTP_PAYMENT_REQUIRED, HttpURLConnection.HTTP_FORBIDDEN -> { val otpHeader = connection.getHeaderField(OTP_HEADER_NAME) if (otpHeader != null && otpHeader.contains("required", true)) { GithubTwoFactorAuthenticationException(jsonError?.presentableError ?: errorText) } else if (jsonError?.containsReasonMessage("API rate limit exceeded") == true) { GithubRateLimitExceededException(jsonError.presentableError) } else GithubAuthenticationException("Request response: " + (jsonError?.presentableError ?: errorText)) } else -> { if (jsonError != null) { GithubStatusCodeException("$statusLine - ${jsonError.presentableError}", jsonError, connection.responseCode) } else { GithubStatusCodeException("$statusLine - ${errorText}", connection.responseCode) } } } } private fun getErrorText(connection: HttpURLConnection): String { val errorStream = connection.errorStream ?: return "" val stream = if (connection.contentEncoding == "gzip") GZIPInputStream(errorStream) else errorStream return InputStreamReader(stream, Charsets.UTF_8).use { it.readText() } } private fun getJsonError(connection: HttpURLConnection, errorText: String): GithubErrorMessage? { if (!connection.contentType.startsWith(GithubApiContentHelper.JSON_MIME_TYPE)) return null return try { return GithubApiContentHelper.fromJson(errorText) } catch (jse: GithubJsonException) { null } } private fun createResponse(request: HttpRequests.Request, indicator: ProgressIndicator): GithubApiResponse { return object : GithubApiResponse { override fun findHeader(headerName: String): String? = request.connection.getHeaderField(headerName) override fun <T> readBody(converter: ThrowableConvertor<Reader, T, IOException>): T = request.getReader(indicator).use { converter.convert(it) } override fun <T> handleBody(converter: ThrowableConvertor<InputStream, T, IOException>): T = request.inputStream.use { converter.convert(it) } } } } class Factory internal constructor(private val githubSettings: GithubSettings) { @CalledInAny fun create(token: String): WithTokenAuth { return create(token, true) } @CalledInAny fun create(token: String, useProxy: Boolean = true): WithTokenAuth { return GithubApiRequestExecutor.WithTokenAuth(githubSettings, token, useProxy) } @CalledInAny internal fun create(login: String, password: CharArray, twoFactorCodeSupplier: Supplier<String?>): WithBasicAuth { return GithubApiRequestExecutor.WithBasicAuth(githubSettings, login, password, twoFactorCodeSupplier) } companion object { @JvmStatic fun getInstance(): Factory = service() } } companion object { private val LOG = logger<GithubApiRequestExecutor>() private const val OTP_HEADER_NAME = "X-GitHub-OTP" } interface AuthDataChangeListener : EventListener { fun authDataChanged() } }
apache-2.0
73608e7ac033fcc2a66c536c959a8928
41.790698
140
0.699792
5.020009
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/parser/internal/service/utils/ExpressionHelper.kt
1
3350
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.parser.internal.service.utils import java.lang.NumberFormatException import java.util.* import org.apache.commons.lang3.math.NumberUtils import org.hisp.dhis.android.core.datavalue.DataValue import org.hisp.dhis.android.core.parser.internal.service.dataobject.DataElementObject import org.hisp.dhis.android.core.parser.internal.service.dataobject.DataElementOperandObject import org.hisp.dhis.android.core.parser.internal.service.dataobject.DimensionalItemObject internal object ExpressionHelper { @JvmStatic fun getValueMap(dataValues: List<DataValue>): Map<DimensionalItemObject, Double> { val valueMap: MutableMap<DimensionalItemObject, Double> = HashMap() for (dataValue in dataValues) { val deId = dataValue.dataElement() val cocId = dataValue.categoryOptionCombo() val dataElementItem: DimensionalItemObject = DataElementObject.create(deId) addDimensionalItemValueToMap(dataElementItem, dataValue.value(), valueMap) val dataElementOperandItem: DimensionalItemObject = DataElementOperandObject.create(deId, cocId) addDimensionalItemValueToMap(dataElementOperandItem, dataValue.value(), valueMap) } return valueMap } private fun addDimensionalItemValueToMap( item: DimensionalItemObject, value: String?, valueMap: MutableMap<DimensionalItemObject, Double> ) { try { val newValue = NumberUtils.createDouble(value) val existingValue = valueMap[item] val result = (existingValue ?: 0.0) + newValue valueMap[item] = result } catch (e: NumberFormatException) { // Ignore non-numeric values } } }
bsd-3-clause
e9e9f22d4a9424899c206b1f113bc850
47.550725
108
0.740896
4.545455
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/AbstractKotlinExceptionFilterTest.kt
3
5607
// 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.debugger.test import com.intellij.execution.filters.FileHyperlinkInfo import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.ThrowableRunnable import org.jetbrains.kotlin.idea.codegen.forTestCompile.ForTestCompileRuntime import org.jetbrains.kotlin.idea.core.util.toVirtualFile import org.jetbrains.kotlin.idea.debugger.InlineFunctionHyperLinkInfo import org.jetbrains.kotlin.idea.debugger.KotlinExceptionFilterFactory import org.jetbrains.kotlin.idea.test.* import java.io.File import java.lang.reflect.InvocationTargetException import java.net.URLClassLoader abstract class AbstractKotlinExceptionFilterTest : KotlinLightCodeInsightFixtureTestCase() { private companion object { val MOCK_LIBRARY_SOURCES = IDEA_TEST_DATA_DIR.resolve("debugger/mockLibraryForExceptionFilter") } private lateinit var mockLibraryFacility: MockLibraryFacility override fun fileName(): String { val testName = getTestName(true) return "$testName/$testName.kt" } override fun setUp() { super.setUp() val mainFile = dataFile() val testDir = mainFile.parentFile ?: error("Invalid test directory") val fileText = FileUtil.loadFile(mainFile, true) val extraOptions = InTextDirectivesUtils.findListWithPrefixes(fileText, "// !LANGUAGE: ").map { "-XXLanguage:$it" } mockLibraryFacility = MockLibraryFacility( sources = listOf(MOCK_LIBRARY_SOURCES, testDir), options = extraOptions ) mockLibraryFacility.setUp(module) } override fun tearDown() { runAll( ThrowableRunnable { mockLibraryFacility.tearDown(module) }, ThrowableRunnable { super.tearDown() } ) } protected fun doTest(unused: String) { val mainFile = dataFile() val testDir = mainFile.parentFile ?: error("Invalid test directory") val fileText = FileUtil.loadFile(mainFile, true) val mainClass = InTextDirectivesUtils.stringWithDirective(fileText, "MAIN_CLASS") val prefix = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// PREFIX: ") ?: "at" val stackTraceElement = getStackTraceElement(mainClass) val stackTraceString = stackTraceElement.toString() val text = "$prefix $stackTraceString" val filter = KotlinExceptionFilterFactory().create(GlobalSearchScope.allScope(project)) var result = filter.applyFilter(text, text.length) ?: throw AssertionError("Couldn't apply filter to $stackTraceElement") if (InTextDirectivesUtils.isDirectiveDefined(fileText, "SMAP_APPLIED")) { val info = result.firstHyperlinkInfo as FileHyperlinkInfo val descriptor = info.descriptor!! val file = descriptor.file val line = descriptor.line + 1 val newStackString = stackTraceString .replace(mainFile.name, file.name) .replace(Regex(":\\d+\\)"), ":$line)") val newText = "$prefix $newStackString" result = filter.applyFilter(newText, newText.length) ?: throw AssertionError("Couldn't apply filter to $stackTraceElement") } val info = result.firstHyperlinkInfo as FileHyperlinkInfo val descriptor = if (InTextDirectivesUtils.isDirectiveDefined(fileText, "NAVIGATE_TO_CALL_SITE")) { (info as? InlineFunctionHyperLinkInfo)?.callSiteDescriptor } else { info.descriptor } if (descriptor == null) { throw AssertionError("`$stackTraceString` did not resolve to an inline function call") } val expectedFileName = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// FILE: ")!! val expectedVirtualFile = File(testDir, expectedFileName).toVirtualFile() ?: File(MOCK_LIBRARY_SOURCES, expectedFileName).toVirtualFile() ?: throw AssertionError("Couldn't find file: name = $expectedFileName") val expectedLineNumber = InTextDirectivesUtils.getPrefixedInt(fileText, "// LINE: ") ?: error("Line directive not found") val document = FileDocumentManager.getInstance().getDocument(expectedVirtualFile)!! val expectedOffset = document.getLineStartOffset(expectedLineNumber - 1) val expectedLocation = "$expectedFileName:$expectedOffset" val actualLocation = descriptor.file.name + ":" + descriptor.offset assertEquals("Wrong result for line $stackTraceElement", expectedLocation, actualLocation) } private fun getStackTraceElement(mainClass: String): StackTraceElement { val libraryRoots = ModuleRootManager.getInstance(module).orderEntries().runtimeOnly().withoutSdk() .classesRoots.map { VfsUtilCore.virtualToIoFile(it).toURI().toURL() } val classLoader = URLClassLoader(libraryRoots.toTypedArray(), ForTestCompileRuntime.runtimeJarClassLoader()) return try { val clazz = classLoader.loadClass(mainClass) clazz.getMethod("box").invoke(null) throw AssertionError("class $mainClass should have box() method and throw exception") } catch (e: InvocationTargetException) { e.targetException.stackTrace[0] } } }
apache-2.0
46e817082e8ba8d884707d141cb09ecf
42.804688
135
0.705368
5.274694
false
true
false
false
Alkaizyr/Trees
src/redblacktree/RedBlackTree.kt
1
8880
package redblacktree import Tree class RedBlackTree<K: Comparable<K>, V>: Tree<K, V>, Iterable<Pair<K, V>> { var root: RBNode<K, V>? = null override fun insert(key: K, value: V) { var father: RBNode<K, V>? = null var current: RBNode<K, V>? = root while (current != null) { father = current when { key < current.key -> current = current.left key > current.key -> current = current.right key == current.key -> { current.value = value return } } } if (father == null) { root = RBNode(key, value, father, true) return } if (key < father.key) { father.left = RBNode(key, value, father, false) insertFixup(father.left) } else { father.right = RBNode(key, value, father, false) insertFixup(father.right) } } private fun insertFixup(node: RBNode<K, V>?) { var uncle: RBNode<K, V>? var current: RBNode<K, V>? = node while (current?.parent?.colorBlack == false) { if (current.parent == current.parent?.parent?.left) { uncle = current.parent?.parent?.right when { uncle?.colorBlack == false -> { current.parent?.colorBlack = true uncle.colorBlack = true current.parent?.parent?.colorBlack = false current = current.parent?.parent } current == current.parent?.right -> { current = current.parent if (current!!.parent?.parent == null) root = current.parent current.rotateLeft() } current == current.parent?.left -> { if (current.parent?.parent?.parent == null) root = current.parent current.parent?.parent?.rotateRight() } } } else { uncle = current.parent?.parent?.left when { uncle?.colorBlack == false -> { current.parent?.colorBlack = true uncle.colorBlack = true current.parent?.parent?.colorBlack = false current = current.parent?.parent } current == current.parent?.left -> { current = current.parent if (current!!.parent?.parent == null) root = current.parent current.rotateRight() } current == current.parent?.right -> { if (current.parent?.parent?.parent == null) root = current.parent current.parent?.parent?.rotateLeft() } } } } root?.colorBlack = true } override fun find(key: K): Pair<K, V>? { val result = findNode(key) if (result == null) return null else return Pair(result.key, result.value) } private fun findNode(key: K): RBNode<K, V>? { var current = root while (current != null ) { if (key == current.key) return current if (key < current.key) current = current.left else current = current.right } return null } override fun delete(key: K) { val node = findNode(key) ?: return deleteNode(node) } private fun deleteNode(node: RBNode<K, V>) { val prev = max(node.left) when { (node.right != null && node.left != null) -> { node.key = prev!!.key node.value = prev.value deleteNode(prev) return } (node == root && node.isLeaf()) -> { root = null return } (!node.colorBlack && node.isLeaf()) -> { if (node == node.parent!!.left) node.parent!!.left = null else node.parent!!.right = null return } (node.colorBlack && node.left != null && !node.left!!.colorBlack) -> { node.key = node.left!!.key node.value = node.left!!.value node.left = null return } (node.colorBlack && node.right != null && !node.right!!.colorBlack) -> { node.key = node.right!!.key node.value = node.right!!.value node.right = null return } else -> { deleteCase1(node) } } if (node == node.parent!!.left) node.parent!!.left = null else node.parent!!.right = null } private fun deleteCase1(node: RBNode<K, V>) { if (node.parent != null) deleteCase2(node) } private fun deleteCase2(node: RBNode<K, V>) { val brother = node.brother() if (!brother!!.colorBlack) { if (node == node.parent!!.left) node.parent!!.rotateLeft() else if (node == node.parent!!.right) node.parent!!.rotateRight() if (root == node.parent) root = node.parent!!.parent } deleteCase3(node) } private fun deleteCase3(node: RBNode<K, V>) { val brother = node.brother() val a: Boolean = brother!!.left == null || brother.left!!.colorBlack val b: Boolean = brother.right == null || brother.right!!.colorBlack if (a && b && brother.colorBlack && node.parent!!.colorBlack) { brother.colorBlack = false deleteCase1(node.parent!!) } else deleteCase4(node) } private fun deleteCase4(node: RBNode<K, V>) { val brother = node.brother() val a: Boolean = brother!!.left == null || brother.left!!.colorBlack val b: Boolean = brother.right == null || brother.right!!.colorBlack if (a && b && brother.colorBlack && !node.parent!!.colorBlack) { brother.colorBlack = false node.parent!!.colorBlack = true } else deleteCase5(node) } private fun deleteCase5(node: RBNode<K, V>) { val brother = node.brother() val a: Boolean = brother!!.left == null || brother.left!!.colorBlack val b: Boolean = brother.right == null || brother.right!!.colorBlack if (brother.colorBlack) { if (brother.left?.colorBlack == false && b && node == node.parent?.left) brother.rotateRight() else if (brother.right?.colorBlack == false && a && node == node.parent?.right) brother.rotateLeft() } deleteCase6(node) } private fun deleteCase6(node: RBNode<K, V>) { val brother = node.brother() if (node == node.parent!!.left) { brother?.right?.colorBlack = true node.parent?.rotateLeft() } else { brother?.left?.colorBlack = true node.parent?.rotateRight() } if (root == node.parent) root = node.parent!!.parent } override fun iterator(): Iterator<Pair<K, V>> { return (object: Iterator<Pair<K, V>> { var node = max(root) var next = max(root) val last = min(root) override fun hasNext(): Boolean { return node != null && node!!.key >= last!!.key } override fun next(): Pair<K, V> { next = node node = nextSmaller(node) return Pair(next!!.key, next!!.value) } }) } private fun nextSmaller(node: RBNode<K, V>?): RBNode<K, V>? { var smaller = node ?: return null if (smaller.left != null) return max(smaller.left!!) else if (smaller == smaller.parent?.left) { while (smaller == smaller.parent?.left) smaller = smaller.parent!! } return smaller.parent } private fun min(node: RBNode<K, V>?): RBNode<K, V>? { if (node?.left == null) return node else return min(node.left) } private fun max(node: RBNode<K, V>?): RBNode<K, V>? { if (node?.right == null) return node else return max(node.right) } }
mit
2a72706b80a06cc0d15927bf20be8636
28.407285
91
0.464189
4.758842
false
false
false
false
paplorinc/intellij-community
plugins/github/src/org/jetbrains/plugins/github/util/GithubAsyncUtil.kt
1
3097
// 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 org.jetbrains.plugins.github.util import com.intellij.openapi.application.runInEdt import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import java.util.concurrent.* import java.util.function.BiFunction object GithubAsyncUtil { @JvmStatic fun <T> awaitFuture(progressIndicator: ProgressIndicator, future: Future<T>): T { var result: T while (true) { try { result = future.get(50, TimeUnit.MILLISECONDS) break } catch (e: TimeoutException) { progressIndicator.checkCanceled() } catch (e: Exception) { if (isCancellation(e)) throw ProcessCanceledException() if (e is ExecutionException) throw e.cause ?: e throw e } } return result } @JvmStatic fun <T> futureOfMutable(futureSupplier: () -> CompletableFuture<T>): CompletableFuture<T> { val result = CompletableFuture<T>() handleToOtherIfCancelled(futureSupplier, result) return result } private fun <T> handleToOtherIfCancelled(futureSupplier: () -> CompletableFuture<T>, other: CompletableFuture<T>) { futureSupplier().handle { result, error -> if (result != null) other.complete(result) if (error != null) { if (isCancellation(error)) handleToOtherIfCancelled(futureSupplier, other) other.completeExceptionally(error.cause) } } } fun isCancellation(error: Throwable): Boolean { return error is ProcessCanceledException || error is CancellationException || error is InterruptedException || error.cause?.let(::isCancellation) ?: false } } fun <T> ProgressManager.submitBackgroundTask(project: Project, title: String, canBeCancelled: Boolean, progressIndicator: ProgressIndicator, process: (indicator: ProgressIndicator) -> T): CompletableFuture<T> { val future = CompletableFuture<T>() runProcessWithProgressAsynchronously(object : Task.Backgroundable(project, title, canBeCancelled) { override fun run(indicator: ProgressIndicator) { future.complete(process(indicator)) } override fun onCancel() { future.cancel(true) } override fun onThrowable(error: Throwable) { future.completeExceptionally(error) } }, progressIndicator) return future } fun <T> CompletableFuture<T>.handleOnEdt(handler: (T?, Throwable?) -> Unit): CompletableFuture<Unit> = handleAsync(BiFunction<T?, Throwable?, Unit> { result: T?, error: Throwable? -> handler(result, error) }, EDT_EXECUTOR) val EDT_EXECUTOR = Executor { runnable -> runInEdt { runnable.run() } }
apache-2.0
fddb396e033bd6ac78834d1cd9710a7a
34.609195
140
0.669357
4.742726
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/openapi/application/JBProtocolCommand.kt
3
3413
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet") package com.intellij.openapi.application import com.intellij.diagnostic.PluginException import com.intellij.ide.IdeBundle import com.intellij.openapi.extensions.ExtensionPointName import io.netty.handler.codec.http.QueryStringDecoder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.future.asDeferred import kotlinx.coroutines.withContext import org.jetbrains.annotations.ApiStatus import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.Future /** * @author Konstantin Bulenkov */ abstract class JBProtocolCommand(private val command: String) { companion object { const val SCHEME = "jetbrains" const val FRAGMENT_PARAM_NAME = "__fragment" private val EP_NAME = ExtensionPointName<JBProtocolCommand>("com.intellij.jbProtocolCommand") @ApiStatus.Internal suspend fun execute(query: String): String? { val decoder = QueryStringDecoder(query) val parts = decoder.path().split('/').dropLastWhile { it.isEmpty() } require(parts.size >= 2) { // expected: at least a platform prefix and a command name query } val commandName = parts[1] for (command in EP_NAME.iterable) { if (command.command != commandName) { continue } val target = if (parts.size > 2) parts[2] else null val parameters = LinkedHashMap<String, String>() for ((key, list) in decoder.parameters()) { parameters.put(key, if (list.isEmpty()) "" else list.get(list.size - 1)) } val fragmentStart = query.lastIndexOf('#') val fragment = if (fragmentStart > 0) query.substring(fragmentStart + 1) else null return command.execute(target, parameters, fragment) } return IdeBundle.message("jb.protocol.unknown.command", commandName) } } @Suppress("unused") @Deprecated("please implement {@link #perform(String, Map, String)} instead", ReplaceWith("perform(String, Map, String)")) open fun perform(target: String?, parameters: Map<String, String?>) { throw PluginException.createByClass(UnsupportedOperationException(), javaClass) } /** * The method should return a future with the command execution result - `null` when successful, * sentence-capitalized localized string in case of an error (see `"ide.protocol.*"` strings in `IdeBundle`). * * @see .parameter */ open fun perform(target: String?, parameters: Map<String, String>, fragment: String?): Future<String?> { @Suppress("DEPRECATION") perform(target, mapOf(FRAGMENT_PARAM_NAME to fragment)) return CompletableFuture.completedFuture(null) } protected open suspend fun execute(target: String?, parameters: Map<String, String>, fragment: String?): String? { val result = withContext(Dispatchers.EDT) { perform(target, parameters, fragment) } return if (result is CompletableFuture) result.asDeferred().await() else withContext(Dispatchers.IO) { result.get() } } protected fun parameter(parameters: Map<String, String>, name: String): String { val value = parameters.get(name) require(!value.isNullOrBlank()) { IdeBundle.message("jb.protocol.parameter.missing", name) } return value } }
apache-2.0
7b502a88cbb6283b4e14c3d2c785fcb0
39.164706
121
0.70964
4.426719
false
false
false
false
google/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/findUsages/KotlinGroupUsagesBySimilarityTest.kt
2
2656
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. // 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.findUsages import com.intellij.testFramework.TestDataPath import com.intellij.testFramework.assertEqualsToFile import com.intellij.usages.UsageInfoToUsageConverter import com.intellij.usages.similarity.clustering.ClusteringSearchSession import org.jetbrains.kotlin.idea.findUsages.similarity.KotlinUsageSimilarityFeaturesProvider import org.jetbrains.kotlin.idea.base.test.TestRoot import org.jetbrains.kotlin.test.TestMetadata import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith import java.io.File @TestRoot("idea/tests") @TestDataPath("\$CONTENT_ROOT") @TestMetadata("testData/findUsages/similarity") @RunWith( JUnit38ClassRunner::class ) class KotlinGroupUsagesBySimilarityTest : AbstractFindUsagesTest() { fun testSimpleFeatures() { myFixture.configureByFile(getTestName(true)+".kt") val elementAtCaret = myFixture.getReferenceAtCaretPosition()!!.element val features = KotlinUsageSimilarityFeaturesProvider().getFeatures(elementAtCaret) assertEquals(1, features["VAR: "]) assertEquals(1, features["{CALL: inc}"]) } @TestMetadata("general.kt") @Throws(Exception::class) fun testGeneral() { doTest() } @TestMetadata("chainCalls") fun testChainCalls() { myFixture.configureByFile(getTestName(true)+".kt") val findUsages = findUsages(myFixture.elementAtCaret, null, false, myFixture.project) val session = ClusteringSearchSession(); findUsages.forEach { usage -> UsageInfoToUsageConverter.convertToSimilarUsage(arrayOf(myFixture.elementAtCaret), usage, session) } val file = File(testDataDirectory, getTestName(true)+".results.txt") assertEqualsToFile("", file, session.clusters.toString()) } fun testListAdd() { doTest() } fun testFilter() { doTest() } private fun doTest() { myFixture.configureByFile(getTestName(true)+".kt") val findUsages = findUsages(myFixture.elementAtCaret, null, false, myFixture.project) val session = ClusteringSearchSession(); findUsages.forEach { usage -> UsageInfoToUsageConverter.convertToSimilarUsage(arrayOf(myFixture.elementAtCaret), usage, session) } val file = File(testDataDirectory, getTestName(true) + ".results.txt") assertEqualsToFile("", file, session.clusters.toString()) } }
apache-2.0
5a6573daed429e5507cd38c8f9035507
40.515625
138
0.738705
4.659649
false
true
false
false
google/intellij-community
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/LibraryWrapper.kt
3
1745
// 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.base.projectStructure import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.Library import com.intellij.serviceContainer.AlreadyDisposedException import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.utils.addToStdlib.safeAs // Workaround for duplicated libraries, see KT-42607 @ApiStatus.Internal class LibraryWrapper(val library: LibraryEx) { private val allRootUrls: Set<String> by lazy { mutableSetOf<String>().apply { for (orderRootType in OrderRootType.getAllTypes()) { ProgressManager.checkCanceled() addAll(library.rootProvider.getUrls(orderRootType)) } } } private val excludedRootUrls: Array<String> by lazy { library.excludedRootUrls } private val hashCode by lazy { 31 + 37 * allRootUrls.hashCode() + excludedRootUrls.contentHashCode() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is LibraryWrapper) return false return allRootUrls == other.allRootUrls && excludedRootUrls.contentEquals(other.excludedRootUrls) } override fun hashCode(): Int = hashCode fun checkValidity() { library.checkValidity() } } fun Library.checkValidity() { safeAs<LibraryEx>()?.let { if (it.isDisposed) { throw AlreadyDisposedException("Library '${name}' is already disposed") } } }
apache-2.0
4e0ce5644c718d53921028a8dda3af53
32.576923
120
0.705444
4.728997
false
false
false
false
JetBrains/intellij-community
plugins/gradle/java/src/service/project/wizard/GradleJavaNewProjectWizardData.kt
1
2329
// 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.plugins.gradle.service.project.wizard import com.intellij.ide.wizard.NewProjectWizardStep import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.util.Key interface GradleJavaNewProjectWizardData : GradleNewProjectWizardData { val addSampleCodeProperty: GraphProperty<Boolean> var addSampleCode: Boolean companion object { @JvmStatic val KEY = Key.create<GradleJavaNewProjectWizardData>(GradleJavaNewProjectWizardData::class.java.name) @JvmStatic val NewProjectWizardStep.gradleData get() = data.getUserData(KEY)!! @JvmStatic val NewProjectWizardStep.sdkProperty get() = gradleData.sdkProperty @JvmStatic val NewProjectWizardStep.gradleDslProperty get() = gradleData.gradleDslProperty @JvmStatic val NewProjectWizardStep.parentProperty get() = gradleData.parentProperty @JvmStatic val NewProjectWizardStep.groupIdProperty get() = gradleData.groupIdProperty @JvmStatic val NewProjectWizardStep.artifactIdProperty get() = gradleData.artifactIdProperty @JvmStatic val NewProjectWizardStep.versionProperty get() = gradleData.versionProperty @JvmStatic val NewProjectWizardStep.addSampleCodeProperty get() = gradleData.addSampleCodeProperty @JvmStatic var NewProjectWizardStep.sdk get() = gradleData.sdk; set(it) { gradleData.sdk = it } @JvmStatic var NewProjectWizardStep.gradleDsl get() = gradleData.gradleDsl; set(it) { gradleData.gradleDsl = it } @JvmStatic var NewProjectWizardStep.parent get() = gradleData.parent; set(it) { gradleData.parent = it } @JvmStatic var NewProjectWizardStep.parentData get() = gradleData.parentData; set(it) { gradleData.parentData = it } @JvmStatic var NewProjectWizardStep.groupId get() = gradleData.groupId; set(it) { gradleData.groupId = it } @JvmStatic var NewProjectWizardStep.artifactId get() = gradleData.artifactId; set(it) { gradleData.artifactId = it } @JvmStatic var NewProjectWizardStep.version get() = gradleData.version; set(it) { gradleData.version = it } @JvmStatic var NewProjectWizardStep.addSampleCode get() = gradleData.addSampleCode; set(it) { gradleData.addSampleCode = it } } }
apache-2.0
552d459ac8ee741b9b725baa1ae890eb
67.529412
158
0.791756
4.772541
false
false
false
false
JetBrains/intellij-community
plugins/full-line/local/src/org/jetbrains/completion/full/line/local/tokenizer/TokenizerTrie.kt
1
3016
package org.jetbrains.completion.full.line.local.tokenizer import kotlin.math.max import kotlin.math.min internal class TokenizerTrie(val tokenizer: Tokenizer) { private val sortedVocabEntries = tokenizer.vocab.toList().sortedBy { it.first } private val root = TrieNode() init { sortedVocabEntries.mapIndexed { index, pair -> root.addWord(pair.first, index) } } fun getValuesWithCompletionAwarePrefix(prefix: String): IntArray { val answer = getInternalValuesWithPrefix(prefix, strict = false) val answerStrings = answer.map { sortedVocabEntries[it].first } val completableAnswerStrings = answerStrings.filter { val subPrefixLen = it.length // TODO: filter by length if (prefix.length > subPrefixLen) { val toComplete = prefix.substring(subPrefixLen) return@filter getInternalValuesWithPrefix(toComplete, strict = true).isNotEmpty() } else { return@filter true } } return completableAnswerStrings.map { tokenizer.vocab.getValue(it) }.toIntArray() } fun getValuesWithPrefix(prefix: String, strict: Boolean): IntArray { return getInternalValuesWithPrefix(prefix, strict).map { sortedVocabEntries[it].second }.toIntArray() } private fun getInternalValuesWithPrefix(prefix: String, strict: Boolean): List<Int> { val (foundTrie, path) = findTrie(prefix) var answer = foundTrie?.subtrieValues ?: emptyList() if (!strict) answer = answer + path.mapNotNull { it.value } return answer } private fun findTrie(word: String): Pair<TrieNode?, List<TrieNode>> { assert(word.isNotEmpty()) { "Word must not be empty" } var curNode = this.root var newNode: TrieNode? = null val path = mutableListOf<TrieNode>() for (char in word) { path.add(curNode) newNode = curNode.moveByChar(char) newNode?.let { curNode = newNode } ?: break } return Pair(newNode, path) } internal class TrieNode { private val moves: MutableMap<Char, TrieNode> = mutableMapOf() var value: Int? = null private var start: Int? = null private var end: Int? = null internal val subtrieValues: List<Int> get() { return ((start ?: return emptyList())..(end ?: return emptyList())).toList() } internal fun addWord(word: String, value: Int) { var curNode = this curNode.updateSubtrie(value) for (char in word) { curNode = curNode.moveByChar(char, createNew = true)!! // Can't be null when createNew is true curNode.updateSubtrie(value) } curNode.value = value } internal fun moveByChar(char: Char, createNew: Boolean = false): TrieNode? { if (!this.moves.containsKey(char)) { if (createNew) this.moves[char] = TrieNode() else return null } return this.moves.getValue(char) } private fun updateSubtrie(value: Int) { start = start?.let { min(it, value) } ?: value end = end?.let { max(it, value) } ?: value } } }
apache-2.0
c26e5a4d4f6a4bc06085301c3ece0a41
31.430108
105
0.663462
4.026702
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/domain/course_purchase/analytic/BuyCourseVerificationSuccessAnalyticEvent.kt
1
907
package org.stepik.android.domain.course_purchase.analytic import org.stepik.android.domain.base.analytic.AnalyticEvent import ru.nobird.app.core.model.mapOfNotNull class BuyCourseVerificationSuccessAnalyticEvent( courseId: Long, coursePurchaseSource: String, isWishlisted: Boolean, promoName: String? ) : AnalyticEvent { companion object { private const val PARAM_COURSE = "course" private const val PARAM_SOURCE = "source" private const val PARAM_IS_WISHLISTED = "is_wishlisted" private const val PARAM_PROMO = "promo" } override val name: String = "Buy course verification success" override val params: Map<String, Any> = mapOfNotNull( PARAM_COURSE to courseId, PARAM_SOURCE to coursePurchaseSource, PARAM_IS_WISHLISTED to isWishlisted, PARAM_PROMO to promoName ) }
apache-2.0
8c7656e202a659c2d7a28f10b0e4e7de
31.428571
63
0.685777
4.402913
false
false
false
false
scenerygraphics/scenery
src/test/kotlin/graphics/scenery/tests/examples/cluster/SlimClient.kt
1
1215
package graphics.scenery.tests.examples.cluster import org.joml.Vector3f import graphics.scenery.* import graphics.scenery.backends.Renderer import graphics.scenery.net.NodeSubscriber import kotlin.concurrent.thread /** * Empty scene to receive content via network * * Start with vm param: * -ea -Dscenery.ServerAddress=tcp://127.0.0.1 [-Dscenery.RemoteCamera=false|true] * * Explanation: * - RemoteCamera: (default false) Has to be set to true if the camera of the server provided scene should be used. */ class SlimClient : SceneryBase("Client", wantREPL = false) { override fun init() { renderer = hub.add(SceneryElement.Renderer, Renderer.createRenderer(hub, applicationName, scene, 512, 512)) if(!Settings().get("RemoteCamera",false)) { val cam: Camera = DetachedHeadCamera() with(cam) { spatial { position = Vector3f(0.0f, 0.0f, 5.0f) } perspectiveCamera(50.0f, 512, 512) scene.addChild(this) } } } companion object { @JvmStatic fun main(args: Array<String>) { SlimClient().main() } } }
lgpl-3.0
906861c74db8f7e660145dd182e2035e
27.255814
115
0.615638
4.023179
false
false
false
false
LivingDoc/livingdoc
livingdoc-converters/src/main/kotlin/org/livingdoc/converters/BooleanConverter.kt
2
1419
package org.livingdoc.converters import java.lang.reflect.AnnotatedElement import org.livingdoc.api.conversion.ConversionException import org.livingdoc.api.conversion.TypeConverter /** * This converter is used to convert a String to a boolean, if the String is "true" or "false" */ open class BooleanConverter : TypeConverter<Boolean> { /** * This function converts the given parameter value with "true" or "false" to a boolean. If the content is not one * of these two values, the function throws a Conversion exception. * * @param value the String that should have "true" or "false" as a content * @return the boolean value of the given String * @throws ConversionException if the content is not "true" or "false" */ @Throws(ConversionException::class) override fun convert(value: String, element: AnnotatedElement?, documentClass: Class<*>?): Boolean { val trimmedLowerCaseValue = value.trim().toLowerCase() when (trimmedLowerCaseValue) { "true" -> return true "false" -> return false } throw ConversionException("Not a boolean value: '$value'") } override fun canConvertTo(targetType: Class<*>): Boolean { val isJavaObjectType = Boolean::class.javaObjectType == targetType val isKotlinType = Boolean::class.java == targetType return isJavaObjectType || isKotlinType } }
apache-2.0
c74a50946b747c97a5e05744ccd9277d
39.542857
118
0.693446
4.698675
false
false
false
false
leafclick/intellij-community
plugins/devkit/devkit-core/src/inspections/missingApi/update/IdeExternalAnnotationsUpdater.kt
1
9487
// 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 org.jetbrains.idea.devkit.inspections.missingApi.update import com.intellij.codeInspection.ex.modifyAndCommitProjectProfile import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationGroup import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runInEdt import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.AnnotationOrderRootType import com.intellij.openapi.util.BuildNumber import com.intellij.profile.codeInspection.ProjectInspectionProfileManager import com.intellij.util.Consumer import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.idea.devkit.inspections.missingApi.MissingRecentApiInspection import org.jetbrains.idea.devkit.inspections.missingApi.resolve.IdeExternalAnnotations import org.jetbrains.idea.devkit.inspections.missingApi.resolve.PublicIdeExternalAnnotationsRepository import org.jetbrains.idea.devkit.inspections.missingApi.resolve.getAnnotationsBuildNumber import org.jetbrains.idea.devkit.inspections.missingApi.resolve.isAnnotationsRoot import java.time.Duration import java.time.Instant import java.time.temporal.ChronoUnit import java.util.concurrent.atomic.AtomicReference /** * Utility class that updates IntelliJ API external annotations. */ class IdeExternalAnnotationsUpdater { companion object { private val LOG = Logger.getInstance(IdeExternalAnnotationsUpdater::class.java) private val NOTIFICATION_GROUP = NotificationGroup.balloonGroup("IntelliJ API Annotations") private val UPDATE_RETRY_TIMEOUT = Duration.of(10, ChronoUnit.MINUTES) fun getInstance(): IdeExternalAnnotationsUpdater = service() } private val buildNumberLastFailedUpdateInstant = hashMapOf<BuildNumber, Instant>() private val buildNumberNotificationShown = hashSetOf<BuildNumber>() private val buildNumberUpdateInProgress = hashSetOf<BuildNumber>() private fun isInspectionEnabled(project: Project): Boolean { return runReadAction { ProjectInspectionProfileManager.getInstance(project).currentProfile .getTools(MissingRecentApiInspection.INSPECTION_SHORT_NAME, project) .isEnabled } } fun updateIdeaJdkAnnotationsIfNecessary(project: Project, ideaJdk: Sdk, buildNumber: BuildNumber) { if (!isInspectionEnabled(project)) { return } if (synchronized(this) { buildNumber in buildNumberUpdateInProgress || buildNumber in buildNumberNotificationShown }) { return } val attachedAnnotations = getAttachedAnnotationsBuildNumbers(ideaJdk) if (attachedAnnotations.any { it >= buildNumber }) { return } runInEdt { val canShowNotification = synchronized(this) { val lastFailedInstant = buildNumberLastFailedUpdateInstant[buildNumber] val lastFailedWasLongAgo = lastFailedInstant == null || Instant.now().isAfter(lastFailedInstant.plus(UPDATE_RETRY_TIMEOUT)) if (lastFailedWasLongAgo && buildNumber !in buildNumberNotificationShown) { buildNumberNotificationShown.add(buildNumber) true } else { false } } if (canShowNotification) { showUpdateAnnotationsNotification(project, ideaJdk, buildNumber) } } } private fun reattachAnnotations(project: Project, ideaJdk: Sdk, annotationsRoot: IdeExternalAnnotations) { val annotationsUrl = runReadAction { annotationsRoot.annotationsRoot.url } ApplicationManager.getApplication().invokeAndWait { if (project.isDisposed) { return@invokeAndWait } runWriteAction { val type = AnnotationOrderRootType.getInstance() val sdkModificator = ideaJdk.sdkModificator val attachedUrls = sdkModificator.getRoots(type) .asSequence() .filter { isAnnotationsRoot(it) } .mapTo(mutableSetOf()) { it.url } if (annotationsUrl !in attachedUrls) { sdkModificator.addRoot(annotationsUrl, type) } for (redundantUrl in attachedUrls - annotationsUrl) { sdkModificator.removeRoot(redundantUrl, type) } sdkModificator.commitChanges() } } } private fun getAttachedAnnotationsBuildNumbers(ideaJdk: Sdk): List<BuildNumber> = ideaJdk.rootProvider .getFiles(AnnotationOrderRootType.getInstance()) .mapNotNull { getAnnotationsBuildNumber(it) } private fun showUpdateAnnotationsNotification(project: Project, ideaJdk: Sdk, buildNumber: BuildNumber) { val notification = NOTIFICATION_GROUP.createNotification( DevKitBundle.message("intellij.api.annotations.update.title", buildNumber), DevKitBundle.message("intellij.api.annotations.update.confirmation.content", buildNumber), NotificationType.INFORMATION, null ).apply { addAction(object : NotificationAction(DevKitBundle.message("intellij.api.annotations.update.confirmation.update.button")) { override fun actionPerformed(e: AnActionEvent, notification: Notification) { updateAnnotationsInBackground(ideaJdk, project, buildNumber) notification.expire() } }) addAction(object : NotificationAction( DevKitBundle.message("intellij.api.annotations.update.confirmation.disable.inspection.button")) { override fun actionPerformed(e: AnActionEvent, notification: Notification) { disableInspection(project) notification.expire() } }) } notification.whenExpired { synchronized(this) { buildNumberNotificationShown.remove(buildNumber) } } notification.notify(project) } private fun disableInspection(project: Project) { modifyAndCommitProjectProfile(project, Consumer { it.disableToolByDefault(listOf(MissingRecentApiInspection.INSPECTION_SHORT_NAME), project) }) } private fun updateAnnotationsInBackground(ideaJdk: Sdk, project: Project, buildNumber: BuildNumber) { if (synchronized(this) { !buildNumberUpdateInProgress.add(buildNumber) }) { return } UpdateTask(project, ideaJdk, buildNumber).queue() } private fun showSuccessfullyUpdated(project: Project, buildNumber: BuildNumber, annotationsBuild: BuildNumber) { synchronized(this) { buildNumberLastFailedUpdateInstant.remove(buildNumber) } val updateMessage = if (annotationsBuild >= buildNumber) { DevKitBundle.message("intellij.api.annotations.update.successfully.updated", buildNumber) } else { DevKitBundle.message("intellij.api.annotations.update.successfully.updated.but.not.latest.version", buildNumber, annotationsBuild) } NOTIFICATION_GROUP .createNotification( DevKitBundle.message("intellij.api.annotations.update.title", buildNumber), updateMessage, NotificationType.INFORMATION, null ) .notify(project) } private fun showUnableToUpdate(project: Project, throwable: Throwable, buildNumber: BuildNumber) { synchronized(this) { buildNumberLastFailedUpdateInstant[buildNumber] = Instant.now() } val message = DevKitBundle.message("intellij.api.annotations.update.failed", throwable.message) LOG.warn(message, throwable) NOTIFICATION_GROUP .createNotification( DevKitBundle.message("intellij.api.annotations.update.title", buildNumber), message, NotificationType.WARNING, null ).notify(project) } private inner class UpdateTask( project: Project, private val ideaJdk: Sdk, private val ideBuildNumber: BuildNumber ) : Task.Backgroundable(project, "Updating IntelliJ API Annotations $ideBuildNumber", true) { private val ideAnnotations = AtomicReference<IdeExternalAnnotations>() override fun run(indicator: ProgressIndicator) { val annotations = tryDownloadAnnotations(ideBuildNumber) ?: throw Exception(DevKitBundle.message("intellij.api.annotations.update.failed.no.annotations.found", ideBuildNumber)) ideAnnotations.set(annotations) reattachAnnotations(project, ideaJdk, annotations) } private fun tryDownloadAnnotations(ideBuildNumber: BuildNumber): IdeExternalAnnotations? { return try { PublicIdeExternalAnnotationsRepository(project).downloadExternalAnnotations(ideBuildNumber) } catch (e: Exception) { throw Exception("Failed to download annotations for $ideBuildNumber", e) } } override fun onSuccess() { showSuccessfullyUpdated(project, ideBuildNumber, ideAnnotations.get().annotationsBuild) } override fun onThrowable(error: Throwable) { showUnableToUpdate(project, error, ideBuildNumber) } override fun onFinished() { synchronized(this@IdeExternalAnnotationsUpdater) { buildNumberUpdateInProgress.remove(ideBuildNumber) } } } }
apache-2.0
7dd129291fd25a98f9204c0deccb51cb
37.104418
140
0.750184
5.040914
false
false
false
false
leafclick/intellij-community
python/src/com/jetbrains/python/sdk/pipenv/PyAddPipEnvPanel.kt
1
6910
// 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.sdk.pipenv import com.intellij.application.options.ModuleListCellRenderer import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.UserDataHolder import com.intellij.ui.DocumentAdapter import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBTextField import com.intellij.util.PlatformUtils import com.intellij.util.text.nullize import com.intellij.util.ui.FormBuilder import com.jetbrains.python.PyBundle import com.jetbrains.python.PythonModuleTypeBase import com.jetbrains.python.sdk.* import com.jetbrains.python.sdk.add.PyAddNewEnvPanel import com.jetbrains.python.sdk.add.PySdkPathChoosingComboBox import com.jetbrains.python.sdk.add.addInterpretersAsync import java.awt.BorderLayout import java.awt.Dimension import java.awt.event.ItemEvent import java.io.File import java.nio.file.Files import javax.swing.Icon import javax.swing.JComboBox import javax.swing.event.DocumentEvent /** * The UI panel for adding the pipenv interpreter for the project. * * @author vlan */ class PyAddPipEnvPanel(private val project: Project?, private val module: Module?, private val existingSdks: List<Sdk>, override var newProjectPath: String?, context: UserDataHolder) : PyAddNewEnvPanel() { override val envName = "Pipenv" override val panelName = "Pipenv Environment" override val icon: Icon = PIPENV_ICON private val moduleField: JComboBox<Module> private val baseSdkField = PySdkPathChoosingComboBox().apply { val preferredSdkPath = PySdkSettings.instance.preferredVirtualEnvBaseSdk val detectedPreferredSdk = items.find { it.homePath == preferredSdkPath } selectedSdk = when { detectedPreferredSdk != null -> detectedPreferredSdk preferredSdkPath != null -> PyDetectedSdk(preferredSdkPath).apply { childComponent.insertItemAt(this, 0) } else -> items.getOrNull(0) } } init { addInterpretersAsync(baseSdkField) { findBaseSdks(existingSdks, module, context) } } private val installPackagesCheckBox = JBCheckBox("Install packages from Pipfile").apply { isVisible = newProjectPath == null isSelected = isVisible } private val pipEnvPathField = TextFieldWithBrowseButton().apply { addBrowseFolderListener(null, null, null, FileChooserDescriptorFactory.createSingleFileDescriptor()) val field = textField as? JBTextField ?: return@apply detectPipEnvExecutable()?.let { field.emptyText.text = PyBundle.message("configurable.pipenv.auto.detected", it.absolutePath) } PropertiesComponent.getInstance().pipEnvPath?.let { field.text = it } } init { layout = BorderLayout() val modules = project?.let { ModuleUtil.getModulesOfType(it, PythonModuleTypeBase.getInstance()) } ?: emptyList() moduleField = JComboBox(modules.toTypedArray()).apply { renderer = ModuleListCellRenderer() preferredSize = Dimension(Int.MAX_VALUE, preferredSize.height) addItemListener { if (it.stateChange == ItemEvent.SELECTED) { update() } } } pipEnvPathField.textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { update() } }) val builder = FormBuilder.createFormBuilder().apply { if (module == null && modules.size > 1) { val associatedObject = if (PlatformUtils.isPyCharm()) "project" else "module" addLabeledComponent("Associated $associatedObject:", moduleField) } addLabeledComponent(PyBundle.message("base.interpreter"), baseSdkField) addComponent(installPackagesCheckBox) addLabeledComponent(PyBundle.message("python.sdk.pipenv.executable"), pipEnvPathField) } add(builder.panel, BorderLayout.NORTH) update() } override fun getOrCreateSdk(): Sdk? { PropertiesComponent.getInstance().pipEnvPath = pipEnvPathField.text.nullize() return setupPipEnvSdkUnderProgress(project, selectedModule, existingSdks, newProjectPath, baseSdkField.selectedSdk?.homePath, installPackagesCheckBox.isSelected)?.apply { PySdkSettings.instance.preferredVirtualEnvBaseSdk = baseSdkField.selectedSdk?.homePath } } override fun validateAll(): List<ValidationInfo> = listOfNotNull(validatePipEnvExecutable(), validatePipEnvIsNotAdded()) override fun addChangeListener(listener: Runnable) { pipEnvPathField.textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { listener.run() } }) super.addChangeListener(listener) } /** * Updates the view according to the current state of UI controls. */ private fun update() { selectedModule?.let { installPackagesCheckBox.isEnabled = it.pipFile != null } } /** * The effective module for which we add a new environment. */ private val selectedModule: Module? get() = module ?: moduleField.selectedItem as? Module /** * Checks if `pipenv` is available on `$PATH`. */ private fun validatePipEnvExecutable(): ValidationInfo? { val executable = pipEnvPathField.text.nullize()?.let { File(it) } ?: detectPipEnvExecutable() ?: return ValidationInfo(PyBundle.message("python.sdk.pipenv.executable.not.found")) return when { !executable.exists() -> ValidationInfo(PyBundle.message("python.sdk.file.not.found", executable.absolutePath)) !Files.isExecutable(executable.toPath()) || !executable.isFile -> ValidationInfo(PyBundle.message("python.sdk.cannot.execute", executable.absolutePath)) else -> null } } /** * Checks if the pipenv for the project hasn't been already added. */ private fun validatePipEnvIsNotAdded(): ValidationInfo? { val path = projectPath ?: return null val addedPipEnv = existingSdks.find { it.associatedModulePath == path && it.isPipEnv } ?: return null return ValidationInfo(PyBundle.message("python.sdk.pipenv.has.been.selected", addedPipEnv.name)) } /** * The effective project path for the new project or for the existing project. */ private val projectPath: String? get() = newProjectPath ?: selectedModule?.basePath ?: project?.basePath }
apache-2.0
0d3b8679db780eb70d3f47e00fc4e68f
36.351351
158
0.723589
4.672076
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/boxInline/nonLocalReturns/tryFinally/exceptionTable/innerAndExternal.kt
5
4252
// FILE: 1.kt package test public class Exception1(message: String) : RuntimeException(message) public class Exception2(message: String) : RuntimeException(message) public inline fun doCall(block: ()-> String, exception: (e: Exception)-> Unit, exception2: (e: Exception)-> Unit, finallyBlock: ()-> String, res: String = "Fail") : String { try { block() } catch (e: Exception1) { exception(e) } catch (e: Exception2) { exception2(e) } finally { finallyBlock() } return res } public inline fun <R> doCall2(block: ()-> R, exception: (e: Exception)-> Unit, finallyBlock: ()-> R) : R { try { return block() } catch (e: Exception) { exception(e) } finally { finallyBlock() } throw RuntimeException("fail") } // FILE: 2.kt import test.* class Holder { var value: String = "" } fun test0(h: Holder): String { try { val localResult = doCall ( { h.value += "OK_NON_LOCAL" return "OK_NON_LOCAL" }, { h.value += ", OK_EXCEPTION1" return "OK_EXCEPTION1" }, { h.value += ", OK_EXCEPTION2" return "OK_EXCEPTION2" }, { try { h.value += ", OK_FINALLY" throw RuntimeException("FINALLY") "OK_FINALLY" } finally { h.value += ", OK_FINALLY_INNER" } }) return localResult; } catch (e: RuntimeException) { if (e.message != "FINALLY") { return "FAIL in exception: " + e.message } else { return "CATCHED_EXCEPTION" } } return "FAIL"; } fun test01(h: Holder): String { val localResult = doCall ( { h.value += "OK_NON_LOCAL" throw Exception1("1") return "OK_NON_LOCAL" }, { h.value += ", OK_EXCEPTION1" return "OK_EXCEPTION1" }, { h.value += ", OK_EXCEPTION2" return "OK_EXCEPTION2" }, { try { h.value += ", OK_FINALLY" throw RuntimeException("FINALLY") } catch(e: RuntimeException) { h.value += ", OK_CATCHED" } finally { h.value += ", OK_FINALLY_INNER" } "OK_FINALLY" }) return localResult; } fun test02(h: Holder): String { val localResult = doCall ( { h.value += "OK_NON_LOCAL" throw Exception2("1") return "OK_NON_LOCAL" }, { h.value += ", OK_EXCEPTION1" return "OK_EXCEPTION1" }, { h.value += ", OK_EXCEPTION2" return "OK_EXCEPTION2" }, { try { h.value += ", OK_FINALLY" throw RuntimeException("FINALLY") } catch(e: RuntimeException) { h.value += ", OK_CATCHED" } finally { h.value += ", OK_FINALLY_INNER" } "OK_FINALLY" }, "OK") return localResult; } fun box(): String { var h = Holder() val test0 = test0(h) if (test0 != "CATCHED_EXCEPTION" || h.value != "OK_NON_LOCAL, OK_FINALLY, OK_FINALLY_INNER") return "test0: ${test0}, holder: ${h.value}" h = Holder() val test01 = test01(h) if (test01 != "OK_EXCEPTION1" || h.value != "OK_NON_LOCAL, OK_EXCEPTION1, OK_FINALLY, OK_CATCHED, OK_FINALLY_INNER") return "test01: ${test01}, holder: ${h.value}" h = Holder() val test02 = test02(h) if (test02 != "OK_EXCEPTION2" || h.value != "OK_NON_LOCAL, OK_EXCEPTION2, OK_FINALLY, OK_CATCHED, OK_FINALLY_INNER") return "test02: ${test02}, holder: ${h.value}" return "OK" }
apache-2.0
b7f2741081bda6c6c3c25ba0ef2f396c
26.61039
173
0.441439
4.214073
false
true
false
false
AndroidX/androidx
compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/visualaid/ColumnConfigurationDemo.kt
3
7140
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.animation.demos.visualaid import androidx.compose.animation.core.Spring import androidx.compose.animation.core.VectorConverter import androidx.compose.animation.core.animate import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.produceState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.InfiniteAnimationPolicy import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.delay @Preview @Composable fun ColumnConfigurationDemo() { val height by produceState(250.dp) { // Skip the animations in tests. while (coroutineContext[InfiniteAnimationPolicy] == null) { animate( Dp.VectorConverter, 250.dp, 520.dp, animationSpec = spring(Spring.DampingRatioMediumBouncy, Spring.StiffnessLow) ) { value, _ -> this.value = value } delay(1000) animate( Dp.VectorConverter, 520.dp, 250.dp, animationSpec = tween(520) ) { value, _ -> this.value = value } delay(1000) } } ResizableColumn(height) } @Composable fun ResizableColumn(height: Dp) { Column( Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Row( verticalAlignment = Alignment.Bottom, modifier = Modifier.background(Color.White, RoundedCornerShape(5.dp)).padding(10.dp) ) { Text( text = "Equal\nWeight", modifier = Modifier.width(50.dp).padding(2.dp), fontSize = 12.sp, textAlign = TextAlign.Center ) Text( text = "Space\nBetween", modifier = Modifier.width(50.dp).padding(2.dp), fontSize = 11.sp, textAlign = TextAlign.Center ) Text( text = "Space\nAround", modifier = Modifier.width(50.dp).padding(2.dp), fontSize = 12.sp, textAlign = TextAlign.Center ) Text( text = "Space\nEvenly", modifier = Modifier.width(50.dp).padding(2.dp), fontSize = 12.sp, textAlign = TextAlign.Center ) Text( text = "Top", modifier = Modifier.width(50.dp).padding(2.dp), fontSize = 12.sp, textAlign = TextAlign.Center ) Text( text = "Center", modifier = Modifier.width(50.dp).padding(2.dp), fontSize = 12.sp, textAlign = TextAlign.Center ) Text( text = "Bottom", modifier = Modifier.width(50.dp).padding(2.dp), fontSize = 12.sp, textAlign = TextAlign.Center ) } Row(Modifier.height(520.dp).requiredHeight(height)) { Column(Modifier.default(androidBlue)) { ColumnItem("A", fixedSize = false) ColumnItem("B", fixedSize = false) ColumnItem("C", fixedSize = false) } Column(Modifier.default(androidDark), verticalArrangement = Arrangement.SpaceBetween) { ColumnItem(text = "A") ColumnItem(text = "B") ColumnItem(text = "C") } Column(Modifier.default(androidGreen), verticalArrangement = Arrangement.SpaceAround) { ColumnItem(text = "A") ColumnItem(text = "B") ColumnItem(text = "C") } Column(Modifier.default(androidBlue), verticalArrangement = Arrangement.SpaceEvenly) { ColumnItem(text = "A") ColumnItem(text = "B") ColumnItem(text = "C") } Column(Modifier.default(androidDark), verticalArrangement = Arrangement.Top) { ColumnItem(text = "A") ColumnItem(text = "B") ColumnItem(text = "C") } Column(Modifier.default(androidGreen), verticalArrangement = Arrangement.Center) { ColumnItem(text = "A") ColumnItem(text = "B") ColumnItem(text = "C") } Column(Modifier.default(androidBlue), verticalArrangement = Arrangement.Bottom) { ColumnItem(text = "A") ColumnItem(text = "B") ColumnItem(text = "C") } } } } private fun Modifier.default(backgroundColor: Color) = this.width(50.dp).padding(2.dp) .background(backgroundColor, RoundedCornerShape(5.dp)).padding(top = 3.dp, bottom = 3.dp) .fillMaxHeight() @Composable fun ColumnScope.ColumnItem(text: String, fixedSize: Boolean = true) { val modifier = if (fixedSize) Modifier.height(80.dp) else Modifier.weight(1f) Box( modifier.width(50.dp).padding(5.dp).shadow(10.dp) .background(Color.White, shape = RoundedCornerShape(5.dp)) .padding(top = 5.dp, bottom = 5.dp) ) { Text(text, Modifier.align(Alignment.Center), color = androidDark) } } val androidBlue = Color(0xff4282f2)
apache-2.0
5bb25e5e52ba33bd6d55609af4e789c3
36.984043
99
0.613165
4.513274
false
false
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/settings/socketing/items/combiner/MythicClickToCombineOptions.kt
1
2210
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * 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.tealcube.minecraft.bukkit.mythicdrops.settings.socketing.items.combiner import com.squareup.moshi.JsonClass import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.socketing.items.combiner.ClickToCombineOptions import com.tealcube.minecraft.bukkit.mythicdrops.getMaterial import com.tealcube.minecraft.bukkit.mythicdrops.getNonNullString import org.bukkit.Material import org.bukkit.configuration.ConfigurationSection @JsonClass(generateAdapter = true) data class MythicClickToCombineOptions internal constructor( override val name: String = "", override val lore: List<String> = emptyList(), override val material: Material = Material.AIR ) : ClickToCombineOptions { companion object { fun fromConfigurationSection(configurationSection: ConfigurationSection) = MythicClickToCombineOptions( configurationSection.getNonNullString("name"), configurationSection.getStringList("lore"), configurationSection.getMaterial("material") ) } }
mit
6456483efc282397731244771fd05d41
49.227273
111
0.775566
4.804348
false
true
false
false
Xenoage/Zong
utils-kotlin/src/com/xenoage/utils/math/Size2f.kt
1
638
package com.xenoage.utils.math import kotlin.coroutines.experimental.EmptyCoroutineContext.get import kotlin.math.roundToInt /** * 2D size in float precision. */ data class Size2f( val width: Float, val height: Float) { constructor(size: Size2i) : this(size.width.toFloat(), size.height.toFloat()) val area: Float get() = width * height fun add(size: Size2i) = Size2f(this.width + size.width, this.height + size.height) fun scale(f: Float) = Size2f(width * f, height * f) override fun toString() = "${width}x${height}" companion object { /** Size with width and height of 0. */ val size0 = Size2f(0f, 0f) } }
agpl-3.0
31e69699c53da02afac4541147e8b675
21
83
0.689655
3.023697
false
false
false
false
smmribeiro/intellij-community
images/src/org/intellij/images/actions/EditExternallyAction.kt
4
3392
// Copyright 2000-2021 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.intellij.images.actions import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.util.EnvironmentUtil import org.intellij.images.ImagesBundle import org.intellij.images.fileTypes.ImageFileTypeManager import org.intellij.images.options.impl.ImagesConfigurable import java.awt.Desktop import java.io.File import java.io.IOException /** * Open image file externally. * * @author [Alexey Efimov](mailto:[email protected]) * @author Konstantin Bulenkov */ internal class EditExternallyAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { val imageFile = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE) var executablePath = PropertiesComponent.getInstance().getValue(EditExternalImageEditorAction.EXT_PATH_KEY, "") if (!StringUtil.isEmpty(executablePath)) { EnvironmentUtil.getEnvironmentMap().forEach { (varName, varValue) -> executablePath = if (SystemInfo.isWindows) StringUtil.replace(executablePath, "%$varName%", varValue, true) else StringUtil.replace(executablePath, "\${$varName}", varValue, false); } executablePath = FileUtil.toSystemDependentName(executablePath); val executable = File(executablePath) val commandLine = GeneralCommandLine() val path = if(executable.exists()) executable.absolutePath else executablePath if (SystemInfo.isMac) { commandLine.exePath = ExecUtil.openCommandPath commandLine.addParameter("-a") commandLine.addParameter(path) } else { commandLine.exePath = path } val typeManager = ImageFileTypeManager.getInstance() if (imageFile.isInLocalFileSystem && typeManager.isImage(imageFile)) { commandLine.addParameter(VfsUtilCore.virtualToIoFile(imageFile).absolutePath) } commandLine.workDirectory = File(executablePath).parentFile try { commandLine.createProcess() } catch (ex: ExecutionException) { Messages.showErrorDialog(e.project, ex.localizedMessage, ImagesBundle.message("error.title.launching.external.editor")); ImagesConfigurable.show(e.project) } } else { try { Desktop.getDesktop().open(imageFile.toNioPath().toFile()) } catch (ignore: IOException) { } } } override fun update(e: AnActionEvent) { val file = e.getData(CommonDataKeys.VIRTUAL_FILE) val enabled = file != null && ImageFileTypeManager.getInstance().isImage(file) if (e.place == ActionPlaces.PROJECT_VIEW_POPUP) { e.presentation.isVisible = enabled } e.presentation.isEnabled = enabled } }
apache-2.0
bd8e5a574f6c10b2f9319f00634a24be
38
140
0.741745
4.589986
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinCocoaPodsModelBuilder.kt
1
1497
// 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.gradleTooling import org.gradle.api.Project import org.jetbrains.plugins.gradle.tooling.AbstractModelBuilderService import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder import org.jetbrains.plugins.gradle.tooling.ModelBuilderContext private const val POD_IMPORT_TASK_NAME = "podImport" interface EnablePodImportTask class KotlinCocoaPodsModelBuilder : AbstractModelBuilderService() { override fun canBuild(modelName: String?): Boolean { return EnablePodImportTask::class.java.name == modelName } override fun buildAll(modelName: String, project: Project, context: ModelBuilderContext): Any? { val startParameter = project.gradle.startParameter val taskNames = mutableListOf<String>() taskNames.addAll(startParameter.taskNames) if (project.tasks.findByPath(POD_IMPORT_TASK_NAME) != null && POD_IMPORT_TASK_NAME !in taskNames) { taskNames.add(POD_IMPORT_TASK_NAME) startParameter.setTaskNames(taskNames) } return null } override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder { return ErrorMessageBuilder.create( project, e, "EnablePodImportTask error" ).withDescription("Unable to create $POD_IMPORT_TASK_NAME task.") } }
apache-2.0
e38e617cc2f4f6732c2092f921fb99bd
40.611111
158
0.742151
4.663551
false
false
false
false
WillowChat/Kale
src/test/kotlin/chat/willow/kale/irc/message/rfc1459/TopicMessageTests.kt
2
2203
package chat.willow.kale.irc.message.rfc1459 import chat.willow.kale.core.message.IrcMessage import chat.willow.kale.irc.prefix.Prefix import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test class TopicMessageTests { private lateinit var messageParser: TopicMessage.Message.Parser private lateinit var messageSerialiser: TopicMessage.Command.Serialiser @Before fun setUp() { messageParser = TopicMessage.Message.Parser messageSerialiser = TopicMessage.Command.Serialiser } @Test fun test_parse_Channel() { val message = messageParser.parse(IrcMessage(command = "TOPIC", prefix = "source", parameters = listOf("#channel"))) assertEquals(TopicMessage.Message(source = Prefix(nick = "source"), channel = "#channel"), message) } @Test fun test_parse_Source_Channel() { val message = messageParser.parse(IrcMessage(command = "TOPIC", prefix = "source", parameters = listOf("#channel"))) assertEquals(TopicMessage.Message(source = Prefix(nick = "source"), channel = "#channel"), message) } @Test fun test_parse_Source_Channel_Topic() { val message = messageParser.parse(IrcMessage(command = "TOPIC", prefix = "source", parameters = listOf("#channel", "channel topic!"))) assertEquals(TopicMessage.Message(source = Prefix(nick = "source"), channel = "#channel", topic = "channel topic!"), message) } @Test fun test_parse_TooFewParameters() { val message = messageParser.parse(IrcMessage(command = "TOPIC", parameters = listOf())) assertNull(message) } @Test fun test_serialise_Source_Channel() { val message = messageSerialiser.serialise(TopicMessage.Command(channel = "#channel")) assertEquals(IrcMessage(command = "TOPIC", parameters = listOf("#channel")), message) } @Test fun test_serialise_Source_Channel_Topic() { val message = messageSerialiser.serialise(TopicMessage.Command(channel = "#channel", topic = "another channel topic!")) assertEquals(IrcMessage(command = "TOPIC", parameters = listOf("#channel", "another channel topic!")), message) } }
isc
e965696ac042dce4cdf4791e08fd61ff
38.357143
142
0.699501
4.459514
false
true
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/CustomizationRecyclerViewAdapter.kt
1
13087
package com.habitrpg.android.habitica.ui.adapter import android.content.Context import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.core.os.bundleOf import com.facebook.drawee.view.SimpleDraweeView import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.CustomizationGridItemBinding import com.habitrpg.android.habitica.databinding.CustomizationSectionHeaderBinding import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.models.inventory.Customization import com.habitrpg.android.habitica.models.inventory.CustomizationSet import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils import com.habitrpg.android.habitica.ui.helpers.bindView import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.subjects.PublishSubject import java.util.* class CustomizationRecyclerViewAdapter : androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() { var userSize: String? = null var hairColor: String? = null var gemBalance: Int = 0 var unsortedCustomizations: List<Customization> = ArrayList() var customizationList: MutableList<Any> = ArrayList() set(value) { field = value notifyDataSetChanged() } var additionalSetItems: List<Customization> = ArrayList() var activeCustomization: String? = null set(value) { field = value this.notifyDataSetChanged() } var ownedCustomiztations: List<String> = listOf() private val selectCustomizationEvents = PublishSubject.create<Customization>() private val unlockCustomizationEvents = PublishSubject.create<Customization>() private val unlockSetEvents = PublishSubject.create<CustomizationSet>() fun updateOwnership(ownedCustomizations: List<String>) { this.ownedCustomiztations = ownedCustomizations setCustomizations(unsortedCustomizations) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder { return if (viewType == 0) { val view = LayoutInflater.from(parent.context) .inflate(R.layout.customization_section_header, parent, false) SectionViewHolder(view) } else { val viewID: Int = R.layout.customization_grid_item val view = LayoutInflater.from(parent.context).inflate(viewID, parent, false) CustomizationViewHolder(view) } } override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) { val obj = customizationList[position] if (obj.javaClass == CustomizationSet::class.java) { (holder as SectionViewHolder).bind(obj as CustomizationSet) } else { (holder as CustomizationViewHolder).bind(customizationList[position] as Customization) } } override fun getItemCount(): Int { return customizationList.size } override fun getItemViewType(position: Int): Int { return if (this.customizationList[position].javaClass == CustomizationSet::class.java) { 0 } else { 1 } } fun setCustomizations(newCustomizationList: List<Customization>) { unsortedCustomizations = newCustomizationList this.customizationList = ArrayList() var lastSet = CustomizationSet() val today = Date() for (customization in newCustomizationList.reversed()) { if (customization.availableFrom != null || customization.availableUntil != null) { if ((customization.availableFrom?.compareTo(today) ?: 0 > 0 || customization.availableUntil?.compareTo(today) ?: 0 < 0) && !customization.isUsable(ownedCustomiztations.contains(customization.identifier))) { continue } } if (customization.customizationSet != null && customization.customizationSet != lastSet.identifier) { val set = CustomizationSet() set.identifier = customization.customizationSet set.text = customization.customizationSetName set.price = customization.setPrice set.hasPurchasable = !customization.isUsable(ownedCustomiztations.contains(customization.identifier)) lastSet = set customizationList.add(set) } customizationList.add(customization) if (!customization.isUsable(ownedCustomiztations.contains(customization.identifier)) && !lastSet.hasPurchasable) { lastSet.hasPurchasable = true } } this.notifyDataSetChanged() } fun getSelectCustomizationEvents(): Flowable<Customization> { return selectCustomizationEvents.toFlowable(BackpressureStrategy.DROP) } fun getUnlockCustomizationEvents(): Flowable<Customization> { return unlockCustomizationEvents.toFlowable(BackpressureStrategy.DROP) } fun getUnlockSetEvents(): Flowable<CustomizationSet> { return unlockSetEvents.toFlowable(BackpressureStrategy.DROP) } internal inner class CustomizationViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView), View.OnClickListener { private val binding = CustomizationGridItemBinding.bind(itemView) var customization: Customization? = null init { itemView.setOnClickListener(this) } fun bind(customization: Customization) { this.customization = customization DataBindingUtils.loadImage(binding.imageView, customization.getIconName(userSize, hairColor)) if (customization.type == "background") { val params = (binding.imageView.layoutParams as? LinearLayout.LayoutParams)?.apply { gravity = Gravity.CENTER } binding.imageView.layoutParams = params } if (customization.isUsable(ownedCustomiztations.contains(customization.identifier))) { binding.buyButton.visibility = View.GONE } else { binding.buyButton.visibility = View.VISIBLE if (customization.customizationSet?.contains("timeTravel") == true) { binding.priceLabel.currency = "hourglasses" } else { binding.priceLabel.currency = "gems" } binding.priceLabel.value = customization.price?.toDouble() ?: 0.0 } if (activeCustomization == customization.identifier) { binding.wrapper.background = itemView.context.getDrawable(R.drawable.layout_rounded_bg_gray_700_brand_border) } else { binding.wrapper.background = itemView.context.getDrawable(R.drawable.layout_rounded_bg_gray_700) } } override fun onClick(v: View) { if (customization?.isUsable(ownedCustomiztations.contains(customization?.identifier)) == false) { if (customization?.customizationSet?.contains("timeTravel") == true) { val dialog = HabiticaAlertDialog(itemView.context) dialog.setMessage(R.string.purchase_from_timetravel_shop) dialog.addButton(R.string.go_shopping, true) { _, _ -> MainNavigationController.navigate(R.id.shopsFragment, bundleOf(Pair("selectedTab", 3))) } dialog.addButton(R.string.reward_dialog_dismiss, false) dialog.show() } else { val dialogContent = LayoutInflater.from(itemView.context).inflate(R.layout.dialog_purchase_customization, null) as LinearLayout val imageView = dialogContent.findViewById<SimpleDraweeView>(R.id.imageView) DataBindingUtils.loadImage(imageView, customization?.getImageName(userSize, hairColor)) val priceLabel = dialogContent.findViewById<TextView>(R.id.priceLabel) priceLabel.text = customization?.price.toString() (dialogContent.findViewById<View>(R.id.gem_icon) as? ImageView)?.setImageBitmap(HabiticaIconsHelper.imageOfGem()) val dialog = HabiticaAlertDialog(itemView.context) dialog.addButton(R.string.purchase_button, true) { _, _ -> if (customization?.price ?: 0 > gemBalance) { MainNavigationController.navigate(R.id.gemPurchaseActivity, bundleOf(Pair("openSubscription", false))) return@addButton } customization?.let { unlockCustomizationEvents.onNext(it) } } dialog.setTitle(R.string.purchase_customization) dialog.setAdditionalContentView(dialogContent) dialog.addButton(R.string.reward_dialog_dismiss, false) dialog.show() } return } if (customization?.identifier == activeCustomization) { return } customization?.let { selectCustomizationEvents.onNext(it) } } } internal inner class SectionViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView), View.OnClickListener { private val binding = CustomizationSectionHeaderBinding.bind(itemView) private val label: TextView by bindView(itemView, R.id.label) var context: Context = itemView.context private var set: CustomizationSet? = null init { binding.purchaseSetButton.setOnClickListener(this) } fun bind(set: CustomizationSet) { this.set = set this.label.text = set.text if (set.hasPurchasable && !set.identifier.contains("timeTravel")) { binding.purchaseSetButton.visibility = View.VISIBLE binding.setPriceLabel.value = set.price.toDouble() binding.setPriceLabel.currency = "gems" } else { binding.purchaseSetButton.visibility = View.GONE } } override fun onClick(v: View) { val dialogContent = LayoutInflater.from(context).inflate(R.layout.dialog_purchase_customization, null) as LinearLayout val priceLabel = dialogContent.findViewById<TextView>(R.id.priceLabel) priceLabel.text = set?.price.toString() val dialog = HabiticaAlertDialog(context) dialog.addButton(R.string.purchase_button, true) { _, _ -> if (set?.price ?: 0 > gemBalance) { MainNavigationController.navigate(R.id.gemPurchaseActivity, bundleOf(Pair("openSubscription", false))) return@addButton } set?.customizations = ArrayList() customizationList .filter { Customization::class.java.isAssignableFrom(it.javaClass) } .map { it as Customization } .filter { !it.isUsable(ownedCustomiztations.contains(it.identifier)) && it.customizationSet != null && it.customizationSet == set?.identifier } .forEach { set?.customizations?.add(it) } if (additionalSetItems.isNotEmpty()) { additionalSetItems .filter { !it.isUsable(ownedCustomiztations.contains(it.identifier)) && it.customizationSet != null && it.customizationSet == set?.identifier } .forEach { set?.customizations?.add(it) } } set?.let { unlockSetEvents.onNext(it) } } dialog.setTitle(context.getString(R.string.purchase_set_title, set?.text)) dialog.setAdditionalContentView(dialogContent) dialog.addButton(R.string.reward_dialog_dismiss, false) dialog.show() } } }
gpl-3.0
ded3493126989de55c69913b4837b8b1
44.739286
222
0.618553
5.478024
false
false
false
false
viartemev/requestmapper
src/main/kotlin/com/viartemev/requestmapper/RequestMappingItem.kt
1
1847
package com.viartemev.requestmapper import com.intellij.navigation.ItemPresentation import com.intellij.navigation.NavigationItem import com.intellij.pom.Navigatable import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod class RequestMappingItem(val psiElement: PsiElement, private val urlPath: String, private val requestMethod: String) : NavigationItem { private val navigationElement = psiElement.navigationElement as? Navigatable override fun getName(): String = this.requestMethod + " " + this.urlPath override fun getPresentation(): ItemPresentation = RequestMappingItemPresentation() override fun navigate(requestFocus: Boolean) = navigationElement?.navigate(requestFocus) ?: Unit override fun canNavigate(): Boolean = navigationElement?.canNavigate() ?: false override fun canNavigateToSource(): Boolean = true override fun toString(): String { return "RequestMappingItem(psiElement=$psiElement, urlPath='$urlPath', requestMethod='$requestMethod', navigationElement=$navigationElement)" } private inner class RequestMappingItemPresentation : ItemPresentation { override fun getPresentableText() = [email protected] + " " + [email protected] override fun getLocationString(): String { val psiElement = [email protected] val fileName = psiElement.containingFile?.name return when (psiElement) { is PsiMethod -> (psiElement.containingClass?.name ?: fileName ?: "unknownFile") + "." + psiElement.name is PsiClass -> psiElement.name ?: fileName ?: "unknownFile" else -> "unknownLocation" } } override fun getIcon(b: Boolean) = RequestMapperIcons.SEARCH } }
mit
783bfdafe6fa1fd49a61b1f57eca4df8
40.977273
149
0.726042
5.448378
false
false
false
false
fabmax/kool
kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/vk/OnScreenRenderPass.kt
1
4115
package de.fabmax.kool.platform.vk import de.fabmax.kool.util.logD import org.lwjgl.vulkan.KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR import org.lwjgl.vulkan.VK10.* class OnScreenRenderPass(swapChain: SwapChain) : VkRenderPass(swapChain.sys, swapChain.extent.width(), swapChain.extent.height(), listOf(swapChain.imageFormat)) { override val vkRenderPass: Long init { memStack { val attachments = callocVkAttachmentDescriptionN(3) { this[0] .format(swapChain.imageFormat) .samples(swapChain.sys.physicalDevice.msaaSamples) .loadOp(VK_ATTACHMENT_LOAD_OP_CLEAR) .storeOp(VK_ATTACHMENT_STORE_OP_STORE) .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) .initialLayout(VK_IMAGE_LAYOUT_UNDEFINED) .finalLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) this[1] .format(swapChain.sys.physicalDevice.depthFormat) .samples(swapChain.sys.physicalDevice.msaaSamples) .loadOp(VK_ATTACHMENT_LOAD_OP_CLEAR) .storeOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) .initialLayout(VK_IMAGE_LAYOUT_UNDEFINED) .finalLayout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) this[2] .format(swapChain.imageFormat) .samples(VK_SAMPLE_COUNT_1_BIT) .loadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) .storeOp(VK_ATTACHMENT_STORE_OP_STORE) .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) .initialLayout(VK_IMAGE_LAYOUT_UNDEFINED) .finalLayout(VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) } val colorAttachmentRef = callocVkAttachmentReferenceN(1) { attachment(0) layout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) } val depthAttachmentRef = callocVkAttachmentReferenceN(1) { attachment(1) layout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) } val colorAttachmentResolveRef = callocVkAttachmentReferenceN(1) { attachment(2) layout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) } val subpass = callocVkSubpassDescriptionN(1) { pipelineBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS) colorAttachmentCount(1) pColorAttachments(colorAttachmentRef) pDepthStencilAttachment(depthAttachmentRef[0]) pResolveAttachments(colorAttachmentResolveRef) } val dependency = callocVkSubpassDependencyN(1) { srcSubpass(VK_SUBPASS_EXTERNAL) dstSubpass(0) srcStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) srcAccessMask(0) dstStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_READ_BIT or VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT) } val renderPassInfo = callocVkRenderPassCreateInfo { sType(VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO) pAttachments(attachments) pSubpasses(subpass) pDependencies(dependency) } vkRenderPass = checkCreatePointer { vkCreateRenderPass(swapChain.sys.device.vkDevice, renderPassInfo, null, it) } } swapChain.addDependingResource(this) logD { "Created render pass" } } override fun freeResources() { vkDestroyRenderPass(sys.device.vkDevice, vkRenderPass, null) logD { "Destroyed render pass" } } }
apache-2.0
4b51e04ba93a1c8a438eecac84354b4f
43.73913
125
0.595626
4.497268
false
false
false
false
fabmax/kool
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/procedural/Vase.kt
1
5418
package de.fabmax.kool.demo.procedural import de.fabmax.kool.math.Vec3f import de.fabmax.kool.math.toDeg import de.fabmax.kool.pipeline.Attribute import de.fabmax.kool.pipeline.deferred.deferredPbrShader import de.fabmax.kool.scene.Mesh import de.fabmax.kool.scene.geometry.IndexedVertexList import de.fabmax.kool.scene.geometry.MeshBuilder import de.fabmax.kool.scene.geometry.simpleShape import de.fabmax.kool.util.Color import de.fabmax.kool.util.ColorGradient import de.fabmax.kool.util.MdColor import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin class Vase : Mesh(IndexedVertexList(Attribute.POSITIONS, Attribute.NORMALS, Attribute.COLORS)) { init { generate { makeGeometry() geometry.removeDegeneratedTriangles() geometry.generateNormals() } shader = deferredPbrShader { roughness = 0.3f } } private fun MeshBuilder.makeGeometry() { rotate(90f, Vec3f.NEG_X_AXIS) translate(-7.5f, -2.5f, 0f) scale(1.8f, 1.8f, 1.8f) translate(0f, 0f, 0.15f) val gridGrad = ColorGradient(MdColor.BROWN, MdColor.BLUE tone 300) val tubeColors = Array(10) { i -> gridGrad.getColor(i / 9f).mix(Color.BLACK, 0.3f) } val tubeGrad = ColorGradient(*tubeColors) makeGrid(gridGrad) makeTube(tubeGrad) } private fun MeshBuilder.makeGrid(gridGrad: ColorGradient) { profile { simpleShape(true) { xy(0.8f, 1f); xy(-0.8f, 1f) xy(-1f, 0.8f); xy(-1f, -0.8f) xy(-0.8f, -1f); xy(0.8f, -1f) xy(1f, -0.8f); xy(1f, 0.8f) } val n = 50 val cols = 24 for (c in 0 until cols) { val rad = 2f * PI.toFloat() * c / cols for (i in 0..n) { withTransform { val p = i.toFloat() / n val rot = p * 180f * if (c % 2 == 0) 1 else -1 color = gridGrad.getColor(p).toLinear() rotate(rot, Vec3f.Z_AXIS) val r = 1f + (p - 0.5f) * (p - 0.5f) * 4 translate(cos(rad) * r, sin(rad) * r, 0f) translate(0f, 0f, p * 10f) rotate(rad.toDeg(), Vec3f.Z_AXIS) scale(0.05f, 0.05f, 1f) sample(i != 0) } } } } } private fun MeshBuilder.makeTube(tubeGrad: ColorGradient) { profile { circleShape(2.2f, 60) withTransform { for (i in 0..1) { val invert = i == 1 withTransform { color = tubeGrad.getColor(0f).toLinear() scale(0.97f, 0.97f, 1f) sample(connect = false, inverseOrientation = invert) scale(1 / 0.97f, 1 / 0.97f, 1f) scale(0.96f, 0.96f, 1f) sample(inverseOrientation = invert) scale(1 / 0.96f, 1 / 0.96f, 1f) scale(0.95f, 0.95f, 1f) //sample(inverseOrientation = invert) for (j in 0..20) { withTransform { val p = j / 20f val s = 1 - sin(p * PI.toFloat()) * 0.6f val t = 5f - cos(p * PI.toFloat()) * 5 color = tubeGrad.getColor(p).toLinear() translate(0f, 0f, t) scale(s, s, 1f) sample(inverseOrientation = invert) } if (j == 0) { // actually fills bottom, but with inverted face orientation fillTop() } } translate(0f, 0f, 10f) scale(1 / 0.95f, 1 / 0.95f, 1f) scale(0.96f, 0.96f, 1f) sample(inverseOrientation = invert) scale(1 / 0.96f, 1 / 0.96f, 1f) scale(0.97f, 0.97f, 1f) sample(inverseOrientation = invert) } translate(0f, 0f, -0.15f) scale(1f, 1f, 10.3f / 10f) } } for (i in 0..1) { color = tubeGrad.getColor(i.toFloat()).toLinear() withTransform { translate(0f, 0f, -0.15f + 10.15f * i) scale(0.97f, 0.97f, 1f) sample(connect = false) scale(1f / 0.97f, 1f / 0.97f, 1f) sample() translate(0f, 0f, 0.03f) scale(1.02f, 1.02f, 1f) sample() translate(0f, 0f, 0.09f) sample() translate(0f, 0f, 0.03f) scale(1f / 1.02f, 1f / 1.02f, 1f) sample() scale(0.97f, 0.97f, 1f) sample() } } } } }
apache-2.0
f6a7e72c0e1701b281e3e994c9b38288
33.515924
96
0.428756
3.87
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/checker/recovery/namelessToplevelDeclarations.fir.kt
10
566
package<EOLError descr="Package name must be a '.'-separated identifier list placed on a single line"></EOLError> <error descr="[FUNCTION_DECLARATION_WITH_NO_NAME] Function declaration must have a name">fun ()</error> { } val<error descr="Expecting property name or receiver type"> </error>: Int = 1 class<error descr="Name expected"> </error>{ } interface<error descr="Name expected"> </error>{ } object<error descr="Name expected"> </error>{ } enum class<error descr="Name expected"> </error>{} annotation class<error descr="Name expected"> </error>{}
apache-2.0
da2f85be59563874ab0629f362308ad8
22.583333
113
0.712014
3.675325
false
false
false
false
mseroczynski/CityBikes
app/src/main/kotlin/pl/ches/citybikes/util/extensions/Slimber.kt
1
1913
import android.util.Log import timber.log.Timber inline fun ifPlanted(action: () -> Any) { if (Timber.forest().size > 0) { action.invoke() } } inline fun e(message: () -> String) = ifPlanted { Timber.e(message.invoke()) } inline fun e(throwable: Throwable, message: () -> String) = ifPlanted { Timber.e(throwable, message.invoke()) } inline fun w(message: () -> String) = ifPlanted { Timber.w(message.invoke()) } inline fun w(throwable: Throwable, message: () -> String) = ifPlanted { Timber.w(throwable, message.invoke()) } inline fun i(message: () -> String) = ifPlanted { Timber.i(message.invoke()) } inline fun i(throwable: Throwable, message: () -> String) = ifPlanted { Timber.i(throwable, message.invoke()) } inline fun d(message: () -> String) = ifPlanted { Timber.d(message.invoke()) } inline fun d(throwable: Throwable, message: () -> String) = ifPlanted { Timber.d(throwable, message.invoke()) } inline fun v(message: () -> String) = ifPlanted { Timber.v(message.invoke()) } inline fun v(throwable: Throwable, message: () -> String) = ifPlanted { Timber.v(throwable, message.invoke()) } inline fun wtf(message: () -> String) = ifPlanted { Timber.wtf(message.invoke()) } inline fun wtf(throwable: Throwable, message: () -> String) = ifPlanted { Timber.wtf(throwable, message.invoke()) } inline fun log(priority: Int, t: Throwable, message: () -> String) { when (priority) { Log.ERROR -> e(t, message) Log.WARN -> w(t, message) Log.INFO -> i(t, message) Log.DEBUG -> d(t, message) Log.VERBOSE -> v(t, message) Log.ASSERT -> wtf(t, message) } } inline fun log(priority: Int, message: () -> String) { when (priority) { Log.ERROR -> e(message) Log.WARN -> w(message) Log.INFO -> i(message) Log.DEBUG -> d(message) Log.VERBOSE -> v(message) Log.ASSERT -> wtf(message) } }
gpl-3.0
3b86d2d8f9b94f33ed581807f44fac4b
38.875
115
0.628855
3.362039
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveAtFromAnnotationArgument.kt
1
1432
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.KtAnnotatedExpression import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory class RemoveAtFromAnnotationArgument(constructor: KtAnnotationEntry) : KotlinQuickFixAction<KtAnnotationEntry>(constructor) { override fun getText() = KotlinBundle.message("remove.from.annotation.argument") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val elementToReplace = (element?.parent as? KtAnnotatedExpression) ?: return val noAt = KtPsiFactory(elementToReplace.project).createExpression(elementToReplace.text.replaceFirst("@", "")) elementToReplace.replace(noAt) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtAnnotationEntry>? = (diagnostic.psiElement as? KtAnnotationEntry)?.let { RemoveAtFromAnnotationArgument(it) } } }
apache-2.0
9b701d26de3e961eb37de41a9ad33381
43.75
158
0.782821
4.805369
false
false
false
false
siosio/intellij-community
plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/postProcessing/diagnosticBasedPostProcessing.kt
2
4942
// 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.nj2k.postProcessing import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.RangeMarker import com.intellij.psi.PsiElement import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.idea.core.util.range import org.jetbrains.kotlin.idea.quickfix.AddExclExclCallFix import org.jetbrains.kotlin.idea.quickfix.KotlinIntentionActionsFactory import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.psiUtil.elementsInRange import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.utils.addToStdlib.safeAs class DiagnosticBasedPostProcessingGroup(diagnosticBasedProcessings: List<DiagnosticBasedProcessing>) : FileBasedPostProcessing() { constructor(vararg diagnosticBasedProcessings: DiagnosticBasedProcessing) : this(diagnosticBasedProcessings.toList()) private val diagnosticToFix = diagnosticBasedProcessings.asSequence().flatMap { processing -> processing.diagnosticFactories.asSequence().map { it to processing::fix } }.groupBy { it.first }.mapValues { (_, list) -> list.map { it.second } } override fun runProcessing(file: KtFile, allFiles: List<KtFile>, rangeMarker: RangeMarker?, converterContext: NewJ2kConverterContext) { val diagnostics = runReadAction { val resolutionFacade = KotlinCacheService.getInstance(converterContext.project).getResolutionFacade(allFiles) analyzeFileRange(file, rangeMarker, resolutionFacade).all() } for (diagnostic in diagnostics) { val elementIsInRange = runReadAction { val range = rangeMarker?.range ?: file.textRange diagnostic.psiElement.isInRange(range) } if (!elementIsInRange) continue diagnosticToFix[diagnostic.factory]?.forEach { fix -> val elementIsValid = runReadAction { diagnostic.psiElement.isValid } if (elementIsValid) { fix(diagnostic) } } } } private fun analyzeFileRange(file: KtFile, rangeMarker: RangeMarker?, resolutionFacade: ResolutionFacade): Diagnostics { val elements = when { rangeMarker == null -> listOf(file) rangeMarker.isValid -> file.elementsInRange(rangeMarker.range!!).filterIsInstance<KtElement>() else -> emptyList() } return if (elements.isNotEmpty()) resolutionFacade.analyzeWithAllCompilerChecks(elements).bindingContext.diagnostics else Diagnostics.EMPTY } } interface DiagnosticBasedProcessing { val diagnosticFactories: List<DiagnosticFactory<*>> fun fix(diagnostic: Diagnostic) } inline fun <reified T : PsiElement> diagnosticBasedProcessing( vararg diagnosticFactory: DiagnosticFactory<*>, crossinline fix: (T, Diagnostic) -> Unit ) = object : DiagnosticBasedProcessing { override val diagnosticFactories = diagnosticFactory.toList() override fun fix(diagnostic: Diagnostic) { val element = diagnostic.psiElement as? T if (element != null) runUndoTransparentActionInEdt(inWriteAction = true) { fix(element, diagnostic) } } } fun diagnosticBasedProcessing(fixFactory: KotlinIntentionActionsFactory, vararg diagnosticFactory: DiagnosticFactory<*>) = object : DiagnosticBasedProcessing { override val diagnosticFactories = diagnosticFactory.toList() override fun fix(diagnostic: Diagnostic) { val fix = runReadAction { fixFactory.createActions(diagnostic).singleOrNull() } ?: return runUndoTransparentActionInEdt(inWriteAction = true) { fix.invoke(diagnostic.psiElement.project, null, diagnostic.psiFile) } } } fun addExclExclFactoryNoImplicitReceiver(initialFactory: KotlinSingleIntentionActionFactory) = object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? = initialFactory.createActions(diagnostic).singleOrNull() ?.safeAs<AddExclExclCallFix>() ?.let { AddExclExclCallFix(diagnostic.psiElement, checkImplicitReceivers = false) } }
apache-2.0
c164aba99aaf7fca76017dec9ceab9c3
45.622642
158
0.717928
5.442731
false
false
false
false
vovagrechka/fucking-everything
attic/photlin-dev-tools/src/photlin/devtools/photlin-devtools.kt
1
14385
package photlin.devtools import com.intellij.codeInsight.highlighting.TooltipLinkHandler import com.intellij.codeInsight.hint.HintManager import com.intellij.codeInsight.hint.HintUtil import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandlerBase import com.intellij.codeInsight.preview.PreviewHintProvider import com.intellij.execution.actions.ChooseRunConfigurationPopupAction import com.intellij.execution.filters.HyperlinkInfo import com.intellij.execution.impl.ConsoleViewImpl import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.ide.IdeBundle import com.intellij.lang.ASTNode import com.intellij.lang.Language import com.intellij.lang.ParserDefinition import com.intellij.lang.PsiParser import com.intellij.lang.documentation.DocumentationProvider import com.intellij.lexer.FlexAdapter import com.intellij.lexer.Lexer import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.components.ApplicationComponent import com.intellij.openapi.editor.* import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileEditor.ex.FileEditorProviderManager import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.IconLoader import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.wm.IdeFocusManager import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.IFileElementType import com.intellij.psi.tree.TokenSet import com.intellij.util.lang.UrlClassLoader import org.eclipse.jetty.server.Server import org.eclipse.jetty.servlet.ServletHandler import org.eclipse.jetty.servlet.ServletHolder import photlin.devtools.psi.* import vgrechka.* import vgrechka.idea.* import java.io.File import javax.servlet.http.HttpServlet import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.swing.Icon import kotlin.concurrent.thread import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.event.EditorMouseEvent import com.intellij.openapi.editor.event.EditorMouseListener import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileTypes.* import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.util.PsiUtil import vgrechka.idea.hripos.* import vgrechka.ideabackdoor.* import javax.swing.JComponent import javax.swing.JLabel import javax.swing.event.HyperlinkEvent private var bs by notNullOnce<Bullshitter>() object PhotlinDevToolsGlobal { val rpcServerPort = 12321 } fun openFile(path: String, line: Int) { val projects = ProjectManager.getInstance().openProjects check(projects.size == 1) {"e5469c93-424d-4eef-81de-41c190b7f188"} val project = projects.first() if (openFile(project, path, line)) return Messages.showErrorDialog("File not fucking found", "Fuck You") } @Ser class PDTRemoteCommand_TestResult( val rawResponseFromPHPScript: String ) : Servant { override fun serve(): Any { bs.mumble("\n------------------- TEST RESULT ------------------\n") val re = Regex("<b>([^<]*?)</b> on line <b>([^<]*?)</b>") var searchStart = 0 while (true) { val mr = re.find(rawResponseFromPHPScript, searchStart) ?: break val filePath = mr.groupValues[1] val lineNumber = mr.groupValues[2].toInt() bs.mumbleNoln(rawResponseFromPHPScript.substring(searchStart, mr.range.start)) bs.mumbleNoln("$filePath on line ") bs.consoleView.printHyperlink("$lineNumber") { openFile(filePath, lineNumber) } bs.mumbleNoln("(") bs.consoleView.printHyperlink("@") { openFile("$filePath--tagged", lineNumber) } bs.mumbleNoln(")") searchStart = mr.range.endInclusive + 1 if (searchStart > rawResponseFromPHPScript.lastIndex) break } if (searchStart < rawResponseFromPHPScript.lastIndex) bs.mumbleNoln(rawResponseFromPHPScript.substring(searchStart)) bs.mumble("") (bs.consoleView as ConsoleViewImpl).scrollToEnd() return "Cool" } } class PhotlinDevToolsPlugin : ApplicationComponent { override fun getComponentName(): String { return this::class.qualifiedName!! } override fun disposeComponent() { } override fun initComponent() { EditorFactory.getInstance().eventMulticaster.addEditorMouseListener(object : EditorMouseListener { override fun mouseReleased(e: EditorMouseEvent?) { } override fun mouseEntered(e: EditorMouseEvent?) { } override fun mouseClicked(e: EditorMouseEvent) { val virtualFile = (e.editor as EditorImpl).virtualFile ?: return val psiFile = PsiUtil.getPsiFile(e.editor.project!!, virtualFile) if (psiFile is PHPTaggedFile) { val el = psiFile.findElementAt(e.editor.caretModel.offset) if (el is LeafPsiElement && el.elementType == PHPTaggedTypes.AT_TOKEN) { check(el.text.last() == '@') {"0ba8fb8b-4800-4cb8-b136-f4ce2106c39b"} val debugTag = el.text.dropLast(1) HintManager.getInstance().showInformationHint(e.editor, HintUtil.createInformationLabel( "<a href='fuck'>Debug $debugTag</a>", {linkEvent-> if (linkEvent.eventType == HyperlinkEvent.EventType.ACTIVATED) { breakOnDebugTag(e.editor.project, debugTag) } }, null, null)) } } } override fun mouseExited(e: EditorMouseEvent?) { } override fun mousePressed(e: EditorMouseEvent?) { } }) val pm = ProjectManager.getInstance() pm.addProjectManagerListener(object : ProjectManagerListener { override fun projectOpened(project: Project) { clog("Opened project", project.name) bs = Bullshitter(project) bs.mumble("Hello, sweetheart. I am Photlin Development Tools. Now use me") } }) val am = ActionManager.getInstance() val group = am.getAction("ToolsMenu") as DefaultActionGroup group.addSeparator() run { val action = object : AnAction("PDT: _Mess Around") { override fun actionPerformed(event: AnActionEvent) { messAroundAction(event) } } group.add(action) } // run { // val action = object : AnAction("Backdoor: Bullshit Something") { // override fun actionPerformed(event: AnActionEvent) { // val bs = Bullshitter(event.project!!) // bs.mumble("Something? How about fuck you?") // } // } // group.add(action) // } // run { // val action = object : AnAction("Backdoor: _Mess Around") { // override fun actionPerformed(event: AnActionEvent) { // val title = "Fucking through backdoor" // object : Task.Backgroundable(event.project, title, true) { // var rawResponse by notNullOnce<String>() // // override fun run(indicator: ProgressIndicator) { // indicator.text = title // indicator.fraction = 0.5 // val json = "{projectName: '${event.project!!.name}'}" // rawResponse = HTTPClient.postJSON("http://localhost:${BackdoorGlobal.rpcServerPort}?proc=MessAround", json) // indicator.fraction = 1.0 // } // // override fun onFinished() { // // Messages.showInfoMessage(rawResponse, "Response") // } // }.queue() // } // } // group.add(action) // } startRPCServer() } inner class startRPCServer { init { thread { try { Server(PhotlinDevToolsGlobal.rpcServerPort)-{o-> o.handler = ServletHandler() -{o-> o.addServletWithMapping(ServletHolder(FuckingServlet()), "/*") } o.start() clog("Shit is spinning") o.join() } } catch(e: Exception) { e.printStackTrace() } } } inner class FuckingServlet : HttpServlet() { override fun service(req: HttpServletRequest, res: HttpServletResponse) { req.characterEncoding = "UTF-8" req.queryString val rawRequest = req.reader.readText() clog("Got request:", rawRequest) val requestClass = Class.forName(this::class.java.`package`.name + ".PDTRemoteCommand_" + req.getParameter("proc")) val servant = relaxedObjectMapper.readValue(rawRequest, requestClass) as Servant var response by notNullOnce<Any>() ApplicationManager.getApplication().invokeAndWait { response = servant.serve() } val rawResponse = relaxedObjectMapper.writeValueAsString(response) res.contentType = "application/json; charset=utf-8" res.writer.println(rawResponse) res.status = HttpServletResponse.SC_OK } } } } private interface Servant { fun serve(): Any } private class messAroundAction(val event: AnActionEvent) { init { fuck1() } fun fuck2() { breakOnDebugTag(event.project, "234") } fun fuck1() { PDTRemoteCommand_TestResult(rawResponseFromPHPScript = """<br /> <b>Notice</b>: Use of undefined constant aps - assumed 'aps' in <b>C:\opt\xampp\htdocs\TryPhotlin\aps-back\aps-back.php</b> on line <b>16392</b><br /> <br /> <b>Fatal error</b>: Call to undefined function back_main() in <b>C:\opt\xampp\htdocs\TryPhotlin\aps-back\aps-back.php</b> on line <b>16392</b><br /> """).serve() } } object PHPTaggedLanguage : Language("PHPTagged") { } object PDTIcons { val phpTagged = IconLoader.getIcon("/photlin/devtools/php--tagged.png") } object PHPTaggedFileType : LanguageFileType(PHPTaggedLanguage) { override fun getIcon(): Icon? { return PDTIcons.phpTagged } override fun getName(): String { return "PHPTagged file" } override fun getDefaultExtension(): String { return "php--tagged" } override fun getDescription(): String { return name } } class PHPTaggedFileTypeFactory : FileTypeFactory() { override fun createFileTypes(consumer: FileTypeConsumer) { consumer.consume(PHPTaggedFileType, PHPTaggedFileType.defaultExtension) } } class PHPTaggedLexerAdapter : FlexAdapter(PHPTaggedLexer()) class PHPTaggedParserDefinition : ParserDefinition { override fun createParser(project: Project): PsiParser { return PHPTaggedParser() } override fun createFile(viewProvider: FileViewProvider): PsiFile { return PHPTaggedFile(viewProvider) } override fun spaceExistanceTypeBetweenTokens(left: ASTNode?, right: ASTNode?): ParserDefinition.SpaceRequirements { return ParserDefinition.SpaceRequirements.MAY } override fun getStringLiteralElements(): TokenSet { return TokenSet.EMPTY } val FILE = IFileElementType(PHPTaggedLanguage) override fun getFileNodeType(): IFileElementType { return FILE } override fun getWhitespaceTokens(): TokenSet { return TokenSet.create(PHPTaggedTypes.NL) // return TokenSet.EMPTY } override fun createLexer(project: Project?): Lexer { return PHPTaggedLexerAdapter() } override fun createElement(node: ASTNode): PsiElement { return PHPTaggedTypes.Factory.createElement(node) } override fun getCommentTokens(): TokenSet { return TokenSet.EMPTY } } class PHPTaggedSyntaxHighlighter : SyntaxHighlighterBase() { override fun getHighlightingLexer(): Lexer { return PHPTaggedLexerAdapter() } override fun getTokenHighlights(tokenType: IElementType): Array<TextAttributesKey> { // clog("tokenType: $tokenType") if (tokenType == PHPTaggedTypes.AT_TOKEN) { return VALUE_KEYS } else { return EMPTY_KEYS } } companion object { val VALUE = TextAttributesKey.createTextAttributesKey("SIMPLE_VALUE", DefaultLanguageHighlighterColors.STRING) private val VALUE_KEYS = arrayOf(VALUE) private val EMPTY_KEYS = arrayOf<TextAttributesKey>() } } class PHPTaggedSyntaxHighlighterFactory : SyntaxHighlighterFactory() { override fun getSyntaxHighlighter(project: Project?, virtualFile: VirtualFile?): SyntaxHighlighter { return PHPTaggedSyntaxHighlighter() } } private fun breakOnDebugTag(localProject: Project?, debugTag: String) { rubRemoteIdeaTits(localProject, Command_Photlin_BreakOnDebugTag(debugTag = debugTag), onError = { Messages.showErrorDialog(it, "Fuck You") }) }
apache-2.0
a9a0d15fbecbb36a7d01646f241fde71
32.767606
151
0.637956
4.71794
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/gamedashboard/GameDashboardFragment.kt
1
5054
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.screens.gamedashboard import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.app.playhvz.R import com.app.playhvz.common.globals.SharedPreferencesConstants import com.app.playhvz.firebase.classmodels.Game import com.app.playhvz.firebase.classmodels.Player import com.app.playhvz.firebase.viewmodels.GameViewModel import com.app.playhvz.navigation.NavigationUtil import com.app.playhvz.screens.gamedashboard.cards.* import com.app.playhvz.utils.PlayerUtils import com.app.playhvz.utils.SystemUtils /** Fragment for showing a list of Games the user is registered for.*/ class GameDashboardFragment : Fragment() { companion object { private val TAG = GameDashboardFragment::class.qualifiedName } private lateinit var firestoreViewModel: GameViewModel private lateinit var declareAllegianceCard: DeclareAllegianceCard private lateinit var infectCard: InfectCard private lateinit var leaderboardCard: LeaderboardCard private lateinit var lifeCodeCard: LifeCodeCard private lateinit var missionCard: MissionCard var gameId: String? = null var playerId: String? = null var game: Game? = null var player: Player? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) firestoreViewModel = ViewModelProvider(requireActivity()).get(GameViewModel::class.java) val sharedPrefs = activity?.getSharedPreferences( SharedPreferencesConstants.PREFS_FILENAME, 0 )!! gameId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_GAME_ID, null) playerId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_PLAYER_ID, null) if (gameId == null || playerId == null) { SystemUtils.clearSharedPrefs(requireActivity()) NavigationUtil.navigateToGameList(findNavController(), requireActivity()) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { setupObservers() setupCards() val view = inflater.inflate(R.layout.fragment_game_dashboard, container, false) declareAllegianceCard.onCreateView(view) infectCard.onCreateView(view) leaderboardCard.onCreateView(view) lifeCodeCard.onCreateView(view) missionCard.onCreateView(view) setupToolbar() return view } fun setupToolbar() { val toolbar = (activity as AppCompatActivity).supportActionBar if (toolbar != null) { toolbar.title = if (game == null || game?.name.isNullOrEmpty()) requireContext().getString(R.string.app_name) else game?.name } } private fun setupObservers() { if (gameId == null || playerId == null) { return } firestoreViewModel.getGame(this, gameId!!) .observe(viewLifecycleOwner, androidx.lifecycle.Observer { serverGame: Game -> updateGame(serverGame) }) PlayerUtils.getPlayer(gameId!!, playerId!!) .observe(viewLifecycleOwner, androidx.lifecycle.Observer { serverPlayer -> updatePlayer(serverPlayer) }) } private fun setupCards() { declareAllegianceCard = DeclareAllegianceCard(this, gameId!!, playerId!!) infectCard = InfectCard(this, gameId!!, playerId!!) leaderboardCard = LeaderboardCard(this, gameId!!, playerId!!) lifeCodeCard = LifeCodeCard(this, gameId!!, playerId!!) missionCard = MissionCard(this, findNavController(), gameId!!, playerId!!) } private fun updateGame(serverGame: Game?) { game = serverGame setupToolbar() } private fun updatePlayer(serverPlayer: Player?) { if (serverPlayer == null) { NavigationUtil.navigateToGameList(findNavController(), requireActivity()) } declareAllegianceCard.onPlayerUpdated(serverPlayer!!) infectCard.onPlayerUpdated(serverPlayer) leaderboardCard.onPlayerUpdated(serverPlayer) lifeCodeCard.onPlayerUpdated(serverPlayer) } }
apache-2.0
0ead1bf434b1b31cf846fba55c6e6513
36.723881
109
0.702216
4.827125
false
false
false
false
androidx/androidx
compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/lower/LiveLiteralTransformer.kt
3
38740
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.compiler.plugins.kotlin.lower import androidx.compose.compiler.plugins.kotlin.ComposeCallableIds import androidx.compose.compiler.plugins.kotlin.ComposeClassIds import androidx.compose.compiler.plugins.kotlin.ModuleMetrics import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET import org.jetbrains.kotlin.ir.builders.declarations.IrFunctionBuilder import org.jetbrains.kotlin.ir.builders.declarations.addConstructor import org.jetbrains.kotlin.ir.builders.declarations.addFunction import org.jetbrains.kotlin.ir.builders.declarations.addGetter import org.jetbrains.kotlin.ir.builders.declarations.addProperty import org.jetbrains.kotlin.ir.builders.declarations.addValueParameter import org.jetbrains.kotlin.ir.builders.declarations.buildClass import org.jetbrains.kotlin.ir.builders.declarations.buildField import org.jetbrains.kotlin.ir.builders.irBlock import org.jetbrains.kotlin.ir.builders.irBlockBody import org.jetbrains.kotlin.ir.builders.irCall import org.jetbrains.kotlin.ir.builders.irDelegatingConstructorCall import org.jetbrains.kotlin.ir.builders.irGet import org.jetbrains.kotlin.ir.builders.irGetField import org.jetbrains.kotlin.ir.builders.irIfNull import org.jetbrains.kotlin.ir.builders.irReturn import org.jetbrains.kotlin.ir.builders.irSet import org.jetbrains.kotlin.ir.builders.irSetField import org.jetbrains.kotlin.ir.builders.irString import org.jetbrains.kotlin.ir.builders.irTemporary import org.jetbrains.kotlin.ir.declarations.IrAnnotationContainer import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin import org.jetbrains.kotlin.ir.declarations.IrEnumEntry import org.jetbrains.kotlin.ir.declarations.IrFactory import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import org.jetbrains.kotlin.ir.declarations.IrProperty import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction import org.jetbrains.kotlin.ir.declarations.IrValueParameter import org.jetbrains.kotlin.ir.declarations.IrVariable import org.jetbrains.kotlin.ir.expressions.IrBlock import org.jetbrains.kotlin.ir.expressions.IrBlockBody import org.jetbrains.kotlin.ir.expressions.IrBody import org.jetbrains.kotlin.ir.expressions.IrBranch import org.jetbrains.kotlin.ir.expressions.IrCall import org.jetbrains.kotlin.ir.expressions.IrComposite import org.jetbrains.kotlin.ir.expressions.IrConst import org.jetbrains.kotlin.ir.expressions.IrConstKind import org.jetbrains.kotlin.ir.expressions.IrConstructorCall import org.jetbrains.kotlin.ir.expressions.IrDelegatingConstructorCall import org.jetbrains.kotlin.ir.expressions.IrElseBranch import org.jetbrains.kotlin.ir.expressions.IrEnumConstructorCall import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.expressions.IrLoop import org.jetbrains.kotlin.ir.expressions.IrSetField import org.jetbrains.kotlin.ir.expressions.IrSetValue import org.jetbrains.kotlin.ir.expressions.IrStatementOrigin import org.jetbrains.kotlin.ir.expressions.IrStringConcatenation import org.jetbrains.kotlin.ir.expressions.IrTry import org.jetbrains.kotlin.ir.expressions.IrVararg import org.jetbrains.kotlin.ir.expressions.IrVarargElement import org.jetbrains.kotlin.ir.expressions.IrWhen import org.jetbrains.kotlin.ir.expressions.impl.IrBranchImpl import org.jetbrains.kotlin.ir.expressions.impl.IrCallImpl import org.jetbrains.kotlin.ir.expressions.impl.IrConstructorCallImpl import org.jetbrains.kotlin.ir.expressions.impl.IrElseBranchImpl import org.jetbrains.kotlin.ir.expressions.impl.IrExpressionBodyImpl import org.jetbrains.kotlin.ir.expressions.impl.IrGetObjectValueImpl import org.jetbrains.kotlin.ir.expressions.impl.IrStringConcatenationImpl import org.jetbrains.kotlin.ir.expressions.impl.IrVarargImpl import org.jetbrains.kotlin.ir.expressions.impl.copyWithOffsets import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.types.defaultType import org.jetbrains.kotlin.ir.types.makeNullable import org.jetbrains.kotlin.ir.types.typeWith import org.jetbrains.kotlin.ir.util.DeepCopySymbolRemapper import org.jetbrains.kotlin.ir.util.SYNTHETIC_OFFSET import org.jetbrains.kotlin.ir.util.addChild import org.jetbrains.kotlin.ir.util.constructors import org.jetbrains.kotlin.ir.util.copyTo import org.jetbrains.kotlin.ir.util.createParameterDeclarations import org.jetbrains.kotlin.ir.util.defaultType import org.jetbrains.kotlin.ir.util.getPropertyGetter import org.jetbrains.kotlin.ir.util.isAnnotationClass import org.jetbrains.kotlin.ir.util.parentAsClass import org.jetbrains.kotlin.ir.util.primaryConstructor import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils import org.jetbrains.kotlin.name.Name /** * This transformer transforms constant literal expressions into expressions which read a * MutableState instance so that changes to the source code of the constant literal can be * communicated to the runtime without a recompile. This transformation is intended to improve * developer experience and should never be enabled in a release build as it will significantly * slow down performance-conscious code. * * The nontrivial piece of this transform is to create a stable "durable" unique key for every * single constant in the module. It does this by creating a path-based key which roughly maps to * the semantic structure of the code, and uses an incrementing index on sibling constants as a * last resort. The constant expressions in the IR will be transformed into property getter calls * to a synthetic "Live Literals" class that is generated per file. The class is an object * singleton where each property is lazily backed by a MutableState instance which is accessed * using the runtime's `liveLiteral(String,T)` top level API. * * Roughly speaking, the transform will turn the following: * * // file: Foo.kt * fun Foo() { * print("Hello World") * } * * into the following equivalent representation: * * // file: Foo.kt * fun Foo() { * print(LiveLiterals$FooKt.`getString$arg-0$call-print$fun-Foo`()) * } * object LiveLiterals$FooKt { * var `String$arg-0$call-print$fun-Foo`: String = "Hello World" * var `State$String$arg-0$call-print$fun-Foo`: MutableState<String>? = null * fun `getString$arg-0$call-print$fun-Foo`(): String { * val field = this.`String$arg-0$call-print$fun-Foo` * val state = if (field == null) { * val tmp = liveLiteral( * "String$arg-0$call-print$fun-Foo", * this.`String$arg-0$call-print$fun-Foo` * ) * this.`String$arg-0$call-print$fun-Foo` = tmp * tmp * } else field * return field.value * } * } * * @see DurableKeyVisitor */ open class LiveLiteralTransformer( private val liveLiteralsEnabled: Boolean, private val usePerFileEnabledFlag: Boolean, private val keyVisitor: DurableKeyVisitor, context: IrPluginContext, symbolRemapper: DeepCopySymbolRemapper, metrics: ModuleMetrics, ) : AbstractComposeLowering(context, symbolRemapper, metrics), ModuleLoweringPass { override fun lower(module: IrModuleFragment) { module.transformChildrenVoid(this) } private val liveLiteral = getTopLevelFunction(ComposeCallableIds.liveLiteral) private val isLiveLiteralsEnabled = getTopLevelPropertyGetter(ComposeCallableIds.isLiveLiteralsEnabled) private val liveLiteralInfoAnnotation = getTopLevelClass(ComposeClassIds.LiveLiteralInfo) private val liveLiteralFileInfoAnnotation = getTopLevelClass(ComposeClassIds.LiveLiteralFileInfo) private val stateInterface = getTopLevelClass(ComposeClassIds.State) private val NoLiveLiteralsAnnotation = getTopLevelClass(ComposeClassIds.NoLiveLiterals) private fun IrAnnotationContainer.hasNoLiveLiteralsAnnotation(): Boolean = annotations.any { it.symbol.owner == NoLiveLiteralsAnnotation.owner.primaryConstructor } private fun <T> enter(key: String, block: () -> T) = keyVisitor.enter(key, block) private fun <T> siblings(key: String, block: () -> T) = keyVisitor.siblings(key, block) private fun <T> siblings(block: () -> T) = keyVisitor.siblings(block) private var liveLiteralsClass: IrClass? = null private var liveLiteralsEnabledSymbol: IrSimpleFunctionSymbol? = null private var currentFile: IrFile? = null private fun irGetLiveLiteralsClass(startOffset: Int, endOffset: Int): IrExpression { return IrGetObjectValueImpl( startOffset = startOffset, endOffset = endOffset, type = liveLiteralsClass!!.defaultType, symbol = liveLiteralsClass!!.symbol ) } private fun Name.asJvmFriendlyString(): String { return if (!isSpecial) identifier else asString().replace('<', '$').replace('>', '$').replace(' ', '-') } private fun irLiveLiteralInfoAnnotation( key: String, offset: Int ): IrConstructorCall = IrConstructorCallImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, liveLiteralInfoAnnotation.defaultType, liveLiteralInfoAnnotation.constructors.single(), 0, 0, 2 ).apply { putValueArgument(0, irConst(key)) putValueArgument(1, irConst(offset)) } private fun irLiveLiteralFileInfoAnnotation( file: String ): IrConstructorCall = IrConstructorCallImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, liveLiteralFileInfoAnnotation.defaultType, liveLiteralFileInfoAnnotation.constructors.single(), 0, 0, 1 ).apply { putValueArgument(0, irConst(file)) } private fun irLiveLiteralGetter( key: String, literalValue: IrExpression, literalType: IrType, startOffset: Int ): IrSimpleFunction { val clazz = liveLiteralsClass!! val stateType = stateInterface.owner.typeWith(literalType).makeNullable() val stateGetValue = stateInterface.getPropertyGetter("value")!! val defaultProp = clazz.addProperty { name = Name.identifier(key) visibility = DescriptorVisibilities.PRIVATE }.also { p -> p.backingField = context.irFactory.buildField { name = Name.identifier(key) isStatic = true type = literalType visibility = DescriptorVisibilities.PRIVATE }.also { f -> f.correspondingPropertySymbol = p.symbol f.parent = clazz f.initializer = IrExpressionBodyImpl( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, literalValue ) } p.addGetter { returnType = literalType visibility = DescriptorVisibilities.PRIVATE origin = IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR }.also { fn -> fn.correspondingPropertySymbol = p.symbol val thisParam = clazz.thisReceiver!!.copyTo(fn) fn.dispatchReceiverParameter = thisParam fn.body = DeclarationIrBuilder(context, fn.symbol).irBlockBody { +irReturn(irGetField(irGet(thisParam), p.backingField!!)) } } } val stateProp = clazz.addProperty { name = Name.identifier("State\$$key") visibility = DescriptorVisibilities.PRIVATE isVar = true }.also { p -> p.backingField = context.irFactory.buildField { name = Name.identifier("State\$$key") type = stateType visibility = DescriptorVisibilities.PRIVATE isStatic = true }.also { f -> f.correspondingPropertySymbol = p.symbol f.parent = clazz } p.addGetter { returnType = stateType visibility = DescriptorVisibilities.PRIVATE origin = IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR }.also { fn -> fn.correspondingPropertySymbol = p.symbol val thisParam = clazz.thisReceiver!!.copyTo(fn) fn.dispatchReceiverParameter = thisParam fn.body = DeclarationIrBuilder(context, fn.symbol).irBlockBody { +irReturn(irGetField(irGet(thisParam), p.backingField!!)) } } p.addSetter { returnType = context.irBuiltIns.unitType visibility = DescriptorVisibilities.PRIVATE origin = IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR }.also { fn -> fn.correspondingPropertySymbol = p.symbol val thisParam = clazz.thisReceiver!!.copyTo(fn) fn.dispatchReceiverParameter = thisParam val valueParam = fn.addValueParameter("value", stateType) fn.body = DeclarationIrBuilder(context, fn.symbol).irBlockBody { +irSetField(irGet(thisParam), p.backingField!!, irGet(valueParam)) } } } return clazz.addFunction( name = key, returnType = literalType ).also { fn -> val thisParam = fn.dispatchReceiverParameter!! fn.annotations += irLiveLiteralInfoAnnotation(key, startOffset) fn.body = DeclarationIrBuilder(context, fn.symbol).irBlockBody { // if (!isLiveLiteralsEnabled) return defaultValueField // val a = stateField // val b = if (a == null) { // val c = liveLiteralState("key", defaultValueField) // stateField = c // c // } else a // return b.value val condition = if (usePerFileEnabledFlag) irNot( irGet(builtIns.booleanType, irGet(thisParam), liveLiteralsEnabledSymbol!!) ) else irNot(irCall(isLiveLiteralsEnabled)) +irIf( condition = condition, body = irReturn( irGet( literalType, irGet(thisParam), defaultProp.getter!!.symbol ) ) ) val a = irTemporary(irGet(stateType, irGet(thisParam), stateProp.getter!!.symbol)) val b = irIfNull( type = stateType, subject = irGet(a), thenPart = irBlock(resultType = stateType) { val liveLiteralCall = irCall(liveLiteral).apply { putValueArgument(0, irString(key)) putValueArgument( 1, irGet( literalType, irGet(thisParam), defaultProp.getter!!.symbol ) ) putTypeArgument(0, literalType) } val c = irTemporary(liveLiteralCall) +irSet( stateType, irGet(thisParam), stateProp.setter!!.symbol, irGet(c) ) +irGet(c) }, elsePart = irGet(a) ) val call = IrCallImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, literalType, stateGetValue, stateGetValue.owner.typeParameters.size, stateGetValue.owner.valueParameters.size, IrStatementOrigin.FOR_LOOP_ITERATOR ).apply { dispatchReceiver = b } +irReturn(call) } } } override fun visitConst(expression: IrConst<*>): IrExpression { when (expression.kind) { IrConstKind.Null -> return expression else -> { /* Continue visiting expression */ } } val (key, success) = keyVisitor.buildPath( prefix = expression.kind.asString, pathSeparator = "\$", siblingSeparator = "-" ) // NOTE: Even if `liveLiteralsEnabled` is false, we are still going to throw an exception // here because the presence of a duplicate key represents a bug in this transform since // it should be impossible. By checking this always, we are making it so that bugs in // this transform will get caught _early_ and that there will be implicitly high coverage // of the key generation algorithm despite this transform only being used by tooling. // Developers have the ability to "silence" this exception by marking the surrounding // class/file/function with the `@NoLiveLiterals` annotation. if (!success) { val file = currentFile ?: return expression val src = file.fileEntry.getSourceRangeInfo( expression.startOffset, expression.endOffset ) error( "Duplicate live literal key found: $key\n" + "Caused by element at: " + "${src.filePath}:${src.startLineNumber}:${src.startColumnNumber}\n" + "If you encounter this error, please file a bug at " + "https://issuetracker.google.com/issues?q=componentid:610764\n" + "Try adding the `@NoLiveLiterals` annotation around the surrounding code to " + "avoid this exception." ) } // If live literals are enabled, don't do anything if (!liveLiteralsEnabled) return expression // create the getter function on the live literals class val getter = irLiveLiteralGetter( key = key, // Move the start/endOffsets to the call of the getter since we don't // want to step into <clinit> in the debugger. literalValue = expression.copyWithOffsets(UNDEFINED_OFFSET, UNDEFINED_OFFSET), literalType = expression.type, startOffset = expression.startOffset ) // return a call to the getter in place of the constant return IrCallImpl( expression.startOffset, expression.endOffset, expression.type, getter.symbol, getter.symbol.owner.typeParameters.size, getter.symbol.owner.valueParameters.size ).apply { dispatchReceiver = irGetLiveLiteralsClass(expression.startOffset, expression.endOffset) } } override fun visitClass(declaration: IrClass): IrStatement { if (declaration.hasNoLiveLiteralsAnnotation()) return declaration // constants in annotations need to be compile-time values, so we can never transform them if (declaration.isAnnotationClass) return declaration return siblings("class-${declaration.name.asJvmFriendlyString()}") { super.visitClass(declaration) } } open fun makeKeySet(): MutableSet<String> { return mutableSetOf() } override fun visitFile(declaration: IrFile): IrFile { includeFileNameInExceptionTrace(declaration) { if (declaration.hasNoLiveLiteralsAnnotation()) return declaration val filePath = declaration.fileEntry.name val fileName = filePath.split('/').last() val keys = makeKeySet() return keyVisitor.root(keys) { val prevEnabledSymbol = liveLiteralsEnabledSymbol var nextEnabledSymbol: IrSimpleFunctionSymbol? = null val prevClass = liveLiteralsClass val nextClass = context.irFactory.buildClass { kind = ClassKind.OBJECT visibility = DescriptorVisibilities.INTERNAL val shortName = PackagePartClassUtils.getFilePartShortName(fileName) // the name of the LiveLiterals class is per-file, so we use the same name that // the kotlin file class lowering produces, prefixed with `LiveLiterals$`. name = Name.identifier("LiveLiterals${"$"}$shortName") }.also { it.createParameterDeclarations() // store the full file path to the file that this class is associated with in an // annotation on the class. This will be used by tooling to associate the keys // inside of this class with actual PSI in the editor. it.annotations += irLiveLiteralFileInfoAnnotation(declaration.fileEntry.name) it.addConstructor { isPrimary = true }.also { ctor -> ctor.body = DeclarationIrBuilder(context, it.symbol).irBlockBody { +irDelegatingConstructorCall( context .irBuiltIns .anyClass .owner .primaryConstructor!! ) } } if (usePerFileEnabledFlag) { val enabledProp = it.addProperty { name = Name.identifier("enabled") visibility = DescriptorVisibilities.PRIVATE }.also { p -> p.backingField = context.irFactory.buildField { name = Name.identifier("enabled") isStatic = true type = builtIns.booleanType visibility = DescriptorVisibilities.PRIVATE }.also { f -> f.correspondingPropertySymbol = p.symbol f.parent = it f.initializer = IrExpressionBodyImpl( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, irConst(false) ) } p.addGetter { returnType = builtIns.booleanType visibility = DescriptorVisibilities.PRIVATE origin = IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR }.also { fn -> val thisParam = it.thisReceiver!!.copyTo(fn) fn.dispatchReceiverParameter = thisParam fn.body = DeclarationIrBuilder(context, fn.symbol).irBlockBody { +irReturn(irGetField(irGet(thisParam), p.backingField!!)) } } } nextEnabledSymbol = enabledProp.getter?.symbol } } try { liveLiteralsClass = nextClass currentFile = declaration liveLiteralsEnabledSymbol = nextEnabledSymbol val file = super.visitFile(declaration) // if there were no constants found in the entire file, then we don't need to // create this class at all if (liveLiteralsEnabled && keys.isNotEmpty()) { file.addChild(nextClass) } file } finally { liveLiteralsClass = prevClass liveLiteralsEnabledSymbol = prevEnabledSymbol } } } } override fun visitTry(aTry: IrTry): IrExpression { aTry.tryResult = enter("try") { aTry.tryResult.transform(this, null) } siblings { aTry.catches.forEach { it.result = enter("catch") { it.result.transform(this, null) } } } aTry.finallyExpression = enter("finally") { aTry.finallyExpression?.transform(this, null) } return aTry } override fun visitDelegatingConstructorCall( expression: IrDelegatingConstructorCall ): IrExpression { val owner = expression.symbol.owner // annotations are represented as constructor calls in IR, but the parameters need to be // compile-time values only, so we can't transform them at all. if (owner.parentAsClass.isAnnotationClass) return expression val name = owner.name.asJvmFriendlyString() return enter("call-$name") { expression.dispatchReceiver = enter("\$this") { expression.dispatchReceiver?.transform(this, null) } expression.extensionReceiver = enter("\$\$this") { expression.extensionReceiver?.transform(this, null) } for (i in 0 until expression.valueArgumentsCount) { val arg = expression.getValueArgument(i) if (arg != null) { enter("arg-$i") { expression.putValueArgument(i, arg.transform(this, null)) } } } expression } } override fun visitEnumConstructorCall(expression: IrEnumConstructorCall): IrExpression { val owner = expression.symbol.owner val name = owner.name.asJvmFriendlyString() return enter("call-$name") { expression.dispatchReceiver = enter("\$this") { expression.dispatchReceiver?.transform(this, null) } expression.extensionReceiver = enter("\$\$this") { expression.extensionReceiver?.transform(this, null) } for (i in 0 until expression.valueArgumentsCount) { val arg = expression.getValueArgument(i) if (arg != null) { enter("arg-$i") { expression.putValueArgument(i, arg.transform(this, null)) } } } expression } } override fun visitConstructorCall(expression: IrConstructorCall): IrExpression { val owner = expression.symbol.owner // annotations are represented as constructor calls in IR, but the parameters need to be // compile-time values only, so we can't transform them at all. if (owner.parentAsClass.isAnnotationClass) return expression val name = owner.name.asJvmFriendlyString() return enter("call-$name") { expression.dispatchReceiver = enter("\$this") { expression.dispatchReceiver?.transform(this, null) } expression.extensionReceiver = enter("\$\$this") { expression.extensionReceiver?.transform(this, null) } for (i in 0 until expression.valueArgumentsCount) { val arg = expression.getValueArgument(i) if (arg != null) { enter("arg-$i") { expression.putValueArgument(i, arg.transform(this, null)) } } } expression } } override fun visitCall(expression: IrCall): IrExpression { val owner = expression.symbol.owner val name = owner.name.asJvmFriendlyString() return enter("call-$name") { expression.dispatchReceiver = enter("\$this") { expression.dispatchReceiver?.transform(this, null) } expression.extensionReceiver = enter("\$\$this") { expression.extensionReceiver?.transform(this, null) } for (i in 0 until expression.valueArgumentsCount) { val arg = expression.getValueArgument(i) if (arg != null) { enter("arg-$i") { expression.putValueArgument(i, arg.transform(this, null)) } } } expression } } override fun visitEnumEntry(declaration: IrEnumEntry): IrStatement { return enter("entry-${declaration.name.asJvmFriendlyString()}") { super.visitEnumEntry(declaration) } } override fun visitVararg(expression: IrVararg): IrExpression { if (expression !is IrVarargImpl) return expression return enter("vararg") { expression.elements.forEachIndexed { i, arg -> expression.elements[i] = enter("$i") { arg.transform(this, null) as IrVarargElement } } expression } } override fun visitSimpleFunction(declaration: IrSimpleFunction): IrStatement { if (declaration.hasNoLiveLiteralsAnnotation()) return declaration val name = declaration.name.asJvmFriendlyString() val path = if (name == "<anonymous>") "lambda" else "fun-$name" return enter(path) { super.visitSimpleFunction(declaration) } } override fun visitLoop(loop: IrLoop): IrExpression { return when (loop.origin) { // in these cases, the compiler relies on a certain structure for the condition // expression, so we only touch the body IrStatementOrigin.WHILE_LOOP, IrStatementOrigin.FOR_LOOP_INNER_WHILE -> enter("loop") { loop.body = enter("body") { loop.body?.transform(this, null) } loop } else -> enter("loop") { loop.condition = enter("cond") { loop.condition.transform(this, null) } loop.body = enter("body") { loop.body?.transform(this, null) } loop } } } override fun visitStringConcatenation(expression: IrStringConcatenation): IrExpression { if (expression !is IrStringConcatenationImpl) return expression return enter("str") { siblings { expression.arguments.forEachIndexed { index, expr -> expression.arguments[index] = enter("$index") { expr.transform(this, null) } } expression } } } override fun visitWhen(expression: IrWhen): IrExpression { return when (expression.origin) { // ANDAND needs to have an 'if true then false' body on its second branch, so only // transform the first branch IrStatementOrigin.ANDAND -> { expression.branches[0] = expression.branches[0].transform(this, null) expression } // OROR condition should have an 'if a then true' body on its first branch, so only // transform the second branch IrStatementOrigin.OROR -> { expression.branches[1] = expression.branches[1].transform(this, null) expression } IrStatementOrigin.IF -> siblings("if") { super.visitWhen(expression) } else -> siblings("when") { super.visitWhen(expression) } } } override fun visitValueParameter(declaration: IrValueParameter): IrStatement { return enter("param-${declaration.name.asJvmFriendlyString()}") { super.visitValueParameter(declaration) } } override fun visitElseBranch(branch: IrElseBranch): IrElseBranch { return IrElseBranchImpl( startOffset = branch.startOffset, endOffset = branch.endOffset, // the condition of an else branch is a constant boolean but we don't want // to convert it into a live literal, so we don't transform it condition = branch.condition, result = enter("else") { branch.result.transform(this, null) } ) } override fun visitBranch(branch: IrBranch): IrBranch { return IrBranchImpl( startOffset = branch.startOffset, endOffset = branch.endOffset, condition = enter("cond") { branch.condition.transform(this, null) }, // only translate the result, as the branch is a constant boolean but we don't want // to convert it into a live literal result = enter("branch") { branch.result.transform(this, null) } ) } override fun visitComposite(expression: IrComposite): IrExpression { return siblings { super.visitComposite(expression) } } override fun visitBlock(expression: IrBlock): IrExpression { return when (expression.origin) { // The compiler relies on a certain structure for the "iterator" instantiation in For // loops, so we avoid transforming the first statement in this case IrStatementOrigin.FOR_LOOP, IrStatementOrigin.FOR_LOOP_INNER_WHILE -> { expression.statements[1] = expression.statements[1].transform(this, null) as IrStatement expression } // IrStatementOrigin.SAFE_CALL // IrStatementOrigin.WHEN // IrStatementOrigin.IF // IrStatementOrigin.ELVIS // IrStatementOrigin.ARGUMENTS_REORDERING_FOR_CALL else -> siblings { super.visitBlock(expression) } } } override fun visitSetValue(expression: IrSetValue): IrExpression { val owner = expression.symbol.owner val name = owner.name return when (owner.origin) { // for these synthetic variable declarations we want to avoid transforming them since // the compiler will rely on their compile time value in some cases. IrDeclarationOrigin.FOR_LOOP_IMPLICIT_VARIABLE -> expression IrDeclarationOrigin.IR_TEMPORARY_VARIABLE -> expression IrDeclarationOrigin.FOR_LOOP_VARIABLE -> expression else -> enter("set-$name") { super.visitSetValue(expression) } } } override fun visitSetField(expression: IrSetField): IrExpression { val name = expression.symbol.owner.name return enter("set-$name") { super.visitSetField(expression) } } override fun visitBlockBody(body: IrBlockBody): IrBody { return siblings { super.visitBlockBody(body) } } override fun visitVariable(declaration: IrVariable): IrStatement { return enter("val-${declaration.name.asJvmFriendlyString()}") { super.visitVariable(declaration) } } override fun visitProperty(declaration: IrProperty): IrStatement { if (declaration.hasNoLiveLiteralsAnnotation()) return declaration val backingField = declaration.backingField val getter = declaration.getter val setter = declaration.setter val name = declaration.name.asJvmFriendlyString() return enter("val-$name") { // turn them into live literals. We should consider transforming some simple cases like // `val foo = 123`, but in general turning this initializer into a getter is not a // safe operation. We should figure out a way to do this for "static" expressions // though such as `val foo = 16.dp`. declaration.backingField = backingField declaration.getter = enter("get") { getter?.transform(this, null) as? IrSimpleFunction } declaration.setter = enter("set") { setter?.transform(this, null) as? IrSimpleFunction } declaration } } inline fun IrProperty.addSetter(builder: IrFunctionBuilder.() -> Unit = {}): IrSimpleFunction = IrFunctionBuilder().run { name = Name.special("<set-${[email protected]}>") builder() context.irFactory.buildFunction(this).also { setter -> [email protected] = setter setter.parent = [email protected] } } fun IrFactory.buildFunction(builder: IrFunctionBuilder): IrSimpleFunction = with(builder) { createFunction( startOffset, endOffset, origin, IrSimpleFunctionSymbolImpl(), name, visibility, modality, returnType, isInline, isExternal, isTailrec, isSuspend, isOperator, isInfix, isExpect, isFakeOverride, containerSource, ) } }
apache-2.0
43933425c82b384106e12a18c4836b64
41.99667
100
0.602375
5.182609
false
false
false
false
androidx/androidx
buildSrc/private/src/main/kotlin/androidx/build/metalava/GenerateApiTask.kt
3
3074
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.metalava import androidx.build.checkapi.ApiBaselinesLocation import androidx.build.checkapi.ApiLocation import androidx.build.java.JavaCompileInputs import org.gradle.api.provider.Property import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.Internal import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputFiles import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.gradle.workers.WorkerExecutor import java.io.File import javax.inject.Inject /** Generate an API signature text file from a set of source files. */ @CacheableTask abstract class GenerateApiTask @Inject constructor( workerExecutor: WorkerExecutor ) : MetalavaTask(workerExecutor) { @get:Internal // already expressed by getApiLintBaseline() abstract val baselines: Property<ApiBaselinesLocation> @Optional @PathSensitive(PathSensitivity.NONE) @InputFile fun getApiLintBaseline(): File? { val baseline = baselines.get().apiLintFile return if (baseline.exists()) baseline else null } @get:Input var targetsJavaConsumers: Boolean = true @get:Input var generateRestrictToLibraryGroupAPIs = true /** Text file to which API signatures will be written. */ @get:Internal // already expressed by getTaskOutputs() abstract val apiLocation: Property<ApiLocation> @OutputFiles fun getTaskOutputs(): List<File> { val prop = apiLocation.get() return listOfNotNull( prop.publicApiFile, prop.removedApiFile, prop.experimentalApiFile, prop.restrictedApiFile ) } @TaskAction fun exec() { check(bootClasspath.files.isNotEmpty()) { "Android boot classpath not set." } check(sourcePaths.files.isNotEmpty()) { "Source paths not set." } val inputs = JavaCompileInputs( sourcePaths, dependencyClasspath, bootClasspath ) generateApi( metalavaClasspath, inputs, apiLocation.get(), ApiLintMode.CheckBaseline(baselines.get().apiLintFile, targetsJavaConsumers), generateRestrictToLibraryGroupAPIs, workerExecutor, manifestPath.orNull?.asFile?.absolutePath ) } }
apache-2.0
c3761ee249a47f7cfd951fa4e3482df2
32.053763
89
0.710475
4.487591
false
false
false
false
androidx/androidx
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/layout/PlacementLayoutCoordinatesTest.kt
3
25330
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.layout import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.activity.ComponentActivity import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.movableContentOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.AbsoluteAlignment import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.round import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @OptIn(ExperimentalComposeUiApi::class) @MediumTest @RunWith(AndroidJUnit4::class) class PlacementLayoutCoordinatesTest { @get:Rule val rule = createAndroidComposeRule<ComponentActivity>() /** * The [Placeable.PlacementScope.coordinates] should not be `null` during normal placement * and should have the position of the parent that is placing. */ @Test fun coordinatesWhilePlacing() { val locations = mutableStateListOf<LayoutCoordinates?>() var locationAtPlace: IntOffset? by mutableStateOf(null) var boxSize by mutableStateOf(IntSize.Zero) var alignment by mutableStateOf(Alignment.Center) rule.setContent { Box(Modifier.fillMaxSize()) { Box( Modifier .align(alignment) .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates locationAtPlace = coordinates ?.positionInRoot() ?.round() boxSize = IntSize(p.width, p.height) p.place(0, 0) } } .size(10.dp, 10.dp) ) } } rule.waitForIdle() assertNotNull(locationAtPlace) assertNotEquals(IntOffset.Zero, locationAtPlace) assertEquals(1, locations.size) locationAtPlace = null locations.clear() alignment = AbsoluteAlignment.TopLeft rule.waitForIdle() assertNotNull(locationAtPlace) assertEquals(IntOffset.Zero, locationAtPlace) assertEquals(1, locations.size) locationAtPlace = null locations.clear() alignment = AbsoluteAlignment.BottomRight rule.waitForIdle() assertNotNull(locationAtPlace) assertEquals(1, locations.size) val content = rule.activity.findViewById<View>(android.R.id.content) val bottomRight = IntOffset(content.width - boxSize.width, content.height - boxSize.height) assertEquals(bottomRight, locationAtPlace) } /** * The [Placeable.PlacementScope.coordinates] should not be `null` during normal placement * and should have the position of the parent that is placing. */ @OptIn(ExperimentalComposeUiApi::class) @Test fun coordinatesWhilePlacingWithLookaheadLayout() { val locations = mutableStateListOf<LayoutCoordinates?>() var locationAtPlace: IntOffset? by mutableStateOf(null) var boxSize by mutableStateOf(IntSize.Zero) var alignment by mutableStateOf(Alignment.Center) rule.setContent { SimpleLookaheadLayout { Box(Modifier.fillMaxSize()) { Box( Modifier .align(alignment) .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates locationAtPlace = coordinates ?.positionInRoot() ?.round() boxSize = IntSize(p.width, p.height) p.place(0, 0) } } .size(10.dp, 10.dp) ) } } } rule.waitForIdle() locationAtPlace = null locations.clear() alignment = AbsoluteAlignment.TopLeft rule.waitForIdle() assertNotNull(locationAtPlace) assertEquals(IntOffset.Zero, locationAtPlace) assertEquals(2, locations.size) locationAtPlace = null locations.clear() alignment = AbsoluteAlignment.BottomRight rule.waitForIdle() assertNotNull(locationAtPlace) assertEquals(2, locations.size) val content = rule.activity.findViewById<View>(android.R.id.content) val bottomRight = IntOffset(content.width - boxSize.width, content.height - boxSize.height) assertEquals(bottomRight, locationAtPlace) } /** * The [Placeable.PlacementScope.coordinates] should be `null` while calculating the alignment, * but should be non-null after the alignment has been calculated. */ @Test fun coordinatesWhileAligning() { val locations = mutableStateListOf<LayoutCoordinates?>() rule.setContent { Row(Modifier.fillMaxSize()) { Box(Modifier.alignByBaseline()) { Text("Hello") } Box( Modifier .alignByBaseline() .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } }) { Text("World") } } } rule.waitForIdle() assertTrue(locations.size > 1) assertNull(locations[0]) assertNotNull(locations.last()) } /** * The [Placeable.PlacementScope.coordinates] should be `null` while calculating the alignment, * but should be non-null after the alignment has been calculated. */ @OptIn(ExperimentalComposeUiApi::class) @Test fun coordinatesWhileAligningWithLookaheadLayout() { val locations = mutableStateListOf<LayoutCoordinates?>() rule.setContent { SimpleLookaheadLayout { Row(Modifier.fillMaxSize()) { Box(Modifier.alignByBaseline()) { Text("Hello") } Box( Modifier .alignByBaseline() .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } }) { Text("World") } } } } rule.waitForIdle() // There may be a way to make this only 2 invocations for the first pass rather than 3. assertEquals(4, locations.size) assertNull(locations[0]) // Lookahead pass assertNull(locations[1]) // Lookahead pass - second look at alignment line assertNotNull(locations[2]) // Lookahead pass placement assertNotNull(locations[3]) // Measure pass } /** * The [Placeable.PlacementScope.coordinates] should be `null` while calculating the alignment, * but should be non-null after the alignment has been calculated. */ @Test fun coordinatesWhileAligningInLayout() { val locations = mutableStateListOf<LayoutCoordinates?>() rule.setContent { Row(Modifier.fillMaxSize()) { Box(Modifier.alignByBaseline()) { Text("Hello") } val content = @Composable { Text("World") } Layout(content, Modifier.alignByBaseline()) { measurables, constraints -> val p = measurables[0].measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } } } rule.waitForIdle() assertEquals(2, locations.size) assertNull(locations[0]) assertNotNull(locations[1]) } /** * The [Placeable.PlacementScope.coordinates] should be `null` while calculating the alignment, * but should be non-null after the alignment has been calculated. */ @OptIn(ExperimentalComposeUiApi::class) @Test fun coordinatesWhileAligningInLookaheadLayout() { val locations = mutableStateListOf<LayoutCoordinates?>() rule.setContent { SimpleLookaheadLayout { Row(Modifier.fillMaxSize()) { Box(Modifier.alignByBaseline()) { Text("Hello") } val content = @Composable { Text("World") } Layout(content, Modifier.alignByBaseline()) { measurables, constraints -> val p = measurables[0].measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } } } } rule.waitForIdle() assertEquals(3, locations.size) assertNull(locations[0]) // Lookahead pass assertNotNull(locations[1]) // Lookahead pass assertNotNull(locations[2]) // Measure pass } @Test fun coordinatesInNestedAlignmentLookup() { val locations = mutableStateListOf<LayoutCoordinates?>() var textLayoutInvocations = 0 rule.setContent { Row(Modifier.fillMaxSize()) { Box(Modifier.alignByBaseline()) { Text("Hello", modifier = Modifier.layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { textLayoutInvocations++ p.place(0, 0) } }) } val content = @Composable { Text("World") } Layout(content, Modifier .alignByBaseline() .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height + 10) { p[LastBaseline] // invoke alignment p.place(0, 10) } }) { measurables, constraints -> val p = measurables[0].measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } } } rule.waitForIdle() assertEquals(1, textLayoutInvocations) assertTrue(locations.size > 1) assertNull(locations[0]) assertNotNull(locations.last()) } @Test fun parentCoordateChangeCausesRelayout() { val locations = mutableStateListOf<LayoutCoordinates?>() var offset by mutableStateOf(DpOffset(0.dp, 0.dp)) rule.setContent { Box(Modifier.fillMaxSize()) { Box(Modifier.offset(offset.x, offset.y)) { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp, 10.dp) ) } } } rule.waitForIdle() assertEquals(1, locations.size) locations.clear() offset = DpOffset(1.dp, 2.dp) rule.waitForIdle() assertEquals(1, locations.size) } @Test fun grandParentCoordateChangeCausesRelayout() { val locations = mutableStateListOf<LayoutCoordinates?>() var offset by mutableStateOf(DpOffset(0.dp, 0.dp)) rule.setContent { Box(Modifier.fillMaxSize()) { Box(Modifier.offset(offset.x, offset.y)) { Box { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp, 10.dp) ) } } } } rule.waitForIdle() assertEquals(1, locations.size) locations.clear() offset = DpOffset(1.dp, 2.dp) rule.waitForIdle() assertEquals(1, locations.size) } @Test fun newlyAddedStillUpdated() { val locations = mutableStateListOf<LayoutCoordinates?>() var offset by mutableStateOf(DpOffset(0.dp, 0.dp)) var showContent2 by mutableStateOf(false) rule.setContent { Box(Modifier.fillMaxSize()) { Box(Modifier.offset(offset.x, offset.y)) { Box { Box(Modifier.fillMaxSize()) if (showContent2) { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp, 10.dp) ) } } } } } rule.waitForIdle() showContent2 = true rule.waitForIdle() assertEquals(1, locations.size) locations.clear() offset = DpOffset(1.dp, 2.dp) rule.waitForIdle() assertEquals(1, locations.size) } @Test fun removedStopsUpdating() { var readCoordinates by mutableStateOf(true) val layoutCalls = mutableStateListOf<LayoutCoordinates?>() var offset by mutableStateOf(DpOffset.Zero) rule.setContent { Box(Modifier.fillMaxSize()) { Box(Modifier.offset(offset.x, offset.y)) { Box { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { layoutCalls += if (readCoordinates) coordinates else null p.place(0, 0) } } .size(10.dp, 10.dp) ) } } } } rule.waitForIdle() assertEquals(1, layoutCalls.size) layoutCalls.clear() offset = DpOffset(10.dp, 5.dp) rule.waitForIdle() assertEquals(1, layoutCalls.size) layoutCalls.clear() readCoordinates = false rule.waitForIdle() assertEquals(1, layoutCalls.size) layoutCalls.clear() offset = DpOffset.Zero rule.waitForIdle() assertEquals(0, layoutCalls.size) } /** * When a LayoutNode is moved, its usage of coordinates should follow. */ @Test fun movedContentNotifies() { val locations = mutableStateListOf<LayoutCoordinates?>() var offset1 by mutableStateOf(DpOffset.Zero) var offset2 by mutableStateOf(DpOffset.Zero) var showInOne by mutableStateOf(true) rule.setContent { val usingCoordinates = remember { movableContentOf { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp, 10.dp) ) } } Box(Modifier.fillMaxSize()) { Box( Modifier .size(50.dp) .offset(offset1.x, offset1.y) ) { if (showInOne) { usingCoordinates() } } Box( Modifier .size(50.dp) .offset(offset2.x, offset2.y) ) { if (!showInOne) { usingCoordinates() } } } } rule.waitForIdle() assertEquals(1, locations.size) offset1 = DpOffset(1.dp, 1.dp) rule.waitForIdle() assertEquals(2, locations.size) showInOne = false rule.waitForIdle() assertEquals(3, locations.size) offset2 = DpOffset(1.dp, 1.dp) rule.waitForIdle() assertEquals(4, locations.size) } /** * When [Placeable.PlacementScope.coordinates] is accessed during placement then changing the * layer properties on an ancestor should cause relayout. */ @Test fun ancestorLayerChangesCausesPlacement() { val locations = mutableStateListOf<LayoutCoordinates?>() var offset by mutableStateOf(Offset.Zero) rule.setContent { Box(Modifier.fillMaxSize()) { Box(Modifier.graphicsLayer { translationX = offset.x translationY = offset.y }) { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp, 10.dp) ) } } } rule.waitForIdle() assertEquals(1, locations.size) offset = Offset(1f, 2f) rule.waitForIdle() assertEquals(2, locations.size) } /** * When [Placeable.PlacementScope.coordinates] is accessed during placement then changing the * layer properties of the LayoutNode should cause relayout. */ @Test fun layerChangesCausesPlacement() { val locations = mutableStateListOf<LayoutCoordinates?>() var offset by mutableStateOf(Offset.Zero) rule.setContent { Box(Modifier.fillMaxSize()) { Box( Modifier .graphicsLayer { translationX = offset.x translationY = offset.y } .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp, 10.dp) ) } } rule.waitForIdle() assertEquals(1, locations.size) offset = Offset(1f, 2f) rule.waitForIdle() assertEquals(2, locations.size) } @Test fun viewPositionChangeCausesPlacement() { val locations = mutableStateListOf<LayoutCoordinates?>() lateinit var composeView: ComposeView rule.runOnUiThread { val container = FrameLayout(rule.activity) composeView = ComposeView(rule.activity).apply { setContent { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp) ) } } container.addView( composeView, FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.TOP or Gravity.LEFT ) ) container.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) rule.activity.setContentView(container) } rule.waitForIdle() locations.clear() rule.runOnUiThread { val lp = composeView.layoutParams as FrameLayout.LayoutParams lp.gravity = Gravity.CENTER composeView.layoutParams = lp } rule.waitForIdle() assertEquals(1, locations.size) } } @OptIn(ExperimentalComposeUiApi::class) @Composable private fun SimpleLookaheadLayout(content: @Composable LookaheadLayoutScope.() -> Unit) { LookaheadLayout( content = content, measurePolicy = { measurables, constraints -> val p = measurables[0].measure(constraints) layout(p.width, p.height) { p.place(0, 0) } } ) }
apache-2.0
e553cbfa0ce1b151ad55a535fed0ca46
35.979562
99
0.499961
5.689578
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/capturedVariablesInSamLambda.kt
3
672
package capturedVariablesInSamLambda fun invoke(runnable: Runnable) { runnable.run() } class A { val a = 1 } class B { val b = 1 } fun main() { val a = A() val b = B() invoke { // EXPRESSION: a // RESULT: instance of capturedVariablesInSamLambda.A(id=ID): LcapturedVariablesInSamLambda/A; // EXPRESSION: b // RESULT: instance of capturedVariablesInSamLambda.B(id=ID): LcapturedVariablesInSamLambda/B; // EXPRESSION: a.a // RESULT: 1: I // EXPRESSION: b.b // RESULT: 1: I //Breakpoint! println(a) println(b) } } // PRINT_FRAME // SHOW_KOTLIN_VARIABLES
apache-2.0
1bb779069167a4704bf59d053f3cf576
18.764706
102
0.581845
3.5
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/java/src/service/project/MavenRepositoriesProjectResolver.kt
13
2377
// 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 org.jetbrains.plugins.gradle.service.project import com.intellij.externalSystem.MavenRepositoryData import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import org.gradle.tooling.model.idea.IdeaModule import org.gradle.tooling.model.idea.IdeaProject import org.jetbrains.plugins.gradle.model.RepositoriesModel import org.jetbrains.plugins.gradle.util.GradleConstants import java.util.* class MavenRepositoriesProjectResolver: AbstractProjectResolverExtension() { override fun populateProjectExtraModels(gradleProject: IdeaProject, ideProject: DataNode<ProjectData>) { val repositories = resolverCtx.getExtraProject(RepositoriesModel::class.java) addRepositoriesToProject(ideProject, repositories) super.populateProjectExtraModels(gradleProject, ideProject) } override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) { val repositories = resolverCtx.getExtraProject(gradleModule, RepositoriesModel::class.java) val ideProject = ExternalSystemApiUtil.findParent(ideModule, ProjectKeys.PROJECT) ideProject?.let { addRepositoriesToProject(it, repositories) } super.populateModuleExtraModels(gradleModule, ideModule) } override fun getExtraProjectModelClasses(): MutableSet<Class<*>> { return Collections.singleton(RepositoriesModel::class.java) } private fun addRepositoriesToProject(ideProject: DataNode<ProjectData>, repositories: RepositoriesModel?) { if (repositories != null) { val knownRepositories = ExternalSystemApiUtil.getChildren(ideProject, MavenRepositoryData.KEY) .asSequence() .map { it.data } .toSet() repositories.all.asSequence() .map { MavenRepositoryData(GradleConstants.SYSTEM_ID, it.name, it.url) } .filter { !knownRepositories.contains(it) } .forEach { ideProject.addChild(DataNode(MavenRepositoryData.KEY, it, ideProject)) } } } }
apache-2.0
68a90b592f066218dc0c627a7111b936
45.627451
140
0.782499
4.993697
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddFunctionParametersFix.kt
2
12816
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.builtins.isKFunctionType import org.jetbrains.kotlin.builtins.isKSuspendFunctionType import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.intentions.reflectToRegularFunctionType import org.jetbrains.kotlin.idea.refactoring.changeSignature.* import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.getDataFlowAwareTypes import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getCall import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker class AddFunctionParametersFix( callElement: KtCallElement, functionDescriptor: FunctionDescriptor, private val kind: Kind ) : ChangeFunctionSignatureFix(callElement, functionDescriptor) { sealed class Kind { object ChangeSignature : Kind() object AddParameterGeneric : Kind() class AddParameter(val argumentIndex: Int) : Kind() } private val argumentIndex: Int? get() = (kind as? Kind.AddParameter)?.argumentIndex private val callElement: KtCallElement? get() = element as? KtCallElement private val typesToShorten = ArrayList<KotlinType>() override fun getText(): String { val callElement = callElement ?: return "" val parameters = functionDescriptor.valueParameters val arguments = callElement.valueArguments val newParametersCnt = arguments.size - parameters.size assert(newParametersCnt > 0) val declarationName = when { isConstructor() -> functionDescriptor.containingDeclaration.name.asString() else -> functionDescriptor.name.asString() } return when (kind) { is Kind.ChangeSignature -> { if (isConstructor()) { KotlinBundle.message("fix.add.function.parameters.change.signature.constructor", declarationName) } else { KotlinBundle.message("fix.add.function.parameters.change.signature.function", declarationName) } } is Kind.AddParameterGeneric -> { if (isConstructor()) { KotlinBundle.message("fix.add.function.parameters.add.parameter.generic.constructor", newParametersCnt, declarationName) } else { KotlinBundle.message("fix.add.function.parameters.add.parameter.generic.function", newParametersCnt, declarationName) } } is Kind.AddParameter -> { if (isConstructor()) { KotlinBundle.message( "fix.add.function.parameters.add.parameter.constructor", kind.argumentIndex + 1, newParametersCnt, declarationName ) } else { KotlinBundle.message( "fix.add.function.parameters.add.parameter.function", kind.argumentIndex + 1, newParametersCnt, declarationName ) } } } } override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { if (!super.isAvailable(project, editor, file)) return false val callElement = callElement ?: return false // newParametersCnt <= 0: psi for this quickfix is no longer valid val newParametersCnt = callElement.valueArguments.size - functionDescriptor.valueParameters.size if (argumentIndex != null && newParametersCnt != 1) return false return newParametersCnt > 0 } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val callElement = callElement ?: return runChangeSignature(project, editor, functionDescriptor, addParameterConfiguration(), callElement, text) } private fun addParameterConfiguration(): KotlinChangeSignatureConfiguration { return object : KotlinChangeSignatureConfiguration { override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor { val argumentIndex = [email protected] return originalDescriptor.modify(fun(descriptor: KotlinMutableMethodDescriptor) { val callElement = callElement ?: return val arguments = callElement.valueArguments val parameters = functionDescriptor.valueParameters val validator = CollectingNameValidator() val receiverCount = if (descriptor.receiver != null) 1 else 0 if (argumentIndex != null) { parameters.forEach { validator.addName(it.name.asString()) } val argument = arguments[argumentIndex] val parameterInfo = getNewParameterInfo( originalDescriptor.baseDescriptor as FunctionDescriptor, argument, validator, ) descriptor.addParameter(argumentIndex + receiverCount, parameterInfo) return } val call = callElement.getCall(callElement.analyze()) ?: return for (i in arguments.indices) { val argument = arguments[i] val expression = argument.getArgumentExpression() if (i < parameters.size) { validator.addName(parameters[i].name.asString()) val argumentType = expression?.let { val bindingContext = it.analyze() val smartCasts = bindingContext[BindingContext.SMARTCAST, it] smartCasts?.defaultType ?: smartCasts?.type(call) ?: bindingContext.getType(it) } val parameterType = parameters[i].type if (argumentType != null && !KotlinTypeChecker.DEFAULT.isSubtypeOf(argumentType, parameterType)) { descriptor.parameters[i + receiverCount].currentTypeInfo = KotlinTypeInfo(false, argumentType) typesToShorten.add(argumentType) } } else { val parameterInfo = getNewParameterInfo( originalDescriptor.baseDescriptor as FunctionDescriptor, argument, validator, ) descriptor.addParameter(parameterInfo) } } }) } override fun performSilently(affectedFunctions: Collection<PsiElement>): Boolean { val onlyFunction = affectedFunctions.singleOrNull() ?: return false return kind != Kind.ChangeSignature && !isConstructor() && !hasOtherUsages(onlyFunction) } } } private fun getNewParameterInfo( functionDescriptor: FunctionDescriptor, argument: ValueArgument, validator: (String) -> Boolean ): KotlinParameterInfo { val name = getNewArgumentName(argument, validator) val expression = argument.getArgumentExpression() val type = (expression?.let { getDataFlowAwareTypes(it).firstOrNull() } ?: functionDescriptor.builtIns.nullableAnyType).let { if (it.isKFunctionType || it.isKSuspendFunctionType) it.reflectToRegularFunctionType() else it } return KotlinParameterInfo(functionDescriptor, -1, name, KotlinTypeInfo(false, null)).apply { currentTypeInfo = KotlinTypeInfo(false, type) originalTypeInfo.type?.let { typesToShorten.add(it) } if (expression != null) defaultValueForCall = expression } } private fun hasOtherUsages(function: PsiElement): Boolean { (function as? PsiNamedElement)?.let { val name = it.name ?: return false val project = runReadAction { it.project } val psiSearchHelper = PsiSearchHelper.getInstance(project) val globalSearchScope = GlobalSearchScope.projectScope(project) val cheapEnoughToSearch = psiSearchHelper.isCheapEnoughToSearch(name, globalSearchScope, null, null) if (cheapEnoughToSearch == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) return false } return ReferencesSearch.search(function).any { val call = it.element.getParentOfType<KtCallElement>(false) call != null && callElement != call } } private fun isConstructor() = functionDescriptor is ConstructorDescriptor companion object TypeMismatchFactory : KotlinSingleIntentionActionFactoryWithDelegate<KtCallElement, Pair<FunctionDescriptor, Int>>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtCallElement? { val (_, valueArgumentList) = diagnostic.valueArgument() ?: return null return valueArgumentList.getStrictParentOfType() } override fun extractFixData(element: KtCallElement, diagnostic: Diagnostic): Pair<FunctionDescriptor, Int>? { val (valueArgument, valueArgumentList) = diagnostic.valueArgument() ?: return null val arguments = valueArgumentList.arguments + element.lambdaArguments val argumentIndex = arguments.indexOfFirst { it == valueArgument } val context = element.analyze() val functionDescriptor = element.getResolvedCall(context)?.resultingDescriptor as? FunctionDescriptor ?: return null val parameters = functionDescriptor.valueParameters if (arguments.size - 1 != parameters.size) return null if ((arguments - valueArgument).zip(parameters).any { (argument, parameter) -> val argumentType = argument.getArgumentExpression()?.let { context.getType(it) } argumentType == null || !KotlinTypeChecker.DEFAULT.isSubtypeOf(argumentType, parameter.type) }) return null return functionDescriptor to argumentIndex } override fun createFix(originalElement: KtCallElement, data: Pair<FunctionDescriptor, Int>): IntentionAction? { val (functionDescriptor, argumentIndex) = data val parameters = functionDescriptor.valueParameters val arguments = originalElement.valueArguments return if (arguments.size > parameters.size) { AddFunctionParametersFix(originalElement, functionDescriptor, Kind.AddParameter(argumentIndex)) } else { null } } private fun Diagnostic.valueArgument(): Pair<KtValueArgument, KtValueArgumentList>? { val element = DiagnosticFactory.cast( this, Errors.TYPE_MISMATCH, Errors.CONSTANT_EXPECTED_TYPE_MISMATCH, Errors.NULL_FOR_NONNULL_TYPE, ).psiElement val valueArgument = element.getStrictParentOfType<KtValueArgument>() ?: return null val valueArgumentList = valueArgument.getStrictParentOfType<KtValueArgumentList>() ?: return null return valueArgument to valueArgumentList } } }
apache-2.0
db4be101583407fb5f98815d97cf0f47
48.482625
158
0.644585
6.011257
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceExplicitFunctionLiteralParamWithItIntention.kt
2
5995
// 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.intentions import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.refactoring.rename.RenameProcessor import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.descriptors.ParameterDescriptor import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.analysis.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.copied import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.addToStdlib.safeAs class ReplaceExplicitFunctionLiteralParamWithItIntention : PsiElementBaseIntentionAction() { override fun getFamilyName() = KotlinBundle.message("replace.explicit.lambda.parameter.with.it") override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean { val functionLiteral = targetFunctionLiteral(element, editor.caretModel.offset) ?: return false val parameter = functionLiteral.valueParameters.singleOrNull() ?: return false if (parameter.typeReference != null) return false if (parameter.destructuringDeclaration != null) return false if (functionLiteral.anyDescendantOfType<KtFunctionLiteral> { literal -> literal.usesName(element.text) && (!literal.hasParameterSpecification() || literal.usesName("it")) }) return false val lambda = functionLiteral.parent as? KtLambdaExpression ?: return false val lambdaParent = lambda.parent if (lambdaParent is KtWhenEntry || lambdaParent is KtContainerNodeForControlStructureBody) return false val call = lambda.getStrictParentOfType<KtCallExpression>() if (call != null) { val argumentIndex = call.valueArguments.indexOfFirst { it.getArgumentExpression() == lambda } val callOrQualified = call.getQualifiedExpressionForSelectorOrThis() val newCallOrQualified = callOrQualified.copied() val newCall = newCallOrQualified.safeAs<KtQualifiedExpression>()?.callExpression ?: newCallOrQualified.safeAs() ?: return false val newArgument = newCall.valueArguments.getOrNull(argumentIndex) ?: newCall.lambdaArguments.singleOrNull() ?: return false newArgument.replace(KtPsiFactory(element).createLambdaExpression("", "TODO()")) val newContext = newCallOrQualified.analyzeAsReplacement(callOrQualified, callOrQualified.analyze(BodyResolveMode.PARTIAL)) if (newCallOrQualified.getResolvedCall(newContext)?.resultingDescriptor == null) return false } text = KotlinBundle.message("replace.explicit.parameter.0.with.it", parameter.name.toString()) return true } private fun KtFunctionLiteral.usesName(name: String): Boolean = anyDescendantOfType<KtSimpleNameExpression> { nameExpr -> nameExpr.getReferencedName() == name } override fun startInWriteAction(): Boolean = false override fun invoke(project: Project, editor: Editor, element: PsiElement) { val caretOffset = editor.caretModel.offset val functionLiteral = targetFunctionLiteral(element, editor.caretModel.offset) ?: return val cursorInParameterList = functionLiteral.valueParameterList?.textRange?.containsOffset(caretOffset) ?: return ParamRenamingProcessor(editor, functionLiteral, cursorInParameterList).run() } private fun targetFunctionLiteral(element: PsiElement, caretOffset: Int): KtFunctionLiteral? { val expression = element.getParentOfType<KtNameReferenceExpression>(true) if (expression != null) { val target = expression.resolveMainReferenceToDescriptors().singleOrNull() as? ParameterDescriptor ?: return null val functionDescriptor = target.containingDeclaration as? AnonymousFunctionDescriptor ?: return null return DescriptorToSourceUtils.descriptorToDeclaration(functionDescriptor) as? KtFunctionLiteral } val functionLiteral = element.getParentOfType<KtFunctionLiteral>(true) ?: return null val arrow = functionLiteral.arrow ?: return null if (caretOffset > arrow.endOffset) return null return functionLiteral } private class ParamRenamingProcessor( val editor: Editor, val functionLiteral: KtFunctionLiteral, val cursorWasInParameterList: Boolean ) : RenameProcessor( editor.project!!, functionLiteral.valueParameters.single(), "it", false, false ) { override fun performRefactoring(usages: Array<out UsageInfo>) { super.performRefactoring(usages) functionLiteral.deleteChildRange(functionLiteral.valueParameterList, functionLiteral.arrow ?: return) if (cursorWasInParameterList) { editor.caretModel.moveToOffset(functionLiteral.bodyExpression?.textOffset ?: return) } val project = functionLiteral.project PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) CodeStyleManager.getInstance(project).adjustLineIndent(functionLiteral.containingFile, functionLiteral.textRange) } } }
apache-2.0
959c7f74f0fa2579a331e820df78c015
52.053097
158
0.75146
5.645009
false
false
false
false
NlRVANA/Unity
app/src/test/java/com/zwq65/unity/kotlin/Coroutine/6Channels.kt
1
13028
package com.zwq65.unity.kotlin.Coroutine import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import org.junit.Test /** * ================================================ * 通道 * * 递延值提供了在协程之间传递单个值的便捷方法. * 通道提供了一种传输值流的方法. * <p> * Created by NIRVANA on 2020/1/8. * Contact with <[email protected]> * ================================================ */ @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class `6Channels` { /** * 通道 * * 延期的值提供了一种便捷的方法使单个值在多个协程之间进行相互传输. 通道提供了一种在流中传输值的方法. * * 通道基础:一个[Channel]是一个和 BlockingQueue 非常相似的概念. * 其中一个不同是它代替了阻塞的 put 操作并提供了挂起的[Channel.send],还替代了阻塞的 take 操作并提供了挂起的[Channel.receive]. */ @Test fun test1() = runBlocking<Unit>() { val channel = Channel<Int>() launch { // 这里可能是消耗大量 CPU 运算的异步逻辑,我们将仅仅做 5 次整数的平方并发送 for (x in 1..5) channel.send(x * x) } // 这里我们打印了 5 次被接收的整数: repeat(5) { println(channel.receive()) } println("Done!") } /** * 关闭与迭代通道 * * 和队列不同,一个通道可以通过被关闭来表明没有更多的元素将会进入通道. * 在接收者中可以定期的使用 for 循环来从通道中接收元素. * 从概念上来说,一个 [Channel.close] 操作就像向通道发送了一个特殊的关闭指令. * 这个迭代停止就说明关闭指令已经被接收了.所以这里保证所有先前发送出去的元素都在通道关闭前被接收到. */ @Test fun test2() = runBlocking<Unit>() { val channel = Channel<Int>() launch { for (x in 1..5) channel.send(x * x) channel.close() // 我们结束发送 } // 这里我们使用 `for` 循环来打印所有被接收到的元素(直到通道被关闭) for (y in channel) println(y) println("Done!") } /** * 构建通道生产者 * * 协程生成一系列元素的模式很常见. 这是 生产者——消费者 模式的一部分,并且经常能在并发的代码中看到它. * 你可以将生产者抽象成一个函数,并且使通道作为它的参数,但这与必须从函数中返回结果的常识相违悖. * 这里有一个名为[produce]的便捷的协程构建器,可以很容易的在生产者端正确工作, 并且我们使用扩展函数[consumeEach]在消费者端替代for循环 */ @Test fun test3() = runBlocking { val squares = produceSquares() squares.consumeEach { println(it) } println("Done!") } private fun CoroutineScope.produceSquares(): ReceiveChannel<Int> = produce { for (x in 1..5) send(x * x) } /** * 管道 * * 管道是一种一个协程在流中开始生产可能无穷多个元素的模式 * 并且另一个或多个协程开始消费这些流,做一些操作,并生产了一些额外的结果. 在下面的例子中,对这些数字仅仅做了平方操作 * 所有创建了协程的函数被定义在了[CoroutineScope]的扩展上, 所以我们可以依靠结构化并发来确保没有常驻在我们的应用程序中的全局协程. */ @Test fun test4() = runBlocking { //启动并连接了整个管道 // 从 1 开始生产整数 val numbers = produceNumbers() // 对整数做平方 val squares = square(numbers) // 打印前 5 个数字 for (i in 1..5) println(squares.receive()) // 我们的操作已经结束了 println("Done!") // 取消子协程 coroutineContext.cancelChildren() } private fun CoroutineScope.produceNumbers() = produce<Int> { var x = 1 while (true) send(x++) // 从 1 开始的无限的整数流 } private fun CoroutineScope.square(numbers: ReceiveChannel<Int>): ReceiveChannel<Int> = produce { for (x in numbers) send(x * x) } /** * 在协程中使用一个管道来生成素数.我们开启了一个数字的无限序列. * 下面的例子打印了前十个素数, 在主线程的上下文中运行整个管道. * 直到所有的协程在该主协[runBlocking]的作用域中被启动完成. * 我们不必使用一个显式的列表来保存所有被我们已经启动的协程.我们使用[cancelChildren]扩展函数在我们打印了前十个素数以后来取消所有的子协程. * */ @Test fun test5() = runBlocking { var cur = numbersFrom(2) /** * 现在我们开启了一个从 2 开始的数字流管道,从当前的通道中取一个素数, 并为每一个我们发现的素数启动一个流水线阶段: * numbersFrom(2) -> filter(2) -> filter(3) -> filter(5) -> filter(7) …… */ for (i in 1..10) { val prime = cur.receive() println("prime:$prime") cur = filter(cur, prime) } // 取消所有的子协程来让主协程结束 coroutineContext.cancelChildren() } /** * 在下面的管道阶段中过滤了来源于流中的数字,删除了所有可以被给定素数整除的数字. */ private fun CoroutineScope.numbersFrom(start: Int) = produce<Int> { var x = start // 从 start 开始过滤整数流 while (true) send(x++) } private fun CoroutineScope.filter(numbers: ReceiveChannel<Int>, prime: Int) = produce<Int> { for (x in numbers) if (x % prime != 0) send(x) } /** * 扇出 * * 多个协程也许会接收相同的管道,在它们之间进行分布式工作. * 注意,取消生产者协程会关闭它的通道,因此通过正在执行的生产者协程通道来终止迭代. * 还有,注意我们如何使用 for 循环显式迭代通道以在[launchProcessor]代码中执行扇出. * 与[consumeEach]不同,这个 for 循环是安全完美地使用多个协程的.如果其中一个生产者协程执行失败,其它的生产者协程仍然会继续处理通道; * 而通过[consumeEach]编写的生产者始终在正常或非正常完成时消耗(取消)底层通道. */ @Test fun test6() = runBlocking { val producer = produceNumbers2() repeat(5) { launchProcessor(it, producer) } delay(950) producer.cancel() // 取消协程生产者从而将它们全部杀死 } /** * start with a producer coroutine that is periodically producing integers (ten numbers per second) */ private fun CoroutineScope.produceNumbers2() = produce<Int> { var x = 1 // start from 1 while (true) { send(x++) // 产生下一个数字 delay(100) // 等待 0.1 秒 } } /** * Then we can have several processor coroutines. In this example, they just print their id and received number. */ private fun CoroutineScope.launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch { for (msg in channel) { println("Processor #$id received $msg") } } /** * 扇入 * * 多个协程可以发送到同一个通道. * 比如说,让我们创建一个字符串的通道,和一个在这个通道中以指定的延迟反复发送一个指定字符串的挂起函数: */ @Test fun test7() = runBlocking { val channel = Channel<String>() launch { sendString(channel, "foo", 200L) } launch { sendString(channel, "BAR!", 500L) } repeat(6) { // 接收前六个 println(channel.receive()) } // 取消所有子协程来让主协程结束 coroutineContext.cancelChildren() } private suspend fun sendString(channel: SendChannel<String>, s: String, time: Long) { while (true) { delay(time) channel.send(s) } } /** * 带缓冲的通道 * * 到目前为止展示的通道都是没有缓冲区的.无缓冲的通道在发送者和接收者相遇时传输元素. * 如果发送先被调用,则它将被挂起直到接收被调用, 如果接收先被调用,它将被挂起直到发送被调用. */ @Test fun test8() = runBlocking { /** * [Channel]工厂函数与[produce]建造器通过一个可选的参数capacity来指定 缓冲区大小 . * 缓冲允许发送者在被挂起前发送多个元素, 就像 BlockingQueue 有指定的容量一样,当缓冲区被占满的时候将会引起阻塞. */ val channel = Channel<Int>(4) // 启动带缓冲的通道 val sender = launch { // 启动发送者协程 repeat(10) { println("Sending $it") // 将在缓冲区被占满时挂起,前四个元素被加入到了缓冲区并且发送者在试图发送第五个元素的时候被挂起. channel.send(it) } } // 没有接收到东西……只是等待…… delay(1000) // 取消发送者协程 sender.cancel() } /** * 通道是公平的 * * 发送和接收操作是 公平的 并且尊重调用它们的多个协程. * 它们遵守先进先出原则,可以看到第一个协程调用 receive 并得到了元素. * 在下面的例子中两个协程“乒”和“乓”都从共享的“桌子”通道接收到这个“球”元素. */ @Test fun test9() = runBlocking { // 一个共享的 table(桌子) val table = Channel<Ball>() /** * “乒”协程首先被启动,所以它首先接收到了球. * 甚至虽然“乒” 协程在将球发送会桌子以后立即开始接收,但是球还是被“乓” 协程接收了,因为它一直在等待着接收球; * 注意,有时候通道执行时由于执行者的性质而看起来不那么公平.点击这个[https://github.com/Kotlin/kotlinx.coroutines/issues/111]来查看更多细节. */ launch { player("ping", table) } launch { player("pong", table) } // 发球 table.send(Ball(0)) delay(1000) // 延迟 1 秒钟 coroutineContext.cancelChildren() } suspend fun player(name: String, table: Channel<Ball>) { for (ball in table) { // 在循环中接收球 ball.hits++ println("$name $ball") delay(300) // 等待一段时间 table.send(ball) // 将球发送回去 } } data class Ball(var hits: Int) /** * 计时器通道 * * 计时器通道是一种特别的会合通道,每次经过特定的延迟都会从该通道进行消费并产生[Unit]. * 虽然它看起来似乎没用,它被用来构建分段来创建复杂的基于时间的[produce]管道和进行窗口化操作以及其它时间相关的处理. */ @Test fun test10() = runBlocking <Unit>{ //创建计时器通道 val tickerChannel = ticker(delayMillis = 1000, initialDelayMillis = 0) var nextElement = withTimeoutOrNull(1) { tickerChannel.receive() } // 初始尚未经过的延迟 println("Initial element is available immediately: $nextElement") // 所有随后到来的元素都经过了 100 毫秒的延迟 nextElement = withTimeoutOrNull(500) { tickerChannel.receive() } println("Next element is not ready in 500 ms: $nextElement") nextElement = withTimeoutOrNull(600) { tickerChannel.receive() } println("Next element is ready in 1000 ms: $nextElement") // 模拟大量消费延迟 println("Consumer pauses for 1500ms") delay(1500) /** * 请注意,[ticker]可能知道消费者的暂停,默认情况下,如果发生暂停,则调整下一个生成的元素的延迟时间,尝试保持固定的生成元素速率. * 给可选的 mode 参数传入[TickerMode.FIXED_DELAY]可以保持固定元素之间的延迟. */ // 下一个元素立即可用 nextElement = withTimeoutOrNull(1) { tickerChannel.receive() } println("Next element is available immediately after large consumer delay: $nextElement") // 请注意,`receive` 调用之间的暂停被考虑在内,下一个元素的到达速度更快 nextElement = withTimeoutOrNull(600) { tickerChannel.receive() } println("Next element is ready in 500ms after consumer pause in 150ms: $nextElement") // 表明不再需要更多的元素 tickerChannel.cancel() } }
apache-2.0
040120011acd93246d8add2befc29528
28.185897
116
0.584779
2.804435
false
true
false
false
Archinamon/AndroidGradleSwagger
src/main/kotlin/com/archinamon/lang/kotlin/GroovyInteroperability.kt
1
2317
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.archinamon.lang.kotlin import groovy.lang.Closure import org.gradle.internal.Cast.uncheckedCast /** * Adapts a Kotlin function to a single argument Groovy [Closure]. * * @param T the expected type of the single argument to the closure. * @param action the function to be adapted. * * @see KotlinClosure */ fun <T : Any> Any.closureOf(action: T.() -> Unit): Closure<Any?> = KotlinClosure(action, this, this) /** * Adapts a Kotlin function to a Groovy [Closure] that operates on the * configured Closure delegate. * * @param T the expected type of the delegate argument to the closure. * @param function the function to be adapted. * * @see KotlinClosure */ fun <T> Any.delegateClosureOf(action: T.() -> Unit) = object : Closure<Unit>(this, this) { @Suppress("unused") // to be called dynamically by Groovy fun doCall() = uncheckedCast<T>(delegate).action() } /** * Adapts a Kotlin function to a single argument Groovy [Closure]. * * @param T the type of the single argument to the closure. * @param V the return type. * @param function the function to be adapted. * @param owner optional owner of the Closure. * @param thisObject optional _this Object_ of the Closure. * * @see Closure */ class KotlinClosure<in T : Any, V : Any>( private val function: T.() -> V?, owner: Any? = null, thisObject: Any? = null) : Closure<V?>(owner, thisObject) { @Suppress("unused") // to be called dynamically by Groovy fun doCall(it: T): V? = it.function() } operator fun <T> Closure<T>.invoke(): T = call() operator fun <T> Closure<T>.invoke(x: Any?): T = call(x) operator fun <T> Closure<T>.invoke(vararg xs: Any?): T = call(*xs)
apache-2.0
8644a8d4c0f6787999374b72281f29ca
32.1
100
0.693569
3.72508
false
false
false
false
aosp-mirror/platform_frameworks_support
jetifier/jetifier/core/src/main/kotlin/com/android/tools/build/jetifier/core/proguard/ProGuardTypesMap.kt
1
3283
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.build.jetifier.core.proguard import com.android.tools.build.jetifier.core.utils.Log /** * Contains custom mappings to map support library types referenced in ProGuard to new ones. */ data class ProGuardTypesMap(private val rules: Map<ProGuardType, Set<ProGuardType>>) { companion object { const val TAG = "ProGuardTypesMap" val EMPTY = ProGuardTypesMap(emptyMap()) } private val expandedRules: Map<ProGuardType, Set<ProGuardType>> by lazy { val expandedMap = mutableMapOf<ProGuardType, Set<ProGuardType>>() rules.forEach { (from, to) -> if (from.needsExpansion() || to.any { it.needsExpansion() }) { ProGuardType.EXPANSION_TOKENS.forEach { t -> expandedMap.put(from.expandWith(t), to.map { it.expandWith(t) }.toSet()) } } else { expandedMap.put(from, to) } } expandedMap } constructor(vararg rules: Pair<ProGuardType, ProGuardType>) : this(rules.map { it.first to setOf(it.second) }.toMap()) /** Returns JSON data model of this class */ fun toJson(): JsonData { return JsonData(rules.map { it.key.value to it.value.map { it.value }.toList() }.toMap()) } fun mapType(type: ProGuardType): Set<ProGuardType>? { return expandedRules[type] } /** * JSON data model for [ProGuardTypesMap]. */ data class JsonData(val rules: Map<String, List<String>>) { /** Creates instance of [ProGuardTypesMap] */ fun toMappings(): ProGuardTypesMap { return ProGuardTypesMap(rules .map { ProGuardType(it.key) to it.value.map { ProGuardType(it) }.toSet() } .toMap()) } } /** * Creates reversed version of this map (values become keys). If there are multiple keys mapped * to the same value only the first value is used and warning message is printed. */ fun reverseMap(): ProGuardTypesMap { val reversed = mutableMapOf<ProGuardType, ProGuardType>() for ((from, to) in rules) { if (to.size > 1) { // Skip reversal of a set continue } val conflictFrom = reversed[to.single()] if (conflictFrom != null) { // Conflict - skip Log.w(TAG, "Conflict: %s -> (%s, %s)", to, from, conflictFrom) continue } reversed[to.single()] = from } return ProGuardTypesMap(reversed .map { it.key to setOf(it.value) } .toMap()) } }
apache-2.0
8254e55f966b0ef5ad904027301905cd
33.208333
99
0.606762
4.336856
false
false
false
false
aosp-mirror/platform_frameworks_support
jetifier/jetifier/processor/src/main/kotlin/com/android/tools/build/jetifier/processor/transform/pom/XmlUtils.kt
1
4685
/* * Copyright 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.android.tools.build.jetifier.processor.transform.pom import com.android.tools.build.jetifier.core.pom.PomDependency import com.android.tools.build.jetifier.core.utils.Log import org.jdom2.Document import org.jdom2.Element import org.jdom2.input.SAXBuilder import org.jdom2.output.Format import org.jdom2.output.XMLOutputter import java.io.ByteArrayOutputStream import java.util.regex.Pattern /** * Utilities for handling XML documents. */ class XmlUtils { companion object { private val variablePattern = Pattern.compile("\\$\\{([^}]*)}") /** Saves the given [Document] to a new byte array */ fun convertDocumentToByteArray(document: Document): ByteArray { val xmlOutput = XMLOutputter() ByteArrayOutputStream().use { xmlOutput.format = Format.getPrettyFormat() xmlOutput.output(document, it) return it.toByteArray() } } /** Creates a new [Document] from the given [ByteArray] */ fun createDocumentFromByteArray(data: ByteArray): Document { val builder = SAXBuilder() data.inputStream().use { return builder.build(it) } } /** * Creates a new XML element with the given [id] and text given in [value] and puts it under * the given [parent]. Nothing is created if the [value] argument is null or empty. */ fun addStringNodeToNode(parent: Element, id: String, value: String?) { if (value.isNullOrEmpty()) { return } val element = Element(id) element.text = value element.namespace = parent.namespace parent.children.add(element) } fun resolveValue(value: String?, properties: Map<String, String>): String? { if (value == null) { return null } val matcher = variablePattern.matcher(value) if (matcher.matches()) { val variableName = matcher.group(1) val varValue = properties[variableName] if (varValue == null) { Log.e("TAG", "Failed to resolve variable '%s'", value) return value } return varValue } return value } /** * Creates a new [PomDependency] from the given XML [Element]. */ fun createDependencyFrom(node: Element, properties: Map<String, String>): PomDependency { var groupId: String? = null var artifactId: String? = null var version: String? = null var classifier: String? = null var type: String? = null var scope: String? = null var systemPath: String? = null var optional: String? = null for (childNode in node.children) { when (childNode.name) { "groupId" -> groupId = resolveValue(childNode.value, properties) "artifactId" -> artifactId = resolveValue(childNode.value, properties) "version" -> version = resolveValue(childNode.value, properties) "classifier" -> classifier = resolveValue(childNode.value, properties) "type" -> type = resolveValue(childNode.value, properties) "scope" -> scope = resolveValue(childNode.value, properties) "systemPath" -> systemPath = resolveValue(childNode.value, properties) "optional" -> optional = resolveValue(childNode.value, properties) } } return PomDependency( groupId = groupId, artifactId = artifactId, version = version, classifier = classifier, type = type, scope = scope, systemPath = systemPath, optional = optional) } } }
apache-2.0
8cb86cfad4e58070117d58d135cb4ccd
35.897638
100
0.58079
4.947202
false
false
false
false
slisson/intellij-community
plugins/settings-repository/testSrc/RespositoryHelper.kt
13
2371
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository.test import com.intellij.mock.MockVirtualFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.LightVirtualFile import com.intellij.testFramework.isFile import gnu.trove.THashSet import org.assertj.core.api.Assertions.assertThat import org.eclipse.jgit.lib.Constants import java.nio.file.Files import java.nio.file.Path data class FileInfo(val name: String, val data: ByteArray) fun fs() = MockVirtualFileSystem() private fun getChildrenStream(path: Path, excludes: Array<out String>? = null) = Files.list(path) .filter { !it.endsWith(Constants.DOT_GIT) && (excludes == null || !excludes.contains(it.getFileName().toString())) } .sorted() private fun compareFiles(path1: Path, path2: Path, path3: VirtualFile? = null, vararg localExcludes: String) { assertThat(path1).isDirectory() assertThat(path2).isDirectory() if (path3 != null) { assertThat(path3.isDirectory()).isTrue() } val notFound = THashSet<Path>() for (path in getChildrenStream(path1, localExcludes)) { notFound.add(path) } for (child2 in getChildrenStream(path2)) { val fileName = child2.getFileName() val child1 = path1.resolve(fileName) val child3 = path3?.findChild(fileName.toString()) if (child1.isFile()) { assertThat(child2).hasSameContentAs(child1) if (child3 != null) { assertThat(child3.isDirectory()).isFalse() assertThat(child1).hasContent(if (child3 is LightVirtualFile) child3.getContent().toString() else VfsUtilCore.loadText(child3)) } } else { compareFiles(child1, child2, child3, *localExcludes) } notFound.remove(child1) } assertThat(notFound).isEmpty() }
apache-2.0
d9df4d5da3f5ba461c0a00e8af35dd14
34.402985
135
0.735555
3.899671
false
false
false
false
JetBrains/teamcity-azure-plugin
plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/AzureCloudImage.kt
1
19077
/* * Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure.arm import com.intellij.openapi.diagnostic.Logger import jetbrains.buildServer.clouds.CloudException import jetbrains.buildServer.clouds.CloudInstanceUserData import jetbrains.buildServer.clouds.InstanceStatus import jetbrains.buildServer.clouds.QuotaException import jetbrains.buildServer.clouds.azure.AzureUtils import jetbrains.buildServer.clouds.azure.arm.connector.AzureApiConnector import jetbrains.buildServer.clouds.azure.arm.connector.AzureInstance import jetbrains.buildServer.clouds.azure.arm.types.* import jetbrains.buildServer.clouds.base.AbstractCloudImage import jetbrains.buildServer.clouds.base.connector.AbstractInstance import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo import jetbrains.buildServer.serverSide.TeamCityProperties import kotlinx.coroutines.* import java.lang.StringBuilder import java.util.* import java.util.concurrent.atomic.AtomicReference /** * Azure cloud image. */ class AzureCloudImage(private val myImageDetails: AzureCloudImageDetails, private val myApiConnector: AzureApiConnector, private val myScope: CoroutineScope) : AbstractCloudImage<AzureCloudInstance, AzureCloudImageDetails>(myImageDetails.sourceId, myImageDetails.sourceId) { private val myImageHandlers = mapOf( AzureCloudImageType.Vhd to AzureVhdHandler(myApiConnector), AzureCloudImageType.Image to AzureImageHandler(myApiConnector), AzureCloudImageType.GalleryImage to AzureImageHandler(myApiConnector), AzureCloudImageType.Template to AzureTemplateHandler(myApiConnector), AzureCloudImageType.Container to AzureContainerHandler(myApiConnector) ) private val myInstanceHandler = AzureInstanceHandler(myApiConnector) private val myActiveStatuses = setOf( InstanceStatus.SCHEDULED_TO_START, InstanceStatus.STARTING, InstanceStatus.RUNNING, InstanceStatus.RESTARTING, InstanceStatus.SCHEDULED_TO_STOP, InstanceStatus.STOPPING, InstanceStatus.ERROR ) private var azureCpuQuotaExceeded: Set<String>? = null private val overlimitInstanceToDelete = AtomicReference<AzureCloudInstance?>(null) override fun getImageDetails(): AzureCloudImageDetails = myImageDetails override fun createInstanceFromReal(realInstance: AbstractInstance): AzureCloudInstance { return AzureCloudInstance(this, realInstance.name).apply { properties = realInstance.properties } } override fun detectNewInstances(realInstances: MutableMap<String, out AbstractInstance>?) { super.detectNewInstances(realInstances) if (realInstances == null) { return } // Update properties instances.forEach { instance -> realInstances[instance.instanceId]?.let { instance.properties = it.properties } } } override fun canStartNewInstance(): Boolean { if (activeInstances.size >= myImageDetails.maxInstances) return false // Check Azure CPU quota state azureCpuQuotaExceeded?.let { instances -> if (instances == getInstanceIds()) { return false } else { azureCpuQuotaExceeded = null LOG.info("Azure CPU quota limit has been reset due to change in the number of active instances for image ${imageDetails.sourceId}.") } } if (imageDetails.deployTarget == AzureCloudDeployTarget.Instance && stoppedInstances.isEmpty()) { return false } return true } override fun startNewInstance(userData: CloudInstanceUserData) = runBlocking { if (!canStartNewInstance()) { throw QuotaException("Unable to start more instances. Limit has reached") } val instance = if (myImageDetails.deployTarget == AzureCloudDeployTarget.Instance) { startStoppedInstance() } else { tryToStartStoppedInstance(userData) ?: createInstance(userData) } instance.apply { setStartDate(Date()) } } /** * Creates a new virtual machine. * * @param userData info about server. * @return created instance. */ private fun createInstance(userData: CloudInstanceUserData): AzureCloudInstance { val instance = createAzureCloudInstance() val data = AzureUtils.setVmNameForTag(userData, instance.name) val image = this myScope.launch { val hash = handler!!.getImageHash(imageDetails) instance.properties[AzureConstants.TAG_PROFILE] = userData.profileId instance.properties[AzureConstants.TAG_SOURCE] = imageDetails.sourceId instance.properties[AzureConstants.TAG_DATA_HASH] = getDataHash(data) instance.properties[AzureConstants.TAG_IMAGE_HASH] = hash parseCustomTags(myImageDetails.customTags).forEach { instance.properties[it.first] = it.second } try { instance.provisioningInProgress = true instance.status = InstanceStatus.STARTING LOG.info("Creating new virtual machine ${instance.name}") myApiConnector.createInstance(instance, data) updateInstanceStatus(image, instance) } catch (e: Throwable) { LOG.warnAndDebugDetails(e.message, e) handleDeploymentError(e) instance.status = InstanceStatus.ERROR instance.updateErrors(TypedCloudErrorInfo.fromException(e)) if (TeamCityProperties.getBooleanOrTrue(AzureConstants.PROP_DEPLOYMENT_DELETE_FAILED)) { LOG.info("Removing allocated resources for virtual machine ${instance.name}") try { myApiConnector.deleteInstance(instance) LOG.info("Allocated resources for virtual machine ${instance.name} have been removed") } catch (e: Throwable) { val message = "Failed to delete allocated resources for virtual machine ${instance.name}: ${e.message}" LOG.warnAndDebugDetails(message, e) } } else { LOG.info("Allocated resources for virtual machine ${instance.name} would not be deleted. Cleanup them manually.") } } finally { instance.provisioningInProgress = false } } return instance } private fun createAzureCloudInstance(): AzureCloudInstance { do { val instance = AzureCloudInstance(this, getInstanceName()) instance.status = InstanceStatus.SCHEDULED_TO_START if (addInstanceIfAbsent(instance)) { while(activeInstances.size > myImageDetails.maxInstances) { val lastStartingInstance = instances.filter { it.status == InstanceStatus.SCHEDULED_TO_START }.sortedBy { it.name }.lastOrNull() if (lastStartingInstance == null) { throw QuotaException("Unable to start more instances. Limit has reached") } if (overlimitInstanceToDelete.compareAndSet(null, instance)) { removeInstance(instance.instanceId) overlimitInstanceToDelete.set(null) throw QuotaException("Unable to start more instances. Limit has reached") } } return instance }; } while (true); } /** * Tries to find and start stopped instance. * * @return instance if it found. */ private suspend fun tryToStartStoppedInstance(userData: CloudInstanceUserData): AzureCloudInstance? { val image = this return coroutineScope { if (myImageDetails.behaviour.isDeleteAfterStop && myImageDetails.spotVm != true) return@coroutineScope null if (stoppedInstances.isEmpty()) return@coroutineScope null val instances = stoppedInstances val validInstances = instances.filter { if (!isSameImageInstance(it)) { LOG.info("Will remove virtual machine ${it.name} due to changes in image source") return@filter false } val data = AzureUtils.setVmNameForTag(userData, it.name) if (it.properties[AzureConstants.TAG_DATA_HASH] != getDataHash(data)) { LOG.info("Will remove virtual machine ${it.name} due to changes in cloud profile") return@filter false } return@filter true } val invalidInstances = instances - validInstances val instance = validInstances.firstOrNull() instance?.status = InstanceStatus.SCHEDULED_TO_START myScope.launch { invalidInstances.forEach { val instanceToRemove = removeInstance(it.instanceId) if (instanceToRemove != null) { try { LOG.info("Removing virtual machine ${it.name}") it.provisioningInProgress = true myApiConnector.deleteInstance(it) } catch (e: Throwable) { LOG.warnAndDebugDetails(e.message, e) it.status = InstanceStatus.ERROR it.updateErrors(TypedCloudErrorInfo.fromException(e)) addInstance(instanceToRemove) } finally { it.provisioningInProgress = false } } } instance?.let { try { instance.provisioningInProgress = true it.status = InstanceStatus.STARTING LOG.info("Starting stopped virtual machine ${it.name}") myApiConnector.startInstance(it) updateInstanceStatus(image, it) } catch (e: Throwable) { LOG.warnAndDebugDetails(e.message, e) handleDeploymentError(e) it.status = InstanceStatus.ERROR it.updateErrors(TypedCloudErrorInfo.fromException(e)) } finally { instance.provisioningInProgress = false } } } return@coroutineScope instance } } /** * Starts stopped instance. * * @return instance. */ private fun startStoppedInstance(): AzureCloudInstance { val instance = stoppedInstances.singleOrNull() ?: throw CloudException("Instance ${imageDetails.vmNamePrefix ?: imageDetails.sourceId} was not found") instance.status = InstanceStatus.SCHEDULED_TO_START val image = this myScope.launch { try { instance.provisioningInProgress = true instance.status = InstanceStatus.STARTING LOG.info("Starting virtual machine ${instance.name}") myApiConnector.startInstance(instance) updateInstanceStatus(image, instance) } catch (e: Throwable) { LOG.warnAndDebugDetails(e.message, e) handleDeploymentError(e) instance.status = InstanceStatus.ERROR instance.updateErrors(TypedCloudErrorInfo.fromException(e)) } finally { instance.provisioningInProgress = false } } return instance } private fun updateInstanceStatus(image: AzureCloudImage, instance: AzureCloudInstance) { val instances = myApiConnector.fetchInstances<AzureInstance>(image) instances.get(instance.name)?.let { it.startDate?.let { instance.setStartDate(it) } it.ipAddress?.let { instance.setNetworkIdentify(it) } instance.status = it.instanceStatus } } private suspend fun isSameImageInstance(instance: AzureCloudInstance) = coroutineScope { if (imageDetails.deployTarget == AzureCloudDeployTarget.Instance) { return@coroutineScope true } handler?.let { val hash = it.getImageHash(imageDetails) return@coroutineScope hash == instance.properties[AzureConstants.TAG_IMAGE_HASH] } false } private fun getDataHash(userData: CloudInstanceUserData): String { val dataHash = StringBuilder(userData.agentName) .append(userData.profileId) .append(userData.serverAddress) .toString() .hashCode() return Integer.toHexString(dataHash) } override fun restartInstance(instance: AzureCloudInstance) { instance.status = InstanceStatus.RESTARTING val image = this myScope.launch { try { instance.provisioningInProgress = true instance.status = InstanceStatus.STARTING LOG.info("Restarting virtual machine ${instance.name}") myApiConnector.restartInstance(instance) updateInstanceStatus(image, instance) } catch (e: Throwable) { LOG.warnAndDebugDetails(e.message, e) instance.status = InstanceStatus.ERROR instance.updateErrors(TypedCloudErrorInfo.fromException(e)) } finally { instance.provisioningInProgress = false } } } override fun terminateInstance(instance: AzureCloudInstance) { if (instance.properties.containsKey(AzureConstants.TAG_INVESTIGATION)) { LOG.info("Could not stop virtual machine ${instance.name} under investigation. To do that remove ${AzureConstants.TAG_INVESTIGATION} tag from it.") return } val image = this instance.status = InstanceStatus.SCHEDULED_TO_STOP myScope.launch { try { instance.provisioningInProgress = true instance.status = InstanceStatus.STOPPING val sameVhdImage = isSameImageInstance(instance) if (myImageDetails.behaviour.isDeleteAfterStop) { LOG.info("Removing virtual machine ${instance.name} due to cloud image settings") myApiConnector.deleteInstance(instance) instance.status = InstanceStatus.STOPPED } else if (!sameVhdImage) { LOG.info("Removing virtual machine ${instance.name} due to cloud image retention policy") myApiConnector.deleteInstance(instance) instance.status = InstanceStatus.STOPPED } else { LOG.info("Stopping virtual machine ${instance.name}") myApiConnector.stopInstance(instance) updateInstanceStatus(image, instance) } LOG.info("Virtual machine ${instance.name} has been successfully terminated") } catch (e: Throwable) { LOG.warnAndDebugDetails(e.message, e) instance.status = InstanceStatus.ERROR instance.updateErrors(TypedCloudErrorInfo.fromException(e)) } finally { instance.provisioningInProgress = false } } } override fun getAgentPoolId(): Int? = myImageDetails.agentPoolId val handler: AzureHandler? get() = if (imageDetails.deployTarget == AzureCloudDeployTarget.Instance) { myInstanceHandler } else { myImageHandlers[imageDetails.type] } private fun getInstanceName(): String { val keys = instances.map { it.instanceId.toLowerCase() } val sourceName = myImageDetails.sourceId.toLowerCase() var i = 1 while (keys.contains(sourceName + i)) i++ return sourceName + i } /** * Returns active instances. * * @return instances. */ private val activeInstances: List<AzureCloudInstance> get() = instances.filter { instance -> myActiveStatuses.contains(instance.status) } /** * Returns stopped instances. * * @return instances. */ private val stoppedInstances: List<AzureCloudInstance> get() = instances.filter { instance -> instance.status == InstanceStatus.STOPPED && !instance.properties.containsKey(AzureConstants.TAG_INVESTIGATION) } private fun handleDeploymentError(e: Throwable) { if (AZURE_CPU_QUOTA_EXCEEDED.containsMatchIn(e.message!!)) { azureCpuQuotaExceeded = getInstanceIds() LOG.info("Exceeded Azure CPU quota limit for image ${imageDetails.sourceId}. Would not start new cloud instances until active instances termination.") } } private fun getInstanceIds() = activeInstances.asSequence().map { it.instanceId }.toSortedSet() companion object { private val LOG = Logger.getInstance(AzureCloudImage::class.java.name) private val AZURE_CPU_QUOTA_EXCEEDED = Regex("Operation results in exceeding quota limits of Core\\. Maximum allowed: \\d+, Current in use: \\d+, Additional requested: \\d+\\.") fun parseCustomTags(rawString: String?): List<Pair<String, String>> { return if (rawString != null && rawString.isNotEmpty()) { rawString.lines().map { it.trim() }.filter { it.isNotEmpty() }.mapNotNull { val tag = it val equalsSignIndex = tag.indexOf("=") if (equalsSignIndex >= 1) { Pair(tag.substring(0, equalsSignIndex), tag.substring(equalsSignIndex + 1)) } else { null } } } else { Collections.emptyList() } } } }
apache-2.0
793f021faedf4948d176223845df44c8
40.652838
185
0.607485
5.452129
false
false
false
false
RSDT/Japp
app/src/main/java/nl/rsdt/japp/jotial/auth/AeSimpleSHA1.kt
1
1329
package nl.rsdt.japp.jotial.auth import android.util.Log import java.io.UnsupportedEncodingException import java.security.MessageDigest import java.security.NoSuchAlgorithmException /** * @author ? * @version 1.0 * @since 15-1-2016 * Tool for SHA1. */ object AeSimpleSHA1 { private fun convertToHex(data: ByteArray): String { val buf = StringBuilder() for (b in data) { var halfbyte = (b.toInt() ushr 4) and 0x0F var two_halfs = 0 do { buf.append(if (0 <= halfbyte && halfbyte <= 9) ('0'.toInt() + halfbyte).toChar() else ('a'.toInt() + (halfbyte - 10)).toChar()) halfbyte = b.toInt() and 0x0F } while (two_halfs++ < 1) } return buf.toString() } @Throws(NoSuchAlgorithmException::class, UnsupportedEncodingException::class) fun SHA1(text: String): String { val md = MessageDigest.getInstance("SHA-1") md.update(text.toByteArray(charset("iso-8859-1")), 0, text.length) val sha1hash = md.digest() return convertToHex(sha1hash) } fun trySHA1(text: String): String { try { return SHA1(text) } catch (e: Exception) { Log.e("AeSImpleSHA1", e.localizedMessage, e) } return "error-in-trySHA1" } }
apache-2.0
e692ab0edd54242580fdab2b7b2ea8f8
26.708333
143
0.591422
3.691667
false
false
false
false
artjimlop/clean-architecture-kotlin
domain/src/test/java/com/example/usecases/GetComicByIdUseCaseTest.kt
1
1639
package com.example.usecases import com.example.bos.Comic import com.example.callback.ComicCallback import com.example.executor.TestExecutionThread import com.example.executor.TestThreadExecutor import com.example.repositories.LocalComicsRepository import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.verify import org.junit.Before import org.junit.Test import org.mockito.Mockito import java.util.* class GetComicByIdUseCaseTest { private val FAKE_COMIC_ID = 0 lateinit var localComicsRepository: LocalComicsRepository lateinit var comicCallback: ComicCallback private lateinit var useCase: GetComicByIdUseCase @Before fun setUp() { localComicsRepository = Mockito.mock(LocalComicsRepository::class.java) comicCallback = Mockito.mock(ComicCallback::class.java) val postExecutionThread = TestExecutionThread() val threadExecutor = TestThreadExecutor() useCase = GetComicByIdUseCase(threadExecutor, postExecutionThread, localComicsRepository) } @Test fun comicObtainedFromLocalRepository() { useCase.execute(FAKE_COMIC_ID, comicCallback) verify(localComicsRepository).getComic(FAKE_COMIC_ID) } @Test fun comicObtainedFromLocalRepositoryIsNotified() { Mockito.`when`(localComicsRepository.getComic(FAKE_COMIC_ID)).thenReturn(comic()) useCase.execute(FAKE_COMIC_ID, comicCallback) verify(comicCallback).onComicLoaded(any()) } private fun comic(): Comic? { return Comic(FAKE_COMIC_ID, "", "", 0, "", Collections.emptyList()) } }
apache-2.0
b7f16ea5404fa5182b6d85c3d090d9fc
28.818182
89
0.732154
4.441734
false
true
false
false
jrenner/kotlin-voxel
test/src/kotlin/org/jrenner/learngl/test/CubeDataGridTest.kt
1
15516
package org.jrenner.learngl.test import org.junit.Test import org.junit.Assert.* import org.jrenner.learngl.cube.CubeDataGrid import com.badlogic.gdx.utils.Array as Arr import com.badlogic.gdx.math.Vector3 import org.jrenner.learngl.utils.IntVector3 import com.badlogic.gdx.math.MathUtils import com.badlogic.gdx.utils.GdxRuntimeException import com.badlogic.gdx.utils.ObjectSet import org.jrenner.learngl.gameworld.Chunk import org.jrenner.learngl.gameworld.CubeData import org.jrenner.learngl.gameworld.CubeType import org.jrenner.learngl.gameworld.World import org.jrenner.learngl.utils.calculateHiddenFaces import org.jrenner.learngl.utils.threeIntegerHashCode import org.jrenner.learngl.world class CubeDataGridTest { fun basicCDG(): CubeDataGrid { val origin = Vector3(0f, 0f, 0f) return CubeDataGrid.create(origin.x, origin.y, origin.z) } val expectedNumElements = CubeDataGrid.width * CubeDataGrid.height * CubeDataGrid.depth @Test fun constructor() { val cdg = basicCDG() assertEquals(expectedNumElements, cdg.numElements) } @Test fun hashCodeTest() { val set = ObjectSet<Int>() val size = 100 for (x in 0..size) { //println("hashCodeTest, x: $x") for (y in 0..size) { for (z in 0..size) { //val cdg = CubeDataGrid() //cdg.init(x.toFloat(), y.toFloat(), z.toFloat()) //val hash = cdg.hashCode() val hash = threeIntegerHashCode(x, y, z) assertFalse("duplicate hash codes must not exist for CubeDataGrid\n(xyz: $x, $y, $z) hash: $hash", set.contains(hash)) set.add(hash) } } } } @Test fun iteration() { // test multiple times to test reset() method val cdg = basicCDG() for (n in 1..3) { var count = 0 for (item in cdg) { count++ } assertEquals(expectedNumElements, count) } } /** test iteration order of Y, then X, then Z */ @Test fun iterationOrder() { val cdg = basicCDG() val grid = cdg.grid val manualCollection = Arr<CubeData>() for (y in grid.indices) { for (x in grid[y].indices) { for (z in grid[y][x].indices) { val cubeData = grid[y][x][z] manualCollection.add(cubeData) } } } val iteratorCollection = Arr<CubeData>() for (cubeData in cdg) { iteratorCollection.add(cubeData) } assertEquals(manualCollection.size, iteratorCollection.size) val manualPos = Vector3() val iteratorPos = Vector3() for (i in 0 until manualCollection.size) { manualPos.set(manualCollection.get(i).getPositionTempVec()) iteratorPos.set(iteratorCollection.get(i).getPositionTempVec()) assertEquals(manualPos, iteratorPos) } } @Test fun hasCube() { val width = CubeDataGrid.width val height = CubeDataGrid.height val depth = CubeDataGrid.depth val cdg = basicCDG() val under = 0.99f for (x in 0 until width) { for (y in 0 until height) { for (z in 0 until depth) { assertTrue(cdg.hasCubeAt(x.toFloat(), y.toFloat(), z.toFloat())) assertTrue(cdg.hasCubeAt(x + under, y + under, z + under)) } } } assertTrue(cdg.hasCubeAt(0f, 0f, 0f)) assertFalse(cdg.hasCubeAt(-0.01f, -0.01f, -0.01f)) assertFalse(cdg.hasCubeAt(-0.01f, 1f, 1f)) assertFalse(cdg.hasCubeAt(width.toFloat(), height.toFloat(), depth.toFloat())) assertFalse(cdg.hasCubeAt(width + 0.01f, height + 0.01f, depth + 0.01f)) } @Test fun getNeighbor() { val width = CubeDataGrid.width val height = CubeDataGrid.height val depth = CubeDataGrid.depth val origin = Vector3(50f, 25f, 12f) val grid = CubeDataGrid.create(origin.x, origin.y, origin.z) assertTrue(grid.hasCubeAt(origin)) assertTrue(grid.hasCubeAt(origin.x + width-1, origin.y + height-1, origin.z + depth-1)) assertFalse(grid.hasCubeAt(-100f, -100f, -100f)) assertFalse(grid.hasCubeAt(0f, 0f, 0f)) assertFalse(grid.hasCubeAt(origin.x + width, origin.y + height, origin.z + depth)) assertFalse(grid.hasCubeAt(origin.x - 1, origin.y - 1, origin.z - 1)) val iv = IntVector3().set(origin) for (x in iv.x..iv.x+width-1) { for (y in iv.y..iv.y+height-1) { for (z in iv.z..iv.z+depth-1) { assertTrue(grid.hasCubeAt(x.toFloat(), y.toFloat(), z.toFloat())) assertNotNull(grid.getCubeAt(x.toFloat(), y.toFloat(), z.toFloat())) } } } } @Test fun chunkElevation() { val cdg = basicCDG() val maxElevation = 5 for (cube in cdg) { if(cube.yf > maxElevation) { cube.cubeType = CubeType.Void } else { cube.cubeType = CubeType.Grass } } fun CubeDataGrid.test(x: Float, z: Float, expected: Int) { assertEquals(expected, this.getElevation(x, z)) } val sz = Chunk.chunkSize println("chunk size: $sz") cdg.test(0f, 0f, maxElevation) cdg.test(0f, sz-1f, maxElevation) cdg.test(sz-1f, 0f, maxElevation) cdg.test(sz/2f, sz/2f, maxElevation) for (x in 0..sz-1) { for (z in 0..sz-1) { cdg.test(x.toFloat(), z.toFloat(), expected = maxElevation) } } val cdg2 = basicCDG() cdg2.forEach { it.cubeType = CubeType.Grass } cdg2.getCubeAt(0f, 5f, 0f).cubeType = CubeType.Void cdg2.test(0f, 0f, expected = sz-1) cdg2.getCubeAt(0f, 3f, 0f).cubeType = CubeType.Void cdg2.test(0f, 0f, expected = sz-1) } } class WorldTest { fun createWorld(w: Int, h: Int, d: Int): World { val w = World(w, h, d) world = w w.updatesEnabled = false w.createAllChunks() return w } @Test fun chunkDivisionCubeCount() { fun testCubeCount(szMult: Int) { val sz = szMult * Chunk.chunkSize if (sz % Chunk.chunkSize != 0) { throw GdxRuntimeException("Invalid world size, world size must be divisible by chunk size") } val world = createWorld(sz, sz, sz) val expectedTotalCubes = sz * sz * sz var ct = 0 world.chunks.forEach { ct += it.dataGrid.numElements } val totalCubes = ct //val totalCubes = world.chunks.fold(0, {(value: Int, chunk: Chunk!) -> value + chunk.dataGrid.numElements }) assertEquals(expectedTotalCubes, totalCubes) } for (worldSize in 1..4) { testCubeCount(worldSize) } } @Test fun chunkDivisionChunkCount() { fun assertCounts(world: World, xCount: Int, yCount: Int, zCount: Int) { //println("world: ${world.width}, ${world.height}, ${world.depth}") assertEquals(world.numChunksX, xCount) assertEquals(world.numChunksY, yCount) assertEquals(world.numChunksZ, zCount) } val sz = Chunk.chunkSize var w = createWorld(sz, sz, sz) assertCounts(w, 1, 1, 1) w = createWorld(sz*2, sz, sz) assertCounts(w, 2, 1, 1) w = createWorld(sz, sz*2, sz) assertCounts(w, 1, 2, 1) w = createWorld(sz, sz, sz*2) assertCounts(w, 1, 1, 2) w = createWorld(sz*10, sz*5, sz*3) assertCounts(w, 10, 5, 3) } @Test fun crossChunkGetNeighbor() { val sz = Chunk.chunkSize var world = createWorld(sz, sz, sz) fun testNeighbor(x: Float, y: Float, z: Float) { assertTrue(world.hasCubeAt(x, y, z)) assertNotNull(world.getCubeAt(x, y, z)) } testNeighbor(0f, 0f, 0f) testNeighbor(0.1f, 0.1f, 0.1f) testNeighbor(7f, 7f, 7f) val lo = sz-0.01f testNeighbor(lo, lo, lo) assertFalse(world.hasCubeAt(sz+0.1f, 0f, 0f)) assertFalse(world.hasCubeAt(0f, sz+0.1f, 0f)) assertFalse(world.hasCubeAt(0f, 0f, sz+0.1f)) assertFalse(world.hasCubeAt(-0.1f, -0.1f, -0.1f)) world = createWorld(17, 17, 17) for (y in 0..16) { for (x in 0..16) { for (z in 0..16) { testNeighbor(x.toFloat(), y.toFloat(), z.toFloat()) } } } } @Test fun hiddenFaces() { fun createTestWorld(w: Int, h: Int, d: Int): World { val wor = createWorld(w, h, d) wor.calculateHiddenFaces() return wor } fun World.testHiddenFaces(x: Float, y: Float, z: Float, expected: Int) { val cube = this.getCubeAt(x, y, z) //println("CUBE AT ${cube.getPositionTempVec()}") //println(cube.debugHiddenFaces) assertEquals(expected, this.getCubeAt(x, y, z).hiddenFacesCount) } val sz = 32 val max = sz-1.toFloat() val testWorld = createTestWorld(sz, sz, sz) //println("world chunks: ${testWorld.chunks.size}") var total = 0 //print("hidden faces per chunk: ") for (chunk in testWorld.chunks) { chunk.dataGrid.calculateHiddenFaces(testWorld) var subTotal = chunk.dataGrid.numberOfHiddenFaces() //print(", $subTotal") total += subTotal } //println("\ntotal hidden faces in world: $total") testWorld.testHiddenFaces(0f, 0f, 0f, expected = 3) testWorld.testHiddenFaces(1f, 0f, 0f, expected = 4) testWorld.testHiddenFaces(0f, 1f, 0f, expected = 4) testWorld.testHiddenFaces(0f, 0f, 1f, expected = 4) testWorld.testHiddenFaces(1f, 1f, 0f, expected = 5) testWorld.testHiddenFaces(1f, 1f, 1f, expected = 6) testWorld.testHiddenFaces(max-1, max-1, max-1, expected = 6) testWorld.testHiddenFaces(max, max, max, expected = 3) val world2 = createTestWorld(128, 16, 16) world2.testHiddenFaces(0f, 0f, 0f, expected = 3) world2.testHiddenFaces(127.5f, 0f, 0f, expected = 3) world2.testHiddenFaces(127.5f, 15.5f, 15.5f, expected = 3) world2.testHiddenFaces(15.5f, 15.5f, 15.5f, expected = 3) world2.testHiddenFaces(15.0f, 15.0f, 8.0f, expected = 4) } @Test fun testChunkSnapping() { // world size is actually irrelvant to this test, see world.snapToChunkCenter method contents for details val w = createWorld(8, 8, 8) val v = Vector3() val sz = Chunk.chunkSize val szf = sz.toFloat() val origin = Vector3() val delta = 0.00001f fun test() { assertEquals(origin.x, w.snapToChunkOrigin(v.x), delta) assertEquals(origin.y, w.snapToChunkOrigin(v.y), delta) assertEquals(origin.z, w.snapToChunkOrigin(v.z), delta) val centerOffset = Chunk.chunkSize / 2f assertEquals(centerOffset + origin.x, w.snapToChunkCenter(v.x), delta) assertEquals(centerOffset + origin.y, w.snapToChunkCenter(v.y), delta) assertEquals(centerOffset + origin.z, w.snapToChunkCenter(v.z), delta) } if (sz < 4) { throw GdxRuntimeException("this test depends on chunk size being >= 8") } origin.set(0f, 0f, 0f) v.set(1.12f, 2.98f, 3.84f) test() origin.set(0f, 0f, 0f) v.set(sz-0.1f, sz-0.1f, sz-0.1f) test() origin.set(szf, szf, szf) v.set(szf, szf, szf) test() origin.set(szf, szf, szf) v.set(szf+0.01f, szf+0.01f, szf+0.01f) test() origin.set(0f, 0f, 0f) v.set(szf-0.01f, szf-0.01f, szf-0.01f) test() origin.set(128f, 128f, 128f) v.set(129f, 129f, 130f) test() } @Test fun hasCube_and_hasChunk() { val sz = 32 val w = createWorld(sz, sz, sz) val max = sz-1 fun testHas(x: Float, y: Float, z: Float) { assertTrue("xyz: $x, $y, $z", w.hasChunkAt(x, y, z)) assertTrue("xyz: $x, $y, $z", w.hasCubeAt(x, y, z)) } fun testHasNot(x: Float, y: Float, z: Float) { assertFalse("xyz: $x, $y, $z", w.hasChunkAt(x, y, z)) assertFalse("xyz: $x, $y, $z", w.hasCubeAt(x, y, z)) } for (xi in 0..max) { for (yi in 0..max) { for (zi in 0..max) { val x = xi.toFloat() val y = yi.toFloat() val z = zi.toFloat() testHas(x, y, z) } } } testHas(0f, 0f, 0f) testHasNot(-0.01f, -0.01f, -0.01f) testHas(0.05f, 0.05f, 0.05f) testHasNot(max + 1.1f, max + 1.1f, max + 1.1f) val fsz = sz.toFloat() testHasNot(fsz, fsz, fsz) } @Test fun getCube() { val sz = 32 val max = sz-1 val w = createWorld(sz, sz, sz) val tmp = Vector3() fun Float.i(): Int = MathUtils.floor(this) // snap float values to integer before comparing fun equivalentAsIntegers(v1: Vector3, v2: Vector3) { assertTrue(v1.x.i() == v2.x.i()) assertTrue(v1.y.i() == v2.y.i()) assertTrue(v1.z.i() == v2.z.i()) } fun test(x: Float, y: Float, z: Float) { val cube = w.getCubeAt(x, y, z) tmp.set(x, y, z) equivalentAsIntegers(tmp, cube.getPositionTempVec()) } for (x in 0..max) { for (y in 0..max) { for (z in 0..max) { test(x + 0f, y + 0f, z + 0f) test(x + 0.95f, y + 0.95f, z + 0.95f) test(x + 0.01f, y + 0.01f, z + 0.01f) } } } } @Test fun getChunk() { val sz = 32 val max = sz-1 val w = createWorld(sz, sz, sz) fun test(x: Float, y: Float, z: Float) { val chunk = w.getChunkAt(x, y, z) val worldCube = w.getCubeAt(x, y, z) val chunkCube = chunk.dataGrid.getCubeAt(x, y, z) assertEquals(worldCube, chunkCube) assertTrue(worldCube == chunkCube) } for (x in 0..max) { for (y in 0..max) { for (z in 0..max) { test(x + 0f, y + 0f, z + 0f) test(x + 0.95f, y + 0.95f, z + 0.95f) test(x + 0.01f, y + 0.01f, z + 0.01f) } } } } }
apache-2.0
bb9b98e572e965cb7aa6d01e834bfd60
33.833718
121
0.520108
3.445703
false
true
false
false
Camano/CoolKotlin
games/rps.kt
1
3356
import java.util.* /********************************************** * Simple game made by Frekvens1 * - Version 1.1 * - Self explaining code * - Made for newer developers to learn more * Changelog * 1.1: * - Bug fixes * - Added more inputs * - Increased readability * - Optimized some functions * - Added changelog and credits * Credits - Thanks for testing my code! * Shlvam Rawat & Sasha_Kuprii * - Shortened the inputs to "r, p, s" * Ivan * - Made me convert to switch, as its more correct usage. * Gabriel Carvalho * - Bug hunter: "NoSuchElementException" when input was null * Alexandre da Costa Leite * - Bug hunter: Changing from && to || in function check for win * - Important change if converting this to multiplayer * Uploaded 19.07.2016 (DDMMYYYY) * Last updated 04.02.2017 (DDMMYYYY) */ fun main(args: Array<String>) { try { val sc = Scanner(System.`in`) if (sc.hasNext()) { //Checks for null values val userInput = quickFormat(sc.next()) sc.close() if (isValid(userInput)) { game(userInput) } else { displayInputs() } } else { displayInputs() //Null value, displaying correct inputs } } catch (e: Exception) { e.printStackTrace() } } fun game(user: String) { val computer = computerResults() print("$user vs $computer\n") if (user.equals(computer, ignoreCase = true)) { print("Stalemate! No winners.") } else { if (checkWin(user, computer)) { print("You won against the computer!") } else { print("You lost against the computer!") } } } fun computerResults(): String { val types = arrayOf("rock", "paper", "scissors") val rand = Random() val computerChoice = rand.nextInt(3) return types[computerChoice] } fun isValid(input: String): Boolean { when (input.toLowerCase()) { "rock" -> return true "paper" -> return true "scissors" -> return true else -> return false } } fun checkWin(user: String, opponent: String): Boolean { if (!isValid(user) || !isValid(opponent)) { return false } val rock = "rock" val paper = "paper" val scissors = "scissors" if (user.equals(rock, ignoreCase = true) && opponent.equals(scissors, ignoreCase = true)) { return true } if (user.equals(scissors, ignoreCase = true) && opponent.equals(paper, ignoreCase = true)) { return true } if (user.equals(paper, ignoreCase = true) && opponent.equals(rock, ignoreCase = true)) { return true } return false //If no possible win, assume loss. } /********************************************** * Libraries */ fun displayInputs() { //One place to edit it all! print("Invalid user input!\nWrite rock, paper or scissors!") } fun print(text: String) { //Makes printing text easier println(text) } fun quickFormat(input: String): String { //Just some quick function to shorten inputs. var output = input when (input.toLowerCase()) { "r" -> output = "rock" "p" -> output = "paper" "s" -> output = "scissors" "scissor" -> output = "scissors" } return output }
apache-2.0
80a924716e8a0e4a6da77d2149004aae
18.97619
96
0.572706
3.902326
false
false
false
false
VerifAPS/verifaps-lib
exec/src/main/kotlin/edu/kit/iti/formal/automation/Flycheck.kt
1
6562
package edu.kit.iti.formal.automation import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.arguments.multiple import com.github.ajalt.clikt.parameters.options.flag import com.github.ajalt.clikt.parameters.options.multiple import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.types.file import edu.kit.iti.formal.automation.analysis.ReportCategory import edu.kit.iti.formal.automation.analysis.ReportLevel import edu.kit.iti.formal.automation.analysis.Reporter import edu.kit.iti.formal.automation.analysis.ReporterMessage import edu.kit.iti.formal.automation.builtin.BuiltinLoader import edu.kit.iti.formal.automation.parser.IEC61131Lexer import edu.kit.iti.formal.automation.parser.IEC61131Parser import edu.kit.iti.formal.automation.parser.IECParseTreeToAST import edu.kit.iti.formal.automation.st.ast.PouElements import edu.kit.iti.formal.util.info import org.antlr.v4.runtime.* import org.antlr.v4.runtime.atn.ATNConfigSet import org.antlr.v4.runtime.dfa.DFA import java.io.File import java.util.* object Check { @JvmStatic fun main(args: Array<String>) = CheckApp().main(args) } object Flycheck { @JvmStatic fun main(args: Array<String>) { //println("{version:\"0.9\"}") val reader = System.`in`.bufferedReader() do { val line = reader.readLine() ?: break if (line.isEmpty()) continue CheckApp().main(parseArgs(line)) } while (true) } /** * from https://stackoverflow.com/questions/1082953/shlex-alternative-for-java * license. unlicense/public domain */ @JvmStatic fun parseArgs(argString: CharSequence): List<String> { val tokens = ArrayList<String>() var escaping = false var quoteChar = ' ' var quoting = false var current = StringBuilder() for (i in 0 until argString.length) { val c = argString[i] if (escaping) { current.append(c) escaping = false } else if (c == '\\' && !(quoting && quoteChar == '\'')) { escaping = true } else if (quoting && c == quoteChar) { quoting = false } else if (!quoting && (c == '\'' || c == '"')) { quoting = true quoteChar = c } else if (!quoting && Character.isWhitespace(c)) { if (current.length > 0) { tokens.add(current.toString()) current = StringBuilder() } } else { current.append(c) } } if (current.isNotEmpty()) { tokens.add(current.toString()) } return tokens } } class CheckApp : CliktCommand() { val verbose by option(help = "enable verbose mode").flag() val format by option("--json", help = "Flag for enabling json, line based format").flag() val include by option("-L", help = "folder for looking includes") .file() .multiple() val includeBuiltIn by option("-b", help = "") .flag("-B") val files by argument(name = "FILE", help = "Files to check") .file() .multiple() override fun run() { val base = if (includeBuiltIn) BuiltinLoader.loadDefault() else PouElements() val r = FlycheckRunner( files.map { CharStreams.fromFileName(it.absolutePath) }, base, verbose, format, include ) r.run() } } class FlycheckRunner( val streams: List<CharStream>, val library: PouElements = PouElements(), val verbose: Boolean = false, val json: Boolean = false, val includeStubs: List<File> = arrayListOf()) { val underInvestigation: PouElements = PouElements() private val reporter = Reporter() val messages: MutableList<ReporterMessage> get() = reporter.messages private val errorListener = MyAntlrErrorListener(reporter) fun run() { info("Start with parsing") streams.forEach { parse(it) } info("Resolving...") resolve() info("Checking...") check() info("Print.") printMessages() } fun parse(stream: CharStream) { val lexer = IEC61131Lexer(stream) val parser = IEC61131Parser(CommonTokenStream(lexer)) lexer.removeErrorListeners() parser.removeErrorListeners() parser.addErrorListener(errorListener) val ctx = parser.start() val tles = ctx.accept(IECParseTreeToAST()) as PouElements library.addAll(tles) underInvestigation.addAll(tles) } private fun resolve() { IEC61131Facade.resolveDataTypes(library) } fun check() { messages.addAll(IEC61131Facade.check(underInvestigation)) } private fun printMessages() { if (messages.isEmpty()) { if (json) { println("{ok:true}") } else { info("Everything is fine.") } } else { if (json) { val msg = messages.joinToString(",") { it.toJson() } print("[$msg]\n") System.out.flush() } else { messages.forEach { info(it.toHuman()) } } } } private fun printMessage(message: ReporterMessage) { } class MyAntlrErrorListener(private val reporter: Reporter) : ANTLRErrorListener { override fun syntaxError(recognizer: Recognizer<*, *>?, offendingSymbol: Any?, line: Int, charPositionInLine: Int, msg: String?, e: RecognitionException?) { val token = (offendingSymbol as Token) reporter.report(token, msg!!, ReportCategory.SYNTAX, ReportLevel.ERROR) } override fun reportAttemptingFullContext(recognizer: Parser?, dfa: DFA?, startIndex: Int, stopIndex: Int, conflictingAlts: BitSet?, configs: ATNConfigSet?) {} override fun reportAmbiguity(recognizer: Parser?, dfa: DFA?, startIndex: Int, stopIndex: Int, exact: Boolean, ambigAlts: BitSet?, configs: ATNConfigSet?) {} override fun reportContextSensitivity(recognizer: Parser?, dfa: DFA?, startIndex: Int, stopIndex: Int, prediction: Int, configs: ATNConfigSet?) {} } }
gpl-3.0
774c451b9682970671407f892af4422f
31.646766
166
0.598903
4.305774
false
false
false
false
AlmasB/FXGL
fxgl-controllerinput/src/main/kotlin/com/almasb/fxgl/controllerinput/ControllerInputService.kt
1
4047
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.controllerinput import com.almasb.fxgl.controllerinput.impl.GameControllerImpl import com.almasb.fxgl.core.EngineService import com.almasb.fxgl.core.Inject import com.almasb.fxgl.core.util.Platform import com.almasb.fxgl.core.util.Platform.* import com.almasb.fxgl.logging.Logger import javafx.collections.FXCollections import javafx.collections.ObservableList import java.nio.file.Files import java.nio.file.Paths /** * Provides access to game controllers. Currently support is limited: no hot-swaps/reloads and * the controller(s) must be plugged in before the start of the engine. * * @author Almas Baimagambetov ([email protected]) */ class ControllerInputService : EngineService() { private val log = Logger.get(javaClass) @Inject("platform") private lateinit var platform: Platform private var isNativeLibLoaded = false private val resourceDirNames = hashMapOf( WINDOWS to "windows64", LINUX to "linux64", MAC to "mac64" ) private val nativeLibNames = hashMapOf( WINDOWS to listOf("SDL2.dll", "fxgl_controllerinput.dll"), LINUX to listOf("libSDL2.so", "libfxgl_controllerinput.so") ) private val controllers = FXCollections.observableArrayList<GameController>() val gameControllers: ObservableList<GameController> by lazy { FXCollections.unmodifiableObservableList(controllers) } override fun onInit() { try { log.debug("Loading nativeLibs for $platform") // copy native libs to cache if needed // use openjfx dir since we know it is (will be) there val fxglCacheDir = Paths.get(System.getProperty("user.home")).resolve(".openjfx").resolve("cache").resolve("fxgl-11") if (Files.notExists(fxglCacheDir)) { log.debug("Creating FXGL native libs cache: $fxglCacheDir") Files.createDirectories(fxglCacheDir) } nativeLibNames[platform]?.forEach { libName -> val nativeLibPath = fxglCacheDir.resolve(libName) if (Files.notExists(nativeLibPath)) { log.debug("Copying $libName into cache") val dirName = resourceDirNames[platform]!! javaClass.getResource("/nativeLibs/$dirName/$libName").openStream().use { Files.copy(it, nativeLibPath) } } log.debug("Loading $nativeLibPath") System.load(nativeLibPath.toAbsolutePath().toString()) } isNativeLibLoaded = true log.debug("Successfully loaded nativeLibs. Calling to check back-end version.") val version = GameControllerImpl.getBackendVersion() log.info("Controller back-end version: $version") log.debug("Connecting to plugged-in controllers") val numControllers = GameControllerImpl.connectControllers() if (numControllers > 0) { log.debug("Successfully connected to $numControllers controller(s)") } else { log.debug("No controllers found") } for (id in 0 until numControllers) { controllers += GameController(id) } } catch (e: Exception) { log.warning("Loading nativeLibs for controller support failed", e) log.warning("Printing stacktrace:") e.printStackTrace() } } override fun onUpdate(tpf: Double) { if (!isNativeLibLoaded || controllers.isEmpty()) return GameControllerImpl.updateState(0); controllers.forEach { it.update() } } override fun onExit() { if (!isNativeLibLoaded || controllers.isEmpty()) return GameControllerImpl.disconnectControllers() } }
mit
6c72056887f7ccfa889a6dcb92b34abc
30.874016
129
0.631826
4.772406
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/firstball/SplitsStatistic.kt
1
1313
package ca.josephroque.bowlingcompanion.statistics.impl.firstball import android.content.SharedPreferences import android.os.Parcel import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator import ca.josephroque.bowlingcompanion.games.lane.Deck import ca.josephroque.bowlingcompanion.games.lane.isSplit import ca.josephroque.bowlingcompanion.settings.Settings /** * Copyright (C) 2018 Joseph Roque * * Percentage of shots which are splits. */ class SplitsStatistic(numerator: Int = 0, denominator: Int = 0) : FirstBallStatistic(numerator, denominator) { companion object { @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::SplitsStatistic) const val Id = R.string.statistic_splits } override val titleId = Id override val id = Id.toLong() private var countS2asS: Boolean = Settings.BooleanSetting.CountS2AsS.default // MARK: Statistic override fun isModifiedBy(deck: Deck) = deck.isSplit(countS2asS) override fun updatePreferences(preferences: SharedPreferences) { countS2asS = Settings.BooleanSetting.CountS2AsS.getValue(preferences) } // MARK: Constructors private constructor(p: Parcel): this(numerator = p.readInt(), denominator = p.readInt()) }
mit
0d20da395061e2e866d04f020850a0ee
31.02439
110
0.757045
4.420875
false
false
false
false
AsynkronIT/protoactor-kotlin
proto-mailbox/src/main/kotlin/actor/proto/mailbox/MailboxProducers.kt
1
2333
package actor.proto.mailbox import org.jctools.queues.MpscArrayQueue import org.jctools.queues.MpscGrowableArrayQueue import org.jctools.queues.MpscLinkedQueue8 import org.jctools.queues.MpscUnboundedArrayQueue import org.jctools.queues.QueueFactory.newQueue import org.jctools.queues.atomic.MpscAtomicArrayQueue import org.jctools.queues.atomic.MpscGrowableAtomicArrayQueue import org.jctools.queues.atomic.MpscUnboundedAtomicArrayQueue import org.jctools.queues.spec.ConcurrentQueueSpec import java.util.concurrent.ConcurrentLinkedQueue private val emptyStats : Array<MailboxStatistics> = arrayOf() fun newUnboundedMailbox(stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), ConcurrentLinkedQueue<Any>(), stats) fun newMpscAtomicArrayMailbox(capacity: Int = 1000, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscAtomicArrayQueue(capacity), stats) fun newMpscArrayMailbox(capacity: Int = 1000, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscArrayQueue(capacity), stats) fun newMpscUnboundedArrayMailbox(chunkSize: Int = 5, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscUnboundedArrayQueue(chunkSize), stats) fun newMpscUnboundedAtomicArrayMailbox(chunkSize: Int = 5, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscUnboundedAtomicArrayQueue(chunkSize), stats) fun newMpscGrowableArrayMailbox(initialCapacity: Int = 5, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscGrowableArrayQueue(initialCapacity, 2 shl 11), stats) fun newMpscGrowableAtomicArrayMailbox(initialCapacity: Int = 5, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscGrowableAtomicArrayQueue(initialCapacity, 2 shl 11), stats) fun newMpscLinkedMailbox(stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscLinkedQueue8(), stats) fun newSpecifiedMailbox(spec:ConcurrentQueueSpec, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), newQueue(spec) , stats)
apache-2.0
67ae054a62d8599873ef946d7196296c
76.766667
229
0.833262
4.092982
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/listener/PlayerMoveListener.kt
1
2042
/* * Copyright 2021 Ren Binden * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.characters.bukkit.listener import com.rpkit.characters.bukkit.RPKCharactersBukkit import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.Location import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerMoveEvent /** * Player move listener for preventing players from moving about with a dead character. */ class PlayerMoveListener(private val plugin: RPKCharactersBukkit) : Listener { @EventHandler fun onPlayerMove(event: PlayerMoveEvent) { val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return val characterService = Services[RPKCharacterService::class.java] ?: return val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(event.player) ?: return val character = characterService.getPreloadedActiveCharacter(minecraftProfile) if (character == null || !character.isDead) return if (event.from.blockX == event.to?.blockX && event.from.blockZ == event.to?.blockZ) return event.player.teleport(Location(event.from.world, event.from.blockX + 0.5, event.from.blockY + 0.5, event.from.blockZ.toDouble(), event.from.yaw, event.from.pitch)) event.player.sendMessage(plugin.messages["dead-character"]) } }
apache-2.0
0dbf2fc194e3b6bc98d6554aba5f235d
45.409091
171
0.764447
4.381974
false
false
false
false
cketti/k-9
backend/testing/src/main/java/app/k9mail/backend/testing/InMemoryBackendStorage.kt
1
2254
package app.k9mail.backend.testing import com.fsck.k9.backend.api.BackendFolderUpdater import com.fsck.k9.backend.api.BackendStorage import com.fsck.k9.backend.api.FolderInfo import com.fsck.k9.mail.FolderType class InMemoryBackendStorage : BackendStorage { val folders: MutableMap<String, InMemoryBackendFolder> = mutableMapOf() val extraStrings: MutableMap<String, String> = mutableMapOf() val extraNumbers: MutableMap<String, Long> = mutableMapOf() override fun getFolder(folderServerId: String): InMemoryBackendFolder { return folders[folderServerId] ?: error("Folder $folderServerId not found") } override fun getFolderServerIds(): List<String> { return folders.keys.toList() } override fun createFolderUpdater(): BackendFolderUpdater { return InMemoryBackendFolderUpdater() } override fun getExtraString(name: String): String? = extraStrings[name] override fun setExtraString(name: String, value: String) { extraStrings[name] = value } override fun getExtraNumber(name: String): Long? = extraNumbers[name] override fun setExtraNumber(name: String, value: Long) { extraNumbers[name] = value } private inner class InMemoryBackendFolderUpdater : BackendFolderUpdater { override fun createFolders(folders: List<FolderInfo>) { folders.forEach { folder -> if ([email protected](folder.serverId)) { error("Folder ${folder.serverId} already present") } [email protected][folder.serverId] = InMemoryBackendFolder(folder.name, folder.type) } } override fun deleteFolders(folderServerIds: List<String>) { for (folderServerId in folderServerIds) { folders.remove(folderServerId) ?: error("Folder $folderServerId not found") } } override fun changeFolder(folderServerId: String, name: String, type: FolderType) { val folder = folders[folderServerId] ?: error("Folder $folderServerId not found") folder.name = name folder.type = type } override fun close() = Unit } }
apache-2.0
8cf6a6abce31dfbf2313ddec9b6c7e22
35.354839
118
0.675688
4.705637
false
false
false
false
nickthecoder/tickle
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/resources/Resources.kt
1
5096
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.resources import uk.co.nickthecoder.tickle.* import uk.co.nickthecoder.tickle.events.CompoundInput import uk.co.nickthecoder.tickle.graphics.Texture import uk.co.nickthecoder.tickle.sound.Sound import java.io.File import java.lang.IllegalStateException open class Resources { var file: File = File("") val resourceDirectory: File get() = file.parentFile ?: File(".").absoluteFile val gameInfo = GameInfo("Tickle", "ticklegame", 600, 400, fullScreen = false, resizable = false) val preferences = EditorPreferences() val textures = ResourceMap<Texture>(this) val poses = ResourceMap<Pose>(this) val costumes = ResourceMap<Costume>(this) val costumeGroups = ResourceMap<CostumeGroup>(this) val inputs = ResourceMap<CompoundInput>(this) val layouts = ResourceMap<Layout>(this) val fontResources = ResourceMap<FontResource>(this) val sounds = ResourceMap<Sound>(this) val sceneDirectory: File get() = File(file.parentFile, "scenes").absoluteFile val texturesDirectory: File get() = File(file.parentFile, "images").absoluteFile val listeners = mutableListOf<ResourcesListener>() init { instance = this } open fun save() { throw IllegalStateException("Resources are read-only") } open fun createAttributes(): Attributes { return RuntimeAttributes() } fun findName(resource: Any): String? { return when (resource) { is Texture -> textures.findName(resource) is Pose -> poses.findName(resource) is Costume -> costumes.findName(resource) is CostumeGroup -> costumeGroups.findName(resource) is CompoundInput -> inputs.findName(resource) is Layout -> layouts.findName(resource) is FontResource -> fontResources.findName(resource) is SceneStub -> resource.name else -> null } } fun findCostumeGroup(costumeName: String): CostumeGroup? { costumeGroups.items().values.forEach { costumeGroup -> if (costumeGroup.find(costumeName) != null) { return costumeGroup } } return null } fun toPath(file: File): String { try { return file.absoluteFile.toRelativeString(resourceDirectory) } catch(e: Exception) { return file.absolutePath } } fun fromPath(path: String): File { return resourceDirectory.resolve(path).absoluteFile } fun scenePathToFile(path: String): File { return sceneDirectory.resolve(path + ".scene") } fun sceneFileToPath(file: File): String { val path = if (file.isAbsolute) { file.relativeToOrSelf(sceneDirectory).path } else { file.path } if (path.endsWith(".scene")) { return path.substring(0, path.length - 6) } else { return path } } fun fireAdded(resource: Any, name: String) { listeners.toList().forEach { it.resourceAdded(resource, name) } } fun fireRemoved(resource: Any, name: String) { listeners.toList().forEach { it.resourceRemoved(resource, name) } } fun fireRenamed(resource: Any, oldName: String, newName: String) { listeners.toList().forEach { it.resourceRenamed(resource, oldName, newName) } } fun fireChanged(resource: Any) { listeners.toList().forEach { it.resourceChanged(resource) } } /** * Reloads the textures, sounds and fonts. */ fun reload() { textures.items().values.forEach { it.reload() } sounds.items().values.forEach { it.reload() } fontResources.items().values.forEach { it.reload() } } fun scriptDirectory() = File(file.parentFile.absoluteFile, "scripts") fun fxcoderDirectory() = File(file.parentFile.absoluteFile, "fxcoder") fun destroy() { textures.items().values.forEach { it.destroy() } fontResources.items().values.forEach { it.destroy() } sounds.items().values.forEach { it.destroy() } } companion object { /** * A convenience, so that game scripts can easily get access to the resources. */ lateinit var instance: Resources } }
gpl-3.0
05255f0d47eb060e3ab46dd8c127c00f
27.629213
100
0.639129
4.442895
false
false
false
false
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/scene/Layers.kt
1
6449
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.editor.scene import javafx.event.EventHandler import javafx.scene.control.CheckMenuItem import javafx.scene.control.MenuButton import javafx.scene.control.MenuItem import javafx.scene.control.SeparatorMenuItem import javafx.scene.image.ImageView import javafx.scene.input.MouseEvent import javafx.scene.layout.StackPane import uk.co.nickthecoder.tickle.editor.EditorAction import uk.co.nickthecoder.tickle.editor.resources.DesignJsonScene import uk.co.nickthecoder.tickle.editor.resources.DesignSceneResource import uk.co.nickthecoder.tickle.resources.LayoutView import uk.co.nickthecoder.tickle.resources.NoStageConstraint import uk.co.nickthecoder.tickle.resources.Resources import uk.co.nickthecoder.tickle.resources.StageConstraint import uk.co.nickthecoder.tickle.stage.StageView import uk.co.nickthecoder.tickle.stage.View import uk.co.nickthecoder.tickle.stage.ZOrderStageView /** */ class Layers(val sceneEditor: SceneEditor) { val stack = StackPane() private val allLayers = mutableListOf<Layer>() private val stageLayers = mutableListOf<StageLayer>() private val includedLayers = mutableMapOf<String, List<StageLayer>>() val glass = GlassLayer(sceneEditor) private val map = mutableMapOf<String, StageLayer>() val stageButton = MenuButton("no stage selected") var scale: Double = 1.0 set(v) { field = v allLayers.forEach { it.scale(v) } } var currentLayer: StageLayer? = null set(v) { field = v if (v == null) { stageButton.text = "<no stage selected>" } else { stageButton.text = v.stageName if (singleLayerMode.isSelected) { stageLayers.forEach { it.isLocked = true } } v.isLocked = false v.isVisible = true } } val singleLayerMode = CheckMenuItem("Single Layer Mode") init { stageButton.graphic = ImageView(EditorAction.imageResource("layers.png")) stageButton.items.add(singleLayerMode) stageButton.items.add(SeparatorMenuItem()) loadIncludes() val layout = Resources.instance.layouts.find(sceneEditor.sceneResource.layoutName) createStageLayers(sceneEditor.sceneResource).forEach { layer: StageLayer -> add(layer) stageLayers.add(layer) map[layer.stageName] = layer stageButton.items.add(createMenuItem(layer)) if (layout?.layoutStages?.get(layer.stageName)?.isDefault == true) { currentLayer = layer } } // If no stage was set as default, the use the first layer. if (currentLayer == null) { currentLayer = stageLayers.firstOrNull() } add(glass) } private fun createStageLayers(sceneResource: DesignSceneResource): List<StageLayer> { val result = mutableListOf<StageLayer>() sceneResource.stageResources.forEach { stageName, stageResource -> val layout = Resources.instance.layouts.find(sceneResource.layoutName)!! val constraintName = layout.layoutStages[stageName]?.stageConstraintString var constraint: StageConstraint = NoStageConstraint() try { constraint = Class.forName(constraintName).newInstance() as StageConstraint } catch(e: Exception) { System.err.println("WARNING : Failed to create the StageConstraint for stage $stageName. Using NoStageConstraint") } constraint.forStage(stageName, stageResource) val layoutView: LayoutView? = layout.layoutViews.values.firstOrNull() { it.stageName == stageName } val view: View? = layoutView?.createView() val stageView: StageView = if (view is StageView) view else ZOrderStageView() val layer = StageLayer(sceneResource, stageName, stageResource, stageView, constraint) result.add(layer) } return result } private fun loadIncludes() { sceneEditor.sceneResource.includes.forEach { include -> val includedSR = DesignJsonScene(include).sceneResource as DesignSceneResource val layers = mutableListOf<StageLayer>() includedLayers.put(include.nameWithoutExtension, layers) createStageLayers(includedSR).forEach { layer -> layer.isLocked = true layers.add(layer) add(layer) } } } fun names(): Collection<String> = map.keys fun stageLayer(name: String): StageLayer? = map[name] fun stageLayers(): List<StageLayer> = stageLayers fun editableLayers() = stageLayers.filter { it.isVisible && !it.isLocked } fun visibleLayers() = stageLayers.filter { it.isVisible } fun add(layer: Layer) { allLayers.add(layer) stack.children.add(layer.canvas) } fun createMenuItem(layer: StageLayer): MenuItem { val menuItem = MenuItem(layer.stageName) menuItem.onAction = EventHandler { stageButton.text = layer.stageName currentLayer = layer } return menuItem } fun viewX(event: MouseEvent): Double { return glass.centerX + (event.x - glass.canvas.width / 2) / scale } fun viewY(event: MouseEvent): Double { return glass.centerY + (glass.canvas.height / 2 - event.y) / scale } fun panBy(dx: Double, dy: Double) { allLayers.forEach { it.panBy(dx, dy) } } fun draw() { allLayers.forEach { it.draw() } } fun currentLayer(): StageLayer? { return currentLayer } }
gpl-3.0
9f2352d4fb76dac498a7103547fad58e
31.736041
130
0.660257
4.525614
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/commands/options/LocalizedCommandOptions.kt
1
3957
package net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options import dev.kord.common.Locale import dev.kord.common.entity.ChannelType import dev.kord.core.entity.Role import dev.kord.core.entity.User import dev.kord.core.entity.channel.Channel import net.perfectdreams.discordinteraktions.common.autocomplete.AutocompleteHandler import net.perfectdreams.discordinteraktions.common.commands.options.* import net.perfectdreams.i18nhelper.core.keydata.StringI18nData import net.perfectdreams.loritta.common.locale.LanguageManager import net.perfectdreams.loritta.common.utils.text.TextUtils.shortenWithEllipsis import net.perfectdreams.loritta.cinnamon.discord.utils.DiscordResourceLimits import net.perfectdreams.loritta.cinnamon.discord.utils.SlashTextUtils abstract class LocalizedCommandOption<T>( val languageManager: LanguageManager, val descriptionI18n: StringI18nData, ) : NameableCommandOption<T> { override val description = languageManager.defaultI18nContext.get(descriptionI18n).shortenWithEllipsis(DiscordResourceLimits.Command.Options.Description.Length) override val descriptionLocalizations = SlashTextUtils.createShortenedLocalizedStringMapExcludingDefaultLocale(languageManager, descriptionI18n) override val nameLocalizations: Map<Locale, String> = emptyMap() } // ===[ STRING ]=== class LocalizedStringCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean, override val choices: List<CommandChoice<String>>?, override val minLength: Int?, override val maxLength: Int?, override val autocompleteExecutor: AutocompleteHandler<String>? ) : LocalizedCommandOption<String>(languageManager, descriptionI18n), StringCommandOption // ===[ INTEGER ]=== class LocalizedIntegerCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean, override val choices: List<CommandChoice<Long>>?, override val minValue: Long?, override val maxValue: Long?, override val autocompleteExecutor: AutocompleteHandler<Long>? ) : LocalizedCommandOption<Long>(languageManager, descriptionI18n), IntegerCommandOption // ===[ NUMBER ]=== class LocalizedNumberCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean, override val choices: List<CommandChoice<Double>>?, override val minValue: Double?, override val maxValue: Double?, override val autocompleteExecutor: AutocompleteHandler<Double>? ) : LocalizedCommandOption<Double>(languageManager, descriptionI18n), NumberCommandOption // ===[ BOOLEAN ]=== class LocalizedBooleanCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean ) : LocalizedCommandOption<Boolean>(languageManager, descriptionI18n), BooleanCommandOption // ===[ USER ]=== class LocalizedUserCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean ) : LocalizedCommandOption<User>(languageManager, descriptionI18n), UserCommandOption // ===[ CHANNEL ]=== class LocalizedChannelCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean, override val channelTypes: List<ChannelType>? ) : LocalizedCommandOption<Channel>(languageManager, descriptionI18n), ChannelCommandOption // ===[ ROLE ]=== class LocalizedRoleCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean ) : LocalizedCommandOption<Role>(languageManager, descriptionI18n), RoleCommandOption
agpl-3.0
e95b889f2b3152c3f6dd647e66d8d38d
42.021739
164
0.795552
4.75601
false
false
false
false
ericberman/MyFlightbookAndroid
app/src/main/java/com/myflightbook/android/ActNewFlight.kt
1
83584
/* MyFlightbook for Android - provides native access to MyFlightbook pilot's logbook Copyright (C) 2017-2022 MyFlightbook, LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.myflightbook.android import android.Manifest import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.location.Location import android.os.Bundle import android.os.Handler import android.os.Looper import android.text.format.DateFormat import android.util.Log import android.view.* import android.view.ContextMenu.ContextMenuInfo import android.view.View.OnFocusChangeListener import android.widget.* import androidx.activity.result.ActivityResult import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts.RequestPermission import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult import androidx.core.app.ShareCompat.IntentBuilder import androidx.lifecycle.lifecycleScope import com.myflightbook.android.ActMFBForm.GallerySource import com.myflightbook.android.ActOptions.AltitudeUnits import com.myflightbook.android.ActOptions.SpeedUnits import com.myflightbook.android.DlgDatePicker.DateTimeUpdate import com.myflightbook.android.MFBMain.Invalidatable import com.myflightbook.android.webservices.* import com.myflightbook.android.webservices.AuthToken.Companion.isValid import com.myflightbook.android.webservices.CustomPropertyTypesSvc.Companion.cachedPropertyTypes import com.myflightbook.android.webservices.MFBSoap.Companion.isOnline import com.myflightbook.android.webservices.RecentFlightsSvc.Companion.clearCachedFlights import com.myflightbook.android.webservices.UTCDate.isNullDate import kotlinx.coroutines.launch import model.* import model.Aircraft.Companion.getAircraftById import model.Aircraft.Companion.getHighWaterHobbsForAircraft import model.Aircraft.Companion.getHighWaterTachForAircraft import model.Airport.Companion.appendCodeToRoute import model.Airport.Companion.appendNearestToRoute import model.CustomPropertyType.Companion.getPinnedProperties import model.CustomPropertyType.Companion.isPinnedProperty import model.DecimalEdit.CrossFillDelegate import model.FlightProperty.Companion.crossProduct import model.FlightProperty.Companion.distillList import model.FlightProperty.Companion.rewritePropertiesForFlight import model.GPSSim.Companion.autoFill import model.LogbookEntry.SigStatus import model.MFBConstants.nightParam import model.MFBFlightListener.ListenerFragmentDelegate import model.MFBImageInfo.PictureDestination import model.MFBLocation.AutoFillOptions import model.MFBLocation.Companion.getMainLocation import model.MFBLocation.Companion.hasGPS import model.MFBLocation.GPSQuality import model.MFBUtil.alert import model.MFBUtil.getForKey import model.MFBUtil.nowWith0Seconds import model.MFBUtil.removeForKey import model.MFBUtil.removeSeconds import model.PropertyTemplate.Companion.anonTemplate import model.PropertyTemplate.Companion.defaultTemplates import model.PropertyTemplate.Companion.getSharedTemplates import model.PropertyTemplate.Companion.mergeTemplates import model.PropertyTemplate.Companion.simTemplate import model.PropertyTemplate.Companion.templatesWithIDs import java.io.UnsupportedEncodingException import java.net.URL import java.net.URLEncoder import java.text.SimpleDateFormat import java.util.* import kotlin.math.abs import kotlin.math.roundToInt class ActNewFlight : ActMFBForm(), View.OnClickListener, ListenerFragmentDelegate, DateTimeUpdate, PropertyEdit.PropertyListener, GallerySource, CrossFillDelegate, Invalidatable { private var mRgac: Array<Aircraft>? = null private var mle: LogbookEntry? = null private var mActivetemplates: HashSet<PropertyTemplate?>? = HashSet() private var needsDefaultTemplates = true private var txtQuality: TextView? = null private var txtStatus: TextView? = null private var txtSpeed: TextView? = null private var txtAltitude: TextView? = null private var txtSunrise: TextView? = null private var txtSunset: TextView? = null private var txtLatitude: TextView? = null private var txtLongitude: TextView? = null private var imgRecording: ImageView? = null private var mHandlerupdatetimer: Handler? = null private var mUpdateelapsedtimetask: Runnable? = null private var mTimeCalcLauncher: ActivityResultLauncher<Intent>? = null private var mApproachHelperLauncher: ActivityResultLauncher<Intent>? = null private var mMapRouteLauncher: ActivityResultLauncher<Intent>? = null private var mTemplateLauncher: ActivityResultLauncher<Intent>? = null private var mPropertiesLauncher: ActivityResultLauncher<Intent>? = null private var mAppendAdhocLauncher: ActivityResultLauncher<String>? = null private var mAppendNearestLauncher: ActivityResultLauncher<String>? = null private var mAddAircraftLauncher: ActivityResultLauncher<Intent>? = null private fun deleteFlight(le : LogbookEntry?) { if (le == null) return val soapCall = when { (le is PendingFlight) -> PendingFlightSvc() else -> DeleteFlightSvc() } val pf = le as? PendingFlight lifecycleScope.launch { doAsync<MFBSoap, Boolean?>( requireActivity(), soapCall, getString(R.string.prgDeletingFlight), { s -> if (pf != null && pf.getPendingID().isNotEmpty()) ActRecentsWS.cachedPendingFlights = (s as PendingFlightSvc).deletePendingFlight(AuthToken.m_szAuthToken, pf.getPendingID(), requireContext()) else (s as DeleteFlightSvc).deleteFlightForUser(AuthToken.m_szAuthToken, le.idFlight, requireContext()) s.lastError.isEmpty() }, { _, result -> if (result!!) { clearCachedFlights() MFBMain.invalidateCachedTotals() finish() } } ) } } private fun submitFlight(le : LogbookEntry?) { if (le == null) return val fIsNew = le.isNewFlight() val pf = le as? PendingFlight lifecycleScope.launch { doAsync<MFBSoap, Boolean?>( requireActivity(), if (le.fForcePending || (pf != null && pf.getPendingID().isNotEmpty())) PendingFlightSvc() else CommitFlightSvc(), getString(R.string.prgSavingFlight), { s -> submitFlightWorker(le, s) }, { _, result -> if (result!!) { MFBMain.invalidateCachedTotals() // success, so we our cached recents are invalid clearCachedFlights() val ocl: DialogInterface.OnClickListener // the flight was successfully saved, so delete any local copy regardless le.deleteUnsubmittedFlightFromLocalDB() if (fIsNew) { // Reset the flight and we stay on this page resetFlight(true) ocl = DialogInterface.OnClickListener { d: DialogInterface, _: Int -> d.cancel() } } else { // no need to reset the current flight because we will finish. ocl = DialogInterface.OnClickListener { d: DialogInterface, _: Int -> d.cancel() finish() } mle = null // so that onPause won't cause it to be saved on finish() call. } AlertDialog.Builder(requireActivity(), R.style.MFBDialog) .setMessage(getString(R.string.txtSavedFlight)) .setTitle(getString(R.string.txtSuccess)) .setNegativeButton("OK", ocl) .create().show() } else alert(requireContext(), getString(R.string.txtError), le.szError) }) } } private fun submitFlightWorker(le : LogbookEntry, s : MFBSoap) : Boolean { /* Scenarios: - fForcePending is false, Regular flight, new or existing: call CommitFlightWithOptions - fForcePending is false, Pending flight without a pending ID call CommitFlightWithOptions. Shouldn't happen, but no big deal if it does - fForcePending is false, Pending flight with a Pending ID: call CommitPendingFlight to commit it - fForcePending is false, Pending flight without a pending ID: THROW EXCEPTION, how did this happen? - fForcePending is true, Regular flight that is not new/pending (sorry about ambiguous "pending"): THROW EXCEPTION; this is an error - fForcePending is true, Regular flight that is NEW: call CreatePendingFlight - fForcePending is true, PendingFlight without a PendingID: call CreatePendingFlight. Shouldn't happen, but no big deal if it does - fForcePending is true, PendingFlight with a PendingID: call UpdatePendingFlight */ val pf = le as? PendingFlight if (le.fForcePending) { val pfs = s as PendingFlightSvc check(!le.isExistingFlight()) { "Attempt to save an existing flight as a pending flight" } if (pf == null || pf.getPendingID().isEmpty()) { pfs.createPendingFlight(AuthToken.m_szAuthToken, le, requireContext()) .also { ActRecentsWS.cachedPendingFlights = it } le.szError = pfs.lastError } else { // existing pending flight but still force pending - call updatependingflight pfs.updatePendingFlight(AuthToken.m_szAuthToken, pf, requireContext()) .also { ActRecentsWS.cachedPendingFlights = it } le.szError = pfs.lastError } } else { // Not force pending. // If regular flight (new or existing), or pending without a pendingID if (pf == null || pf.getPendingID().isEmpty()) { val cf = s as CommitFlightSvc cf.fCommitFlightForUser(AuthToken.m_szAuthToken, le, requireContext()) le.szError = cf.lastError } else { // By definition, here pf is non-null and it has a pending ID so it is a valid pending flight and we are not forcing - call commitpendingflight val pfs = s as PendingFlightSvc val rgpf = pfs.commitPendingFlight(AuthToken.m_szAuthToken, pf, requireContext()) ActRecentsWS.cachedPendingFlights = rgpf pf.szError = pfs.lastError } } return le.szError.isEmpty() } private fun fetchDigitizedSig(url : String?, iv : ImageView) { if (url == null || url.isEmpty()) return lifecycleScope.launch { doAsync<String, Bitmap?>( requireActivity(), url, null, { url -> try { val str = URL(url).openStream() BitmapFactory.decodeStream(str) } catch (e: Exception) { Log.e(MFBConstants.LOG_TAG, e.message!!) null } }, { _, result -> if (result != null) iv.setImageBitmap(result) } ) } } private fun refreshAircraft() { lifecycleScope.launch { doAsync<AircraftSvc, Array<Aircraft>?>( requireActivity(), AircraftSvc(), getString(R.string.prgAircraft), { s -> s.getAircraftForUser(AuthToken.m_szAuthToken, requireContext()) }, { s, result -> if (result == null) alert(requireActivity(),getString(R.string.txtError), s.lastError) else refreshAircraft(result, false) } ) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { setHasOptionsMenu(true) return inflater.inflate(R.layout.newflight, container, false) } override fun onStop() { super.onStop() if (mle == null || mle!!.isNewFlight()) MFBMain.setInProgressFlightActivity(context, null) } private fun setUpActivityLaunchers() { mApproachHelperLauncher = registerForActivityResult( StartActivityForResult() ) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { val approachDesc = result.data!!.getStringExtra(ActAddApproach.APPROACHDESCRIPTIONRESULT) if (approachDesc!!.isNotEmpty()) { mle!!.addApproachDescription(approachDesc) val cApproachesToAdd = result.data!!.getIntExtra(ActAddApproach.APPROACHADDTOTOTALSRESULT, 0) if (cApproachesToAdd > 0) { mle!!.cApproaches += cApproachesToAdd setIntForField(R.id.txtApproaches, mle!!.cApproaches) } toView() } } } mTimeCalcLauncher = registerForActivityResult( StartActivityForResult() ) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { setDoubleForField( R.id.txtTotal, result.data!!.getDoubleExtra(ActTimeCalc.COMPUTED_TIME, mle!!.decTotal) .also { mle!!.decTotal = it }) } } mMapRouteLauncher = registerForActivityResult( StartActivityForResult() ) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { mle!!.szRoute = result.data!!.getStringExtra(ActFlightMap.ROUTEFORFLIGHT)!! setStringForField(R.id.txtRoute, mle!!.szRoute) findViewById(R.id.txtRoute)!!.requestFocus() } } mTemplateLauncher = registerForActivityResult( StartActivityForResult() ) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { val b = result.data!!.extras try { val o = b!!.getSerializable(ActViewTemplates.ACTIVE_PROPERTYTEMPLATES) mActivetemplates = o as HashSet<PropertyTemplate?>? updateTemplatesForAircraft(true) toView() } catch (ex: ClassCastException) { Log.e(MFBConstants.LOG_TAG, ex.message!!) } } } mPropertiesLauncher = registerForActivityResult( StartActivityForResult() ) { setUpPropertiesForFlight() if (MFBLocation.fPrefAutoFillTime === AutoFillOptions.BlockTime) doAutoTotals() } mAppendAdhocLauncher = registerForActivityResult( RequestPermission() ) { result: Boolean -> if (result) { val loc = getMainLocation()!! if (loc.currentLoc() == null) return@registerForActivityResult val szAdHoc = LatLong(loc.currentLoc()!!).toAdHocLocString() val txtRoute = findViewById(R.id.txtRoute) as TextView? mle!!.szRoute = appendCodeToRoute(txtRoute!!.text.toString(), szAdHoc) txtRoute.text = mle!!.szRoute } } mAppendNearestLauncher = registerForActivityResult( RequestPermission() ) { result: Boolean -> if (result) { val txtRoute = findViewById(R.id.txtRoute) as TextView? mle!!.szRoute = appendNearestToRoute( txtRoute!!.text.toString(), getMainLocation()!!.currentLoc() ) txtRoute.text = mle!!.szRoute } } mAddAircraftLauncher = registerForActivityResult( StartActivityForResult() ) { val rgac = AircraftSvc().cachedAircraft mRgac = rgac refreshAircraft(mRgac, false) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpActivityLaunchers() addListener(R.id.btnFlightSet) addListener(R.id.btnFlightStartSet) addListener(R.id.btnEngineStartSet) addListener(R.id.btnFlightEndSet) addListener(R.id.btnEngineEndSet) addListener(R.id.btnBlockOut) addListener(R.id.btnBlockIn) addListener(R.id.btnProps) addListener(R.id.btnAppendNearest) addListener(R.id.btnAddAircraft) findViewById(R.id.btnAppendNearest)!!.setOnLongClickListener { appendAdHoc() true } // Expand/collapse addListener(R.id.txtViewInTheCockpit) addListener(R.id.txtImageHeader) addListener(R.id.txtPinnedPropertiesHeader) addListener(R.id.txtSignatureHeader) enableCrossFill(R.id.txtNight) enableCrossFill(R.id.txtSimIMC) enableCrossFill(R.id.txtIMC) enableCrossFill(R.id.txtXC) enableCrossFill(R.id.txtDual) enableCrossFill(R.id.txtGround) enableCrossFill(R.id.txtCFI) enableCrossFill(R.id.txtSIC) enableCrossFill(R.id.txtPIC) enableCrossFill(R.id.txtHobbsStart) enableCrossFill(R.id.txtTachStart) findViewById(R.id.txtTotal)!!.setOnLongClickListener { val i = Intent(requireActivity(), ActTimeCalc::class.java) i.putExtra(ActTimeCalc.INITIAL_TIME, doubleFromField(R.id.txtTotal)) mTimeCalcLauncher!!.launch(i) true } findViewById(R.id.btnFlightSet)!!.setOnLongClickListener { resetDateOfFlight() true } var b = findViewById(R.id.btnPausePlay) as ImageButton? b!!.setOnClickListener(this) b = findViewById(R.id.btnViewOnMap) as ImageButton? b!!.setOnClickListener(this) b = findViewById(R.id.btnAddApproach) as ImageButton? b!!.setOnClickListener(this) // cache these views for speed. txtQuality = findViewById(R.id.txtFlightGPSQuality) as TextView? txtStatus = findViewById(R.id.txtFlightStatus) as TextView? txtSpeed = findViewById(R.id.txtFlightSpeed) as TextView? txtAltitude = findViewById(R.id.txtFlightAltitude) as TextView? txtSunrise = findViewById(R.id.txtSunrise) as TextView? txtSunset = findViewById(R.id.txtSunset) as TextView? txtLatitude = findViewById(R.id.txtLatitude) as TextView? txtLongitude = findViewById(R.id.txtLongitude) as TextView? imgRecording = findViewById(R.id.imgRecording) as ImageView? // get notification of hobbs changes, or at least focus changes val s = OnFocusChangeListener { v: View, hasFocus: Boolean -> if (!hasFocus) onHobbsChanged(v) } findViewById(R.id.txtHobbsStart)!!.onFocusChangeListener = s findViewById(R.id.txtHobbsEnd)!!.onFocusChangeListener = s val i = requireActivity().intent val keyForLeToView = i.getStringExtra(ActRecentsWS.VIEWEXISTINGFLIGHT) val leToView = if (keyForLeToView == null) null else getForKey(keyForLeToView) as LogbookEntry? removeForKey(keyForLeToView) val fIsNewFlight = leToView == null if (!fIsNewFlight && mRgac == null) mRgac = AircraftSvc().cachedAircraft val sp = findViewById(R.id.spnAircraft) as Spinner? sp!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>, view: View?, position: Int, id: Long ) { val ac = parent.selectedItem as Aircraft if (mle != null && mle!!.idAircraft != ac.aircraftID) { if (ac.aircraftID == -1) { // show all! refreshAircraft(mRgac, true) sp.performClick() } else { fromView() mle!!.idAircraft = ac.aircraftID updateTemplatesForAircraft(false) toView() } } } override fun onNothingSelected(parent: AdapterView<*>?) {} } // set for no focus. findViewById(R.id.btnFlightSet)!!.requestFocus() if (fIsNewFlight) { // re-use the existing in-progress flight mle = MFBMain.newFlightListener?.getInProgressFlight(requireActivity()) MFBMain.registerNotifyResetAll(this) val pref = requireActivity().getPreferences(Context.MODE_PRIVATE) val fExpandCockpit = pref.getBoolean(m_KeyShowInCockpit, true) setExpandedState( (findViewById(R.id.txtViewInTheCockpit) as TextView?)!!, findViewById(R.id.sectInTheCockpit)!!, fExpandCockpit, false ) } else { // view an existing flight mle = leToView if (mle!!.isExistingFlight() || mle is PendingFlight) { mle!!.toDB() // ensure that this is in the database - above call could have pulled from cache rewritePropertiesForFlight(mle!!.idLocalDB, mle!!.rgCustomProperties) } setUpPropertiesForFlight() } if (mle != null && mle!!.rgFlightImages == null) mle!!.imagesForFlight // Refresh aircraft on create if (isValid() && (mRgac == null || mRgac!!.isEmpty())) refreshAircraft() Log.w( MFBConstants.LOG_TAG, String.format( "ActNewFlight - created, m_le is %s", if (mle == null) "null" else "non-null" ) ) } private fun enableCrossFill(id: Int) { val de = findViewById(id) as DecimalEdit? de!!.setDelegate(this) } override fun crossFillRequested(sender: DecimalEdit?) { fromView() if (sender!!.id == R.id.txtHobbsStart) { val d = getHighWaterHobbsForAircraft(mle!!.idAircraft) if (d > 0) sender.doubleValue = d } else if (sender.id == R.id.txtTachStart) { val d = getHighWaterTachForAircraft(mle!!.idAircraft) if (d > 0) sender.doubleValue = d } else if (mle!!.decTotal > 0) sender.doubleValue = mle!!.decTotal fromView() } private fun selectibleAircraft(): Array<Aircraft>? { if (mRgac == null) return null val lst: MutableList<Aircraft> = ArrayList() for (ac in mRgac!!) { if (!ac.hideFromSelection || mle != null && ac.aircraftID == mle!!.idAircraft) lst.add( ac ) } if (lst.size == 0) return mRgac if (lst.size != mRgac!!.size) { // some aircraft are filtered // Issue #202 - add a "Show all Aircraft" option val ac = Aircraft() ac.aircraftID = -1 ac.modelDescription = getString(R.string.fqShowAllAircraft) ac.tailNumber = "#" lst.add(ac) } return lst.toTypedArray() } private fun refreshAircraft(rgac: Array<Aircraft>?, fShowAll: Boolean) { mRgac = rgac val spnAircraft = findViewById(R.id.spnAircraft) as Spinner? val rgFilteredAircraft = if (fShowAll) rgac else selectibleAircraft() if (rgFilteredAircraft != null && rgFilteredAircraft.isNotEmpty()) { var pos = 0 for (i in rgFilteredAircraft.indices) { if (mle == null || mle!!.idAircraft == rgFilteredAircraft[i].aircraftID) { pos = i break } } // Create a list of the aircraft to show, which are the ones that are not hidden OR the active one for the flight val adapter = ArrayAdapter( requireActivity(), R.layout.mfbsimpletextitem, rgFilteredAircraft ) spnAircraft!!.adapter = adapter spnAircraft.setSelection(pos) // need to notifydatasetchanged or else setselection doesn't // update correctly. adapter.notifyDataSetChanged() } else { spnAircraft!!.prompt = getString(R.string.errNoAircraftFoundShort) alert(this, getString(R.string.txtError), getString(R.string.errMustCreateAircraft)) } } override fun onResume() { // refresh the aircraft list (will be cached if we already have it) // in case a new aircraft has been added. super.onResume() if (!isValid()) { val d = DlgSignIn(requireActivity()) d.show() } val rgac = AircraftSvc().cachedAircraft mRgac = rgac if (mRgac != null) refreshAircraft(mRgac, false) // Not sure why le can sometimes be empty here... if (mle == null) mle = MFBMain.newFlightListener?.getInProgressFlight(requireActivity()) // show/hide GPS controls based on whether this is a new flight or existing. val fIsNewFlight = mle!!.isNewFlight() val l = findViewById(R.id.sectGPS) as LinearLayout? l!!.visibility = if (fIsNewFlight) View.VISIBLE else View.GONE findViewById(R.id.btnAppendNearest)!!.visibility = if (fIsNewFlight && hasGPS(requireContext())) View.VISIBLE else View.GONE val btnViewFlight = findViewById(R.id.btnViewOnMap) as ImageButton? btnViewFlight!!.visibility = if (MFBMain.hasMaps()) View.VISIBLE else View.GONE if (fIsNewFlight) { // ensure that we keep the elapsed time up to date updatePausePlayButtonState() mHandlerupdatetimer = Handler(Looper.getMainLooper()) val elapsedTimeTask = object : Runnable { override fun run() { updateElapsedTime() mHandlerupdatetimer!!.postDelayed(this, 1000) } } mUpdateelapsedtimetask = elapsedTimeTask mHandlerupdatetimer!!.postDelayed(elapsedTimeTask, 1000) } setUpGalleryForFlight() restoreState() // set the ensure that we are following the right numerical format setDecimalEditMode(R.id.txtCFI) setDecimalEditMode(R.id.txtDual) setDecimalEditMode(R.id.txtGround) setDecimalEditMode(R.id.txtIMC) setDecimalEditMode(R.id.txtNight) setDecimalEditMode(R.id.txtPIC) setDecimalEditMode(R.id.txtSIC) setDecimalEditMode(R.id.txtSimIMC) setDecimalEditMode(R.id.txtTotal) setDecimalEditMode(R.id.txtXC) // Make sure the date of flight is up-to-date if (mle!!.isKnownEngineStart || mle!!.isKnownFlightStart) resetDateOfFlight() // First resume after create should pull in default templates; // subsequent resumes should NOT. updateTemplatesForAircraft(!needsDefaultTemplates) needsDefaultTemplates = false // reset this. toView() // do this last to start GPS service if (fIsNewFlight) MFBMain.setInProgressFlightActivity(context, this) } private fun setUpGalleryForFlight() { if (mle!!.rgFlightImages == null) mle!!.imagesForFlight setUpImageGallery(getGalleryID(), mle!!.rgFlightImages, getGalleryHeader()) } override fun onPause() { super.onPause() // should only happen when we are returning from viewing an existing/queued/pending flight, may have been submitted // either way, no need to save this if (mle == null) return fromView() saveCurrentFlight() Log.w(MFBConstants.LOG_TAG, String.format("Paused, landings are %d", mle!!.cLandings)) saveState() // free up some scheduling resources. if (mHandlerupdatetimer != null) mHandlerupdatetimer!!.removeCallbacks( mUpdateelapsedtimetask!! ) } private fun restoreState() { try { val mPrefs = requireActivity().getPreferences(Activity.MODE_PRIVATE) fPaused = mPrefs.getBoolean(m_KeysIsPaused, false) dtPauseTime = mPrefs.getLong(m_KeysPausedTime, 0) dtTimeOfLastPause = mPrefs.getLong(m_KeysTimeOfLastPause, 0) accumulatedNight = mPrefs.getFloat(m_KeysAccumulatedNight, 0.0.toFloat()).toDouble() } catch (e: Exception) { Log.e(MFBConstants.LOG_TAG, Log.getStackTraceString(e)) } } private fun saveState() { // Save UI state changes to the savedInstanceState. // This bundle will be passed to onCreate if the process is // killed and restarted. val ed = requireActivity().getPreferences(Activity.MODE_PRIVATE).edit() ed.putBoolean(m_KeysIsPaused, fPaused) ed.putLong(m_KeysPausedTime, dtPauseTime) ed.putLong(m_KeysTimeOfLastPause, dtTimeOfLastPause) ed.putFloat(m_KeysAccumulatedNight, accumulatedNight.toFloat()) ed.apply() } override fun saveCurrentFlight() { if (!mle!!.isExistingFlight()) mle!!.toDB() if (activity == null) // sometimes not yet set up return // and we only want to save the current flightID if it is a new (not queued!) flight if (mle!!.isNewFlight()) MFBMain.newFlightListener?.saveCurrentFlightId(activity) } private fun setLogbookEntry(le: LogbookEntry) { mle = le saveCurrentFlight() if (view == null) return setUpGalleryForFlight() toView() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { val idMenu: Int if (mle != null) { idMenu = if (mle!!.isExistingFlight()) R.menu.mfbexistingflightmenu else if (mle!!.isNewFlight()) R.menu.mfbnewflightmenu else if (mle is PendingFlight) R.menu.mfbpendingflightmenu else if (mle!!.isQueuedFlight()) R.menu.mfbqueuedflightmenu else R.menu.mfbqueuedflightmenu inflater.inflate(idMenu, menu) } super.onCreateOptionsMenu(menu, inflater) } override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo?) { super.onCreateContextMenu(menu, v, menuInfo) val inflater = requireActivity().menuInflater inflater.inflate(R.menu.imagemenu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Should never happen. if (mle == null) return false // Handle item selection when (val menuId = item.itemId) { R.id.menuUploadLater -> submitFlight(true) R.id.menuResetFlight -> { if (mle!!.idLocalDB > 0) mle!!.deleteUnsubmittedFlightFromLocalDB() resetFlight(false) } R.id.menuSignFlight -> { try { ActWebView.viewURL( requireActivity(), String.format( Locale.US, MFBConstants.urlSign, MFBConstants.szIP, mle!!.idFlight, URLEncoder.encode(AuthToken.m_szAuthToken, "UTF-8"), nightParam(context) ) ) } catch (ignored: UnsupportedEncodingException) { } } R.id.btnDeleteFlight -> AlertDialog.Builder( requireActivity(), R.style.MFBDialog ) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.lblConfirm) .setMessage(R.string.lblConfirmFlightDelete) .setPositiveButton(R.string.lblOK) { _: DialogInterface?, _: Int -> if (mle!!.isAwaitingUpload()) { mle!!.deleteUnsubmittedFlightFromLocalDB() mle = null // clear this out since we're going to finish(). clearCachedFlights() finish() } else if (mle!!.isExistingFlight() || mle is PendingFlight) deleteFlight(mle) } .setNegativeButton(R.string.lblCancel, null) .show() R.id.btnSubmitFlight, R.id.btnUpdateFlight -> submitFlight( false ) R.id.btnSavePending -> { mle!!.fForcePending = true submitFlight(false) } R.id.menuTakePicture -> takePictureClicked() R.id.menuTakeVideo -> takeVideoClicked() R.id.menuChoosePicture -> choosePictureClicked() R.id.menuChooseTemplate -> { val i = Intent(requireActivity(), ViewTemplatesActivity::class.java) val b = Bundle() b.putSerializable(ActViewTemplates.ACTIVE_PROPERTYTEMPLATES, mActivetemplates) i.putExtras(b) mTemplateLauncher!!.launch(i) } R.id.menuRepeatFlight, R.id.menuReverseFlight -> { assert(mle != null) val leNew = if (menuId == R.id.menuRepeatFlight) mle!!.clone() else mle!!.cloneAndReverse() leNew!!.idFlight = LogbookEntry.ID_QUEUED_FLIGHT_UNSUBMITTED leNew.toDB() rewritePropertiesForFlight(leNew.idLocalDB, leNew.rgCustomProperties) leNew.syncProperties() clearCachedFlights() AlertDialog.Builder(requireActivity(), R.style.MFBDialog) .setMessage(getString(R.string.txtRepeatFlightComplete)) .setTitle(getString(R.string.txtSuccess)) .setNegativeButton("OK") { d: DialogInterface, _: Int -> d.cancel() finish() } .create().show() return true } R.id.menuSendFlight -> sendFlight() R.id.menuShareFlight -> shareFlight() R.id.btnAutoFill -> { assert(mle != null) fromView() autoFill(requireContext(), mle) toView() } else -> return super.onOptionsItemSelected(item) } return true } private fun sendFlight() { if (mle == null || mle!!.sendLink.isEmpty()) { alert(this, getString(R.string.txtError), getString(R.string.errCantSend)) return } IntentBuilder(requireActivity()) .setType("message/rfc822") .setSubject(getString(R.string.sendFlightSubject)) .setText( String.format( Locale.getDefault(), getString(R.string.sendFlightBody), mle!!.sendLink ) ) .setChooserTitle(getString(R.string.menuSendFlight)) .startChooser() } private fun shareFlight() { if (mle == null || mle!!.shareLink.isEmpty()) { alert(this, getString(R.string.txtError), getString(R.string.errCantShare)) return } val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra( Intent.EXTRA_SUBJECT, String.format(Locale.getDefault(), "%s %s", mle!!.szComments, mle!!.szRoute) .trim { it <= ' ' }) intent.putExtra(Intent.EXTRA_TEXT, mle!!.shareLink) startActivity(Intent.createChooser(intent, getString(R.string.menuShareFlight))) } override fun onContextItemSelected(item: MenuItem): Boolean { val menuID = item.itemId return if (menuID == R.id.menuAddComment || menuID == R.id.menuDeleteImage || menuID == R.id.menuViewImage) onImageContextItemSelected( item, this ) else true } //region append to route // NOTE: I had been doing this with an AsyncTask, but it // wasn't thread safe with the database. DB is pretty fast, // so we can just make sure we do all DB stuff on the main thread. private fun appendNearest() { assert(getMainLocation() != null) mAppendNearestLauncher!!.launch(Manifest.permission.ACCESS_FINE_LOCATION) } private fun appendAdHoc() { assert(getMainLocation() != null) mAppendAdhocLauncher!!.launch(Manifest.permission.ACCESS_FINE_LOCATION) } //endregion private fun takePictureClicked() { saveCurrentFlight() takePicture() } private fun takeVideoClicked() { saveCurrentFlight() takeVideo() } private fun choosePictureClicked() { saveCurrentFlight() choosePicture() } override fun onClick(v: View) { fromView() when (val id = v.id) { R.id.btnEngineStartSet -> { if (!mle!!.isKnownEngineStart) { mle!!.dtEngineStart = nowWith0Seconds() engineStart() } else setDateTime( id, mle!!.dtEngineStart, this, DlgDatePicker.DatePickMode.UTCDATETIME ) } R.id.btnEngineEndSet -> { if (!mle!!.isKnownEngineEnd) { mle!!.dtEngineEnd = nowWith0Seconds() engineStop() } else setDateTime(id, mle!!.dtEngineEnd, this, DlgDatePicker.DatePickMode.UTCDATETIME) } R.id.btnBlockOut -> { val dtBlockOut = mle!!.propDateForID(CustomPropertyType.idPropTypeBlockOut) if (dtBlockOut == null) { mle!!.addOrSetPropertyDate(CustomPropertyType.idPropTypeBlockOut, nowWith0Seconds()) resetDateOfFlight() } else setDateTime(id, dtBlockOut, this, DlgDatePicker.DatePickMode.UTCDATETIME) } R.id.btnBlockIn -> { val dtBlockIn = mle!!.propDateForID(CustomPropertyType.idPropTypeBlockIn) if (dtBlockIn == null) mle!!.addOrSetPropertyDate(CustomPropertyType.idPropTypeBlockIn, nowWith0Seconds()) else setDateTime(id, dtBlockIn, this, DlgDatePicker.DatePickMode.UTCDATETIME) } R.id.btnFlightStartSet -> { if (!mle!!.isKnownFlightStart) { mle!!.dtFlightStart = nowWith0Seconds() flightStart() } else setDateTime( id, mle!!.dtFlightStart, this, DlgDatePicker.DatePickMode.UTCDATETIME ) } R.id.btnFlightEndSet -> { if (!mle!!.isKnownFlightEnd) { mle!!.dtFlightEnd = nowWith0Seconds() flightStop() } else setDateTime(id, mle!!.dtFlightEnd, this, DlgDatePicker.DatePickMode.UTCDATETIME) } R.id.btnFlightSet -> { val dlg = DlgDatePicker( requireActivity(), DlgDatePicker.DatePickMode.LOCALDATEONLY, mle!!.dtFlight ) dlg.mDelegate = this dlg.mId = id dlg.show() } R.id.btnProps -> viewPropsForFlight() R.id.btnAppendNearest -> appendNearest() R.id.btnAddAircraft -> mAddAircraftLauncher!!.launch( Intent( activity, NewAircraftActivity::class.java ) ) R.id.btnAddApproach -> { val i = Intent(requireActivity(), ActAddApproach::class.java) i.putExtra(ActAddApproach.AIRPORTSFORAPPROACHES, mle!!.szRoute) mApproachHelperLauncher!!.launch(i) } R.id.btnViewOnMap -> { val i = Intent(requireActivity(), ActFlightMap::class.java) i.putExtra(ActFlightMap.ROUTEFORFLIGHT, mle!!.szRoute) i.putExtra( ActFlightMap.EXISTINGFLIGHTID, if (mle!!.isExistingFlight()) mle!!.idFlight else 0 ) i.putExtra( ActFlightMap.PENDINGFLIGHTID, if (mle!!.isAwaitingUpload()) mle!!.idLocalDB else 0 ) i.putExtra( ActFlightMap.NEWFLIGHTID, if (mle!!.isNewFlight()) LogbookEntry.ID_NEW_FLIGHT else 0 ) i.putExtra(ActFlightMap.ALIASES, "") mMapRouteLauncher!!.launch(i) } R.id.btnPausePlay -> toggleFlightPause() R.id.txtViewInTheCockpit -> { val target = findViewById(R.id.sectInTheCockpit) val fExpandCockpit = target!!.visibility != View.VISIBLE if (mle != null && mle!!.isNewFlight()) { val e = requireActivity().getPreferences(Context.MODE_PRIVATE).edit() e.putBoolean(m_KeyShowInCockpit, fExpandCockpit) e.apply() } setExpandedState((v as TextView), target, fExpandCockpit) } R.id.txtImageHeader -> { val target = findViewById(R.id.tblImageTable) setExpandedState((v as TextView), target!!, target.visibility != View.VISIBLE) } R.id.txtSignatureHeader -> { val target = findViewById(R.id.sectSignature) setExpandedState((v as TextView), target!!, target.visibility != View.VISIBLE) } R.id.txtPinnedPropertiesHeader -> { val target = findViewById(R.id.sectPinnedProperties) setExpandedState((v as TextView), target!!, target.visibility != View.VISIBLE) } } toView() } //region Image support override fun chooseImageCompleted(result: ActivityResult?) { addGalleryImage(result!!.data!!) } override fun takePictureCompleted(result: ActivityResult?) { addCameraImage(mTempfilepath, false) } override fun takeVideoCompleted(result: ActivityResult?) { addCameraImage(mTempfilepath, true) } //endregion private fun viewPropsForFlight() { val i = Intent(requireActivity(), ActViewProperties::class.java) i.putExtra(PROPSFORFLIGHTID, mle!!.idLocalDB) i.putExtra(PROPSFORFLIGHTEXISTINGID, mle!!.idFlight) i.putExtra(PROPSFORFLIGHTCROSSFILLVALUE, mle!!.decTotal) i.putExtra( TACHFORCROSSFILLVALUE, getHighWaterTachForAircraft( mle!!.idAircraft ) ) mPropertiesLauncher!!.launch(i) } private fun onHobbsChanged(v: View) { if (mle != null && MFBLocation.fPrefAutoFillTime === AutoFillOptions.HobbsTime) { val txtHobbsStart = findViewById(R.id.txtHobbsStart) as EditText? val txtHobbsEnd = findViewById(R.id.txtHobbsEnd) as EditText? val newHobbsStart = doubleFromField(R.id.txtHobbsStart) val newHobbsEnd = doubleFromField(R.id.txtHobbsEnd) if (v === txtHobbsStart && newHobbsStart != mle!!.hobbsStart || v === txtHobbsEnd && newHobbsEnd != mle!!.hobbsEnd ) doAutoTotals() } } override fun updateDate(id: Int, dt: Date?) { var dt2 = dt fromView() var fEngineChanged = false var fFlightChanged = false var fBlockChanged = false dt2 = removeSeconds(dt2!!) when (id) { R.id.btnEngineStartSet -> { mle!!.dtEngineStart = dt2 fEngineChanged = true resetDateOfFlight() } R.id.btnEngineEndSet -> { mle!!.dtEngineEnd = dt2 fEngineChanged = true showRecordingIndicator() } R.id.btnBlockOut -> { handlePotentiallyDefaultedProperty(mle!!.addOrSetPropertyDate(CustomPropertyType.idPropTypeBlockOut, dt2)) resetDateOfFlight() fBlockChanged = true } R.id.btnBlockIn -> { handlePotentiallyDefaultedProperty(mle!!.addOrSetPropertyDate(CustomPropertyType.idPropTypeBlockIn, dt2)) fBlockChanged = true } R.id.btnFlightStartSet -> { mle!!.dtFlightStart = dt2 resetDateOfFlight() fFlightChanged = true } R.id.btnFlightEndSet -> { mle!!.dtFlightEnd = dt2 fFlightChanged = true } R.id.btnFlightSet -> { mle!!.dtFlight = dt2 } } toView() when (MFBLocation.fPrefAutoFillHobbs) { AutoFillOptions.EngineTime -> if (fEngineChanged) doAutoHobbs() AutoFillOptions.FlightTime -> if (fFlightChanged) doAutoHobbs() else -> {} } when (MFBLocation.fPrefAutoFillTime) { AutoFillOptions.EngineTime -> if (fEngineChanged) doAutoTotals() AutoFillOptions.FlightTime -> if (fFlightChanged) doAutoTotals() AutoFillOptions.BlockTime -> if (fBlockChanged) doAutoTotals() AutoFillOptions.HobbsTime -> {} AutoFillOptions.FlightStartToEngineEnd -> doAutoTotals() else -> {} } } private fun validateAircraftID(id: Int): Int { var idAircraftToUse = -1 if (mRgac != null) { for (ac in mRgac!!) if (ac.aircraftID == id) { idAircraftToUse = id break } } return idAircraftToUse } private fun resetFlight(fCarryHobbs: Boolean) { // start up a new flight with the same aircraft ID and public setting. // first, validate that the aircraft is still OK for the user val hobbsEnd = mle!!.hobbsEnd val leNew = LogbookEntry(validateAircraftID(mle!!.idAircraft), mle!!.fPublic) if (fCarryHobbs) leNew.hobbsStart = hobbsEnd mActivetemplates!!.clear() mle!!.idAircraft = leNew.idAircraft // so that updateTemplatesForAircraft works updateTemplatesForAircraft(false) setLogbookEntry(leNew) MFBMain.newFlightListener?.setInProgressFlight(leNew) saveCurrentFlight() // flush any pending flight data getMainLocation()!!.resetFlightData() // and flush any pause/play data fPaused = false dtPauseTime = 0 dtTimeOfLastPause = 0 accumulatedNight = 0.0 } private fun submitFlight(forceQueued: Boolean) { val le = mle!! if (le.isNewFlight() || le.signatureStatus != SigStatus.Valid) submitFlightConfirmed(forceQueued) else { AlertDialog.Builder( requireActivity(), R.style.MFBDialog ) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.lblConfirm) .setMessage(R.string.lblConfirmModifySignedFlight) .setPositiveButton(R.string.lblOK) { _: DialogInterface?, _: Int -> submitFlightConfirmed(forceQueued) } .setNegativeButton(R.string.lblCancel, null) .show() } } private fun submitFlightConfirmed(forceQueued: Boolean) { fromView() val a: Activity = requireActivity() if (a.currentFocus != null) a.currentFocus!!.clearFocus() // force any in-progress edit to commit, particularly for properties. val fIsNew = mle!!.isNewFlight() // hold onto this because we can change the status. if (fIsNew) { getMainLocation()?.isRecording = false showRecordingIndicator() } // load any pending properties from the DB into the logbookentry object itself. mle!!.syncProperties() // load the telemetry string, if it's a first submission. if (mle!!.isNewFlight()) mle!!.szFlightData = getMainLocation()!!.flightDataString // Save for later if offline or if forceQueued val fIsOnline = isOnline(context) if (forceQueued || !fIsOnline) { // save the flight with id of -2 if it's a new flight if (fIsNew) mle!!.idFlight = if (forceQueued) LogbookEntry.ID_QUEUED_FLIGHT_UNSUBMITTED else LogbookEntry.ID_UNSUBMITTED_FLIGHT // Existing flights can't be saved for later. No good reason for that except work. if (mle!!.isExistingFlight()) { AlertDialog.Builder(requireActivity(), R.style.MFBDialog) .setMessage(getString(R.string.errNoInternetNoSave)) .setTitle(getString(R.string.txtError)) .setNegativeButton(getString(R.string.lblOK)) { d: DialogInterface, _: Int -> d.cancel() finish() } .create().show() return } // now save it - but check for success if (!mle!!.toDB()) { // Failure! // Try saving it without the flight data string, in case that was the issue mle!!.szFlightData = "" if (!mle!!.toDB()) { // still didn't work. give an error message and, if necessary, // restore to being a new flight. alert(this, getString(R.string.txtError), mle!!.szError) // restore the previous idFlight if we were saving a new flight. if (fIsNew) { mle!!.idFlight = LogbookEntry.ID_NEW_FLIGHT saveCurrentFlight() } return } // if we're here, then phew - saved without the string } // if we're here, save was successful (even if flight data was dropped) clearCachedFlights() MFBMain.invalidateCachedTotals() if (fIsNew) { resetFlight(true) alert(this, getString(R.string.txtSuccess), getString(R.string.txtFlightQueued)) } else { AlertDialog.Builder(requireActivity(), R.style.MFBDialog) .setMessage(getString(R.string.txtFlightQueued)) .setTitle(getString(R.string.txtSuccess)) .setNegativeButton("OK") { d: DialogInterface, _: Int -> d.cancel() finish() } .create().show() } } else { val le = mle submitFlight(le) } } private fun setVisibilityForRow(rowID: Int, visible : Boolean) { val v = findViewById(rowID) v!!.visibility = if (visible) View.VISIBLE else View.GONE } override fun toView() { if (view == null) return setStringForField(R.id.txtComments, mle!!.szComments) setStringForField(R.id.txtRoute, mle!!.szRoute) setIntForField(R.id.txtApproaches, mle!!.cApproaches) setIntForField(R.id.txtLandings, mle!!.cLandings) setIntForField(R.id.txtFSNightLandings, mle!!.cNightLandings) setIntForField(R.id.txtDayLandings, mle!!.cFullStopLandings) setCheckState(R.id.ckMyFlightbook, mle!!.fPublic) setCheckState(R.id.ckHold, mle!!.fHold) setLocalDateForField(R.id.btnFlightSet, mle!!.dtFlight) // Engine/Flight dates val tachStart = mle!!.propDoubleForID(CustomPropertyType.idPropTypeTachStart) val tachEnd = mle!!.propDoubleForID(CustomPropertyType.idPropTypeTachEnd) val blockOut = mle!!.propDateForID(CustomPropertyType.idPropTypeBlockOut) val blockIn = mle!!.propDateForID(CustomPropertyType.idPropTypeBlockIn) setUTCDateForField(R.id.btnEngineStartSet, mle!!.dtEngineStart) setUTCDateForField(R.id.btnEngineEndSet, mle!!.dtEngineEnd) setUTCDateForField(R.id.btnFlightStartSet, mle!!.dtFlightStart) setUTCDateForField(R.id.btnFlightEndSet, mle!!.dtFlightEnd) setDoubleForField(R.id.txtHobbsStart, mle!!.hobbsStart) setDoubleForField(R.id.txtHobbsEnd, mle!!.hobbsEnd) setDoubleForField(R.id.txtTachStart, tachStart) setDoubleForField(R.id.txtTachEnd, tachEnd) setUTCDateForField(R.id.btnBlockOut, blockOut) setUTCDateForField(R.id.btnBlockIn, blockIn) // show tach/block in "In the cockpit" only if the options are selected (will otherwise show in properties)... val showTach = fShowTach val showBlock = fShowBlock //...but hobbs/engine/flight must be shown if they have values, since they won't show anywhere else. val showHobbs = fShowHobbs || mle!!.hobbsStart > 0 || mle!!.hobbsEnd > 0 val showEngine = fShowEngine || mle!!.isKnownEngineStart || mle!!.isKnownEngineEnd val showFlight = fShowFlight || mle!!.isKnownFlightStart || mle!!.isKnownFlightEnd setVisibilityForRow(R.id.rowTachStart, showTach) setVisibilityForRow(R.id.rowTachEnd, showTach) setVisibilityForRow(R.id.rowHobbsStart, showHobbs) setVisibilityForRow(R.id.rowHobbsEnd, showHobbs) setVisibilityForRow(R.id.rowEngineStart, showEngine) setVisibilityForRow(R.id.rowEngineEnd, showEngine) setVisibilityForRow(R.id.rowBlockOut, showBlock) setVisibilityForRow(R.id.rowBlockIn, showBlock) setVisibilityForRow(R.id.rowFlightStart, showFlight) setVisibilityForRow(R.id.rowFlightEnd, showFlight) setDoubleForField(R.id.txtCFI, mle!!.decCFI) setDoubleForField(R.id.txtDual, mle!!.decDual) setDoubleForField(R.id.txtGround, mle!!.decGrndSim) setDoubleForField(R.id.txtIMC, mle!!.decIMC) setDoubleForField(R.id.txtNight, mle!!.decNight) setDoubleForField(R.id.txtPIC, mle!!.decPIC) setDoubleForField(R.id.txtSIC, mle!!.decSIC) setDoubleForField(R.id.txtSimIMC, mle!!.decSimulatedIFR) setDoubleForField(R.id.txtTotal, mle!!.decTotal) setDoubleForField(R.id.txtXC, mle!!.decXC) val fIsSigned = mle!!.signatureStatus !== SigStatus.None findViewById(R.id.sectSignature)!!.visibility = if (fIsSigned) View.VISIBLE else View.GONE findViewById(R.id.txtSignatureHeader)!!.visibility = if (fIsSigned) View.VISIBLE else View.GONE if (fIsSigned) { val imgSigStatus = findViewById(R.id.imgSigState) as ImageView? when (mle!!.signatureStatus) { SigStatus.None -> {} SigStatus.Valid -> { imgSigStatus!!.setImageResource(R.drawable.sigok) imgSigStatus.contentDescription = getString(R.string.cdIsSignedValid) (findViewById(R.id.txtSigState) as TextView?)!!.text = getString(R.string.cdIsSignedValid) } SigStatus.Invalid -> { imgSigStatus!!.setImageResource(R.drawable.siginvalid) imgSigStatus.contentDescription = getString(R.string.cdIsSignedInvalid) (findViewById(R.id.txtSigState) as TextView?)!!.text = getString(R.string.cdIsSignedInvalid) } } val szSigInfo1 = if (isNullDate(mle!!.signatureDate)) "" else String.format( Locale.getDefault(), getString(R.string.lblSignatureTemplate1), DateFormat.getDateFormat(requireActivity()).format(mle!!.signatureDate!!), mle!!.signatureCFIName ) val szSigInfo2 = if (isNullDate(mle!!.signatureCFIExpiration)) String.format( Locale.getDefault(), getString(R.string.lblSignatureTemplate2NoExp), mle!!.signatureCFICert ) else String.format( Locale.getDefault(), getString(R.string.lblSignatureTemplate2), mle!!.signatureCFICert, DateFormat.getDateFormat(requireActivity()).format( mle!!.signatureCFIExpiration!! ) ) (findViewById(R.id.txtSigInfo1) as TextView?)!!.text = szSigInfo1 (findViewById(R.id.txtSigInfo2) as TextView?)!!.text = szSigInfo2 (findViewById(R.id.txtSigComment) as TextView?)!!.text = mle!!.signatureComments val ivDigitizedSig = findViewById(R.id.imgDigitizedSig) as ImageView? if (mle!!.signatureHasDigitizedSig) { if (ivDigitizedSig!!.drawable == null) { val szURL = String.format( Locale.US, "https://%s/Logbook/Public/ViewSig.aspx?id=%d", MFBConstants.szIP, mle!!.idFlight ) fetchDigitizedSig(szURL, ivDigitizedSig) } } else ivDigitizedSig!!.visibility = View.GONE } // Aircraft spinner val rgSelectibleAircraft = selectibleAircraft() if (rgSelectibleAircraft != null) { val sp = findViewById(R.id.spnAircraft) as Spinner? // Pick the first selectible aircraft, if no aircraft is selected if (mle!!.idAircraft == -1 && rgSelectibleAircraft.isNotEmpty()) mle!!.idAircraft = rgSelectibleAircraft[0].aircraftID // Issue #188 set the spinner, but ONLY if it's not currently set to the correct tail. val ac = sp!!.selectedItem as Aircraft? if (ac == null || ac.aircraftID != mle!!.idAircraft) { for (i in rgSelectibleAircraft.indices) { if (mle!!.idAircraft == rgSelectibleAircraft[i].aircraftID) { sp.setSelection(i) sp.prompt = "Current Aircraft: " + rgSelectibleAircraft[i].tailNumber break } } } } // Current properties if (!mle!!.isExistingFlight() && mle!!.rgCustomProperties.isEmpty()) mle!!.syncProperties() setUpPropertiesForFlight() updateElapsedTime() updatePausePlayButtonState() } override fun fromView() { if (view == null || mle == null) return // Integer fields mle!!.cApproaches = intFromField(R.id.txtApproaches) mle!!.cFullStopLandings = intFromField(R.id.txtDayLandings) mle!!.cLandings = intFromField(R.id.txtLandings) mle!!.cNightLandings = intFromField(R.id.txtFSNightLandings) // Double fields mle!!.decCFI = doubleFromField(R.id.txtCFI) mle!!.decDual = doubleFromField(R.id.txtDual) mle!!.decGrndSim = doubleFromField(R.id.txtGround) mle!!.decIMC = doubleFromField(R.id.txtIMC) mle!!.decNight = doubleFromField(R.id.txtNight) mle!!.decPIC = doubleFromField(R.id.txtPIC) mle!!.decSIC = doubleFromField(R.id.txtSIC) mle!!.decSimulatedIFR = doubleFromField(R.id.txtSimIMC) mle!!.decTotal = doubleFromField(R.id.txtTotal) mle!!.decXC = doubleFromField(R.id.txtXC) mle!!.hobbsStart = doubleFromField(R.id.txtHobbsStart) mle!!.hobbsEnd = doubleFromField(R.id.txtHobbsEnd) // Date - no-op because it should be in sync // Flight/Engine times - ditto // But tach, if shown, isn't coming from props, so load it here. if (fShowTach) { handlePotentiallyDefaultedProperty(mle!!.addOrSetPropertyDouble(CustomPropertyType.idPropTypeTachStart, doubleFromField(R.id.txtTachStart))) handlePotentiallyDefaultedProperty(mle!!.addOrSetPropertyDouble(CustomPropertyType.idPropTypeTachEnd, doubleFromField(R.id.txtTachEnd))) } // checkboxes mle!!.fHold = checkState(R.id.ckHold) mle!!.fPublic = checkState(R.id.ckMyFlightbook) // And strings mle!!.szComments = stringFromField(R.id.txtComments) mle!!.szRoute = stringFromField(R.id.txtRoute) // Aircraft spinner mle!!.idAircraft = selectedAircraftID() } private fun selectedAircraftID(): Int { val rgSelectibleAircraft = selectibleAircraft() if (rgSelectibleAircraft != null && rgSelectibleAircraft.isNotEmpty()) { val sp = findViewById(R.id.spnAircraft) as Spinner? val ac = sp!!.selectedItem as Aircraft return ac.aircraftID } return -1 } private fun doAutoTotals() { fromView() val sp = findViewById(R.id.spnAircraft) as Spinner? if (mle!!.autoFillTotal( if (mle!!.idAircraft > 0 && sp!!.selectedItem != null) sp.selectedItem as Aircraft else null, totalTimePaused() ) > 0 ) toView() } private fun doAutoHobbs() { fromView() if (mle!!.autoFillHobbs(totalTimePaused()) > 0) { toView() // sync the view to the change we just made - especially since autototals can read it. // if total is linked to hobbs, need to do autotime too if (MFBLocation.fPrefAutoFillTime === AutoFillOptions.HobbsTime) doAutoTotals() } } private fun resetDateOfFlight() { if (mle != null && mle!!.isNewFlight()) { // set the date of the flight to now in local time. var dt = Date() if (mle!!.isKnownEngineStart && mle!!.dtEngineStart < dt) dt = mle!!.dtEngineStart if (mle!!.isKnownFlightStart && mle!!.dtFlightStart < dt) dt = mle!!.dtFlightStart val dtBlockOut = mle!!.propDateForID(CustomPropertyType.idPropTypeBlockOut) if (dtBlockOut != null && !isNullDate(dtBlockOut) && dtBlockOut < dt) dt = dtBlockOut mle!!.dtFlight = dt setLocalDateForField(R.id.btnFlightSet, mle!!.dtFlight) } } private fun engineStart() { // don't do any GPS stuff unless this is a new flight if (!mle!!.isNewFlight()) return resetDateOfFlight() if (MFBLocation.fPrefAutoDetect) appendNearest() getMainLocation()?.isRecording = true // will respect preference showRecordingIndicator() if (MFBConstants.fFakeGPS) { getMainLocation()!!.stopListening(requireContext()) getMainLocation()?.isRecording = true // will respect preference val gpss = GPSSim(getMainLocation()!!) gpss.feedEvents() } } private fun engineStop() { // don't do any GPS stuff unless this is a new flight if (!mle!!.isNewFlight()) return if (MFBLocation.fPrefAutoDetect) appendNearest() getMainLocation()?.isRecording = false doAutoHobbs() doAutoTotals() showRecordingIndicator() unPauseFlight() } private fun flightStart() { // don't do any GPS stuff unless this is a new flight if (!mle!!.isNewFlight()) return if (!mle!!.isKnownEngineStart) resetDateOfFlight() getMainLocation()?.isRecording = true if (MFBLocation.fPrefAutoDetect) appendNearest() unPauseFlight() // don't pause in flight } private fun flightStop() { // don't do any GPS stuff unless this is a new flight if (!mle!!.isNewFlight()) return if (MFBLocation.fPrefAutoDetect) appendNearest() } private fun showRecordingIndicator() { imgRecording!!.visibility = if (getMainLocation() != null && getMainLocation()?.isRecording!!) View.VISIBLE else View.INVISIBLE } private var dfSunriseSunset: SimpleDateFormat? = null private fun displaySpeed(s: Double): String { val res = resources return if (s < 1) res.getString(R.string.strEmpty) else when (ActOptions.speedUnits) { SpeedUnits.Knots -> String.format( Locale.getDefault(), res.getString(R.string.lblSpeedFormatKts), s * MFBConstants.MPS_TO_KNOTS ) SpeedUnits.KmPerHour -> String.format( Locale.getDefault(), res.getString(R.string.lblSpeedFormatKph), s * MFBConstants.MPS_TO_KPH ) SpeedUnits.MilesPerHour -> String.format( Locale.getDefault(), res.getString(R.string.lblSpeedFormatMph), s * MFBConstants.MPS_TO_MPH ) } } private fun displayAlt(a: Double): String { val res = resources return when (ActOptions.altitudeUnits) { AltitudeUnits.Feet -> String.format( Locale.getDefault(), res.getString(R.string.lblAltFormatFt), (a * MFBConstants.METERS_TO_FEET).roundToInt() ) AltitudeUnits.Meters -> String.format( Locale.getDefault(), res.getString(R.string.lblAltFormatMeters), a.roundToInt() ) } } override fun updateStatus( quality: GPSQuality, fAirborne: Boolean?, loc: Location?, fRecording: Boolean? ) { if (!isAdded || isDetached) { return } else { requireActivity() } showRecordingIndicator() val res = resources val idSzQuality: Int = when (quality) { GPSQuality.Excellent -> R.string.lblGPSExcellent GPSQuality.Good -> R.string.lblGPSGood GPSQuality.Poor -> R.string.lblGPSPoor else -> R.string.lblGPSUnknown } if (loc != null) { txtQuality!!.text = res.getString(idSzQuality) txtSpeed!!.text = displaySpeed(loc.speed.toDouble()) txtAltitude!!.text = displayAlt(loc.altitude) val lat = loc.latitude val lon = loc.longitude txtLatitude!!.text = String.format( Locale.getDefault(), "%.5f°%s", abs(lat), if (lat > 0) "N" else "S" ) txtLongitude!!.text = String.format( Locale.getDefault(), "%.5f°%s", abs(lon), if (lon > 0) "E" else "W" ) val sst = SunriseSunsetTimes(Date(loc.time), lat, lon) if (dfSunriseSunset == null) dfSunriseSunset = SimpleDateFormat("hh:mm a z", Locale.getDefault()) txtSunrise!!.text = dfSunriseSunset!!.format(sst.sunrise) txtSunset!!.text = dfSunriseSunset!!.format(sst.sunset) } // don't show in-air/on-ground if we aren't actually detecting these if (MFBLocation.fPrefAutoDetect) txtStatus!!.text = res.getString(if (fAirborne!!) R.string.lblFlightInAir else R.string.lblFlightOnGround) else txtStatus!!.text = res.getString(R.string.lblGPSUnknown) if (fAirborne!!) unPauseFlight() } // Pause/play functionality private fun timeSinceLastPaused(): Long { return if (fPaused) Date().time - dtTimeOfLastPause else 0 } private fun totalTimePaused(): Long { return dtPauseTime + timeSinceLastPaused() } private fun pauseFlight() { dtTimeOfLastPause = Date().time fPaused = true } override fun unPauseFlight() { if (fPaused) { dtPauseTime += timeSinceLastPaused() fPaused = false // do this AFTER calling [self timeSinceLastPaused] } } override fun isPaused(): Boolean { return fPaused } override fun togglePausePlay() { if (fPaused) unPauseFlight() else pauseFlight() updatePausePlayButtonState() } override fun startEngine() { if (mle != null && !mle!!.isKnownEngineStart) { mle!!.dtEngineStart = nowWith0Seconds() engineStart() toView() } } override fun stopEngine() { if (mle != null && !mle!!.isKnownEngineEnd) { mle!!.dtEngineEnd = nowWith0Seconds() engineStop() toView() } } private fun updateElapsedTime() { // update the button state val ib = findViewById(R.id.btnPausePlay) as ImageButton? // pause/play should only be visible on ground with engine running (or flight start known but engine end unknown) if (mle == null) // should never happen! return val fShowPausePlay = !MFBLocation.IsFlying && (mle!!.isKnownEngineStart || mle!!.isKnownFlightStart) && !mle!!.isKnownEngineEnd ib!!.visibility = if (fShowPausePlay) View.VISIBLE else View.INVISIBLE val txtElapsed = findViewById(R.id.txtElapsedTime) as TextView? if (txtElapsed != null) { var dtTotal: Long var dtFlight: Long = 0 var dtEngine: Long = 0 val fIsKnownFlightStart = mle!!.isKnownFlightStart val fIsKnownEngineStart = mle!!.isKnownEngineStart if (fIsKnownFlightStart) { dtFlight = if (!mle!!.isKnownFlightEnd) // in flight Date().time - mle!!.dtFlightStart.time else mle!!.dtFlightEnd.time - mle!!.dtFlightStart.time } if (fIsKnownEngineStart) { dtEngine = if (!mle!!.isKnownEngineEnd) Date().time - mle!!.dtEngineStart.time else mle!!.dtEngineEnd.time - mle!!.dtEngineStart.time } // if totals mode is FLIGHT TIME, then elapsed time is based on flight time if/when it is known. // OTHERWISE, we use engine time (if known) or else flight time. dtTotal = if (MFBLocation.fPrefAutoFillTime === AutoFillOptions.FlightTime) if (fIsKnownFlightStart) dtFlight else 0 else if (fIsKnownEngineStart) dtEngine else dtFlight dtTotal -= totalTimePaused() if (dtTotal <= 0) dtTotal = 0 // should never happen // dtTotal is in milliseconds - convert it to seconds for ease of reading dtTotal = (dtTotal / 1000.0).toLong() val sTime = String.format( Locale.US, "%02d:%02d:%02d", (dtTotal / 3600).toInt(), dtTotal.toInt() % 3600 / 60, dtTotal.toInt() % 60 ) txtElapsed.text = sTime } showRecordingIndicator() } private fun updatePausePlayButtonState() { // update the button state val ib = findViewById(R.id.btnPausePlay) as ImageButton? ib!!.setImageResource(if (fPaused) R.drawable.play else R.drawable.pause) } private fun toggleFlightPause() { // don't pause or play if we're not flying/engine started if (mle!!.isKnownFlightStart || mle!!.isKnownEngineStart) { if (fPaused) unPauseFlight() else pauseFlight() } else { unPauseFlight() dtPauseTime = 0 } updateElapsedTime() updatePausePlayButtonState() } /* * (non-Javadoc) * @see com.myflightbook.android.ActMFBForm.GallerySource#getGalleryID() * GallerySource protocol */ override fun getGalleryID(): Int { return R.id.tblImageTable } override fun getGalleryHeader(): View { return findViewById(R.id.txtImageHeader)!! } override fun getImages(): Array<MFBImageInfo> { return if (mle == null || mle!!.rgFlightImages == null) arrayOf() else mle!!.rgFlightImages!! } override fun setImages(rgmfbii: Array<MFBImageInfo>?) { if (mle == null) { throw NullPointerException("m_le is null in setImages") } mle!!.rgFlightImages = rgmfbii } override fun newImage(mfbii: MFBImageInfo?) { Log.w( MFBConstants.LOG_TAG, String.format("newImage called. m_le is %s", if (mle == null) "null" else "not null") ) mle!!.addImageForflight(mfbii!!) } override fun refreshGallery() { setUpGalleryForFlight() } override fun getPictureDestination(): PictureDestination { return PictureDestination.FlightImage } override fun invalidate() { resetFlight(false) } private fun updateIfChanged(id: Int, value: Int) { if (intFromField(id) != value) setIntForField(id, value) } // Update the fields which could possibly have changed via auto-detect override fun refreshDetectedFields() { setUTCDateForField(R.id.btnFlightStartSet, mle!!.dtFlightStart) setUTCDateForField(R.id.btnFlightEndSet, mle!!.dtFlightEnd) updateIfChanged(R.id.txtLandings, mle!!.cLandings) updateIfChanged(R.id.txtFSNightLandings, mle!!.cNightLandings) updateIfChanged(R.id.txtDayLandings, mle!!.cFullStopLandings) setDoubleForField(R.id.txtNight, mle!!.decNight) setStringForField(R.id.txtRoute, mle!!.szRoute) } private fun setUpPropertiesForFlight() { val a: Activity = requireActivity() val l = a.layoutInflater val tl = findViewById(R.id.tblPinnedProperties) as TableLayout? ?: return tl.removeAllViews() if (mle == null) return // Handle block Out having been specified by viewprops var fHadBlockOut = false for (fp in mle!!.rgCustomProperties) if (fp.idPropType == CustomPropertyType.idPropTypeBlockOut) { fHadBlockOut = true break } mle!!.syncProperties() val pinnedProps = getPinnedProperties( requireActivity().getSharedPreferences( CustomPropertyType.prefSharedPinnedProps, Activity.MODE_PRIVATE ) ) val templateProps = mergeTemplates( mActivetemplates!!.toTypedArray() ) val rgcptAll = cachedPropertyTypes Arrays.sort(rgcptAll) val rgProps = crossProduct(mle!!.rgCustomProperties, rgcptAll) var fHasBlockOutAdded = false for (fp in rgProps) { // should never happen, but does - not sure why if (fp.getCustomPropertyType() == null) fp.refreshPropType() if (fp.idPropType == CustomPropertyType.idPropTypeBlockOut && !fp.isDefaultValue()) fHasBlockOutAdded = true // Don't show any properties that are: // a) unpinned and default value, or // b) "hoisted" into the "in the cockpit" section val fIsPinned = isPinnedProperty(pinnedProps, fp.idPropType) if (!fIsPinned && !templateProps.contains(fp.idPropType) && fp.isDefaultValue()) continue if (fShowTach && (fp.idPropType == CustomPropertyType.idPropTypeTachStart || fp.idPropType == CustomPropertyType.idPropTypeTachEnd)) continue if (fShowBlock && (fp.idPropType == CustomPropertyType.idPropTypeBlockOut || fp.idPropType == CustomPropertyType.idPropTypeBlockIn)) continue val tr = l.inflate(R.layout.cpttableitem, tl, false) as TableRow tr.id = View.generateViewId() val pe: PropertyEdit = tr.findViewById(R.id.propEdit) val onCrossFill = object : CrossFillDelegate { override fun crossFillRequested(sender: DecimalEdit?) { val d = getHighWaterTachForAircraft(selectedAircraftID()) if (d > 0 && sender != null) sender.doubleValue = d } } pe.initForProperty( fp, tr.id, this, if (fp.getCustomPropertyType()!!.idPropType == CustomPropertyType.idPropTypeTachStart) onCrossFill else this) tr.findViewById<View>(R.id.imgFavorite).visibility = if (fIsPinned) View.VISIBLE else View.INVISIBLE tl.addView( tr, TableLayout.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT ) ) } if (!fHadBlockOut && fHasBlockOutAdded) resetDateOfFlight() } //region in-line property editing private fun deleteProperty(fp : FlightProperty) { lifecycleScope.launch { doAsync<FlightPropertiesSvc, Any?>( requireActivity(), FlightPropertiesSvc(), getString(R.string.prgDeleteProp), { s -> s.deletePropertyForFlight(AuthToken.m_szAuthToken, fp.idFlight, fp.idProp,requireContext()) }, { _, _ -> setUpPropertiesForFlight() } ) } } private fun deleteDefaultedProperty(fp: FlightProperty) { if (fp.idProp > 0 && fp.isDefaultValue()) { deleteProperty(fp) return } // Otherwise, save it val rgProps = crossProduct(mle!!.rgCustomProperties, cachedPropertyTypes) val rgfpUpdated = distillList(rgProps) rewritePropertiesForFlight(mle!!.idLocalDB, rgfpUpdated) } private fun handlePotentiallyDefaultedProperty(fp : FlightProperty?) { if (mle!!.idFlight > 0 && fp != null && fp.idProp > 0 && fp.isDefaultValue()) { fp.idFlight = mle!!.idFlight // this is pointing to the LOCAL db ID of the flight, so we need to point it instead to the server-based flight id2 deleteProperty(fp) } } override fun updateProperty(id: Int, fp: FlightProperty) { if (mle == null) { // this can get called by PropertyEdit as it loses focus. return } val rgProps = crossProduct(mle!!.rgCustomProperties, cachedPropertyTypes) for (i in rgProps.indices) { if (rgProps[i].idPropType == fp.idPropType) { rgProps[i] = fp deleteDefaultedProperty(fp) rewritePropertiesForFlight(mle!!.idLocalDB, distillList(rgProps)) mle!!.syncProperties() break } } if (MFBLocation.fPrefAutoFillTime === AutoFillOptions.BlockTime && (fp.idPropType == CustomPropertyType.idPropTypeBlockOut || fp.idPropType == CustomPropertyType.idPropTypeBlockIn) ) doAutoTotals() } override fun dateOfFlightShouldReset(dt: Date) { resetDateOfFlight() } //endregion // region Templates private fun updateTemplatesForAircraft(noDefault: Boolean) { val a = activity ?: return // this can be called via invalidate, which can be called before everything is set up, so check for null if (PropertyTemplate.sharedTemplates == null && getSharedTemplates( a.getSharedPreferences( PropertyTemplate.PREF_KEY_TEMPLATES, Activity.MODE_PRIVATE ) ) == null ) return val rgDefault = defaultTemplates val ptAnon = anonTemplate val ptSim = simTemplate val ac = getAircraftById(mle!!.idAircraft, mRgac) if (ac != null && ac.defaultTemplates.size > 0) mActivetemplates!!.addAll( listOf( *templatesWithIDs( ac.defaultTemplates ) ) ) else if (rgDefault.isNotEmpty() && !noDefault) mActivetemplates!!.addAll( listOf(*rgDefault) ) mActivetemplates!!.remove(ptAnon) mActivetemplates!!.remove(ptSim) // Always add in sims or anon as appropriate if (ac != null) { if (ac.isAnonymous() && ptAnon != null) mActivetemplates!!.add(ptAnon) if (!ac.isReal() && ptSim != null) mActivetemplates!!.add(ptSim) } } // endregion companion object { const val PROPSFORFLIGHTID = "com.myflightbook.android.FlightPropsID" const val PROPSFORFLIGHTEXISTINGID = "com.myflightbook.android.FlightPropsIDExisting" const val PROPSFORFLIGHTCROSSFILLVALUE = "com.myflightbook.android.FlightPropsXFill" const val TACHFORCROSSFILLVALUE = "com.myflightbook.android.TachStartXFill" // current state of pause/play and accumulated night var fPaused = false private var dtPauseTime: Long = 0 private var dtTimeOfLastPause: Long = 0 var accumulatedNight = 0.0 // pause/play state private const val m_KeysIsPaused = "flightIsPaused" private const val m_KeysPausedTime = "totalPauseTime" private const val m_KeysTimeOfLastPause = "timeOfLastPause" private const val m_KeysAccumulatedNight = "accumulatedNight" // Expand state of "in the cockpit" private const val m_KeyShowInCockpit = "inTheCockpit" // Display options var fShowTach = false var fShowHobbs = true var fShowEngine = true var fShowBlock = false var fShowFlight = true const val prefKeyShowTach = "cockpitShowTach" const val prefKeyShowHobbs = "cockpitShowHobbs" const val prefKeyShowEngine = "cockpitShowEngine" const val prefKeyShowBlock = "cockpitShowBlock" const val prefKeyShowFlight = "cockpitShowFlight" } }
gpl-3.0
482388b9114f0ee8036c6b2a4fc912d4
41.064922
279
0.591204
4.492448
false
false
false
false
stokito/IdeaSingletonInspection
src/main/java/com/github/stokito/IdeaSingletonInspection/quickFixes/QuickFixes.kt
1
377
package com.github.stokito.IdeaSingletonInspection.quickFixes object QuickFixes { val INSTANCE_GETTERS_MODIFIERS = InstanceGettersModifiersFix() val INSTANCE_GETTERS_RETURN_TYPE = InstanceGettersReturnTypeFix() val CONSTRUCTOR_MODIFIERS = ConstructorModifiersFix() val CREATE_CONSTRUCTOR = CreateConstructorFix() val SET_CLASS_FINAL = SetClassFinalFix() }
apache-2.0
b61509790fcf4cb81c5757362597bc04
40.888889
69
0.795756
4.597561
false
false
false
false
YaroslavHavrylovych/android_playground
ex_sqlite/app/src/main/kotlin/ex/android/yaroslavlancelot/com/sql/activeandroid/Contact.kt
1
936
package ex.android.yaroslavlancelot.com.sql.activeandroid import com.activeandroid.Model import com.activeandroid.annotation.Column import com.activeandroid.annotation.Table import ex.android.yaroslavlancelot.com.sql.DBConstants /** * Represent row in the database. * * @author Yaroslav Havrylovych */ @Table(name = DBConstants.TABLE_NAME, id = DBConstants.COLUMN_NAME_ID) class Contact : Model { @Column(notNull = true, name = DBConstants.COLUMN_NAME_NAME) var name: String? = null @Column(notNull = true, name = DBConstants.COLUMN_NAME_SURNAME) var surname: String? = null @Column(notNull = true, name = DBConstants.COLUMN_NAME_PHONE_NUMBER) var phoneNumber: String? = null constructor() { //just for Ormlite } constructor(name: String, surname: String, phoneNumber: String) { this.name = name this.surname = surname this.phoneNumber = phoneNumber } }
apache-2.0
581917221bee604e0177ffc95972e6d4
27.363636
72
0.708333
3.685039
false
false
false
false
RyanAndroidTaylor/Rapido
rapidosqlite/src/main/java/com/izeni/rapidosqlite/DataConnection.kt
1
8583
package com.izeni.rapidosqlite import android.annotation.SuppressLint import android.database.Cursor import android.database.sqlite.SQLiteConstraintException import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteException import android.database.sqlite.SQLiteOpenHelper import android.util.Log import com.izeni.rapidosqlite.item_builder.ItemBuilder import com.izeni.rapidosqlite.query.Query import com.izeni.rapidosqlite.query.RawQuery import com.izeni.rapidosqlite.table.DataTable import com.izeni.rapidosqlite.table.ParentDataTable import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.Single import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject import java.util.* import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicInteger /** * Created by ryantaylor on 9/22/16. */ class DataConnection private constructor(val database: SQLiteDatabase) { companion object { private val connectionCount = AtomicInteger() private val databaseExecutor = Executors.newSingleThreadExecutor() private val databaseSubject: PublishSubject<DataAction<*>> by lazy { PublishSubject.create<DataAction<*>>() } private lateinit var sqliteOpenHelper: SQLiteOpenHelper fun init(databaseHelper: SQLiteOpenHelper) { this.sqliteOpenHelper = databaseHelper } @Suppress("UNCHECKED_CAST") fun <T : DataTable> watchTableSaves(tableName: String): Flowable<SaveAction<T>> { return databaseSubject.filter { it is SaveAction<*> && it.tableName == tableName } .map { it as SaveAction<T> } .toFlowable(BackpressureStrategy.BUFFER) } @Suppress("UNCHECKED_CAST") fun <T : DataTable> watchTableUpdates(tableName: String): Flowable<UpdateAction<T>> { return databaseSubject.filter { it is UpdateAction<*> && it.tableName == tableName } .map { it as UpdateAction<T> } .toFlowable(BackpressureStrategy.BUFFER) } @Suppress("UNCHECKED_CAST") fun <T : DataTable> watchTableDeletes(tableName: String): Flowable<DeleteAction<T>> { return databaseSubject.filter { it is DeleteAction<*> && it.tableName == tableName } .map { it as DeleteAction<T> } .toFlowable(BackpressureStrategy.BUFFER) } fun <T> asyncGetAndClose(block: (DataConnection) -> T): Single<T> { Log.i("DataConnection", "Called on thread: ${Thread.currentThread().name}") return Single.just(Unit) .subscribeOn(Schedulers.from(databaseExecutor)) .map { Log.i("DataConnection", "Executed on thread: ${Thread.currentThread().name}") val connection = openConnection() val items = block(connection) connection.close() items } } fun <T> getAndClose(block: (DataConnection) -> T): T { val connection = openConnection() val items = block(connection) connection.close() return items } fun asyncDoAndClose(block: (DataConnection) -> Unit) { Single.just(Unit) .subscribeOn(Schedulers.from(databaseExecutor)) .map { val connection = openConnection() block(connection) connection.close() }.subscribe({}, {}) } fun doAndClose(block: (DataConnection) -> Unit) { val connection = openConnection() block(connection) connection.close() } private fun openConnection(): DataConnection { connectionCount.incrementAndGet() return DataConnection(sqliteOpenHelper.writableDatabase) } } var conflictAlgorithm = SQLiteDatabase.CONFLICT_REPLACE private fun close() { if (connectionCount.decrementAndGet() < 1) database.close() } fun insert(item: DataTable) { database.transaction { insert(item, it) } } fun insertAll(items: List<DataTable>) { database.transaction { database -> items.forEach { insert(it, database) } } } private fun insert(item: DataTable, database: SQLiteDatabase) { if (item is ParentDataTable) { item.getChildren().forEach { insert(it, database) } } database.insertWithOnConflict(item.tableName(), null, item.contentValues(), conflictAlgorithm) databaseSubject.onNext(SaveAction(item.tableName(), item)) } fun upsert(item: DataTable) { database.transaction { upsert(item, it) } } fun upsertAll(items: List<DataTable>) { database.transaction { database -> items.forEach { upsert(it, database) } } } private fun upsert(item: DataTable, database: SQLiteDatabase) { if (item is ParentDataTable) { item.getChildren().forEach { upsert(it, database) } } try { database.insertOrThrow(item.tableName(), null, item.contentValues()) } catch (exception: SQLiteException) { if (exception is SQLiteConstraintException) { val rowsUpdated = database.update(item.tableName(), item.contentValues(), "${item.idColumn().name}=?", arrayOf(item.id())) if (rowsUpdated < 1) throw exception } else { throw exception } } databaseSubject.onNext(SaveAction(item.tableName(), item)) } fun update(item: DataTable) { database.transaction { val rowsUpdated = it.update(item.tableName(), item.contentValues(), "${item.idColumn().name}=?", arrayOf(item.id())) if (rowsUpdated < 1) Log.d("DataConnection", "Failed to update any rows while updating item: \n$item") } } /** * Delete all items from the database */ fun deleteAll(items: List<DataTable>) { database.transaction { database -> items.forEach { delete(it, database) } } } /** * Deletes the item fro the database */ fun delete(item: DataTable) { database.transaction { delete(item, it) } } private fun delete(item: DataTable, database: SQLiteDatabase) { database.delete(item.tableName(), "${item.idColumn().name}=?", arrayOf(item.id())) databaseSubject.onNext(DeleteAction(item.tableName(), item)) } /** * Clears all data in the database for this table * WARNING!!! Data watchers will not be notified when using this method */ fun clear(tableName: String) { database.transaction { it.delete(tableName, null, null) } } fun <T> findFirst(builder: ItemBuilder<T>, query: Query): T? { var cursor: Cursor? = null var item: T? = null database.transaction { cursor = getCursor(database, query).also { if (it.moveToFirst()) item = builder.buildItem(it, this) } } cursor?.close() return item } fun <T> findAll(builder: ItemBuilder<T>, query: Query): List<T> { var cursor: Cursor? = null val items = ArrayList<T>() database.transaction { cursor = getCursor(database, query).also { while (it.moveToNext()) items.add(builder.buildItem(it, this)) } } cursor?.close() return items } // Cursor should be closed in the block that calls this method @SuppressLint("Recycle") private fun getCursor(database: SQLiteDatabase, query: Query): Cursor { if (query is RawQuery) { return database.rawQuery(query.query, query.selectionArgs) } else { return database.query(query.tableName, query.columns, query.selection, query.selectionArgs, query.groupBy, null, query.order, query.limit) } } abstract class DataAction<out T>(val tableName: String) class SaveAction<out T : DataTable>(tableName: String, val item: T) : DataAction<T>(tableName) class UpdateAction<out T : DataTable>(tableName: String, val item: T) : DataAction<T>(tableName) class DeleteAction<out T : DataTable>(tableName: String, val item: T) : DataAction<T>(tableName) }
mit
9761fb7dd3d3e1a4a452a3c9d2528692
32.400778
150
0.61249
4.808403
false
false
false
false
Magneticraft-Team/Magneticraft
ignore/test/tileentity/electric/connectors/ElectricPoleAdapterConnector.kt
2
1344
package tileentity.electric.connectors import com.cout970.magneticraft.api.energy.IElectricNode import com.cout970.magneticraft.api.energy.IWireConnector import com.cout970.magneticraft.api.internal.energy.ElectricNode import com.cout970.magneticraft.block.BlockElectricPoleAdapter import com.cout970.magneticraft.block.ELECTRIC_POLE_PLACE import com.cout970.magneticraft.misc.block.get import com.google.common.collect.ImmutableList import net.minecraft.util.math.Vec3d /** * Created by cout970 on 06/07/2016. */ class ElectricPoleAdapterConnector(val node: ElectricNode) : IElectricNode by node, IWireConnector { override fun getConnectors(): ImmutableList<Vec3d> { val state = world.getBlockState(pos) if (state.block != BlockElectricPoleAdapter) return ImmutableList.of() val offset = state[ELECTRIC_POLE_PLACE].offset.rotateYaw(Math.toRadians(-90.0).toFloat()) val vec = Vec3d(0.5, 1.0 - 0.0625 * 6.5, 0.5).add(offset * 0.5) return ImmutableList.of(vec) } override fun getConnectorsSize(): Int = 1 override fun equals(other: Any?): Boolean { return super.equals(other) || if (other is ElectricNode) node.equals(other) else false } override fun hashCode(): Int { return node.hashCode() } override fun toString() = node.toString() }
gpl-2.0
f9e187df0cf824325cdf295f8521c01e
35.351351
100
0.729911
3.692308
false
false
false
false
Ph1b/MaterialAudiobookPlayer
scanner/src/main/kotlin/de/ph1b/audiobook/scanner/MediaScanner.kt
1
3489
package de.ph1b.audiobook.scanner import androidx.documentfile.provider.DocumentFile import de.ph1b.audiobook.common.comparator.NaturalOrderComparator import de.ph1b.audiobook.data.Book2 import de.ph1b.audiobook.data.BookContent2 import de.ph1b.audiobook.data.Chapter2 import de.ph1b.audiobook.data.repo.BookContentRepo import de.ph1b.audiobook.data.repo.BookRepo2 import de.ph1b.audiobook.data.repo.ChapterRepo import de.ph1b.audiobook.data.toUri import java.time.Instant import javax.inject.Inject class MediaScanner @Inject constructor( private val bookContentRepo: BookContentRepo, private val chapterRepo: ChapterRepo, private val mediaAnalyzer: MediaAnalyzer, private val bookRepo: BookRepo2, ) { suspend fun scan(folders: List<DocumentFile>) { val allFiles = folders.flatMap { it.listFiles().toList() } bookRepo.setAllInactiveExcept(allFiles.map { Book2.Id(it.uri) }) allFiles.forEach { scan(it) } } private suspend fun scan(file: DocumentFile) { val fileName = file.name ?: return val chapters = file.parseChapters() if (chapters.isEmpty()) return val chapterIds = chapters.map { it.id } val id = Book2.Id(file.uri) val content = bookContentRepo.getOrPut(id) { val content = BookContent2( id = id, isActive = true, addedAt = Instant.now(), author = mediaAnalyzer.analyze(chapterIds.first().toUri())?.author, lastPlayedAt = Instant.EPOCH, name = fileName, playbackSpeed = 1F, skipSilence = false, chapters = chapterIds, positionInChapter = 0L, currentChapter = chapters.first().id, cover = null ) validateIntegrity(content, chapters) content } val currentChapterGone = content.currentChapter !in chapterIds val currentChapter = if (currentChapterGone) chapterIds.first() else content.currentChapter val positionInChapter = if (currentChapterGone) 0 else content.positionInChapter val updated = content.copy( chapters = chapterIds, currentChapter = currentChapter, positionInChapter = positionInChapter, isActive = true, ) if (content != updated) { validateIntegrity(updated, chapters) bookContentRepo.put(updated) } } private fun validateIntegrity(content: BookContent2, chapters: List<Chapter2>) { // the init block performs integrity validation Book2(content, chapters) } private suspend fun DocumentFile.parseChapters(): List<Chapter2> { val result = mutableListOf<Chapter2>() parseChapters(file = this, result = result) return result } private suspend fun parseChapters(file: DocumentFile, result: MutableList<Chapter2>) { if (file.isFile && file.type?.startsWith("audio/") == true) { val id = Chapter2.Id(file.uri) val chapter = chapterRepo.getOrPut(id, Instant.ofEpochMilli(file.lastModified())) { val metaData = mediaAnalyzer.analyze(file.uri) ?: return@getOrPut null Chapter2( id = id, duration = metaData.duration, fileLastModified = Instant.ofEpochMilli(file.lastModified()), name = metaData.chapterName, markData = metaData.chapters ) } if (chapter != null) { result.add(chapter) } } else if (file.isDirectory) { file.listFiles().sortedWith(NaturalOrderComparator.documentFileComparator) .forEach { parseChapters(it, result) } } } }
lgpl-3.0
992ffb54c02e554f70c3c644e5a6359a
32.228571
95
0.689596
4.239368
false
false
false
false
square/leakcanary
leakcanary-android-instrumentation/src/main/java/leakcanary/TestDescriptionHolder.kt
2
1887
package leakcanary import leakcanary.TestDescriptionHolder.testDescription import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement import shark.SharkLog /** * A [TestRule] that holds onto the test [Description] in a thread local while evaluating, making * it possible to retrieve that test [Description] from the test thread via [testDescription]. * * This rule is automatically applied by [DetectLeaksAfterTestSuccess]. */ object TestDescriptionHolder : TestRule { private val descriptionThreadLocal = ThreadLocal<Description>() fun isEvaluating() = descriptionThreadLocal.get() != null val testDescription: Description get() { return descriptionThreadLocal.get() ?: error( "Test description is null, either you forgot to add the TestDescriptionHolder rule around" + "the current code or you did not call testDescription from the test thread." ) } override fun apply(base: Statement, description: Description): Statement { return wrap(base, description) } fun wrap(base: Statement, description: Description) = object : Statement() { override fun evaluate() { val previousDescription = descriptionThreadLocal.get() val descriptionNotAlreadySet = previousDescription == null if (descriptionNotAlreadySet) { descriptionThreadLocal.set(description) } else { SharkLog.d { "Test description already set, you should remove the TestDescriptionHolder rule." } } try { base.evaluate() } finally { if (descriptionNotAlreadySet) { val currentDescription = descriptionThreadLocal.get() check(currentDescription != null) { "Test description should not be null after the rule evaluates." } descriptionThreadLocal.remove() } } } } }
apache-2.0
61429b977600dd3c9f92553d0a8b5d4e
33.309091
104
0.703233
4.826087
false
true
false
false
google/horologist
media-ui/src/debug/java/com/google/android/horologist/media/ui/components/TextMediaDisplayPreview.kt
1
1404
/* * 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. */ @file:OptIn(ExperimentalHorologistMediaUiApi::class) package com.google.android.horologist.media.ui.components import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.google.android.horologist.compose.tools.WearPreview import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi @WearPreview @Composable fun TextMediaDisplayPreview() { TextMediaDisplay( title = "Song title", artist = "Artist name" ) } @Preview( "With long text", backgroundColor = 0xff000000, showBackground = true ) @Composable fun TextMediaDisplayPreviewLongText() { TextMediaDisplay( title = "I Predict That You Look Good In A Riot", artist = "Arctic Monkeys feat Kaiser Chiefs" ) }
apache-2.0
aff40e7caebee18e5997f52ca5bde2d8
29.521739
78
0.745014
4.129412
false
false
false
false
Constantinuous/Angus
infrastructure/src/main/kotlin/de/constantinuous/angus/sql/impl/AntlrTsqlContextExtensions.kt
1
1921
package de.constantinuous.angus.sql.impl import org.antlr.v4.runtime.RuleContext /** * Created by RichardG on 25.11.2016. */ fun tsqlParser.Select_statementContext.getTableName(): String { val tableSource = this.query_expression().query_specification().table_sources().table_source(0) val table = tableSource.table_source_item_joined().table_source_item().table_name_with_hint().table_name().table val tableName = table.simple_id().getChild(0).text ?: "" return tableName } fun tsqlParser.Select_statementContext.getSelectedColumnNames(): List<String> { val selectedColumnNames = mutableListOf<String>() val selectList = this.query_expression().query_specification().select_list().select_list_elem() for(selectListElement in selectList){ val columnName = selectListElement.expression().getChild(0).text selectedColumnNames.add(columnName) } return selectedColumnNames } fun tsqlParser.Delete_statementContext.getTableName(): String{ val tableName = this.delete_statement_from().table_alias().id().simple_id().getChild(0).text ?: "" return tableName } fun tsqlParser.Insert_statementContext.getTableName(): String{ val tableName = this.ddl_object().full_table_name().getChild(0).text return tableName } fun tsqlParser.Insert_statementContext.getColumnNames(): List<String>{ val columnNames = mutableListOf<String>() val columnNameList = this.column_name_list() if(columnNameList != null){ for(id in columnNameList.id()){ columnNames.add(id.simple_id().getChild(0).text) } } return columnNames } fun tsqlParser.Execute_statementContext.getProcedureNames(): List<String>{ val procedureNames = mutableListOf<String>() val procedures = this.func_proc_name().id() for(procedure in procedures){ procedureNames.add(procedure.simple_id().text) } return procedureNames }
mit
3f9dfe8ee78ccc238131555f1935e650
31.016667
116
0.717335
4.122318
false
false
false
false
googlecodelabs/tv-watchnext
step_final/src/androidTest/java/com/example/android/watchnextcodelab/MockDataUtil.kt
4
1833
/* * 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. */ @file:JvmName("MockDataUtil") package com.example.android.watchnextcodelab import android.media.tv.TvContentRating import android.support.media.tv.TvContractCompat import com.example.android.watchnextcodelab.model.Movie /** * Contains helper method for generating mock data to test with. */ fun createMovieWithTitle(id: Long, title: String): Movie = Movie( movieId = id, title = title, description = "Description...", duration = 1, previewVideoUrl = "preview url", videoUrl = "video url", posterArtAspectRatio = TvContractCompat.PreviewPrograms.ASPECT_RATIO_1_1, aspectRatio = TvContractCompat.PreviewPrograms.ASPECT_RATIO_1_1, thumbnailUrl = "thumb url", cardImageUrl = "card image url", contentRating = TvContentRating.UNRATED, genre = "action", isLive = false, releaseDate = "2001", rating = "3", ratingStyle = TvContractCompat.WatchNextPrograms.REVIEW_RATING_STYLE_STARS, startingPrice = "$1.99", offerPrice = "$0.99", width = 1, height = 1, weight = 1)
apache-2.0
c2cf92694d446d9611564ee93334f079
37.1875
100
0.652482
4.514778
false
false
false
false
Commit451/LabCoat
app/src/main/java/com/commit451/gitlab/widget/ProjectFeedWidgetProvider.kt
2
2477
package com.commit451.gitlab.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.net.Uri import android.widget.RemoteViews import com.commit451.gitlab.R import com.commit451.gitlab.navigation.DeepLinker class ProjectFeedWidgetProvider : AppWidgetProvider() { companion object { const val ACTION_FOLLOW_LINK = "com.commit451.gitlab.ACTION_FOLLOW_LINK" const val EXTRA_LINK = "com.commit451.gitlab.EXTRA_LINK" } override fun onReceive(context: Context, intent: Intent) { if (intent.action == ACTION_FOLLOW_LINK) { val uri = intent.getStringExtra(EXTRA_LINK) val launchIntent = DeepLinker.generateDeeplinkIntentFromUri(context, Uri.parse(uri)) launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(launchIntent) } super.onReceive(context, intent) } override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { for (widgetId in appWidgetIds) { val account = ProjectFeedWidgetPrefs.getAccount(context, widgetId) val feedUrl = ProjectFeedWidgetPrefs.getFeedUrl(context, widgetId) if (account != null && feedUrl != null) { val intent = FeedWidgetService.newIntent(context, widgetId, account, feedUrl) intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)) val rv = RemoteViews(context.packageName, R.layout.widget_layout_entry) rv.setRemoteAdapter(R.id.list_view, intent) rv.setEmptyView(R.id.list_view, R.id.empty_view) val toastIntent = Intent(context, ProjectFeedWidgetProvider::class.java) toastIntent.action = ACTION_FOLLOW_LINK toastIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId) intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)) val toastPendingIntent = PendingIntent.getBroadcast(context, 0, toastIntent, PendingIntent.FLAG_UPDATE_CURRENT) rv.setPendingIntentTemplate(R.id.list_view, toastPendingIntent) appWidgetManager.updateAppWidget(widgetId, rv) } } super.onUpdate(context, appWidgetManager, appWidgetIds) } }
apache-2.0
001a78ee4d18dd0412c15bbad01b3da1
41.706897
105
0.683488
4.595547
false
false
false
false
felipecsl/walkman
okreplay-junit/src/main/kotlin/okreplay/Ascii.kt
3
2888
/* * Copyright (C) 2010 The Guava 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 okreplay internal object Ascii { /** * Returns a copy of the input string in which all [uppercase ASCII][.isUpperCase] have been * converted to lowercase. All other characters are copied without modification. */ fun toLowerCase(string: String): String { val length = string.length var i = 0 while (i < length) { if (isUpperCase(string[i])) { val chars = string.toCharArray() while (i < length) { val c = chars[i] if (isUpperCase(c)) { chars[i] = (c.toInt() xor 0x20).toChar() } i++ } return String(chars) } i++ } return string } /** * Returns a copy of the input string in which all [lowercase ASCII][.isLowerCase] have been * converted to uppercase. All other characters are copied without modification. */ fun toUpperCase(string: String): String { val length = string.length var i = 0 while (i < length) { if (isLowerCase(string[i])) { val chars = string.toCharArray() while (i < length) { val c = chars[i] if (isLowerCase(c)) { chars[i] = (c.toInt() and 0x5f).toChar() } i++ } return String(chars) } i++ } return string } /** * If the argument is a [lowercase ASCII character][.isLowerCase] returns the * uppercase equivalent. Otherwise returns the argument. */ fun toUpperCase(c: Char): Char { return if (isLowerCase(c)) (c.toInt() and 0x5f).toChar() else c } /** * Indicates whether `c` is one of the twenty-six lowercase ASCII alphabetic characters * between `'a'` and `'z'` inclusive. All others (including non-ASCII characters) * return `false`. */ private fun isLowerCase(c: Char): Boolean { // Note: This was benchmarked against the alternate expression "(char)(c - 'a') < 26" (Nov '13) // and found to perform at least as well, or better. return c in 'a'..'z' } /** * Indicates whether `c` is one of the twenty-six uppercase ASCII alphabetic characters * between `'A'` and `'Z'` inclusive. All others (including non-ASCII characters) * return `false`. */ private fun isUpperCase(c: Char): Boolean { return c in 'A'..'Z' } }
apache-2.0
f372840e39a43f7601bfb066aedfbd0e
30.391304
100
0.625346
4.01669
false
false
false
false
OurFriendIrony/MediaNotifier
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/mediaitem/artist/Artist.kt
1
3374
package uk.co.ourfriendirony.medianotifier.mediaitem.artist import android.database.Cursor import android.util.Log import uk.co.ourfriendirony.medianotifier.clients.musicbrainz.artist.get.ArtistGet import uk.co.ourfriendirony.medianotifier.clients.musicbrainz.artist.search.ArtistSearchArtist import uk.co.ourfriendirony.medianotifier.db.artist.ArtistDatabaseDefinition import uk.co.ourfriendirony.medianotifier.general.Helper.getColumnValue import uk.co.ourfriendirony.medianotifier.general.Helper.stringToDate import uk.co.ourfriendirony.medianotifier.mediaitem.MediaItem import java.text.SimpleDateFormat import java.util.* class Artist : MediaItem { override val id: String override val title: String? override val subtitle = "" // TODO: fully implement played as an item override val played = false private var subid = "" override var description: String? = "" private set override var releaseDate: Date? = null private set override val externalLink: String? = null override var children: List<MediaItem> = ArrayList() constructor(artist: ArtistGet) { id = artist.id!! title = artist.name if (artist.disambiguation != null) { description = artist.disambiguation } else if (artist.area!!.name != null && artist.type != null) { description = artist.type + " from " + artist.area!!.name } if (artist.lifeSpan != null && artist.lifeSpan!!.begin != null) { releaseDate = artist.lifeSpan!!.begin } } constructor(artist: ArtistSearchArtist) { id = artist.id!! title = artist.name if (artist.disambiguation != null) { description = artist.disambiguation } else if (artist.area != null && artist.area!!.name != null && artist.type != null) { description = artist.type + " from " + artist.area!!.name } if (artist.lifeSpan != null && artist.lifeSpan!!.begin != null) { releaseDate = artist.lifeSpan!!.begin } Log.d("[API SEARCH]", this.toString()) } @JvmOverloads constructor(cursor: Cursor?, releases: List<MediaItem> = ArrayList()) { // Build Artist from DB with children id = getColumnValue(cursor!!, ArtistDatabaseDefinition.ID) subid = getColumnValue(cursor, ArtistDatabaseDefinition.SUBID) title = getColumnValue(cursor, ArtistDatabaseDefinition.TITLE) description = getColumnValue(cursor, ArtistDatabaseDefinition.DESCRIPTION) releaseDate = stringToDate(getColumnValue(cursor, ArtistDatabaseDefinition.RELEASE_DATE)) children = releases Log.d("[DB READ]", this.toString()) } override val subId: String get() = subid override val releaseDateFull: String get() = if (releaseDate != null) { SimpleDateFormat("dd/MM/yyyy", Locale.UK).format(releaseDate!!) } else MediaItem.NO_DATE override val releaseDateYear: String get() = if (releaseDate != null) { SimpleDateFormat("yyyy", Locale.UK).format(releaseDate!!) } else MediaItem.NO_DATE override fun countChildren(): Int { return children.size } override fun toString(): String { return "Artist: " + title + " > " + releaseDateFull + " > Releases " + countChildren() } }
apache-2.0
e206469c7080617d736b6d8edabc7b32
38.244186
97
0.663308
4.522788
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/psi/element/MdJekyllFrontMatterBlockImpl.kt
1
5306
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.psi.element import com.intellij.lang.ASTNode import com.intellij.navigation.ItemPresentation import com.intellij.openapi.util.TextRange import com.intellij.psi.ElementManipulators import com.intellij.psi.LiteralTextEscaper import com.intellij.psi.PsiElement import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.tree.IElementType import com.vladsch.md.nav.parser.MdFactoryContext import com.vladsch.md.nav.psi.util.BasicTextMapElementTypeProvider import com.vladsch.md.nav.psi.util.MdPsiImplUtil import com.vladsch.md.nav.psi.util.MdTypes import com.vladsch.md.nav.psi.util.TextMapElementType import com.vladsch.plugin.util.ifElse import icons.MdIcons import javax.swing.Icon //class MultiMarkdownJekyllFrontMatterBlockImpl(node: ASTNode) : ASTWrapperPsiElement(node), MultiMarkdownJekyllFrontMatterBlock { class MdJekyllFrontMatterBlockImpl(stub: MdJekyllFrontMatterBlockStub?, nodeType: IStubElementType<MdJekyllFrontMatterBlockStub, MdJekyllFrontMatterBlock>?, node: ASTNode?) : MdStubPlainTextImpl<MdJekyllFrontMatterBlockStub>(stub, nodeType, node), MdJekyllFrontMatterBlock { constructor(stub: MdJekyllFrontMatterBlockStub, nodeType: IStubElementType<MdJekyllFrontMatterBlockStub, MdJekyllFrontMatterBlock>) : this(stub, nodeType, null) constructor(node: ASTNode) : this(null, null, node) override fun getTextMapType(): TextMapElementType { return BasicTextMapElementTypeProvider.JEKYLL_FRONT_MATTER } val referenceableTextType: IElementType = MdTypes.JEKYLL_FRONT_MATTER_BLOCK override fun getReferenceableOffsetInParent(): Int { return MdPlainTextStubElementType.getReferenceableOffsetInParent(node, referenceableTextType) } override fun getReferenceableText(): String { return content } override fun replaceReferenceableText(text: String, startOffset: Int, endOffset: Int): PsiElement { val content = content val sb = StringBuilder(content.length - (endOffset - startOffset) + text.length) sb.append(content, 0, startOffset).append(text).append(content, endOffset, content.length) return setContent(sb.toString()) } override fun getContentElement(): ASTNode? = node.findChildByType(referenceableTextType) override fun getContent(): String { val content = getContentElement() return content?.text ?: "" } override fun setContent(blockText: String): PsiElement { return MdPsiImplUtil.setContent(this, blockText) } override fun getContentRange(inDocument: Boolean): TextRange { val startMarker = node.findChildByType(MdTypes.JEKYLL_FRONT_MATTER_OPEN) val content = node.findChildByType(referenceableTextType) if (startMarker != null && content != null) { return TextRange(startMarker.textLength + 1, startMarker.textLength + 1 + content.textLength).shiftRight(inDocument.ifElse(0, startMarker.startOffset)) } return TextRange(0, 0) } override fun getPresentation(): ItemPresentation { return object : ItemPresentation { override fun getPresentableText(): String? { if (!isValid) return null return "Jekyll front matter block" } override fun getLocationString(): String? { if (!isValid) return null // create a shortened version that is still good to look at return MdPsiImplUtil.truncateStringForDisplay(text, 50, false, true, true) } override fun getIcon(unused: Boolean): Icon? { return MdIcons.getDocumentIcon() } } } override fun isValidHost(): Boolean { return isValid } override fun updateText(text: String): MdPsiLanguageInjectionHost { return ElementManipulators.handleContentChange(this, text) } override fun createLiteralTextEscaper(): LiteralTextEscaper<out MdPsiLanguageInjectionHost> { return object : LiteralTextEscaper<MdPsiLanguageInjectionHost>(this) { override fun decode(rangeInsideHost: TextRange, outChars: StringBuilder): Boolean { outChars.append(rangeInsideHost.substring(myHost.text)) return true } override fun getOffsetInHost(offsetInDecoded: Int, rangeInsideHost: TextRange): Int { return rangeInsideHost.startOffset + offsetInDecoded } override fun getRelevantTextRange(): TextRange { return contentRange } override fun isOneLine(): Boolean { return false } } } companion object { @Suppress("UNUSED_PARAMETER") fun getElementText(factoryContext: MdFactoryContext, content: String?): String { val useContent = content ?: "" if (useContent.isEmpty() || useContent[useContent.length - 1] != '\n') { return "---\n$useContent\n---\n" } else { return "---\n$useContent---\n" } } } }
apache-2.0
dd7efd3ec41d2785f6df393a1acbc534
39.503817
177
0.692801
5.000943
false
false
false
false
komu/siilinkari
src/test/kotlin/siilinkari/translator/BasicBlockGraphTest.kt
1
739
package siilinkari.translator import org.junit.Test import siilinkari.objects.value import kotlin.test.assertFailsWith class BasicBlockGraphTest { val graph = BasicBlockGraph() @Test fun jumpBackwardsDoesNotMaintainBalance() { val end = BasicBlock() graph.start += IR.Push(42.value) graph.start += IR.Push(42.value) graph.start.endWithBranch(graph.start, end) end += IR.Push(42.value) assertInvalidStackUse() } @Test fun stackUnderflow() { graph.start += IR.Pop assertInvalidStackUse() } private fun assertInvalidStackUse() { assertFailsWith<InvalidStackUseException> { graph.buildStackDepthMap() } } }
mit
0ec1728ebdd9d30b13b4e9da6f11ffaa
20.735294
51
0.64682
4.175141
false
true
false
false
chrisbanes/tivi
data/src/main/java/app/tivi/data/repositories/search/SearchRepository.kt
1
2214
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.data.repositories.search import androidx.collection.LruCache import app.tivi.data.daos.ShowTmdbImagesDao import app.tivi.data.daos.TiviShowDao import app.tivi.data.resultentities.ShowDetailed import javax.inject.Inject import javax.inject.Singleton @Singleton class SearchRepository @Inject constructor( private val showTmdbImagesDao: ShowTmdbImagesDao, private val showDao: TiviShowDao, private val tmdbDataSource: TmdbSearchDataSource ) { private val cache by lazy { LruCache<String, LongArray>(32) } suspend fun search(query: String): List<ShowDetailed> { if (query.isBlank()) { return emptyList() } val cacheValues = cache[query] if (cacheValues != null) { return cacheValues.map { showDao.getShowWithIdDetailed(it)!! } } // We need to hit TMDb instead return try { val tmdbResult = tmdbDataSource.search(query) tmdbResult.map { (show, images) -> val showId = showDao.getIdOrSavePlaceholder(show) if (images.isNotEmpty()) { showTmdbImagesDao.saveImagesIfEmpty(showId, images.map { it.copy(showId = showId) }) } showId }.also { results -> // We need to save the search results cache.put(query, results.toLongArray()) }.mapNotNull { // Finally map back to a TiviShow instance showDao.getShowWithIdDetailed(it) } } catch (e: Exception) { emptyList() } } }
apache-2.0
47a798050eef9ca69775809f66154c64
33.59375
104
0.646793
4.454728
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/annotator/RsExpressionAnnotator.kt
2
4043
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator import com.intellij.codeInspection.ProblemHighlightType import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.psi.PsiElement import com.intellij.util.SmartList import org.rust.ide.annotator.fixes.AddStructFieldsFix import org.rust.ide.intentions.RemoveParenthesesFromExprIntention import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import java.util.* import java.io.FileNotFoundException import java.io.IOException class RsExpressionAnnotator : Annotator { override fun annotate(element: PsiElement, holder: AnnotationHolder) { element.accept(RedundantParenthesisVisitor(holder)) if (element is RsStructLiteral) { val decl = element.path.reference.resolve() as? RsFieldsOwner if (decl != null) { checkStructLiteral(holder, decl, element.structLiteralBody) } } } private fun checkStructLiteral( holder: AnnotationHolder, decl: RsFieldsOwner, expr: RsStructLiteralBody ) { expr.structLiteralFieldList .filter { it.reference.resolve() == null } .forEach { holder.createErrorAnnotation(it.identifier, "No such field") .highlightType = ProblemHighlightType.LIKE_UNKNOWN_SYMBOL } for (field in expr.structLiteralFieldList.findDuplicateReferences()) { holder.createErrorAnnotation(field.identifier, "Duplicate field") } if (expr.dotdot != null) return // functional update, no need to declare all the fields. val declaredFields = expr.structLiteralFieldList.map { it.referenceName }.toSet() val missingFields = decl.namedFields.filter { it.name !in declaredFields && !it.queryAttributes.hasCfgAttr() } if (decl is RsStructItem && decl.kind == RsStructKind.UNION) { if (expr.structLiteralFieldList.size > 1) { holder.createErrorAnnotation(expr, "Union expressions should have exactly one field") } } else { if (missingFields.isNotEmpty()) { val structNameRange = expr.parent.childOfType<RsPath>()?.textRange if (structNameRange != null) holder.createErrorAnnotation(structNameRange, "Some fields are missing") .registerFix(AddStructFieldsFix(decl.namedFields, missingFields, expr), expr.parent.textRange) } } } } private class RedundantParenthesisVisitor(private val holder: AnnotationHolder) : RsVisitor() { override fun visitCondition(o: RsCondition) = o.expr.warnIfParens("Predicate expression has unnecessary parentheses") override fun visitRetExpr(o: RsRetExpr) = o.expr.warnIfParens("Return expression has unnecessary parentheses") override fun visitMatchExpr(o: RsMatchExpr) = o.expr.warnIfParens("Match expression has unnecessary parentheses") override fun visitForExpr(o: RsForExpr) = o.expr.warnIfParens("For loop expression has unnecessary parentheses") override fun visitParenExpr(o: RsParenExpr) = o.expr.warnIfParens("Redundant parentheses in expression") private fun RsExpr?.warnIfParens(message: String) { if (this !is RsParenExpr) return val fix = RemoveParenthesesFromExprIntention() if (fix.isAvailable(this)) holder.createWeakWarningAnnotation(this, message) .registerFix(RemoveParenthesesFromExprIntention()) } } private fun <T : RsReferenceElement> Collection<T>.findDuplicateReferences(): Collection<T> { val names = HashSet<String>(size) val result = SmartList<T>() for (item in this) { val name = item.referenceName if (name in names) { result += item } names += name } return result }
mit
f82dcc3ab4d842662511833f11bb46cf
36.435185
118
0.676973
4.636468
false
false
false
false
MyDogTom/detekt
detekt-migration/src/test/kotlin/io/gitlab/arturbosch/detekt/migration/MigrateImportsTest.kt
1
1127
package io.gitlab.arturbosch.detekt.migration import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.test.compileContentForTest import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test /** * @author Artur Bosch */ internal class MigrateImportsTest { @Test fun migrate() { val ktFile = compileContentForTest( """ package hello import io.gitlab.arturbosch.detekt.migration import hello.hello fun main(args: Array<String>) {} """ ) val expected = """ package hello import io.gitlab.arturbosch.detekt.migration import bye.bye fun main(args: Array<String>) {} """ MigrateImportsRule(MigrationTestConfig).visit(ktFile) assertThat(ktFile.text).isEqualTo(expected) } } object MigrationTestConfig : Config { private val map = hashMapOf("imports" to hashMapOf("hello.hello" to "bye.bye")) override fun subConfig(key: String): Config { if (key == "migration") return this else return Config.empty } override fun <T : Any> valueOrDefault(key: String, default: T): T { @Suppress("UNCHECKED_CAST") return map[key] as T? ?: default } }
apache-2.0
de36209e517dacc24ef353e728606873
19.87037
80
0.732032
3.532915
false
true
false
false
outadoc/Twistoast-android
keolisprovider/src/main/kotlin/fr/outadev/android/transport/timeo/dto/DescriptionDTO.kt
1
1385
/* * Twistoast - DescriptionDTO.kt * Copyright (C) 2013-2016 Baptiste Candellier * * Twistoast 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. * * Twistoast 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 fr.outadev.android.transport.timeo.dto import org.simpleframework.xml.Element /** * Represents the details of a stop and line in the XML API. * * @author outadoc */ class DescriptionDTO { @field:Element(name = "code") var code: Int = -1 @field:Element(name = "arret") lateinit var arret: String @field:Element(name = "ligne") lateinit var ligne: String @field:Element(name = "ligne_nom") lateinit var ligne_nom: String @field:Element(name = "sens") lateinit var sens: String @field:Element(name = "vers", required = false) var vers: String? = null @field:Element(name = "couleur") var couleur: String? = null }
gpl-3.0
f92bf258e8e14aee72b78d9b5c12d5f7
36.432432
76
0.71769
3.664021
false
false
false
false
Fitbit/MvRx
mvrx/src/main/kotlin/com/airbnb/mvrx/MavericksFactory.kt
1
4403
package com.airbnb.mvrx import androidx.annotation.RestrictTo import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider internal class MavericksFactory<VM : MavericksViewModel<S>, S : MavericksState>( private val viewModelClass: Class<out VM>, private val stateClass: Class<out S>, private val viewModelContext: ViewModelContext, private val key: String, private val stateRestorer: ((S) -> S)?, private val forExistingViewModel: Boolean = false, private val initialStateFactory: MavericksStateFactory<VM, S> = RealMavericksStateFactory() ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (stateRestorer == null && forExistingViewModel) { throw ViewModelDoesNotExistException(viewModelClass, viewModelContext, key) } val viewModel = createViewModel( viewModelClass, stateClass, viewModelContext, stateRestorer ?: { it }, initialStateFactory ) return viewModel as T } } @Suppress("UNCHECKED_CAST") private fun <VM : MavericksViewModel<S>, S : MavericksState> createViewModel( viewModelClass: Class<out VM>, stateClass: Class<out S>, viewModelContext: ViewModelContext, stateRestorer: (S) -> S, initialStateFactory: MavericksStateFactory<VM, S> ): MavericksViewModelWrapper<VM, S> { val initialState = initialStateFactory.createInitialState(viewModelClass, stateClass, viewModelContext, stateRestorer) val factoryViewModel = viewModelClass.factoryCompanion()?.let { factoryClass -> try { factoryClass.getMethod("create", ViewModelContext::class.java, MavericksState::class.java) .invoke(factoryClass.instance(), viewModelContext, initialState) as VM? } catch (exception: NoSuchMethodException) { // Check for JvmStatic method. viewModelClass.getMethod("create", ViewModelContext::class.java, MavericksState::class.java) .invoke(null, viewModelContext, initialState) as VM? } } val viewModel = requireNotNull(factoryViewModel ?: createDefaultViewModel(viewModelClass, initialState)) { if (viewModelClass.constructors.firstOrNull()?.parameterTypes?.size?.let { it > 1 } == true) { "${viewModelClass.simpleName} takes dependencies other than initialState. " + "It must have companion object implementing ${MavericksViewModelFactory::class.java.simpleName} " + "with a create method returning a non-null ViewModel." } else { "${viewModelClass::class.java.simpleName} must have primary constructor with a " + "single non-optional parameter that takes initial state of ${stateClass.simpleName}." } } return MavericksViewModelWrapper(viewModel) } @Suppress("UNCHECKED_CAST", "NestedBlockDepth") private fun <VM : MavericksViewModel<S>, S : MavericksState> createDefaultViewModel(viewModelClass: Class<VM>, state: S): VM? { // If we are checking for a default ViewModel, we expect only a single default constructor. Any other case // is a misconfiguration and we will throw an appropriate error under further inspection. if (viewModelClass.constructors.size == 1) { val primaryConstructor = viewModelClass.constructors[0] if (primaryConstructor.parameterTypes.size == 1 && primaryConstructor.parameterTypes[0].isAssignableFrom(state::class.java)) { if (!primaryConstructor.isAccessible) { try { primaryConstructor.isAccessible = true } catch (e: SecurityException) { throw IllegalStateException("ViewModel class is not public and MvRx could not make the primary constructor accessible.", e) } } return primaryConstructor?.newInstance(state) as? VM } } return null } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @InternalMavericksApi open class ViewModelDoesNotExistException(message: String) : IllegalStateException(message) { constructor( viewModelClass: Class<*>, viewModelContext: ViewModelContext, key: String ) : this("ViewModel of type ${viewModelClass.name} for ${viewModelContext.owner}[$key] does not exist yet!") }
apache-2.0
8c0e4b7497fdc250a0fb0f0b2587d8da
45.840426
143
0.68794
5.020525
false
false
false
false
http4k/http4k
http4k-contract/src/main/kotlin/org/http4k/contract/openapi/v3/JsonToJsonSchema.kt
1
3645
package org.http4k.contract.openapi.v3 import org.http4k.format.Json import org.http4k.format.JsonType import org.http4k.lens.ParamMeta import org.http4k.util.IllegalSchemaException import org.http4k.util.JsonSchema import org.http4k.util.JsonSchemaCreator class JsonToJsonSchema<NODE>( private val json: Json<NODE>, private val refLocationPrefix: String = "components/schemas" ) : JsonSchemaCreator<NODE, NODE> { override fun toSchema(obj: NODE, overrideDefinitionId: String?, refModelNamePrefix: String?) = JsonSchema(obj, emptySet()).toSchema(overrideDefinitionId, refModelNamePrefix ?: "") private fun JsonSchema<NODE>.toSchema( overrideDefinitionId: String? = null, refModelNamePrefix: String ): JsonSchema<NODE> = when (json.typeOf(node)) { JsonType.Object -> objectSchema(overrideDefinitionId, refModelNamePrefix) JsonType.Array -> arraySchema(overrideDefinitionId, refModelNamePrefix) JsonType.String -> JsonSchema(ParamMeta.StringParam.schema(json.string(json.text(node))), definitions) JsonType.Integer -> numberSchema() JsonType.Number -> numberSchema() JsonType.Boolean -> JsonSchema(ParamMeta.BooleanParam.schema(json.boolean(json.bool(node))), definitions) JsonType.Null -> throw IllegalSchemaException("Cannot use a null value in a schema!") else -> throw IllegalSchemaException("unknown type") } private fun JsonSchema<NODE>.numberSchema(): JsonSchema<NODE> { val text = json.text(node) val schema = when { text.contains(".") -> ParamMeta.NumberParam.schema(json.number(text.toBigDecimal())) else -> ParamMeta.IntegerParam.schema(json.number(text.toBigInteger())) } return JsonSchema(schema, definitions) } private fun JsonSchema<NODE>.arraySchema( overrideDefinitionId: String?, refModelNamePrefix: String ): JsonSchema<NODE> { val (node, definitions) = json.elements(node).toList().firstOrNull()?.let { JsonSchema(it, definitions).toSchema(overrideDefinitionId, refModelNamePrefix) } ?: throw IllegalSchemaException("Cannot use an empty list to generate a schema!") return JsonSchema(json { obj("type" to string("array"), "items" to node) }, definitions) } private fun JsonSchema<NODE>.objectSchema( overrideDefinitionId: String?, refModelNamePrefix: String ): JsonSchema<NODE> { val (fields, subDefinitions) = json.fields(node) .filter { json.typeOf(it.second) != JsonType.Null } // filter out null fields for which type can't be inferred .fold(listOf<Pair<String, NODE>>() to definitions) { (memoFields, memoDefinitions), (first, second) -> JsonSchema(second, memoDefinitions).toSchema(refModelNamePrefix = refModelNamePrefix) .let { memoFields + (first to it.node) to it.definitions } } val newDefinition = json { obj( "type" to string("object"), "required" to array(emptyList()), "properties" to obj(fields) ) } val definitionId = refModelNamePrefix + (overrideDefinitionId ?: ("object" + newDefinition.hashCode())) val allDefinitions = subDefinitions + (definitionId to newDefinition) return JsonSchema(json { obj("\$ref" to string("#/$refLocationPrefix/$definitionId")) }, allDefinitions) } private fun ParamMeta.schema(example: NODE): NODE = json { obj("type" to string(value), "example" to example) } }
apache-2.0
8610ee5cc306e1bf37a1dc4b01f0080e
47.6
122
0.66749
4.344458
false
false
false
false
valich/intellij-markdown
src/commonMain/kotlin/org/intellij/markdown/parser/sequentialparsers/SequentialParserManager.kt
1
924
package org.intellij.markdown.parser.sequentialparsers abstract class SequentialParserManager { abstract fun getParserSequence(): List<SequentialParser> fun runParsingSequence(tokensCache: TokensCache, rangesToParse: List<IntRange>): Collection<SequentialParser.Node> { val result = ArrayList<SequentialParser.Node>() var parsingSpaces = ArrayList<List<IntRange>>() parsingSpaces.add(rangesToParse) for (sequentialParser in getParserSequence()) { val nextLevelSpaces = ArrayList<List<IntRange>>() for (parsingSpace in parsingSpaces) { val currentResult = sequentialParser.parse(tokensCache, parsingSpace) result.addAll(currentResult.parsedNodes) nextLevelSpaces.addAll(currentResult.rangesToProcessFurther) } parsingSpaces = nextLevelSpaces } return result } }
apache-2.0
ee756f9428533adf2934aa280a4c0f1e
34.538462
120
0.686147
5.372093
false
false
false
false
valich/intellij-markdown
src/commonMain/kotlin/org/intellij/markdown/parser/markerblocks/impl/AtxHeaderMarkerBlock.kt
1
2834
package org.intellij.markdown.parser.markerblocks.impl import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.parser.LookaheadText 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.MarkerBlockImpl import org.intellij.markdown.parser.sequentialparsers.SequentialParser class AtxHeaderMarkerBlock(myConstraints: MarkdownConstraints, productionHolder: ProductionHolder, headerRange: IntRange, tailStartPos: Int, endOfLinePos: Int) : MarkerBlockImpl(myConstraints, productionHolder.mark()) { override fun allowsSubBlocks(): Boolean = false init { val curPos = productionHolder.currentPosition productionHolder.addProduction(listOf(SequentialParser.Node( curPos + headerRange.first..curPos + headerRange.last + 1, MarkdownTokenTypes.ATX_HEADER ), SequentialParser.Node( curPos + headerRange.last + 1..tailStartPos, MarkdownTokenTypes.ATX_CONTENT ), SequentialParser.Node( tailStartPos..endOfLinePos, MarkdownTokenTypes.ATX_HEADER ))) } override fun isInterestingOffset(pos: LookaheadText.Position): Boolean = true private val nodeType = calcNodeType(headerRange.last - headerRange.first + 1) private fun calcNodeType(headerSize: Int): IElementType { when (headerSize) { 1 -> return MarkdownElementTypes.ATX_1 2 -> return MarkdownElementTypes.ATX_2 3 -> return MarkdownElementTypes.ATX_3 4 -> return MarkdownElementTypes.ATX_4 5 -> return MarkdownElementTypes.ATX_5 6 -> return MarkdownElementTypes.ATX_6 else -> return MarkdownElementTypes.ATX_6 } } override fun getDefaultNodeType(): IElementType { return nodeType } override fun getDefaultAction(): MarkerBlock.ClosingAction { return MarkerBlock.ClosingAction.DONE } override fun calcNextInterestingOffset(pos: LookaheadText.Position): Int { return pos.nextLineOrEofOffset } override fun doProcessToken(pos: LookaheadText.Position, currentConstraints: MarkdownConstraints): MarkerBlock.ProcessingResult { if (pos.offsetInCurrentLine == -1) { return MarkerBlock.ProcessingResult(MarkerBlock.ClosingAction.DROP, MarkerBlock.ClosingAction.DONE, MarkerBlock.EventAction.PROPAGATE) } return MarkerBlock.ProcessingResult.CANCEL } }
apache-2.0
f390104983157253d400d689a216ea84
40.691176
146
0.700071
5.524366
false
false
false
false
k-r-g/FrameworkBenchmarks
frameworks/Kotlin/http4k/core/src/main/kotlin/WorldRoutes.kt
7
2577
import com.fasterxml.jackson.databind.JsonNode import org.http4k.core.Body import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.NOT_FOUND import org.http4k.core.Status.Companion.OK import org.http4k.core.with import org.http4k.format.Jackson.array import org.http4k.format.Jackson.json import org.http4k.format.Jackson.number import org.http4k.format.Jackson.obj import org.http4k.lens.Query import org.http4k.routing.bind import java.lang.Math.max import java.lang.Math.min import java.sql.Connection import java.sql.ResultSet.CONCUR_READ_ONLY import java.sql.ResultSet.TYPE_FORWARD_ONLY import java.util.* object WorldRoutes { private val jsonBody = Body.json().toLens() private val numberOfQueries = Query .map { try { min(max(it.toInt(), 1), 500) } catch (e: Exception) { 1 } } .defaulted("queries", 1) fun queryRoute(database: Database) = "/db" bind GET to { database.withConnection { findWorld(it, randomWorld()) }?.let { Response(OK).with(jsonBody of it) } ?: Response(NOT_FOUND) } fun multipleRoute(database: Database) = "/queries" bind GET to { val worlds = database.withConnection { con -> (1..numberOfQueries(it)).mapNotNull { findWorld(con, randomWorld()) } } Response(OK).with(jsonBody of array(worlds)) } fun updateRoute(database: Database) = "/updates" bind GET to { val worlds = database.withConnection { con -> (1..numberOfQueries(it)).mapNotNull { val id = randomWorld() updateWorld(con, id) findWorld(con, id) } } Response(OK).with(jsonBody of array(worlds)) } private fun findWorld(it: Connection, id: Int): JsonNode? { val stmtSelect = it.prepareStatement("select * from world where id = ?", TYPE_FORWARD_ONLY, CONCUR_READ_ONLY) stmtSelect.setInt(1, id) return stmtSelect.executeQuery().toList { obj("id" to number(it.getInt("id")), "randomNumber" to number(it.getInt("randomNumber"))) }.firstOrNull() } private fun updateWorld(it: Connection, id: Int) { val stmtSelect = it.prepareStatement("update world set randomNumber = ? where id = ?") stmtSelect.setInt(1, randomWorld()) stmtSelect.setInt(2, id) stmtSelect.executeUpdate() } private fun randomWorld() = Random().nextInt(9999) + 1 }
bsd-3-clause
d7c2c35189db98e039f6c492e21acedb
31.632911
117
0.635235
3.898638
false
false
false
false
xiaopansky/Sketch
sample/src/main/java/me/panpf/sketch/sample/bean/BaiduImageSearchResult.kt
1
985
package me.panpf.sketch.sample.bean import com.google.gson.annotations.SerializedName class BaiduImageSearchResult { @SerializedName("listNum") var total: Int = 0 @SerializedName("data") var imageList: List<BaiduImage>? = null } class BaiduImage { @SerializedName("thumbURL") val thumbURL: String? = null @SerializedName("middleURL") val middleURL: String? = null @SerializedName("hoverURL") val hoverURL: String? = null @SerializedName("replaceUrl") private val replaceUrlList: List<ReplaceUrl>? = null @SerializedName("width") val width: Int = 0 @SerializedName("height") val height: Int = 0 val url: String? get() { return if (hoverURL != middleURL && hoverURL != thumbURL) { hoverURL } else { replaceUrlList?.lastOrNull()?.objUrl } } } class ReplaceUrl { @SerializedName("ObjURL") var objUrl: String? = null }
apache-2.0
78e662948fb9c164af127854e22686e6
20.434783
71
0.619289
4.209402
false
false
false
false
langara/USpek
ktjsreactsample/src/jsTest/kotlin/playground/ExampleTest.kt
1
535
package playground import kotlinx.coroutines.MainScope import kotlinx.coroutines.promise import kotlin.coroutines.CoroutineContext import kotlin.test.Test // temporary workaround from: https://github.com/Kotlin/kotlinx.coroutines/issues/1996 val testScope = MainScope() val testCoroutineContext: CoroutineContext = testScope.coroutineContext fun runBlockingTest(block: suspend () -> Unit): dynamic = testScope.promise { block() } class ExampleTest { @Test fun exampleTest() = runBlockingTest { lsoDelayMs = 5; example() } }
apache-2.0
11a96176d38a01af80d4952ac9908682
32.4375
87
0.786916
4.495798
false
true
false
false
GymDon-P-Q11Info-13-15/game
Game Commons/src/de/gymdon/inf1315/game/Mine.kt
1
550
package de.gymdon.inf1315.game class Mine(x: Int, y: Int) : Building() { var superior = true init { this.x = x this.y = y this.hp = 1 this.cost = 0 this.defense = 0 } override fun occupy(p: Player) { this.owner = p this.hp = 5000 this.defense = 40 if (this.superior) this.income = 150 else this.income = 50 } override fun clicked(phase: Int): BooleanArray { options[5] = false return options } }
gpl-3.0
44e32ca0f264a71be9189997ac5290f1
17.333333
52
0.498182
3.691275
false
false
false
false
LordAkkarin/Beacon
github-api/src/main/kotlin/tv/dotstart/beacon/github/operations/RepositoryOperations.kt
1
3042
/* * Copyright 2020 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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 tv.dotstart.beacon.github.operations import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.Request import tv.dotstart.beacon.github.error.ServiceException import tv.dotstart.beacon.github.error.repository.NoSuchRepositoryException import tv.dotstart.beacon.github.model.repository.Release /** * Provides access to various repository related operations. * * @author [Johannes Donath](mailto:[email protected]) * @date 13/12/2020 */ class RepositoryOperations( client: OkHttpClient, objectMapper: ObjectMapper, urlFactory: HttpUrlFactory, /** * Identifies the owner of the target repository (such as a user or organization). */ val repositoryOwner: String, /** * Identifies the target repository. */ val repositoryName: String) : AbstractOperations(client, objectMapper, urlFactory) { private fun createUrl(block: HttpUrl.Builder.() -> Unit) = this.urlFactory { addEncodedPathSegment("repos") addPathSegment(repositoryOwner) addPathSegment(repositoryName) this.block() } /** * Retrieves a listing of releases for this repository. * * @throws NullPointerException when [page] is given but [resultsPerPage] remains unset. */ fun listReleases(resultsPerPage: Int? = null, page: Int? = null): List<Release> { if (page != null) { requireNotNull(resultsPerPage) } val url = this.createUrl { addEncodedPathSegment("releases") if (resultsPerPage != null) { addQueryParameter("per_page", resultsPerPage.toString()) } if (page != null) { addQueryParameter("page", page.toString()) } } val request = Request.Builder() .url(url) .build() return this.client.newCall(request).execute().use { response -> if (!response.isSuccessful && response.code != 404) { throw ServiceException( "Received illegal response code ${response.code} for request to repository $repositoryOwner/$repositoryName") } response.body ?.let { this.objectMapper.readValue<List<Release>>(it.string()) } ?: throw NoSuchRepositoryException(this.repositoryOwner, this.repositoryName) } } }
apache-2.0
e81c52604712af052e783c75a0aeccba
31.021053
121
0.702498
4.427948
false
false
false
false
pdvrieze/ProcessManager
PE-common/src/commonMain/kotlin/nl/adaptivity/process/processModel/PredecessorInfo.kt
1
2234
/* * 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.process.processModel import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import nl.adaptivity.process.processModel.engine.XmlCondition import nl.adaptivity.xmlutil.serialization.XmlElement import nl.adaptivity.xmlutil.serialization.XmlValue @Serializable class PredecessorInfo private constructor( @SerialName("predecessor") @XmlValue(true) val id: String, @SerialName("condition") @XmlElement(false) private val rawCondition: String? = null, @SerialName("label") @XmlElement(false) val conditionLabel: String? = null ) { val condition: Condition? get() = rawCondition?.let { XmlCondition(it, conditionLabel) } init { if (id.isEmpty()) throw IllegalArgumentException("Empty id's are not valid") } constructor(id: String, condition: Condition? = null) : this(id, condition?.condition, condition?.label) override fun toString(): String { return "PredecessorInfo(id='$id', condition=$condition)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is PredecessorInfo) return false if (id != other.id) return false if ((condition?: "") != (other.condition ?: "")) return false if ((conditionLabel != other.conditionLabel)) return false return true } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + (condition?.hashCode() ?: 0) return result } }
lgpl-3.0
38a2c4aee4291ffa3fe400612b788371
30.914286
112
0.695613
4.459082
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/NewPlayPlayerIsNewFragment.kt
1
5893
package com.boardgamegeek.ui import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isInvisible import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.boardgamegeek.R import com.boardgamegeek.databinding.FragmentNewPlayPlayerIsNewBinding import com.boardgamegeek.databinding.RowNewPlayPlayerIsNewBinding import com.boardgamegeek.entities.NewPlayPlayerEntity import com.boardgamegeek.extensions.* import com.boardgamegeek.ui.viewmodel.NewPlayViewModel import kotlin.properties.Delegates class NewPlayPlayerIsNewFragment : Fragment() { private var _binding: FragmentNewPlayPlayerIsNewBinding? = null private val binding get() = _binding!! private val viewModel by activityViewModels<NewPlayViewModel>() private val adapter: PlayersAdapter by lazy { PlayersAdapter(viewModel) } @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentNewPlayPlayerIsNewBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.recyclerView.adapter = adapter viewModel.mightBeNewPlayers.observe(viewLifecycleOwner) { entity -> adapter.players = entity.sortedBy { it.seat } } binding.nextButton.setOnClickListener { viewModel.finishPlayerIsNew() } } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onResume() { super.onResume() (activity as? AppCompatActivity)?.supportActionBar?.setSubtitle(R.string.title_new_players) } private class Diff(private val oldList: List<NewPlayPlayerEntity>, private val newList: List<NewPlayPlayerEntity>) : DiffUtil.Callback() { override fun getOldListSize() = oldList.size override fun getNewListSize() = newList.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition].id == newList[newItemPosition].id } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition].isNew == newList[newItemPosition].isNew } } private class PlayersAdapter(private val viewModel: NewPlayViewModel) : RecyclerView.Adapter<PlayersAdapter.PlayersViewHolder>() { var players: List<NewPlayPlayerEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue -> val diffCallback = Diff(oldValue, newValue) val diffResult = DiffUtil.calculateDiff(diffCallback) diffResult.dispatchUpdatesTo(this) } init { setHasStableIds(true) } override fun getItemCount() = players.size override fun getItemId(position: Int): Long { return players.getOrNull(position)?.id?.hashCode()?.toLong() ?: RecyclerView.NO_ID } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlayersViewHolder { return PlayersViewHolder(parent.inflate(R.layout.row_new_play_player_is_new)) } override fun onBindViewHolder(holder: PlayersViewHolder, position: Int) { holder.bind(position) } inner class PlayersViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val binding = RowNewPlayPlayerIsNewBinding.bind(itemView) fun bind(position: Int) { val entity = players.getOrNull(position) entity?.let { player -> binding.nameView.text = player.name binding.usernameView.setTextOrHide(player.username) if (player.color.isBlank()) { binding.colorView.isInvisible = true binding.teamView.isVisible = false binding.seatView.setTextColor(Color.TRANSPARENT.getTextColor()) } else { val color = player.color.asColorRgb() if (color == Color.TRANSPARENT) { binding.colorView.isInvisible = true binding.teamView.setTextOrHide(player.color) } else { binding.colorView.setColorViewValue(color) binding.colorView.isVisible = true binding.teamView.isVisible = false } binding.seatView.setTextColor(color.getTextColor()) } if (player.seat == null) { binding.sortView.setTextOrHide(player.sortOrder) binding.seatView.isInvisible = true } else { binding.sortView.isVisible = false binding.seatView.text = player.seat.toString() binding.seatView.isVisible = true } binding.isNewCheckBox.isChecked = player.isNew binding.isNewCheckBox.setOnCheckedChangeListener { _, isChecked -> viewModel.addIsNewToPlayer(player.id, isChecked) binding.isNewCheckBox.setOnCheckedChangeListener { _, _ -> } } } } } } }
gpl-3.0
205fe3f74d4778c8f3ff513eda4b7aca
39.641379
142
0.638385
5.451434
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/ClientVehicleControlsDecoder.kt
1
2272
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.codec.play import io.netty.util.AttributeKey import org.lanternpowered.server.network.buffer.ByteBuffer import org.lanternpowered.server.network.packet.BulkPacket import org.lanternpowered.server.network.packet.Packet import org.lanternpowered.server.network.packet.PacketDecoder import org.lanternpowered.server.network.packet.CodecContext import org.lanternpowered.server.network.vanilla.packet.type.play.ClientSneakStatePacket import org.lanternpowered.server.network.vanilla.packet.type.play.ClientVehicleJumpPacket import org.lanternpowered.server.network.vanilla.packet.type.play.ClientMovementInputPacket object ClientVehicleControlsDecoder : PacketDecoder<Packet> { override fun decode(ctx: CodecContext, buf: ByteBuffer): Packet { var sideways = buf.readFloat() var forwards = buf.readFloat() val flags = buf.readByte().toInt() val jump = flags and 0x1 != 0 val sneak = flags and 0x2 != 0 val packets = mutableListOf<Packet>() val lastSneak = ctx.session.attr(SNEAKING).getAndSet(sneak) ?: false if (lastSneak != sneak) packets += ClientSneakStatePacket(sneak) val lastJump = ctx.session.attr(JUMPING).getAndSet(jump) ?: false if (lastJump != jump && ctx.session.attr(ClientPlayerActionDecoder.CANCEL_NEXT_JUMP_MESSAGE).getAndSet(false) != true) packets += ClientVehicleJumpPacket(jump, 0f) // The mc client already applies the sneak speed, but we want to choose it if (sneak) { sideways /= 0.3f forwards /= 0.3f } packets += ClientMovementInputPacket(forwards, sideways) return if (packets.size == 1) packets[0] else BulkPacket(packets) } private val SNEAKING = AttributeKey.valueOf<Boolean>("last-sneaking-state") private val JUMPING = AttributeKey.valueOf<Boolean>("last-jumping-state") }
mit
3e5e823b6b5b85a93ad156f58ae5a5cc
43.54902
126
0.722711
4.078995
false
false
false
false
davidwhitman/changelogs
dataprovider/src/main/java/com/thunderclouddev/dataprovider/Mapper.kt
1
6049
/* * Copyright (c) 2017. * Distributed under the GNU GPLv3 by David Whitman. * https://www.gnu.org/licenses/gpl-3.0.en.html * * This source code is made available to help others learn. Please don't clone my app. */ package com.thunderclouddev.dataprovider import com.thunderclouddev.persistence.DbAppInfo import com.thunderclouddev.persistence.DbAppInfoEntity import com.thunderclouddev.playstoreapi.model.ApiAppInfo internal fun AppInfo.toDatabaseModel() = DbAppInfoEntity().apply { packageName = [email protected] versionCode = [email protected] title = [email protected] descriptionHtml = [email protected] shortDescription = [email protected] versionName = [email protected] rating = [email protected] bayesianMeanRating = [email protected] ratingsCount = [email protected] oneStarRatings = [email protected] twoStarRatings = [email protected] threeStarRatings = [email protected] fourStarRatings = [email protected] fiveStarRatings = [email protected] developerId = [email protected] developer = [email protected] developerEmail = [email protected] developerWebsite = [email protected] downloadsCount = [email protected] downloadsCountString = [email protected] installSizeBytes = [email protected] recentChangesHtml = [email protected] updateDate = [email protected] category = [email protected] links = com.thunderclouddev.persistence.Links([email protected] ?: emptyMap()) offer = com.thunderclouddev.persistence.Offer([email protected]?.micros, [email protected]?.currencyCode, [email protected]?.formattedAmount, [email protected]?.offerType) permissions = [email protected]?.map { com.thunderclouddev.persistence.Permission(it.name) } contentRating = [email protected] } internal fun DbAppInfo.toModel() = AppInfo( packageName = this.packageName, versionCode = this.versionCode, title = this.title, descriptionHtml = this.descriptionHtml, shortDescription = this.shortDescription, versionName = this.versionName, rating = this.rating, bayesianMeanRating = this.bayesianMeanRating, ratingsCount = this.ratingsCount, oneStarRatings = this.oneStarRatings, twoStarRatings = this.twoStarRatings, threeStarRatings = this.threeStarRatings, fourStarRatings = this.fourStarRatings, fiveStarRatings = this.fiveStarRatings, developerId = this.developerId, developer = this.developer, developerEmail = this.developerEmail, developerWebsite = this.developerWebsite, downloadsCount = this.downloadsCount, downloadsCountString = this.downloadsCountString, installSizeBytes = this.installSizeBytes, recentChangesHtml = this.recentChangesHtml, updateDate = this.updateDate, category = this.category, links = Links(this.links ?: emptyMap()), offer = Offer(this.offer?.micros, this.offer?.currencyCode, this.offer?.formattedAmount, this.offer?.offerType), permissions = this.permissions?.map { Permission(it.name) }, contentRating = this.contentRating) internal fun ApiAppInfo.toModel() = AppInfo( packageName = this.packageName, versionCode = this.versionCode, title = this.title, descriptionHtml = this.descriptionHtml, shortDescription = this.shortDescription, versionName = this.versionName, rating = this.rating, bayesianMeanRating = this.bayesianMeanRating, ratingsCount = this.ratingsCount, oneStarRatings = this.oneStarRatings, twoStarRatings = this.twoStarRatings, threeStarRatings = this.threeStarRatings, fourStarRatings = this.fourStarRatings, fiveStarRatings = this.fiveStarRatings, developerId = this.developerId, developer = this.developer, developerEmail = this.developerEmail, developerWebsite = this.developerWebsite, downloadsCount = this.downloadsCount, downloadsCountString = this.downloadsCountString, installSizeBytes = this.installSizeBytes, recentChangesHtml = this.recentChangesHtml, updateDate = this.updateDate, category = this.category, links = if (this.links != null) Links(this.links!!) else null, offer = Offer(micros = this.offer?.micros, currencyCode = this.offer?.currencyCode, formattedAmount = this.offer?.formattedAmount, offerType = this.offer?.offerType), permissions = this.permissions?.map(::Permission), contentRating = this.contentRating )
gpl-3.0
9371fda8d35bd923ffabcb0677d475db
50.709402
119
0.628699
5.524201
false
false
false
false
PaulWoitaschek/Voice
data/src/main/kotlin/voice/data/repo/internals/migrations/Migration44.kt
1
1741
package voice.data.repo.internals.migrations import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.squareup.anvil.annotations.ContributesMultibinding import voice.common.AppScope import voice.data.repo.internals.getString import javax.inject.Inject @ContributesMultibinding( scope = AppScope::class, boundType = Migration::class, ) class Migration44 @Inject constructor() : IncrementalMigration(44) { override fun migrate(db: SupportSQLiteDatabase) { db.query("SELECT * FROM bookSettings").use { bookSettingsCursor -> while (bookSettingsCursor.moveToNext()) { val bookId = bookSettingsCursor.getString("id") val currentFile = bookSettingsCursor.getString("currentFile") db.query("SELECT * FROM chapters WHERE bookId =?", arrayOf(bookId)).use { chapterCursor -> var chapterForCurrentFileFound = false while (!chapterForCurrentFileFound && chapterCursor.moveToNext()) { val chapterFile = chapterCursor.getString("file") if (chapterFile == currentFile) { chapterForCurrentFileFound = true } } if (!chapterForCurrentFileFound) { if (chapterCursor.moveToFirst()) { val firstChapterFile = chapterCursor.getString("file") val contentValues = ContentValues().apply { put("currentFile", firstChapterFile) put("positionInChapter", 0) } db.update("bookSettings", SQLiteDatabase.CONFLICT_FAIL, contentValues, "id =?", arrayOf(bookId)) } } } } } } }
gpl-3.0
ec0bef3632c4b3f89a20e220e7138127
36.847826
110
0.672602
4.960114
false
false
false
false
danrien/projectBlueWater
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/library/access/LibraryRemoval.kt
2
1487
package com.lasthopesoftware.bluewater.client.browsing.library.access import com.lasthopesoftware.bluewater.client.browsing.library.access.session.ProvideSelectedLibraryId import com.lasthopesoftware.bluewater.client.browsing.library.access.session.SelectBrowserLibrary import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.stored.library.items.IStoredItemAccess import com.namehillsoftware.handoff.promises.Promise class LibraryRemoval( private val storedItems: IStoredItemAccess, private val libraryStorage: ILibraryStorage, private val selectedLibraryIdProvider: ProvideSelectedLibraryId, private val libraryProvider: ILibraryProvider, private val librarySelection: SelectBrowserLibrary) : RemoveLibraries { override fun removeLibrary(library: Library): Promise<*> { val promisedNewLibrarySelection = selectedLibraryIdProvider.selectedLibraryId .eventually { if (library.libraryId != it) Promise.empty() else libraryProvider.allLibraries.eventually { libraries -> val firstOtherLibrary = libraries.firstOrNull { l -> l.libraryId != library.libraryId } if (firstOtherLibrary != null) librarySelection.selectBrowserLibrary(firstOtherLibrary.libraryId) else Promise.empty() } } return promisedNewLibrarySelection.eventually { Promise.whenAll( storedItems.disableAllLibraryItems(library.libraryId), libraryStorage.removeLibrary(library)) } } }
lgpl-3.0
f6f2576c11274fc0b628aac5b4fa06cb
42.735294
103
0.813719
4.547401
false
false
false
false
Chimerapps/moshi-generator
moshi-generator/src/main/kotlin/com/chimerapps/moshigenerator/SimpleLogger.kt
1
987
package com.chimerapps.moshigenerator import java.io.PrintWriter import java.io.StringWriter import javax.annotation.processing.Messager import javax.tools.Diagnostic /** * @author Nicola Verbeeck * Date 26/05/2017. */ class SimpleLogger(val messager: Messager) { fun logInfo(message: String, error: Throwable? = null) { messager.printMessage(Diagnostic.Kind.NOTE, makeMessage(message, error)) } fun logError(message: String, error: Throwable? = null) { messager.printMessage(Diagnostic.Kind.WARNING, makeMessage(message, error)) } companion object { private fun makeMessage(message: String, error: Throwable?): String { if (error == null) return message val stringWriter = StringWriter() PrintWriter(stringWriter).use { it.println(message) error.printStackTrace(it) } return stringWriter.buffer.toString() } } }
apache-2.0
49e468f9c16bb4e48bfc78fe430ab21a
25.702703
83
0.646403
4.486364
false
false
false
false