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
dahlstrom-g/intellij-community
uast/uast-common/src/org/jetbrains/uast/declarations/UClass.kt
8
3431
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast import com.intellij.psi.PsiAnonymousClass import com.intellij.psi.PsiClass import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.internal.acceptList import org.jetbrains.uast.internal.convertOrReport import org.jetbrains.uast.internal.log import org.jetbrains.uast.visitor.UastTypedVisitor import org.jetbrains.uast.visitor.UastVisitor /** * A class wrapper to be used in [UastVisitor]. */ interface UClass : UDeclaration, PsiClass { @get:ApiStatus.ScheduledForRemoval @get:Deprecated("see the base property description") @Deprecated("see the base property description", ReplaceWith("javaPsi")) override val psi: PsiClass override val javaPsi: PsiClass override fun getQualifiedName(): String? override fun isInterface(): Boolean override fun isAnnotationType(): Boolean /** * Returns a [UClass] wrapper of the superclass of this class, or null if this class is [java.lang.Object]. */ @Deprecated("will return null if existing superclass is not convertable to Uast, use `javaPsi.superClass` instead", ReplaceWith("javaPsi.superClass")) override fun getSuperClass(): UClass? { val superClass = javaPsi.superClass ?: return null return UastFacade.convertWithParent(superClass) } val uastSuperTypes: List<UTypeReferenceExpression> /** * Returns [UDeclaration] wrappers for the class declarations. */ val uastDeclarations: List<UDeclaration> override fun getFields(): Array<UField> = javaPsi.fields.mapNotNull { convertOrReport<UField>(it, this) }.toTypedArray() override fun getInitializers(): Array<UClassInitializer> = javaPsi.initializers.mapNotNull { convertOrReport<UClassInitializer>(it, this) }.toTypedArray() override fun getMethods(): Array<UMethod> = javaPsi.methods.mapNotNull { convertOrReport<UMethod>(it, this) }.toTypedArray() override fun getInnerClasses(): Array<UClass> = javaPsi.innerClasses.mapNotNull { convertOrReport<UClass>(it, this) }.toTypedArray() override fun asLogString(): String = log("name = $name") override fun accept(visitor: UastVisitor) { if (visitor.visitClass(this)) return uAnnotations.acceptList(visitor) uastDeclarations.acceptList(visitor) visitor.afterVisitClass(this) } override fun asRenderString(): String = buildString { append(javaPsi.renderModifiers()) val kind = when { javaPsi.isAnnotationType -> "annotation" javaPsi.isInterface -> "interface" javaPsi.isEnum -> "enum" else -> "class" } append(kind).append(' ').append(javaPsi.name) val superTypes = uastSuperTypes if (superTypes.isNotEmpty()) { append(" : ") append(superTypes.joinToString { it.asRenderString() }) } appendln(" {") uastDeclarations.forEachIndexed { _, declaration -> appendln(declaration.asRenderString().withMargin) } append("}") } override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitClass(this, data) } interface UAnonymousClass : UClass, PsiAnonymousClass { @get:ApiStatus.ScheduledForRemoval @get:Deprecated("see the base property description") @Deprecated("see the base property description", ReplaceWith("javaPsi")) override val psi: PsiAnonymousClass }
apache-2.0
bf2f7fc03fd301fb3e16b311e3c7c921
33.656566
140
0.733605
4.668027
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/android/lint/javaPerformance.kt
13
7943
// INSPECTION_CLASS: com.android.tools.idea.lint.AndroidLintDrawAllocationInspection // INSPECTION_CLASS2: com.android.tools.idea.lint.AndroidLintUseSparseArraysInspection // INSPECTION_CLASS3: com.android.tools.idea.lint.AndroidLintUseValueOfInspection import android.annotation.SuppressLint import java.util.HashMap import android.content.Context import android.graphics.* import android.util.AttributeSet import android.util.SparseArray import android.widget.Button @SuppressWarnings("unused") @Suppress("UsePropertyAccessSyntax", "UNUSED_VARIABLE", "unused", "UNUSED_PARAMETER", "DEPRECATION", "UNNECESSARY_NOT_NULL_ASSERTION", "NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") class JavaPerformanceTest(context: Context, attrs: AttributeSet, defStyle: Int) : Button(context, attrs, defStyle) { private var cachedRect: Rect? = null private var shader: LinearGradient? = null private var lastHeight: Int = 0 private var lastWidth: Int = 0 override fun onDraw(canvas: android.graphics.Canvas) { super.onDraw(canvas) // Various allocations: <warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">java.lang.String("foo")</warning> val s = <warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">java.lang.String("bar")</warning> // This one should not be reported: @SuppressLint("DrawAllocation") val i = 5 // Cached object initialized lazily: should not complain about these if (cachedRect == null) { cachedRect = Rect(0, 0, 100, 100) } if (cachedRect == null || cachedRect!!.width() != 50) { cachedRect = Rect(0, 0, 50, 100) } val b = java.lang.Boolean.valueOf(true)!! // auto-boxing dummy(1, 2) // Non-allocations super.animate() dummy2(1, 2) // This will involve allocations, but we don't track // inter-procedural stuff here someOtherMethod() } internal fun dummy(foo: Int?, bar: Int) { dummy2(foo!!, bar) } internal fun dummy2(foo: Int, bar: Int) { } internal fun someOtherMethod() { // Allocations are okay here java.lang.String("foo") val s = java.lang.String("bar") val b = java.lang.Boolean.valueOf(true)!! // auto-boxing // Sparse array candidates val myMap = <warning descr="Use `new SparseArray<String>(...)` instead for better performance">HashMap<Int, String>()</warning> // Should use SparseBooleanArray val myBoolMap = <warning descr="Use `new SparseBooleanArray(...)` instead for better performance">HashMap<Int, Boolean>()</warning> // Should use SparseIntArray val myIntMap = <warning descr="Use new `SparseIntArray(...)` instead for better performance">java.util.HashMap<Int, Int>()</warning> // This one should not be reported: @SuppressLint("UseSparseArrays") val myOtherMap = HashMap<Int, Any>() } protected fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int, x: Boolean) { // wrong signature java.lang.String("not an error") } protected fun onMeasure(widthMeasureSpec: Int) { // wrong signature java.lang.String("not an error") } protected fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int, wrong: Int) { // wrong signature java.lang.String("not an error") } protected fun onLayout(changed: Boolean, left: Int, top: Int, right: Int) { // wrong signature java.lang.String("not an error") } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { <warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">java.lang.String("flag me")</warning> } @SuppressWarnings("null") // not real code override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { <warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">java.lang.String("flag me")</warning> // Forbidden factory methods: <warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">Bitmap.createBitmap(100, 100, null)</warning> <warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">android.graphics.Bitmap.createScaledBitmap(null, 100, 100, false)</warning> <warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">BitmapFactory.decodeFile(null)</warning> val canvas: Canvas? = null <warning descr="Avoid object allocations during draw operations: Use `Canvas.getClipBounds(Rect)` instead of `Canvas.getClipBounds()` which allocates a temporary `Rect`">canvas!!.getClipBounds()</warning> // allocates on your behalf canvas.clipBounds // allocates on your behalf canvas.getClipBounds(null) // NOT an error val layoutWidth = width val layoutHeight = height if (mAllowCrop && (mOverlay == null || mOverlay!!.width != layoutWidth || mOverlay!!.height != layoutHeight)) { mOverlay = Bitmap.createBitmap(layoutWidth, layoutHeight, Bitmap.Config.ARGB_8888) mOverlayCanvas = Canvas(mOverlay!!) } if (widthMeasureSpec == 42) { throw IllegalStateException("Test") // NOT an allocation } // More lazy init tests var initialized = false if (!initialized) { java.lang.String("foo") initialized = true } // NOT lazy initialization if (!initialized || mOverlay == null) { <warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">java.lang.String("foo")</warning> } } internal fun factories() { val i1 = 42 val l1 = 42L val b1 = true val c1 = 'c' val f1 = 1.0f val d1 = 1.0 // The following should not generate errors: val i3 = Integer.valueOf(42) } private val mAllowCrop: Boolean = false private var mOverlayCanvas: Canvas? = null private var mOverlay: Bitmap? = null override fun layout(l: Int, t: Int, r: Int, b: Int) { // Using "this." to reference fields if (this.shader == null) this.shader = LinearGradient(0f, 0f, width.toFloat(), 0f, intArrayOf(0), null, Shader.TileMode.REPEAT) val width = width val height = height if (shader == null || lastWidth != width || lastHeight != height) { lastWidth = width lastHeight = height shader = LinearGradient(0f, 0f, width.toFloat(), 0f, intArrayOf(0), null, Shader.TileMode.REPEAT) } } fun inefficientSparseArray() { <warning descr="Use `new SparseIntArray(...)` instead for better performance">SparseArray<Int>()</warning> // Use SparseIntArray instead SparseArray<Long>() // Use SparseLongArray instead <warning descr="Use `new SparseBooleanArray(...)` instead for better performance">SparseArray<Boolean>()</warning> // Use SparseBooleanArray instead SparseArray<Any>() // OK } fun longSparseArray() { // but only minSdkVersion >= 17 or if has v4 support lib val myStringMap = HashMap<Long, String>() } fun byteSparseArray() { // bytes easily apply to ints val myByteMap = <warning descr="Use `new SparseArray<String>(...)` instead for better performance">HashMap<Byte, String>()</warning> } }
apache-2.0
776435541425365effd60b1bb7d1c24c
40.15544
240
0.64283
4.658651
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/base/ThrowException.kt
1
2349
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores.base import com.github.jonathanxd.kores.Instruction /** * Throws [value]. */ data class ThrowException(override val value: Instruction) : Instruction, ValueHolder { override fun builder(): Builder = Builder(this) class Builder() : ValueHolder.Builder<ThrowException, Builder> { lateinit var value: Instruction constructor(defaults: ThrowException) : this() { this.value = defaults.value } override fun value(value: Instruction): Builder { this.value = value return this } override fun build(): ThrowException = ThrowException(this.value) companion object { @JvmStatic fun builder(): Builder = Builder() @JvmStatic fun builder(defaults: ThrowException): Builder = Builder(defaults) } } }
mit
773ac5942b6f40bf62e887bf577097e8
36.285714
118
0.675181
4.726358
false
false
false
false
paplorinc/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiContentHelper.kt
2
2052
// 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.google.gson.* import com.google.gson.reflect.TypeToken import org.jetbrains.io.mandatory.NullCheckingFactory import org.jetbrains.plugins.github.exceptions.GithubJsonException import java.awt.Image import java.io.IOException import java.io.InputStream import java.io.Reader import javax.imageio.ImageIO object GithubApiContentHelper { const val JSON_MIME_TYPE = "application/json" const val V3_JSON_MIME_TYPE = "application/vnd.github.v3+json" const val V3_HTML_JSON_MIME_TYPE = "application/vnd.github.v3.html+json" val gson: Gson = GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .registerTypeAdapterFactory(NullCheckingFactory.INSTANCE) .create() @Throws(GithubJsonException::class) inline fun <reified T> fromJson(string: String): T = fromJson(string, T::class.java) @JvmStatic @Throws(GithubJsonException::class) fun <T> fromJson(string: String, clazz: Class<T>): T { try { return gson.fromJson(string, TypeToken.get(clazz).type) } catch (e: JsonParseException) { throw GithubJsonException("Can't parse GitHub response", e) } } @JvmStatic @Throws(GithubJsonException::class) fun <T> readJson(reader: Reader, typeToken: TypeToken<T>): T { try { return gson.fromJson(reader, typeToken.type) } catch (e: JsonParseException) { throw GithubJsonException("Can't parse GitHub response", e) } } @JvmStatic @Throws(GithubJsonException::class) fun toJson(content: Any): String { try { return gson.toJson(content) } catch (e: JsonIOException) { throw GithubJsonException("Can't serialize GitHub request body", e) } } @JvmStatic @Throws(IOException::class) fun loadImage(stream: InputStream): Image { return ImageIO.read(stream) } }
apache-2.0
ac8fa240e5f045b91fadd711ff39d971
30.106061
140
0.724172
3.879017
false
false
false
false
google/intellij-community
xml/impl/src/com/intellij/codeInsight/daemon/impl/tagTreeHighlighting/XmlTagTreeHighlightingConfigurable.kt
6
3147
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.daemon.impl.tagTreeHighlighting import com.intellij.application.options.editor.WebEditorOptions import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.options.UiDslUnnamedConfigurable import com.intellij.openapi.project.ProjectManager import com.intellij.ui.components.JBCheckBox import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.xml.XmlBundle import com.intellij.xml.breadcrumbs.BreadcrumbsPanel class XmlTagTreeHighlightingConfigurable : UiDslUnnamedConfigurable.Simple() { override fun Panel.createContent() { val options = WebEditorOptions.getInstance() lateinit var enable: Cell<JBCheckBox> panel { row { enable = checkBox(XmlBundle.message("settings.enable.html.xml.tag.tree.highlighting")) .bindSelected(options::isTagTreeHighlightingEnabled, options::setTagTreeHighlightingEnabled) .onApply { clearTagTreeHighlighting() } } indent { row(XmlBundle.message("settings.levels.to.highlight")) { spinner(1..50) .bindIntValue({ options.tagTreeHighlightingLevelCount }, { options.tagTreeHighlightingLevelCount = it }) .onApply { clearTagTreeHighlighting() } .horizontalAlign(HorizontalAlign.FILL) cell() }.layout(RowLayout.PARENT_GRID) row(XmlBundle.message("settings.opacity")) { spinner(0.0..1.0, step = 0.05) .bind({ ((it.value as Double) * 100).toInt() }, { it, value -> it.value = value * 0.01 }, MutableProperty(options::getTagTreeHighlightingOpacity, options::setTagTreeHighlightingOpacity)) .onApply { clearTagTreeHighlighting() } .horizontalAlign(HorizontalAlign.FILL) cell() }.layout(RowLayout.PARENT_GRID) .bottomGap(BottomGap.SMALL) }.enabledIf(enable.selected) } } companion object { private fun clearTagTreeHighlighting() { for (project in ProjectManager.getInstance().openProjects) { for (fileEditor in FileEditorManager.getInstance(project).allEditors) { if (fileEditor is TextEditor) { val editor = fileEditor.editor XmlTagTreeHighlightingPass.clearHighlightingAndLineMarkers(editor, project) val breadcrumbs = BreadcrumbsPanel.getBreadcrumbsComponent(editor) breadcrumbs?.queueUpdate() } } } } } }
apache-2.0
d3a81ff9a9d2d832ce7ad9811e602343
40.96
116
0.708611
4.746606
false
false
false
false
algra/pact-jvm
pact-jvm-consumer/src/main/kotlin/au/com/dius/pact/consumer/MockHttpServer.kt
1
8755
package au.com.dius.pact.consumer import au.com.dius.pact.model.FullRequestMatch import au.com.dius.pact.model.MockHttpsProviderConfig import au.com.dius.pact.model.MockProviderConfig import au.com.dius.pact.model.OptionalBody import au.com.dius.pact.model.PactReader import au.com.dius.pact.model.PactSpecVersion import au.com.dius.pact.model.PartialRequestMatch import au.com.dius.pact.model.Request import au.com.dius.pact.model.RequestMatching import au.com.dius.pact.model.RequestResponseInteraction import au.com.dius.pact.model.RequestResponsePact import au.com.dius.pact.model.Response import com.sun.net.httpserver.HttpExchange import com.sun.net.httpserver.HttpHandler import com.sun.net.httpserver.HttpServer import com.sun.net.httpserver.HttpsServer import mu.KLogging import org.apache.commons.lang3.StringEscapeUtils import org.apache.http.client.methods.HttpOptions import org.apache.http.entity.ContentType import org.apache.http.impl.client.HttpClients import org.apache.http.impl.conn.BasicHttpClientConnectionManager import scala.collection.JavaConversions import java.lang.Thread.sleep import java.nio.charset.Charset import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentLinkedQueue /** * Returns a mock server for the pact and config */ fun mockServer(pact: RequestResponsePact, config: MockProviderConfig): MockServer { return when (config) { is MockHttpsProviderConfig -> MockHttpsServer(pact, config) else -> MockHttpServer(pact, config) } } interface MockServer { /** * Returns the URL for this mock server. The port will be the one bound by the server. */ fun getUrl(): String /** * Returns the port of the mock server. This will be the port the server is bound to. */ fun getPort(): Int /** * This will start the mock server and execute the test function. Returns the result of running the test. */ fun runAndWritePact(pact: RequestResponsePact, pactVersion: PactSpecVersion, testFn: PactTestRun): PactVerificationResult /** * Returns the results of validating the mock server state */ fun validateMockServerState(): PactVerificationResult } abstract class BaseMockServer( val pact: RequestResponsePact, val config: MockProviderConfig, private val server: HttpServer, private var stopped: Boolean = false ) : HttpHandler, MockServer { private val mismatchedRequests = ConcurrentHashMap<Request, MutableList<PactVerificationResult>>() private val matchedRequests = ConcurrentLinkedQueue<Request>() private val requestMatcher = RequestMatching.apply(JavaConversions.asScalaBuffer(pact.interactions).toSeq()) override fun handle(exchange: HttpExchange) { if (exchange.requestMethod == "OPTIONS" && exchange.requestHeaders.containsKey("X-PACT-BOOTCHECK")) { exchange.responseHeaders.add("X-PACT-BOOTCHECK", "true") exchange.sendResponseHeaders(200, 0) exchange.close() } else { try { val request = toPactRequest(exchange) logger.debug { "Received request: $request" } val response = generatePactResponse(request) logger.debug { "Generating response: $response" } pactResponseToHttpExchange(response, exchange) } catch (e: Exception) { logger.error(e) { "Failed to generate response" } pactResponseToHttpExchange(Response(500, mutableMapOf("Content-Type" to "application/json"), OptionalBody.body("{\"error\": ${e.message}}")), exchange) } } } private fun pactResponseToHttpExchange(response: Response, exchange: HttpExchange) { val headers = response.headers if (headers != null) { exchange.responseHeaders.putAll(headers.mapValues { listOf(it.value) }) } val body = response.body if (body != null && body.isPresent()) { val bytes = body.unwrap().toByteArray() exchange.sendResponseHeaders(response.status, bytes.size.toLong()) exchange.responseBody.write(bytes) } else { exchange.sendResponseHeaders(response.status, 0) } exchange.close() } private fun generatePactResponse(request: Request): Response { val matchResult = requestMatcher.matchInteraction(request) when (matchResult) { is FullRequestMatch -> { val interaction = matchResult.interaction() as RequestResponseInteraction matchedRequests.add(interaction.request) return interaction.response.generatedResponse() } is PartialRequestMatch -> { val interaction = matchResult.problems().keys().head() as RequestResponseInteraction mismatchedRequests.putIfAbsent(interaction.request, mutableListOf()) mismatchedRequests[interaction.request]?.add(PactVerificationResult.PartialMismatch( ScalaCollectionUtils.toList(matchResult.problems()[interaction]))) } else -> { mismatchedRequests.putIfAbsent(request, mutableListOf()) mismatchedRequests[request]?.add(PactVerificationResult.UnexpectedRequest(request)) } } return invalidResponse(request) } private fun invalidResponse(request: Request) = Response(500, mapOf("Access-Control-Allow-Origin" to "*", "Content-Type" to "application/json", "X-Pact-Unexpected-Request" to "1"), OptionalBody.body("{ \"error\": \"Unexpected request : " + StringEscapeUtils.escapeJson(request.toString()) + "\" }")) private fun toPactRequest(exchange: HttpExchange): Request { val headers = exchange.requestHeaders.mapValues { it.value.joinToString(", ") } val bodyContents = exchange.requestBody.bufferedReader(calculateCharset(headers)).readText() val body = if (bodyContents.isNullOrEmpty()) { OptionalBody.empty() } else { OptionalBody.body(bodyContents) } return Request(exchange.requestMethod, exchange.requestURI.path, PactReader.queryStringToMap(exchange.requestURI.rawQuery), headers, body) } private fun initServer() { server.createContext("/", this) } fun start() = server.start() fun stop() { if (!stopped) { stopped = true server.stop(0) } } init { initServer() } override fun runAndWritePact(pact: RequestResponsePact, pactVersion: PactSpecVersion, testFn: PactTestRun): PactVerificationResult { start() waitForServer() try { testFn.run(this) sleep(100) // give the mock server some time to have consistent state } catch (e: Throwable) { return PactVerificationResult.Error(e, validateMockServerState()) } finally { stop() } val result = validateMockServerState() if (result is PactVerificationResult.Ok) { val pactDirectory = pactDirectory() logger.debug { "Writing pact ${pact.consumer.name} -> ${pact.provider.name} to file " + "${pact.fileForPact(pactDirectory)}" } pact.write(pactDirectory, pactVersion) } return result } override fun validateMockServerState(): PactVerificationResult { if (mismatchedRequests.isNotEmpty()) { return PactVerificationResult.Mismatches(mismatchedRequests.values.flatten()) } val expectedRequests = pact.interactions.map { it.request }.filter { !matchedRequests.contains(it) } if (expectedRequests.isNotEmpty()) { return PactVerificationResult.ExpectedButNotReceived(expectedRequests) } return PactVerificationResult.Ok } fun waitForServer() { val httpclient = HttpClients.createMinimal(BasicHttpClientConnectionManager()) val httpOptions = HttpOptions(getUrl()) httpOptions.addHeader("X-PACT-BOOTCHECK", "true") httpclient.execute(httpOptions).close() } override fun getUrl(): String { return if (config.port == 0) { "${config.scheme}://${server.address.hostName}:${server.address.port}" } else { config.url() } } override fun getPort(): Int = server.address.port companion object : KLogging() } open class MockHttpServer(pact: RequestResponsePact, config: MockProviderConfig) : BaseMockServer(pact, config, HttpServer.create(config.address(), 0)) open class MockHttpsServer(pact: RequestResponsePact, config: MockProviderConfig) : BaseMockServer(pact, config, HttpsServer.create(config.address(), 0)) fun calculateCharset(headers: Map<String, String>): Charset { val contentType = headers.entries.find { it.key.toUpperCase() == "CONTENT-TYPE" } val default = Charset.forName("UTF-8") if (contentType != null) { try { return ContentType.parse(contentType.value)?.charset ?: default } catch (e: Exception) { BaseMockServer.Companion.logger.debug(e) { "Failed to parse the charset from the content type header" } } } return default } fun pactDirectory() = System.getProperty("pact.rootDir", "target/pacts")!!
apache-2.0
406a6849a7c315816b9557acf90ffe05
35.479167
110
0.722559
4.423951
false
true
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceCallFix.kt
1
5139
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.intentions.canBeReplacedWithInvokeCall 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.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getImplicitReceiverValue import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode object ReplaceWithSafeCallFixFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val psiElement = diagnostic.psiElement val qualifiedExpression = psiElement.parent as? KtDotQualifiedExpression if (qualifiedExpression != null) { val call = qualifiedExpression.callExpression if (call != null) { val context = qualifiedExpression.analyze(BodyResolveMode.PARTIAL) val psiFactory = KtPsiFactory(psiElement.project) val safeQualifiedExpression = psiFactory.createExpressionByPattern( "$0?.$1", qualifiedExpression.receiverExpression, call, reformat = false ) val newContext = safeQualifiedExpression.analyzeAsReplacement(qualifiedExpression, context) if (safeQualifiedExpression.getResolvedCall(newContext)?.canBeReplacedWithInvokeCall() == true) { return ReplaceInfixOrOperatorCallFix(call, call.shouldHaveNotNullType()) } } return ReplaceWithSafeCallFix(qualifiedExpression, qualifiedExpression.shouldHaveNotNullType()) } else { if (psiElement !is KtNameReferenceExpression) return null if (psiElement.getResolvedCall(psiElement.analyze())?.getImplicitReceiverValue() != null) { val expressionToReplace: KtExpression = psiElement.parent as? KtCallExpression ?: psiElement return ReplaceImplicitReceiverCallFix(expressionToReplace, expressionToReplace.shouldHaveNotNullType()) } return null } } } object ReplaceWithSafeCallForScopeFunctionFixFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val element = diagnostic.psiElement val scopeFunctionLiteral = element.getStrictParentOfType<KtFunctionLiteral>() ?: return null val scopeCallExpression = scopeFunctionLiteral.getStrictParentOfType<KtCallExpression>() ?: return null val scopeDotQualifiedExpression = scopeCallExpression.getStrictParentOfType<KtDotQualifiedExpression>() ?: return null val context = scopeCallExpression.analyze() val scopeFunctionLiteralDescriptor = context[BindingContext.FUNCTION, scopeFunctionLiteral] ?: return null val scopeFunctionKind = scopeCallExpression.scopeFunctionKind(context) ?: return null val internalReceiver = (element.parent as? KtDotQualifiedExpression)?.receiverExpression val internalReceiverDescriptor = internalReceiver.getResolvedCall(context)?.candidateDescriptor val internalResolvedCall = (element.getParentOfType<KtElement>(strict = false))?.getResolvedCall(context) ?: return null when (scopeFunctionKind) { ScopeFunctionKind.WITH_PARAMETER -> { if (internalReceiverDescriptor != scopeFunctionLiteralDescriptor.valueParameters.singleOrNull()) { return null } } ScopeFunctionKind.WITH_RECEIVER -> { if (internalReceiverDescriptor != scopeFunctionLiteralDescriptor.extensionReceiverParameter && internalResolvedCall.getImplicitReceiverValue() == null ) { return null } } } return ReplaceWithSafeCallForScopeFunctionFix( scopeDotQualifiedExpression, scopeDotQualifiedExpression.shouldHaveNotNullType() ) } private fun KtCallExpression.scopeFunctionKind(context: BindingContext): ScopeFunctionKind? { val methodName = getResolvedCall(context)?.resultingDescriptor?.fqNameUnsafe?.asString() return ScopeFunctionKind.values().firstOrNull { kind -> kind.names.contains(methodName) } } private enum class ScopeFunctionKind(vararg val names: String) { WITH_PARAMETER("kotlin.let", "kotlin.also"), WITH_RECEIVER("kotlin.apply", "kotlin.run") } }
apache-2.0
1d787e2a569021a528c66038c2c2c843
52.53125
158
0.721152
6.147129
false
false
false
false
SimpleMobileTools/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/extensions/ExifInterface.kt
2
1951
package com.simplemobiletools.gallery.pro.extensions import androidx.exifinterface.media.ExifInterface import java.lang.reflect.Field import java.lang.reflect.Modifier fun ExifInterface.copyNonDimensionAttributesTo(destination: ExifInterface) { val attributes = ExifInterfaceAttributes.AllNonDimensionAttributes attributes.forEach { val value = getAttribute(it) if (value != null) { destination.setAttribute(it, value) } } try { destination.saveAttributes() } catch (ignored: Exception) { } } private class ExifInterfaceAttributes { companion object { val AllNonDimensionAttributes = getAllNonDimensionExifAttributes() private fun getAllNonDimensionExifAttributes(): List<String> { val tagFields = ExifInterface::class.java.fields.filter { field -> isExif(field) } val excludeAttributes = arrayListOf( ExifInterface.TAG_IMAGE_LENGTH, ExifInterface.TAG_IMAGE_WIDTH, ExifInterface.TAG_PIXEL_X_DIMENSION, ExifInterface.TAG_PIXEL_Y_DIMENSION, ExifInterface.TAG_THUMBNAIL_IMAGE_LENGTH, ExifInterface.TAG_THUMBNAIL_IMAGE_WIDTH, ExifInterface.TAG_ORIENTATION) return tagFields .map { tagField -> tagField.get(null) as String } .filter { x -> !excludeAttributes.contains(x) } .distinct() } private fun isExif(field: Field): Boolean { return field.type == String::class.java && isPublicStaticFinal(field.modifiers) && field.name.startsWith("TAG_") } private const val publicStaticFinal = Modifier.PUBLIC or Modifier.STATIC or Modifier.FINAL private fun isPublicStaticFinal(modifiers: Int): Boolean { return modifiers and publicStaticFinal > 0 } } }
gpl-3.0
9456b8aa51b202bfd461882b07070993
33.22807
98
0.636597
5.054404
false
false
false
false
google/iosched
shared/src/main/java/com/google/samples/apps/iosched/shared/domain/sessions/LoadPinnedSessionsJsonUseCase.kt
3
4188
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.shared.domain.sessions import com.google.gson.Gson import com.google.samples.apps.iosched.model.schedule.PinnedSession import com.google.samples.apps.iosched.model.schedule.PinnedSessionsSchedule import com.google.samples.apps.iosched.model.userdata.UserSession import com.google.samples.apps.iosched.shared.data.userevent.DefaultSessionAndUserEventRepository import com.google.samples.apps.iosched.shared.data.userevent.ObservableUserEvents import com.google.samples.apps.iosched.shared.di.IoDispatcher import com.google.samples.apps.iosched.shared.domain.FlowUseCase import com.google.samples.apps.iosched.shared.result.Result import com.google.samples.apps.iosched.shared.util.TimeUtils import com.google.samples.apps.iosched.shared.util.toEpochMilli import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import javax.inject.Inject /** * Load a list of pinned (starred or reserved) [UserSession]s for a given user as a json format. * * Example JSON is structured as * * { schedule : [ * { * "name": "session1", * "location": "Room 1", * "day": "5/07", * "time": "13:30", * "timestamp": 82547983, * "description": "Session description1" * }, * { * "name": "session2", * "location": "Room 2", * "day": "5/08", * "time": "13:30", * "timestamp": 19238489, * "description": "Session description2" * }, ..... * ] * } */ open class LoadPinnedSessionsJsonUseCase @Inject constructor( private val userEventRepository: DefaultSessionAndUserEventRepository, private val gson: Gson, @IoDispatcher private val ioDispatcher: CoroutineDispatcher ) : FlowUseCase<String, String>(ioDispatcher) { override fun execute(parameters: String): Flow<Result<String>> { return userEventRepository.getObservableUserEvents(parameters) .map { observableResult: Result<ObservableUserEvents> -> when (observableResult) { is Result.Success -> { val useCaseResult = observableResult.data.userSessions.filter { it.userEvent.isStarredOrReserved() }.map { val session = it.session // We assume the conference time zone because only on-site attendees are // going to use the feature val zonedTime = TimeUtils.zonedTime( session.startTime, TimeUtils.CONFERENCE_TIMEZONE ) PinnedSession( name = session.title, location = session.room?.name ?: "", day = TimeUtils.abbreviatedDayForAr(zonedTime), time = TimeUtils.abbreviatedTimeForAr(zonedTime), timestamp = session.startTime.toEpochMilli(), description = session.description ) } val jsonResult = gson.toJson(PinnedSessionsSchedule(useCaseResult)) Result.Success(jsonResult) } is Result.Error -> Result.Error(observableResult.exception) is Result.Loading -> observableResult } } } }
apache-2.0
bd8028ff9430c3b28bfd8355473ade68
41.30303
100
0.611748
4.808266
false
false
false
false
skedgo/DateTimeRangePicker
src/main/java/skedgo/datetimerangepicker/DateTimeRangePickerActivity.kt
1
3314
package skedgo.datetimerangepicker import android.app.Activity import android.app.TimePickerDialog import android.content.Context import android.content.Intent import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.text.format.DateFormat import com.squareup.timessquare.CalendarPickerView import org.joda.time.DateTime import skedgo.datetimerangepicker.databinding.DateTimeRangePickerBinding import java.util.* class DateTimeRangePickerActivity : AppCompatActivity() { companion object { fun newIntent( context: Context?, timeZone: TimeZone?, startTimeInMillis: Long?, endTimeInMillis: Long?): Intent { val intent = Intent(context!!, DateTimeRangePickerActivity::class.java) startTimeInMillis?.let { intent.putExtra(DateTimeRangePickerViewModel.KEY_START_TIME_IN_MILLIS, it) } endTimeInMillis?.let { intent.putExtra(DateTimeRangePickerViewModel.KEY_END_TIME_IN_MILLIS, it) } intent.putExtra(DateTimeRangePickerViewModel.KEY_TIME_ZONE, timeZone!!.id) return intent } } private val viewModel: DateTimeRangePickerViewModel by lazy { DateTimeRangePickerViewModel(TimeFormatter(applicationContext)) } private val binding: DateTimeRangePickerBinding by lazy { DataBindingUtil.setContentView<DateTimeRangePickerBinding>( this, R.layout.date_time_range_picker ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.handleArgs(intent.extras) binding.setViewModel(viewModel) val toolbar = binding.toolbar toolbar.inflateMenu(R.menu.date_time_range_picker) toolbar.setNavigationOnClickListener { v -> finish() } toolbar.setOnMenuItemClickListener { item -> when { item.itemId == R.id.dateTimeRangePickerDoneItem -> { setResult(Activity.RESULT_OK, viewModel.createResultIntent()) finish() } } true } val calendarPickerView = binding.calendarPickerView calendarPickerView.init(viewModel.minDate, viewModel.maxDate) .inMode(CalendarPickerView.SelectionMode.RANGE) viewModel.startDateTime.value?.let { calendarPickerView.selectDate(it.toDate()) } viewModel.endDateTime.value?.let { calendarPickerView.selectDate(it.toDate()) } calendarPickerView.setOnDateSelectedListener(object : CalendarPickerView.OnDateSelectedListener { override fun onDateSelected(date: Date) { viewModel.updateSelectedDates(calendarPickerView.selectedDates) } override fun onDateUnselected(date: Date) { viewModel.updateSelectedDates(calendarPickerView.selectedDates) } }) binding.pickStartTimeView.setOnClickListener { v -> showTimePicker(viewModel.startDateTime.value, viewModel.onStartTimeSelected) } binding.pickEndTimeView.setOnClickListener { v -> showTimePicker(viewModel.endDateTime.value, viewModel.onEndTimeSelected) } } private fun showTimePicker( initialTime: DateTime, listener: TimePickerDialog.OnTimeSetListener) { TimePickerDialog( this, listener, initialTime.hourOfDay, initialTime.minuteOfHour, DateFormat.is24HourFormat(this) ).show() } }
mit
bc1d34bbd817dc717b762c484b57ce60
33.884211
107
0.742305
4.859238
false
false
false
false
kibotu/AndroidBase
app/src/main/kotlin/net/kibotu/base/ui/markdown/MarkdownFragment.kt
1
1127
package net.kibotu.base.ui.markdown import android.os.Bundle import android.text.TextUtils.isEmpty import android.view.View import kotlinx.android.synthetic.main.fragment_markdown.* import net.kibotu.base.R import net.kibotu.base.ui.BaseFragment /** * Created by [Jan Rabe](https://about.me/janrabe). */ class MarkdownFragment : BaseFragment() { override val layout: Int get() = R.layout.fragment_markdown override fun onEnterStatusBarColor(): Int { return R.color.gray } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val arguments = arguments if (arguments != null && !isEmpty(arguments.getString(MARKDOWN_FILENAME))) markdownView.loadMarkdownFromAssets(arguments.getString(MARKDOWN_FILENAME)) else if (arguments != null && !isEmpty(arguments.getString(MARKDOWN_URL))) markdownView.loadUrl(arguments.getString(MARKDOWN_URL)) } companion object { val MARKDOWN_FILENAME = "MARKDOWN_FILENAME" val MARKDOWN_URL = "MARKDOWN_URL" } }
apache-2.0
4e897170e54ea8c212afac64122d8c70
28.657895
87
0.701863
4.318008
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/domain/course_list/interactor/CourseListSearchInteractor.kt
1
3187
package org.stepik.android.domain.course_list.interactor import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import ru.nobird.app.core.model.PagedList import org.stepic.droid.util.then import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.domain.course.model.SourceTypeComposition import org.stepik.android.domain.course_list.model.CourseListItem import org.stepik.android.domain.search.repository.SearchRepository import org.stepik.android.domain.search_result.model.SearchResultQuery import org.stepik.android.domain.search_result.repository.SearchResultRepository import org.stepik.android.model.SearchResult import javax.inject.Inject class CourseListSearchInteractor @Inject constructor( private val searchResultRepository: SearchResultRepository, private val courseListInteractor: CourseListInteractor, private val searchRepository: SearchRepository ) { fun getCoursesBySearch(searchResultQuery: SearchResultQuery): Observable<Pair<PagedList<CourseListItem.Data>, DataSourceType>> = addSearchQuery(searchResultQuery) then searchResultRepository .getSearchResults(searchResultQuery) .flatMapObservable { searchResult -> val ids = searchResult.mapNotNull(SearchResult::course) Single .concat( getCourseListItems(ids, searchResult, searchResultQuery, SourceTypeComposition.CACHE), getCourseListItems(ids, searchResult, searchResultQuery, SourceTypeComposition.REMOTE) ) .toObservable() } private fun addSearchQuery(searchResultQuery: SearchResultQuery): Completable = if (searchResultQuery.query.isNullOrEmpty()) { Completable.complete() } else { searchRepository.saveSearchQuery(query = searchResultQuery.query) } fun getCourseListItems( courseId: List<Long>, courseViewSource: CourseViewSource, sourceTypeComposition: SourceTypeComposition = SourceTypeComposition.REMOTE ): Single<PagedList<CourseListItem.Data>> = courseListInteractor.getCourseListItems(courseId, courseViewSource = courseViewSource, sourceTypeComposition = sourceTypeComposition) private fun getCourseListItems( courseIds: List<Long>, searchResult: PagedList<SearchResult>, searchResultQuery: SearchResultQuery, sourceTypeComposition: SourceTypeComposition ): Single<Pair<PagedList<CourseListItem.Data>, DataSourceType>> = courseListInteractor .getCourseListItems(courseIds, courseViewSource = CourseViewSource.Search(searchResultQuery), sourceTypeComposition = sourceTypeComposition) .map { courseListItems -> PagedList( list = courseListItems, page = searchResult.page, hasPrev = searchResult.hasPrev, hasNext = searchResult.hasNext ) to sourceTypeComposition.generalSourceType } }
apache-2.0
f89f2166a998f6e94fc86cf5ba5fcfe5
45.202899
152
0.721054
5.990602
false
false
false
false
scenerygraphics/scenery
src/test/kotlin/graphics/scenery/tests/examples/basic/SponzaExample.kt
1
3770
package graphics.scenery.tests.examples.basic import org.joml.Vector3f import graphics.scenery.* import graphics.scenery.backends.Renderer import graphics.scenery.numerics.Random import graphics.scenery.Mesh import graphics.scenery.primitives.TextBoard import org.joml.Vector4f import org.scijava.ui.behaviour.ClickBehaviour import kotlin.concurrent.thread /** * Demo loading the Sponza Model, demonstrating multiple moving lights * and transparent objects. * * @author Ulrik Günther <[email protected]> */ class SponzaExample : SceneryBase("SponzaExample", windowWidth = 1280, windowHeight = 720) { private var movingLights = true override fun init() { renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight)) val cam: Camera = DetachedHeadCamera() with(cam) { spatial { position = Vector3f(0.0f, 1.0f, 0.0f) } perspectiveCamera(50.0f, windowWidth, windowHeight) scene.addChild(this) } val ambient = AmbientLight(0.05f) scene.addChild(ambient) val lights = (0 until 128).map { Box(Vector3f(0.1f, 0.1f, 0.1f)) }.map { it.spatial { position = Vector3f( Random.randomFromRange(-6.0f, 6.0f), Random.randomFromRange(0.1f, 1.2f), Random.randomFromRange(-10.0f, 10.0f) ) } val light = PointLight(radius = Random.randomFromRange(0.5f, 4.0f)) it.material { diffuse = Random.random3DVectorFromRange(0.1f, 0.9f) light.emissionColor = diffuse } light.intensity = Random.randomFromRange(0.1f, 0.5f) it.addChild(light) scene.addChild(it) it } val mesh = Mesh() with(mesh) { readFromOBJ(getDemoFilesPath() + "/sponza.obj", importMaterials = true) spatial { rotation.rotateY(Math.PI.toFloat() / 2.0f) scale = Vector3f(0.01f, 0.01f, 0.01f) } name = "Sponza Mesh" scene.addChild(this) } val desc = TextBoard() desc.text = "sponza" desc.spatial { position = Vector3f(-2.0f, -0.1f, -4.0f) } desc.fontColor = Vector4f(0.0f, 0.0f, 0.0f, 1.0f) desc.backgroundColor = Vector4f(0.1f, 0.1f, 0.1f, 1.0f) desc.transparent = 0 scene.addChild(desc) thread { var ticks = 0L while (true) { if(movingLights) { lights.mapIndexed { i, light -> val phi = (Math.PI * 2.0f * ticks / 1000.0f) % (Math.PI * 2.0f) light.spatial { position = Vector3f( position.x(), 5.0f * Math.cos(phi + (i * 0.5f)).toFloat() + 5.2f, position.z()) } light.children.forEach { it.spatialOrNull()?.needsUpdateWorld = true } } ticks++ } Thread.sleep(15) } } } override fun inputSetup() { setupCameraModeSwitching(keybinding = "C") inputHandler?.addBehaviour("toggle_light_movement", ClickBehaviour { _, _ -> movingLights = !movingLights }) inputHandler?.addKeyBinding("toggle_light_movement", "T") } companion object { @JvmStatic fun main(args: Array<String>) { SponzaExample().main() } } }
lgpl-3.0
879a34bbba957006dedf593bcc7f3ffa
29.893443
116
0.522154
4.123632
false
false
false
false
allotria/intellij-community
plugins/ide-features-trainer/src/training/dsl/TaskTestContext.kt
2
13030
// 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 training.dsl import com.intellij.ide.util.treeView.NodeRenderer import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.wm.impl.IdeFrameImpl import com.intellij.ui.KeyStrokeAdapter import com.intellij.ui.MultilineTreeCellRenderer import com.intellij.ui.SimpleColoredComponent import org.fest.swing.core.GenericTypeMatcher import org.fest.swing.core.Robot import org.fest.swing.driver.BasicJListCellReader import org.fest.swing.driver.ComponentDriver import org.fest.swing.exception.ComponentLookupException import org.fest.swing.exception.WaitTimedOutError import org.fest.swing.fixture.AbstractComponentFixture import org.fest.swing.fixture.ContainerFixture import org.fest.swing.fixture.JButtonFixture import org.fest.swing.fixture.JListFixture import org.fest.swing.timing.Condition import org.fest.swing.timing.Pause import org.fest.swing.timing.Timeout import training.ui.LearningUiUtil import training.ui.LearningUiUtil.findComponentWithTimeout import training.util.invokeActionForFocusContext import java.awt.Component import java.awt.Container import java.util.* import java.util.concurrent.TimeUnit import javax.swing.JButton import javax.swing.JDialog import javax.swing.JLabel import javax.swing.JList import kotlin.collections.ArrayList @LearningDsl class TaskTestContext(rt: TaskRuntimeContext): TaskRuntimeContext(rt) { private val defaultTimeout = Timeout.timeout(3, TimeUnit.SECONDS) val robot: Robot get() = LearningUiUtil.robot data class TestScriptProperties ( val duration: Int = 15, //seconds val skipTesting: Boolean = false ) fun type(text: String) { robot.waitForIdle() for (element in text) { robot.type(element) Pause.pause(10, TimeUnit.MILLISECONDS) } Pause.pause(300, TimeUnit.MILLISECONDS) } fun actions(vararg actionIds: String) { for (actionId in actionIds) { val action = ActionManager.getInstance().getAction(actionId) ?: error("Action $actionId is non found") invokeActionForFocusContext(action) } } fun ideFrame(action: ContainerFixture<IdeFrameImpl>.() -> Unit) { with(findIdeFrame(robot, defaultTimeout)) { action() } } fun <ComponentType : Component> waitComponent(componentClass: Class<ComponentType>, partOfName: String? = null) { LearningUiUtil.waitUntilFound(robot, null, typeMatcher(componentClass) { (if (partOfName != null) it.javaClass.name.contains(partOfName) else true) && it.isShowing }, defaultTimeout) } /** * Finds a JList component in hierarchy of context component with a containingItem and returns JListFixture. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.jList(containingItem: String? = null, timeout: Timeout = defaultTimeout): JListFixture { return generalListFinder(timeout, containingItem) { element, p -> element == p } } /** * Finds a JButton component in hierarchy of context component with a name and returns ExtendedButtonFixture. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.button(name: String, timeout: Timeout = defaultTimeout): JButtonFixture { val jButton: JButton = findComponentWithTimeout(timeout) { it.isShowing && it.isVisible && it.text == name } return JButtonFixture(robot(), jButton) } fun <C : Container> ContainerFixture<C>.actionButton(actionName: String, timeout: Timeout = defaultTimeout) : AbstractComponentFixture<*, ActionButton, ComponentDriver<*>> { val actionButton: ActionButton = findComponentWithTimeout(timeout) { it.isShowing && it.isEnabled && actionName == it.action.templatePresentation.text } return ActionButtonFixture(robot(), actionButton) } // Modified copy-paste fun <C : Container> ContainerFixture<C>.jListContains(partOfItem: String? = null, timeout: Timeout = defaultTimeout): JListFixture { return generalListFinder(timeout, partOfItem) { element, p -> element.contains(p) } } /** * Finds JDialog with a specific title (if title is null showing dialog should be only one) and returns created JDialogFixture */ fun dialog(title: String? = null, ignoreCaseTitle: Boolean = false, predicate: (String, String) -> Boolean = { found: String, wanted: String -> found == wanted }, timeout: Timeout = defaultTimeout, func: ContainerFixture<JDialog>.() -> Unit = {}) : AbstractComponentFixture<*, JDialog, ComponentDriver<*>> { val jDialogFixture = if (title == null) { val jDialog = LearningUiUtil.waitUntilFound(robot, null, typeMatcher(JDialog::class.java) { true }, timeout) JDialogFixture(robot, jDialog) } else { try { val dialog = withPauseWhenNull(timeout = timeout) { val allMatchedDialogs = robot.finder().findAll(typeMatcher(JDialog::class.java) { it.isFocused && if (ignoreCaseTitle) predicate(it.title.toLowerCase(), title.toLowerCase()) else predicate(it.title, title) }).filter { it.isShowing && it.isEnabled && it.isVisible } if (allMatchedDialogs.size > 1) throw Exception( "Found more than one (${allMatchedDialogs.size}) dialogs matched title \"$title\"") allMatchedDialogs.firstOrNull() } JDialogFixture(robot, dialog) } catch (timeoutError: WaitTimedOutError) { throw ComponentLookupException("Timeout error for finding JDialog by title \"$title\" for ${timeout.duration()}") } } func(jDialogFixture) return jDialogFixture } fun ContainerFixture<*>.jComponent(target: Component): AbstractComponentFixture<*, Component, ComponentDriver<*>> { return SimpleComponentFixture(robot(), target) } fun invokeActionViaShortcut(shortcut: String) { val keyStroke = KeyStrokeAdapter.getKeyStroke(shortcut) robot.pressAndReleaseKey(keyStroke.keyCode, keyStroke.modifiers) } companion object { @Volatile var inTestMode: Boolean = false } ////////////------------------------------ private fun <C : Container> ContainerFixture<C>.generalListFinder(timeout: Timeout, containingItem: String?, predicate: (String, String) -> Boolean): JListFixture { val extCellReader = ExtendedJListCellReader() val myJList: JList<*> = findComponentWithTimeout(timeout) { jList: JList<*> -> if (containingItem == null) true //if were searching for any jList() else { val elements = (0 until jList.model.size).mapNotNull { extCellReader.valueAt(jList, it) } elements.any { predicate(it, containingItem) } && jList.isShowing } } val jListFixture = JListFixture(robot(), myJList) jListFixture.replaceCellReader(extCellReader) return jListFixture } /** * waits for [timeout] when functionProbeToNull() not return null * * @throws WaitTimedOutError with the text: "Timed out waiting for $timeout second(s) until {@code conditionText} will be not null" */ private fun <ReturnType> withPauseWhenNull(conditionText: String = "function to probe", timeout: Timeout = defaultTimeout, functionProbeToNull: () -> ReturnType?): ReturnType { var result: ReturnType? = null waitUntil("$conditionText will be not null", timeout) { result = functionProbeToNull() result != null } return result!! } private fun waitUntil(condition: String, timeout: Timeout = defaultTimeout, conditionalFunction: () -> Boolean) { Pause.pause(object : Condition("${timeout.duration()} until $condition") { override fun test() = conditionalFunction() }, timeout) } private class SimpleComponentFixture(robot: Robot, target: Component) : ComponentFixture<SimpleComponentFixture, Component>(SimpleComponentFixture::class.java, robot, target) private fun <ComponentType : Component?> typeMatcher(componentTypeClass: Class<ComponentType>, matcher: (ComponentType) -> Boolean): GenericTypeMatcher<ComponentType> { return object : GenericTypeMatcher<ComponentType>(componentTypeClass) { override fun isMatching(component: ComponentType): Boolean = matcher(component) } } } private fun getValueWithCellRenderer(cellRendererComponent: Component, isExtended: Boolean = true): String? { val result = when (cellRendererComponent) { is JLabel -> cellRendererComponent.text is NodeRenderer -> { if (isExtended) cellRendererComponent.getFullText() else cellRendererComponent.getFirstText() } //should stands before SimpleColoredComponent because it is more specific is SimpleColoredComponent -> cellRendererComponent.getFullText() is MultilineTreeCellRenderer -> cellRendererComponent.text else -> cellRendererComponent.findText() } return result?.trimEnd() } private class ExtendedJListCellReader : BasicJListCellReader() { override fun valueAt(list: JList<*>, index: Int): String? { val element = list.model.getElementAt(index) ?: return null @Suppress("UNCHECKED_CAST") val cellRendererComponent = (list as JList<Any>).cellRenderer .getListCellRendererComponent(list, element, index, true, true) return getValueWithCellRenderer(cellRendererComponent) } } private fun SimpleColoredComponent.getFullText(): String { return invokeAndWaitIfNeeded { this.getCharSequence(false).toString() } } private fun SimpleColoredComponent.getFirstText(): String { return invokeAndWaitIfNeeded { this.getCharSequence(true).toString() } } private fun Component.findText(): String? { try { assert(this is Container) val container = this as Container val resultList = ArrayList<String>() resultList.addAll( findAllWithBFS(container, JLabel::class.java) .asSequence() .filter { !it.text.isNullOrEmpty() } .map { it.text } .toList() ) resultList.addAll( findAllWithBFS(container, SimpleColoredComponent::class.java) .asSequence() .filter { it.getFullText().isNotEmpty() } .map { it.getFullText() } .toList() ) return resultList.firstOrNull { it.isNotEmpty() } } catch (ignored: ComponentLookupException) { return null } } private fun <ComponentType : Component> findAllWithBFS(container: Container, clazz: Class<ComponentType>): List<ComponentType> { val result = LinkedList<ComponentType>() val queue: Queue<Component> = LinkedList() @Suppress("UNCHECKED_CAST") fun check(container: Component) { if (clazz.isInstance(container)) result.add(container as ComponentType) } queue.add(container) while (queue.isNotEmpty()) { val polled = queue.poll() check(polled) if (polled is Container) queue.addAll(polled.components) } return result } private open class ComponentFixture<S, C : Component>(selfType: Class<S>, robot: Robot, target: C) : AbstractComponentFixture<S, C, ComponentDriver<*>>(selfType, robot, target) { override fun createDriver(robot: Robot): ComponentDriver<*> { return ComponentDriver<Component>(robot) } } private class ActionButtonFixture(robot: Robot, target: ActionButton): ComponentFixture<ActionButtonFixture, ActionButton>(ActionButtonFixture::class.java, robot, target), ContainerFixture<ActionButton> private class IdeFrameFixture(robot: Robot, target: IdeFrameImpl) : ComponentFixture<IdeFrameFixture, IdeFrameImpl>(IdeFrameFixture::class.java, robot, target), ContainerFixture<IdeFrameImpl> private class JDialogFixture(robot: Robot, jDialog: JDialog) : ComponentFixture<JDialogFixture, JDialog>(JDialogFixture::class.java, robot, jDialog), ContainerFixture<JDialog> private fun findIdeFrame(robot: Robot, timeout: Timeout): IdeFrameFixture { val matcher: GenericTypeMatcher<IdeFrameImpl> = object : GenericTypeMatcher<IdeFrameImpl>( IdeFrameImpl::class.java) { override fun isMatching(frame: IdeFrameImpl): Boolean { return true } } return try { Pause.pause(object : Condition("IdeFrame to show up") { override fun test(): Boolean { return !robot.finder().findAll(matcher).isEmpty() } }, timeout) val ideFrame = robot.finder().find(matcher) IdeFrameFixture(robot, ideFrame) } catch (timedOutError: WaitTimedOutError) { throw ComponentLookupException("Unable to find IdeFrame in " + timeout.duration()) } }
apache-2.0
d06fda557220b0fe49e81a696909644e
37.895522
140
0.707598
4.827714
false
false
false
false
allotria/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/StaticFileHandler.kt
2
4186
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.builtInWebServer import com.intellij.openapi.project.Project import com.intellij.util.PathUtilRt import io.netty.buffer.ByteBufUtf8Writer import io.netty.channel.Channel import io.netty.handler.codec.http.FullHttpRequest import io.netty.handler.codec.http.HttpHeaders import io.netty.handler.codec.http.HttpMethod import io.netty.handler.codec.http.HttpUtil import io.netty.handler.stream.ChunkedStream import org.jetbrains.builtInWebServer.liveReload.WebServerPageConnectionService import org.jetbrains.builtInWebServer.ssi.SsiExternalResolver import org.jetbrains.builtInWebServer.ssi.SsiProcessor import org.jetbrains.io.FileResponses import org.jetbrains.io.addKeepAliveIfNeeded import org.jetbrains.io.flushChunkedResponse import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths private class StaticFileHandler : WebServerFileHandler() { @Suppress("HardCodedStringLiteral") override val pageFileExtensions = arrayOf("html", "htm", "shtml", "stm", "shtm") private var ssiProcessor: SsiProcessor? = null override fun process(pathInfo: PathInfo, canonicalPath: CharSequence, project: Project, request: FullHttpRequest, channel: Channel, projectNameIfNotCustomHost: String?, extraHeaders: HttpHeaders): Boolean { if (pathInfo.ioFile != null || pathInfo.file!!.isInLocalFileSystem) { val ioFile = pathInfo.ioFile ?: Paths.get(pathInfo.file!!.path) val nameSequence = ioFile.fileName.toString() //noinspection SpellCheckingInspection if (nameSequence.endsWith(".shtml", true) || nameSequence.endsWith(".stm", true) || nameSequence.endsWith(".shtm", true)) { processSsi(ioFile, PathUtilRt.getParentPath(canonicalPath.toString()), project, request, channel, extraHeaders) return true } val extraSuffix = WebServerPageConnectionService.getInstance().fileRequested(request, pathInfo::getOrResolveVirtualFile) FileResponses.sendFile(request, channel, ioFile, extraHeaders, extraSuffix) return true } val file = pathInfo.file!! val response = FileResponses.prepareSend(request, channel, file.timeStamp, file.name, extraHeaders) ?: return true val isKeepAlive = response.addKeepAliveIfNeeded(request) if (request.method() != HttpMethod.HEAD) { HttpUtil.setContentLength(response, file.length) } channel.write(response) if (request.method() != HttpMethod.HEAD) { channel.write(ChunkedStream(file.inputStream)) } flushChunkedResponse(channel, isKeepAlive) return true } private fun processSsi(file: Path, path: String, project: Project, request: FullHttpRequest, channel: Channel, extraHeaders: HttpHeaders) { if (ssiProcessor == null) { ssiProcessor = SsiProcessor() } val buffer = channel.alloc().ioBuffer() val isKeepAlive: Boolean var releaseBuffer = true try { val lastModified = ssiProcessor!!.process(SsiExternalResolver(project, request, path, file.parent), file, ByteBufUtf8Writer(buffer)) val response = FileResponses.prepareSend(request, channel, lastModified, file.fileName.toString(), extraHeaders) ?: return isKeepAlive = response.addKeepAliveIfNeeded(request) if (request.method() != HttpMethod.HEAD) { HttpUtil.setContentLength(response, buffer.readableBytes().toLong()) } channel.write(response) if (request.method() != HttpMethod.HEAD) { releaseBuffer = false channel.write(buffer) } } finally { if (releaseBuffer) { buffer.release() } } flushChunkedResponse(channel, isKeepAlive) } } internal fun checkAccess(file: Path, root: Path = file.root): Boolean { var parent = file do { if (!hasAccess(parent)) { return false } parent = parent.parent ?: break } while (parent != root) return true } // deny access to any dot prefixed file internal fun hasAccess(result: Path) = Files.isReadable(result) && !(Files.isHidden(result) || result.fileName.toString().startsWith('.'))
apache-2.0
280b1e847cb1acef38b04d6929394f38
37.768519
208
0.735786
4.439024
false
false
false
false
DeflatedPickle/Quiver
core/src/main/kotlin/com/deflatedpickle/quiver/frontend/widget/ButtonField.kt
1
1035
/* Copyright (c) 2020 DeflatedPickle under the MIT license */ package com.deflatedpickle.quiver.frontend.widget import com.deflatedpickle.undulation.constraints.FillHorizontal import com.deflatedpickle.undulation.constraints.FinishLine import java.awt.GridBagLayout import javax.swing.text.DocumentFilter import javax.swing.text.PlainDocument import org.jdesktop.swingx.JXButton import org.jdesktop.swingx.JXPanel import org.jdesktop.swingx.JXTextField class ButtonField( prompt: String, tooltip: String, filter: DocumentFilter, actionString: String, action: (ButtonField) -> Unit ) : JXPanel() { val field = JXTextField(prompt).apply { toolTipText = tooltip (document as PlainDocument).documentFilter = filter } val button = JXButton(actionString).apply { addActionListener { action(this@ButtonField) } } init { this.isOpaque = false this.layout = GridBagLayout() add(this.field, FillHorizontal) add(this.button, FinishLine) } }
mit
f7fa3f8106ffba66e5e3fccf265ec4ce
27.75
63
0.727536
4.259259
false
false
false
false
grover-ws-1/http4k
src/docs/cookbook/test_driven_apps/example.kt
1
3783
package cookbook.test_driven_apps import com.natpryce.hamkrest.and import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.should.shouldMatch import org.http4k.client.OkHttp import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Method.POST import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.NOT_FOUND import org.http4k.core.Status.Companion.OK import org.http4k.core.Uri import org.http4k.core.then import org.http4k.filter.ClientFilters.SetHostFrom import org.http4k.filter.ServerFilters import org.http4k.hamkrest.hasBody import org.http4k.hamkrest.hasStatus import org.http4k.routing.bind import org.http4k.routing.path import org.http4k.routing.routes import org.http4k.server.Http4kServer import org.http4k.server.Jetty import org.http4k.server.asServer import org.junit.After import org.junit.Before import org.junit.Test class AnswerRecorder(private val httpClient: HttpHandler) : (Int) -> Unit { override fun invoke(answer: Int): Unit { httpClient(Request(POST, "/" + answer.toString())) } } fun myMathsEndpoint(fn: (Int, Int) -> Int, recorder: (Int) -> Unit): HttpHandler = { req -> val answer = fn(req.query("first")!!.toInt(), req.query("second")!!.toInt()) recorder(answer) Response(OK).body("the answer is $answer") } class EndpointUnitTest { @Test fun `adds numbers and records answer`() { var answer: Int? = null val unit = myMathsEndpoint({ first, second -> first + second }, { answer = it }) val response = unit(Request(GET, "/").query("first", "123").query("second", "456")) answer shouldMatch equalTo(579) response shouldMatch hasStatus(OK).and(hasBody("the answer is 579")) } } fun MyMathsApp(recorderHttp: HttpHandler) = ServerFilters.CatchAll().then(routes( "/add" bind GET to myMathsEndpoint({ first, second -> first + second }, AnswerRecorder(recorderHttp)) )) class FakeRecorderHttp : HttpHandler { val calls = mutableListOf<Int>() private val app = routes( "/{answer}" bind POST to { request -> calls.add(request.path("answer")!!.toInt()); Response(OK) } ) override fun invoke(request: Request): Response = app(request) } class FunctionalTest { private val recorderHttp = FakeRecorderHttp() private val app = MyMathsApp(recorderHttp) @Test fun `adds numbers`() { val response = app(Request(GET, "/add").query("first", "123").query("second", "456")) response shouldMatch hasStatus(OK).and(hasBody("the answer is 579")) recorderHttp.calls shouldMatch equalTo(listOf(579)) } @Test fun `not found`() { val response = app(Request(GET, "/nothing").query("first", "123").query("second", "456")) response shouldMatch hasStatus(NOT_FOUND) } } fun MyMathServer(port: Int, recorderUri: Uri): Http4kServer { val recorderHttp = SetHostFrom(recorderUri).then(OkHttp()) return MyMathsApp(recorderHttp).asServer(Jetty(port)) } class EndToEndTest { private val client = OkHttp() private val recorderHttp = FakeRecorderHttp() private val recorder = recorderHttp.asServer(Jetty(8001)) private val server = MyMathServer(8000, Uri.of("http://localhost:8001")) @Before fun setup(): Unit { recorder.start() server.start() } @After fun teardown(): Unit { server.stop() recorder.stop() } @Test fun `adds numbers`() { val response = client(Request(GET, "http://localhost:8000/add").query("first", "123").query("second", "456")) response shouldMatch hasStatus(OK).and(hasBody("the answer is 579")) recorderHttp.calls shouldMatch equalTo(listOf(579)) } }
apache-2.0
96184fec031587f087afab6aa632561e
31.059322
117
0.6894
3.756703
false
true
false
false
zdary/intellij-community
platform/execution-impl/src/com/intellij/execution/impl/statistics/RunConfigurationOptionUsagesCollector.kt
1
6886
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.impl.statistics import com.intellij.execution.impl.statistics.RunConfigurationTypeUsagesCollector.ID_FIELD import com.intellij.execution.ui.FragmentStatisticsService import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.FusInputEvent import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project class RunConfigurationOptionUsagesCollector: CounterUsagesCollector() { override fun getGroup() = GROUP companion object { val GROUP = EventLogGroup("run.configuration.ui.interactions", 6) val optionId = EventFields.String("option_id", listOf("before.launch.editSettings", "before.launch.openToolWindow", "beforeRunTasks", "commandLineParameters", "coverage", "doNotBuildBeforeRun", "environmentVariables", "jrePath", "log.monitor", "mainClass", "module.classpath", "redirectInput", "runParallel", "shorten.command.line", "target.project.path", "vmParameters", "workingDirectory", "count", "junit.test.kind", "repeat", "testScope", // junit "maven.params.workingDir", "maven.params.goals", "maven.params.profiles", "maven.params.resolveToWorkspace", "maven.general.useProjectSettings", "maven.general.workOffline", "maven.general.produceExceptionErrorMessages", "maven.general.usePluginRegistry", "maven.general.recursive", "maven.general.alwaysUpdateSnapshots", "maven.general.threadsEditor", "maven.general.outputLevel", "maven.general.checksumPolicy", "maven.general.failPolicy", "maven.general.showDialogWithAdvancedSettings", "maven.general.mavenHome", "maven.general.settingsFileOverride.checkbox", "maven.general.settingsFileOverride.text", "maven.general.localRepoOverride.checkbox", "maven.general.localRepoOverride.text", "maven.runner.useProjectSettings", "maven.runner.delegateToMaven", "maven.runner.runInBackground", "maven.runner.vmParameters", "maven.runner.envVariables", "maven.runner.jdk", "maven.runner.targetJdk", "maven.runner.skipTests", "maven.runner.properties", "Dump_file_path", "Exe_path", "Program_arguments", "Working_directory", "Environment_variables", "Runtime_arguments", "Use_Mono_runtime", "Use_external_console", "Project", "Target_framework", "Launch_profile", "Open_browser", "Application_URL", "Launch_URL", "IIS_Express_Certificate", "Hosting_model", "Generate_applicationhost.config", "Show_IIS_Express_output", "Send_debug_request", "Additional_IIS_Express_arguments", "Static_method", "URL", "Session_name", "Arguments", "Solution_Configuration", "Executable_file", "Default_arguments", "Optional_arguments" // Rider )) // maven val projectSettingsAvailableField = EventFields.Boolean("projectSettingsAvailable") val useProjectSettingsField = EventFields.Boolean("useProjectSettings") val modifyOption = GROUP.registerVarargEvent("modify.run.option", optionId, projectSettingsAvailableField, useProjectSettingsField, ID_FIELD, EventFields.InputEvent) val navigateOption = GROUP.registerVarargEvent("option.navigate", optionId, ID_FIELD, EventFields.InputEvent) val removeOption = GROUP.registerEvent("remove.run.option", optionId, ID_FIELD, EventFields.InputEvent) val addNew = GROUP.registerEvent("add", ID_FIELD) val remove = GROUP.registerEvent("remove", ID_FIELD) val hintsShown = GROUP.registerEvent("hints.shown", ID_FIELD, EventFields.Int("hint_number"), EventFields.DurationMs) @JvmStatic fun logAddNew(project: Project?, config: String?) { addNew.log(project, config) } @JvmStatic fun logRemove(project: Project?, config: String?) { remove.log(project, config) } @JvmStatic fun logModifyOption(project: Project?, option: String?, config: String?, inputEvent: FusInputEvent?) { modifyOption.log(project, optionId.with(option), ID_FIELD.with(config), EventFields.InputEvent.with(inputEvent)) } @JvmStatic fun logNavigateOption(project: Project?, option: String?, config: String?, inputEvent: FusInputEvent?) { navigateOption.log(project, optionId.with(option), ID_FIELD.with(config), EventFields.InputEvent.with(inputEvent)) } @JvmStatic fun logModifyOption(project: Project?, option: String?, config: String?, projectSettingsAvailable: Boolean, useProjectSettings: Boolean, inputEvent: FusInputEvent?) { modifyOption.log(project, optionId.with(option), ID_FIELD.with(config), projectSettingsAvailableField.with(projectSettingsAvailable), useProjectSettingsField.with(useProjectSettings), EventFields.InputEvent.with(inputEvent)) } @JvmStatic fun logRemoveOption(project: Project?, option: String?, config: String?, inputEvent: FusInputEvent?) { removeOption.log(project, option, config, inputEvent) } @JvmStatic fun logShowHints(project: Project?, config: String?, hintsCount: Int, duration: Long) { hintsShown.log(project, config, hintsCount, duration) } } } class FragmentedStatisticsServiceImpl: FragmentStatisticsService() { override fun logOptionModified(project: Project?, optionId: String?, runConfigId: String?, inputEvent: AnActionEvent?) { RunConfigurationOptionUsagesCollector. logModifyOption(project, optionId, runConfigId, FusInputEvent.from(inputEvent)) } override fun logOptionRemoved(project: Project?, optionId: String?, runConfigId: String?, inputEvent: AnActionEvent?) { RunConfigurationOptionUsagesCollector.logRemoveOption(project, optionId, runConfigId, FusInputEvent.from(inputEvent)) } override fun logNavigateOption(project: Project?, optionId: String?, runConfigId: String?, inputEvent: AnActionEvent?) { RunConfigurationOptionUsagesCollector.logNavigateOption(project, optionId, runConfigId, FusInputEvent.from(inputEvent)) } override fun logHintsShown(project: Project?, runConfigId: String?, hintNumber: Int, duration: Long) { RunConfigurationOptionUsagesCollector.logShowHints(project, runConfigId, hintNumber, duration) } }
apache-2.0
66a9db9e2e3a0a97a77e39b6ea315d12
68.555556
636
0.705489
4.862994
false
true
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/routes/Lookup.kt
1
403
package slatekit.apis.routes open class Lookup<T>( val items: List<T>, val nameFetcher: (T) -> String ) { val size = items.size val keys = items.map(this.nameFetcher) val map = items.map { it -> Pair(this.nameFetcher(it), it) }.toMap() fun contains(name: String): Boolean = map.contains(name) operator fun get(name: String): T? = if (contains(name)) map[name] else null }
apache-2.0
59c302584f35f464e3b5216e885c55a3
27.785714
80
0.650124
3.303279
false
false
false
false
anthonycr/Lightning-Browser
app/src/main/java/acr/browser/lightning/browser/tab/TabWebViewClient.kt
1
10883
package acr.browser.lightning.browser.tab import acr.browser.lightning.R import acr.browser.lightning.adblock.AdBlocker import acr.browser.lightning.adblock.allowlist.AllowListModel import acr.browser.lightning.browser.proxy.Proxy import acr.browser.lightning.databinding.DialogAuthRequestBinding import acr.browser.lightning.databinding.DialogSslWarningBinding import acr.browser.lightning.extensions.resizeAndShow import acr.browser.lightning.js.TextReflow import acr.browser.lightning.log.Logger import acr.browser.lightning.preference.UserPreferences import acr.browser.lightning.ssl.SslState import acr.browser.lightning.ssl.SslWarningPreferences import android.annotation.SuppressLint import android.graphics.Bitmap import android.net.http.SslError import android.os.Build import android.os.Message import android.view.LayoutInflater import android.webkit.HttpAuthHandler import android.webkit.SslErrorHandler import android.webkit.URLUtil import android.webkit.WebResourceRequest import android.webkit.WebResourceResponse import android.webkit.WebView import android.webkit.WebViewClient import androidx.annotation.RequiresApi import androidx.appcompat.app.AlertDialog import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import io.reactivex.subjects.PublishSubject import java.io.ByteArrayInputStream import kotlin.math.abs /** * A [WebViewClient] that supports the tab adaptation. */ class TabWebViewClient @AssistedInject constructor( private val adBlocker: AdBlocker, private val allowListModel: AllowListModel, private val urlHandler: UrlHandler, @Assisted private val headers: Map<String, String>, private val proxy: Proxy, private val userPreferences: UserPreferences, private val sslWarningPreferences: SslWarningPreferences, private val textReflow: TextReflow, private val logger: Logger ) : WebViewClient() { /** * Emits changes to the current URL. */ val urlObservable: PublishSubject<String> = PublishSubject.create() /** * Emits changes to the current SSL state. */ val sslStateObservable: PublishSubject<SslState> = PublishSubject.create() /** * Emits changes to the can go back state of the browser. */ val goBackObservable: PublishSubject<Boolean> = PublishSubject.create() /** * Emits changes to the can go forward state of the browser. */ val goForwardObservable: PublishSubject<Boolean> = PublishSubject.create() /** * The current SSL state of the page. */ var sslState: SslState = SslState.None private set private var currentUrl: String = "" private var isReflowRunning: Boolean = false private var zoomScale: Float = 0.0F private var urlWithSslError: String? = null private fun shouldBlockRequest(pageUrl: String, requestUrl: String) = !allowListModel.isUrlAllowedAds(pageUrl) && adBlocker.isAd(requestUrl) override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) { super.onPageStarted(view, url, favicon) currentUrl = url urlObservable.onNext(url) if (urlWithSslError != url) { urlWithSslError = null sslState = if (URLUtil.isHttpsUrl(url)) { SslState.Valid } else { SslState.None } } sslStateObservable.onNext(sslState) } override fun onPageFinished(view: WebView, url: String) { super.onPageFinished(view, url) urlObservable.onNext(url) goBackObservable.onNext(view.canGoBack()) goForwardObservable.onNext(view.canGoForward()) } override fun onScaleChanged(view: WebView, oldScale: Float, newScale: Float) { if (view.isShown && userPreferences.textReflowEnabled) { if (isReflowRunning) return val changeInPercent = abs(100 - 100 / zoomScale * newScale) if (changeInPercent > 2.5f && !isReflowRunning) { isReflowRunning = view.postDelayed({ zoomScale = newScale view.evaluateJavascript(textReflow.provideJs()) { isReflowRunning = false } }, 100) } } } override fun onReceivedHttpAuthRequest( view: WebView, handler: HttpAuthHandler, host: String, realm: String ) { val context = view.context AlertDialog.Builder(context).apply { val dialogView = DialogAuthRequestBinding.inflate(LayoutInflater.from(context)) val realmLabel = dialogView.authRequestRealmTextview val name = dialogView.authRequestUsernameEdittext val password = dialogView.authRequestPasswordEdittext realmLabel.text = context.getString(R.string.label_realm, realm) setView(dialogView.root) setTitle(R.string.title_sign_in) setCancelable(true) setPositiveButton(R.string.title_sign_in) { _, _ -> val user = name.text.toString() val pass = password.text.toString() handler.proceed(user.trim(), pass.trim()) logger.log(TAG, "Attempting HTTP Authentication") } setNegativeButton(R.string.action_cancel) { _, _ -> handler.cancel() } }.resizeAndShow() } override fun onFormResubmission(view: WebView, dontResend: Message, resend: Message) { val context = view.context AlertDialog.Builder(context).apply { setTitle(context.getString(R.string.title_form_resubmission)) setMessage(context.getString(R.string.message_form_resubmission)) setCancelable(true) setPositiveButton(context.getString(R.string.action_yes)) { _, _ -> resend.sendToTarget() } setNegativeButton(context.getString(R.string.action_no)) { _, _ -> dontResend.sendToTarget() } }.resizeAndShow() } @SuppressLint("WebViewClientOnReceivedSslError") override fun onReceivedSslError(webView: WebView, handler: SslErrorHandler, error: SslError) { val context = webView.context urlWithSslError = webView.url sslState = SslState.Invalid(error) sslStateObservable.onNext(sslState) sslState = SslState.Invalid(error) when (sslWarningPreferences.recallBehaviorForDomain(webView.url)) { SslWarningPreferences.Behavior.PROCEED -> return handler.proceed() SslWarningPreferences.Behavior.CANCEL -> return handler.cancel() null -> Unit } val errorCodeMessageCodes = error.getAllSslErrorMessageCodes() val stringBuilder = StringBuilder() for (messageCode in errorCodeMessageCodes) { stringBuilder.append(" - ").append(context.getString(messageCode)).append('\n') } val alertMessage = context.getString(R.string.message_insecure_connection, stringBuilder.toString()) AlertDialog.Builder(context).apply { val view = DialogSslWarningBinding.inflate(LayoutInflater.from(context)) val dontAskAgain = view.checkBoxDontAskAgain setTitle(context.getString(R.string.title_warning)) setMessage(alertMessage) setCancelable(true) setView(view.root) setOnCancelListener { handler.cancel() } setPositiveButton(context.getString(R.string.action_yes)) { _, _ -> if (dontAskAgain.isChecked) { sslWarningPreferences.rememberBehaviorForDomain( webView.url.orEmpty(), SslWarningPreferences.Behavior.PROCEED ) } handler.proceed() } setNegativeButton(context.getString(R.string.action_no)) { _, _ -> if (dontAskAgain.isChecked) { sslWarningPreferences.rememberBehaviorForDomain( webView.url.orEmpty(), SslWarningPreferences.Behavior.CANCEL ) } handler.cancel() } }.resizeAndShow() } override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { if (!proxy.isProxyReady()) return true return urlHandler.shouldOverrideLoading(view, url, headers) || super.shouldOverrideUrlLoading(view, url) } @RequiresApi(Build.VERSION_CODES.N) override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { if (!proxy.isProxyReady()) return true return urlHandler.shouldOverrideLoading(view, request.url.toString(), headers) || super.shouldOverrideUrlLoading(view, request) } override fun shouldInterceptRequest( view: WebView, request: WebResourceRequest ): WebResourceResponse? { if (shouldBlockRequest(currentUrl, request.url.toString()) || !proxy.isProxyReady()) { val empty = ByteArrayInputStream(emptyResponseByteArray) return WebResourceResponse(BLOCKED_RESPONSE_MIME_TYPE, BLOCKED_RESPONSE_ENCODING, empty) } return null } private fun SslError.getAllSslErrorMessageCodes(): List<Int> { val errorCodeMessageCodes = ArrayList<Int>(1) if (hasError(SslError.SSL_DATE_INVALID)) { errorCodeMessageCodes.add(R.string.message_certificate_date_invalid) } if (hasError(SslError.SSL_EXPIRED)) { errorCodeMessageCodes.add(R.string.message_certificate_expired) } if (hasError(SslError.SSL_IDMISMATCH)) { errorCodeMessageCodes.add(R.string.message_certificate_domain_mismatch) } if (hasError(SslError.SSL_NOTYETVALID)) { errorCodeMessageCodes.add(R.string.message_certificate_not_yet_valid) } if (hasError(SslError.SSL_UNTRUSTED)) { errorCodeMessageCodes.add(R.string.message_certificate_untrusted) } if (hasError(SslError.SSL_INVALID)) { errorCodeMessageCodes.add(R.string.message_certificate_invalid) } return errorCodeMessageCodes } /** * The factory for constructing the client. */ @AssistedFactory interface Factory { /** * Create the client. */ fun create(headers: Map<String, String>): TabWebViewClient } companion object { private const val TAG = "TabWebViewClient" private val emptyResponseByteArray: ByteArray = byteArrayOf() private const val BLOCKED_RESPONSE_MIME_TYPE = "text/plain" private const val BLOCKED_RESPONSE_ENCODING = "utf-8" } }
mpl-2.0
fa3b41166300c59e6dd7576d43b7ba9f
36.143345
100
0.657539
4.931128
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/call/callPrivateJavaMethod.kt
1
898
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT // FILE: J.java public class J { private final String result; private J(String result) { this.result = result; } private String getResult() { return result; } } // FILE: K.kt import kotlin.reflect.full.* import kotlin.reflect.jvm.* import kotlin.test.* fun box(): String { val c = J::class.constructors.single() assertFalse(c.isAccessible) assertFailsWith(IllegalCallableAccessException::class) { c.call("") } c.isAccessible = true assertTrue(c.isAccessible) val j = c.call("OK") val m = J::class.members.single { it.name == "getResult" } assertFalse(m.isAccessible) assertFailsWith(IllegalCallableAccessException::class) { m.call(j)!! } m.isAccessible = true return m.call(j) as String }
apache-2.0
2caa2cedb2f460fd7a11959de478602a
21.45
74
0.663697
3.773109
false
false
false
false
Triple-T/gradle-play-publisher
play/android-publisher/src/main/kotlin/com/github/triplet/gradle/androidpublisher/internal/DefaultPlayPublisher.kt
1
10170
package com.github.triplet.gradle.androidpublisher.internal import com.github.triplet.gradle.androidpublisher.CommitResponse import com.github.triplet.gradle.androidpublisher.EditResponse import com.github.triplet.gradle.androidpublisher.GppProduct import com.github.triplet.gradle.androidpublisher.PlayPublisher import com.github.triplet.gradle.androidpublisher.UpdateProductResponse import com.github.triplet.gradle.androidpublisher.UploadInternalSharingArtifactResponse import com.google.api.client.googleapis.json.GoogleJsonResponseException import com.google.api.client.googleapis.media.MediaHttpUploader import com.google.api.client.googleapis.services.AbstractGoogleClientRequest import com.google.api.client.http.FileContent import com.google.api.client.json.gson.GsonFactory import com.google.api.services.androidpublisher.AndroidPublisher import com.google.api.services.androidpublisher.model.Apk import com.google.api.services.androidpublisher.model.AppDetails import com.google.api.services.androidpublisher.model.Bundle import com.google.api.services.androidpublisher.model.DeobfuscationFilesUploadResponse import com.google.api.services.androidpublisher.model.ExpansionFile import com.google.api.services.androidpublisher.model.Image import com.google.api.services.androidpublisher.model.InAppProduct import com.google.api.services.androidpublisher.model.Listing import com.google.api.services.androidpublisher.model.Track import java.io.File import java.io.InputStream import kotlin.math.roundToInt internal class DefaultPlayPublisher( private val publisher: AndroidPublisher, override val appId: String, ) : InternalPlayPublisher { override fun insertEdit(): EditResponse { return try { EditResponse.Success(publisher.edits().insert(appId, null).execute().id) } catch (e: GoogleJsonResponseException) { EditResponse.Failure(e) } } override fun getEdit(id: String): EditResponse { return try { EditResponse.Success(publisher.edits().get(appId, id).execute().id) } catch (e: GoogleJsonResponseException) { EditResponse.Failure(e) } } override fun commitEdit(id: String, sendChangesForReview: Boolean): CommitResponse { return try { publisher.edits().commit(appId, id) .setChangesNotSentForReview(!sendChangesForReview) .execute() CommitResponse.Success } catch (e: GoogleJsonResponseException) { CommitResponse.Failure(e) } } override fun validateEdit(id: String) { publisher.edits().validate(appId, id).execute() } override fun getAppDetails(editId: String): AppDetails { return publisher.edits().details().get(appId, editId).execute() } override fun getListings(editId: String): List<Listing> { return publisher.edits().listings().list(appId, editId).execute()?.listings.orEmpty() } override fun getImages(editId: String, locale: String, type: String): List<Image> { val response = publisher.edits().images().list(appId, editId, locale, type).execute() return response?.images.orEmpty() } override fun updateDetails(editId: String, details: AppDetails) { publisher.edits().details().update(appId, editId, details).execute() } override fun updateListing(editId: String, locale: String, listing: Listing) { publisher.edits().listings().update(appId, editId, locale, listing).execute() } override fun deleteImages(editId: String, locale: String, type: String) { publisher.edits().images().deleteall(appId, editId, locale, type).execute() } override fun uploadImage(editId: String, locale: String, type: String, image: File) { val content = FileContent(MIME_TYPE_IMAGE, image) publisher.edits().images().upload(appId, editId, locale, type, content).execute() } override fun getTrack(editId: String, track: String): Track { return try { publisher.edits().tracks().get(appId, editId, track).execute() } catch (e: GoogleJsonResponseException) { if (e has "notFound") { Track().setTrack(track) } else { throw e } } } override fun listTracks(editId: String): List<Track> { return publisher.edits().tracks().list(appId, editId).execute()?.tracks.orEmpty() } override fun updateTrack(editId: String, track: Track) { println("Updating ${track.releases.map { it.status }.distinct()} release " + "($appId:${track.releases.flatMap { it.versionCodes.orEmpty() }}) " + "in track '${track.track}'") publisher.edits().tracks().update(appId, editId, track.track, track).execute() } override fun uploadBundle(editId: String, bundleFile: File): Bundle { val content = FileContent(MIME_TYPE_STREAM, bundleFile) return publisher.edits().bundles().upload(appId, editId, content) .trackUploadProgress("App Bundle", bundleFile) .execute() } override fun uploadApk(editId: String, apkFile: File): Apk { val content = FileContent(MIME_TYPE_APK, apkFile) return publisher.edits().apks().upload(appId, editId, content) .trackUploadProgress("APK", apkFile) .execute() } override fun attachObb(editId: String, type: String, appVersion: Int, obbVersion: Int) { val obb = ExpansionFile().also { it.referencesVersion = obbVersion } publisher.edits().expansionfiles() .update(appId, editId, appVersion, type, obb) .execute() } override fun uploadDeobfuscationFile( editId: String, file: File, versionCode: Int, type: String, ): DeobfuscationFilesUploadResponse { val mapping = FileContent(MIME_TYPE_STREAM, file) val humanFileName = when (type) { "proguard" -> "mapping" "nativeCode" -> "native debug symbols" else -> type } return publisher.edits().deobfuscationfiles() .upload(appId, editId, versionCode, type, mapping) .trackUploadProgress("$humanFileName file", file) .execute() } override fun uploadInternalSharingBundle(bundleFile: File): UploadInternalSharingArtifactResponse { val bundle = publisher.internalappsharingartifacts() .uploadbundle(appId, FileContent(MIME_TYPE_STREAM, bundleFile)) .trackUploadProgress("App Bundle", bundleFile) .execute() return UploadInternalSharingArtifactResponse(bundle.toPrettyString(), bundle.downloadUrl) } override fun uploadInternalSharingApk(apkFile: File): UploadInternalSharingArtifactResponse { val apk = publisher.internalappsharingartifacts() .uploadapk(appId, FileContent(MIME_TYPE_APK, apkFile)) .trackUploadProgress("APK", apkFile) .execute() return UploadInternalSharingArtifactResponse(apk.toPrettyString(), apk.downloadUrl) } override fun getInAppProducts(): List<GppProduct> { fun AndroidPublisher.Inappproducts.List.withToken(token: String?) = apply { this.token = token } val products = mutableListOf<InAppProduct>() var token: String? = null do { val response = publisher.inappproducts().list(appId).withToken(token).execute() products += response.inappproduct.orEmpty() token = response.tokenPagination?.nextPageToken } while (token != null) return products.map { GppProduct(it.sku, it.toPrettyString()) } } override fun insertInAppProduct(productFile: File) { publisher.inappproducts().insert(appId, readProductFile(productFile)) .apply { autoConvertMissingPrices = true } .execute() } override fun updateInAppProduct(productFile: File): UpdateProductResponse { val product = readProductFile(productFile) try { publisher.inappproducts().update(appId, product.sku, product) .apply { autoConvertMissingPrices = true } .execute() } catch (e: GoogleJsonResponseException) { if (e.statusCode == 404) { return UpdateProductResponse(true) } else { throw e } } return UpdateProductResponse(false) } private fun readProductFile(product: File) = product.inputStream().use { GsonFactory.getDefaultInstance() .createJsonParser(it) .parse(InAppProduct::class.java) } private fun <T, R : AbstractGoogleClientRequest<T>> R.trackUploadProgress( thing: String, file: File, ): R { mediaHttpUploader?.setProgressListener { @Suppress("NON_EXHAUSTIVE_WHEN") when (it.uploadState) { MediaHttpUploader.UploadState.INITIATION_STARTED -> println("Starting $thing upload: $file") MediaHttpUploader.UploadState.MEDIA_IN_PROGRESS -> println("Uploading $thing: ${(it.progress * 100).roundToInt()}% complete") MediaHttpUploader.UploadState.MEDIA_COMPLETE -> println("${thing.capitalize()} upload complete") } } return this } class Factory : PlayPublisher.Factory { override fun create( credentials: InputStream, appId: String, ): PlayPublisher { val publisher = createPublisher(credentials) return DefaultPlayPublisher(publisher, appId) } } private companion object { const val MIME_TYPE_STREAM = "application/octet-stream" const val MIME_TYPE_APK = "application/vnd.android.package-archive" const val MIME_TYPE_IMAGE = "image/*" } }
mit
38b064397579fdfecb8505ca90ebed18
39.03937
103
0.649066
4.87536
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/collections/GroupingTest/groupingProducers.kt
2
1010
import kotlin.test.* fun box() { fun <T, K> verifyGrouping(grouping: Grouping<T, K>, expectedElements: List<T>, expectedKeys: List<K>) { val elements = grouping.sourceIterator().asSequence().toList() val keys = elements.map { grouping.keyOf(it) } // TODO: replace with grouping::keyOf when supported in JS assertEquals(expectedElements, elements) assertEquals(expectedKeys, keys) } val elements = listOf("foo", "bar", "value", "x") val keySelector: (String) -> Int = { it.length } val keys = elements.map(keySelector) fun verifyGrouping(grouping: Grouping<String, Int>) = verifyGrouping(grouping, elements, keys) verifyGrouping(elements.groupingBy { it.length }) verifyGrouping(elements.toTypedArray().groupingBy(keySelector)) verifyGrouping(elements.asSequence().groupingBy(keySelector)) val charSeq = "some sequence of chars" verifyGrouping(charSeq.groupingBy { it.toInt() }, charSeq.toList(), charSeq.map { it.toInt() }) }
apache-2.0
67cc4dd19b4acef9c2d69d3578122f0b
37.846154
113
0.691089
4.334764
false
false
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/ItemStackExtensions.kt
1
3890
/* * 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 import com.google.common.collect.Multimap import io.pixeloutlaw.minecraft.spigot.hilt.getFromItemMeta import io.pixeloutlaw.minecraft.spigot.hilt.getThenSetItemMeta import io.pixeloutlaw.minecraft.spigot.hilt.setDisplayName import io.pixeloutlaw.minecraft.spigot.hilt.setLore import org.bukkit.attribute.Attribute import org.bukkit.attribute.AttributeModifier import org.bukkit.enchantments.Enchantment import org.bukkit.inventory.EquipmentSlot import org.bukkit.inventory.ItemStack import org.bukkit.inventory.meta.Damageable import org.bukkit.inventory.meta.ItemMeta import org.bukkit.inventory.meta.Repairable internal fun ItemStack.setUnsafeEnchantments(enchantments: Map<Enchantment, Int>) { this.enchantments.keys.toSet().forEach { removeEnchantment(it) } addUnsafeEnchantments(enchantments) } internal const val DEFAULT_REPAIR_COST = 1000 internal fun <R> ItemStack.getFromItemMetaAsDamageable(action: Damageable.() -> R): R? { return (this.itemMeta as? Damageable)?.run(action) } internal fun ItemStack.getThenSetItemMetaAsDamageable(action: Damageable.() -> Unit) { (this.itemMeta as? Damageable)?.let { action(it) this.itemMeta = it as ItemMeta } } internal fun <R> ItemStack.getFromItemMetaAsRepairable(action: Repairable.() -> R): R? { return (this.itemMeta as? Repairable)?.run(action) } internal fun ItemStack.getThenSetItemMetaAsRepairable(action: Repairable.() -> Unit) { (this.itemMeta as? Repairable)?.let { action(it) this.itemMeta = it as ItemMeta } } @JvmOverloads internal fun ItemStack.setRepairCost(cost: Int = DEFAULT_REPAIR_COST) = getThenSetItemMetaAsRepairable { this.repairCost = cost } internal fun ItemStack.setDisplayNameChatColorized(string: String) = setDisplayName(string.chatColorize()) internal fun ItemStack.setLoreChatColorized(strings: List<String>) = setLore(strings.chatColorize()) internal fun ItemStack.getAttributeModifiers() = getFromItemMeta { attributeModifiers } internal fun ItemStack.getAttributeModifiers(attribute: Attribute) = getFromItemMeta { [email protected](attribute) } internal fun ItemStack.getAttributeModifiers(equipmentSlot: EquipmentSlot) = getFromItemMeta { [email protected](equipmentSlot) } internal fun ItemStack.setAttributeModifiers(attributeModifiers: Multimap<Attribute, AttributeModifier>) = getThenSetItemMeta { setAttributeModifiers(attributeModifiers) } internal fun ItemStack.addAttributeModifier(attribute: Attribute, attributeModifier: AttributeModifier) = getThenSetItemMeta { addAttributeModifier(attribute, attributeModifier) }
mit
7423087fa171f24662acbff93405f68f
45.309524
129
0.790231
4.523256
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/rule/attribute/TensorflowNDArrayExtractScalarValue.kt
1
5114
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.tensorflow.rule.attribute import org.nd4j.ir.OpNamespace import org.nd4j.samediff.frameworkimport.argDescriptorType import org.nd4j.samediff.frameworkimport.findOp import org.nd4j.samediff.frameworkimport.ir.IRAttribute import org.nd4j.samediff.frameworkimport.isNd4jTensorName import org.nd4j.samediff.frameworkimport.isOutputFrameworkAttributeName import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder import org.nd4j.samediff.frameworkimport.process.MappingProcess import org.nd4j.samediff.frameworkimport.rule.MappingRule import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType import org.nd4j.samediff.frameworkimport.rule.attribute.NDArrayExtractScalarValue import org.nd4j.samediff.frameworkimport.tensorflow.ir.TensorflowIRAttr import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowAttributeName import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowTensorName import org.nd4j.samediff.frameworkimport.tensorflow.ir.tensorflowAttributeValueTypeFor import org.tensorflow.framework.* @MappingRule("tensorflow","ndarrayextractscalarvalue","attribute") class TensorflowNDArrayExtractScalarValue(mappingNamesToPerform: Map<String, String> = emptyMap(), transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>> = emptyMap()) : NDArrayExtractScalarValue<GraphDef, OpDef, NodeDef, OpDef.AttrDef, AttrValue, TensorProto, DataType> ( mappingNamesToPerform, transformerArgs) { override fun createIRAttribute(name: String, attrDef: OpDef.AttrDef, attributeValueType: AttrValue): IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType> { return TensorflowIRAttr(attrDef, attributeValueType) } override fun convertAttributesReverse(allInputArguments: List<OpNamespace.ArgDescriptor>, inputArgumentsToProcess: List<OpNamespace.ArgDescriptor>): List<IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType>> { TODO("Not yet implemented") } override fun isInputFrameworkTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return isTensorflowTensorName(name, opDef) } override fun isNd4jTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return isNd4jTensorName(name,nd4jOpDescriptor) } override fun isInputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return isTensorflowAttributeName(name, opDef) } override fun isOutputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return isOutputFrameworkAttributeName(name,nd4jOpDescriptor) } override fun argDescriptorType(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): OpNamespace.ArgDescriptor.ArgType { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return argDescriptorType(name,nd4jOpDescriptor) } override fun attributeValueTypeFor(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): AttributeValueType { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return tensorflowAttributeValueTypeFor(attributeName = name, opDef = opDef) } }
apache-2.0
b9e18f2ec88287251473ca25a8a07629
59.892857
221
0.762808
5.043393
false
false
false
false
Fotoapparat/Fotoapparat
fotoapparat/src/test/java/io/fotoapparat/selector/LensPositionSelectorsTest.kt
1
2450
package io.fotoapparat.selector import io.fotoapparat.characteristic.LensPosition import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNull class LensPositionSelectorsTest { @Test fun `Select front camera which is available`() { // Given val availablePositions = listOf( LensPosition.Back, LensPosition.Front, LensPosition.External ) // When val result = front()(availablePositions) // Then assertEquals( LensPosition.Front, result ) } @Test fun `Select front camera which is not available`() { // Given val availablePositions = listOf( LensPosition.Back, LensPosition.External ) // When val result = front()(availablePositions) // Then assertNull(result) } @Test fun `Select back camera which is available`() { // Given val availablePositions = listOf( LensPosition.Back, LensPosition.Front, LensPosition.External ) // When val result = back()(availablePositions) // Then assertEquals( LensPosition.Back, result ) } @Test fun `Select back camera which is not available`() { // Given val availablePositions = listOf( LensPosition.Front, LensPosition.External ) // When val result = back()(availablePositions) // Then assertNull(result) } @Test fun `Select external camera which is available`() { // Given val availablePositions = listOf( LensPosition.Back, LensPosition.Front, LensPosition.External ) // When val result = external()(availablePositions) // Then assertEquals( LensPosition.External, result ) } @Test fun `Select external camera which is not available`() { // Given val availablePositions = listOf( LensPosition.Front, LensPosition.Back ) // When val result = external()(availablePositions) // Then assertNull(result) } }
apache-2.0
3600377017b2994a325363264ee9c170
20.883929
59
0.524082
5.889423
false
true
false
false
Flank/flank
flank-scripts/src/main/kotlin/flank/scripts/data/github/GithubApi.kt
1
9101
package flank.scripts.data.github import com.github.kittinunf.fuel.Fuel import com.github.kittinunf.fuel.core.Parameters import com.github.kittinunf.fuel.core.Request import com.github.kittinunf.fuel.core.extensions.authentication import com.github.kittinunf.fuel.coroutines.awaitResult import com.github.kittinunf.fuel.coroutines.awaitStringResult import com.github.kittinunf.result.Result import com.github.kittinunf.result.onError import com.github.kittinunf.result.success import com.jcabi.github.Coordinates import com.jcabi.github.Release import com.jcabi.github.Releases import com.jcabi.github.Repo import com.jcabi.github.RtGithub import flank.common.config.flankRepository import flank.scripts.data.github.objects.GitHubCommit import flank.scripts.data.github.objects.GitHubCommitListDeserializer import flank.scripts.data.github.objects.GitHubCreateIssueCommentRequest import flank.scripts.data.github.objects.GitHubCreateIssueCommentResponse import flank.scripts.data.github.objects.GitHubCreateIssueCommentResponseDeserializer import flank.scripts.data.github.objects.GitHubCreateIssueRequest import flank.scripts.data.github.objects.GitHubCreateIssueResponse import flank.scripts.data.github.objects.GitHubCreateIssueResponseDeserializer import flank.scripts.data.github.objects.GitHubLabelDeserializable import flank.scripts.data.github.objects.GitHubRelease import flank.scripts.data.github.objects.GitHubSetAssigneesRequest import flank.scripts.data.github.objects.GitHubSetLabelsRequest import flank.scripts.data.github.objects.GitHubUpdateIssueRequest import flank.scripts.data.github.objects.GitHubWorkflowRunsSummary import flank.scripts.data.github.objects.GithubPullRequest import flank.scripts.data.github.objects.GithubPullRequestDeserializer import flank.scripts.data.github.objects.GithubPullRequestListDeserializer import flank.scripts.data.github.objects.GithubReleaseDeserializable import flank.scripts.data.github.objects.GithubWorkflowRunsSummaryDeserializer import flank.scripts.utils.exceptions.mapClientErrorToGithubException import flank.scripts.utils.toJson private const val URL_BASE = "https://api.github.com/repos" // ============= HTTP GITHUB API ============= suspend fun getPrDetailsByCommit( commitSha: String, githubToken: String, repo: String = flankRepository ): Result<List<GithubPullRequest>, Exception> = Fuel.get("$URL_BASE/$repo/commits/$commitSha/pulls") .appendGitHubHeaders(githubToken, "application/vnd.github.groot-preview+json") .awaitResult(GithubPullRequestListDeserializer) .mapClientErrorToGithubException() .onError { println("Could not download info for commit $commitSha, because of ${it.message}") } suspend fun getLatestReleaseTag(githubToken: String, repo: String = flankRepository): Result<GitHubRelease, Exception> = Fuel.get("$URL_BASE/$repo/releases/latest") .appendGitHubHeaders(githubToken) .awaitResult(GithubReleaseDeserializable) .mapClientErrorToGithubException() suspend fun getGitHubPullRequest( githubToken: String, issueNumber: Int, repo: String = flankRepository ): Result<GithubPullRequest, Exception> = Fuel.get("$URL_BASE/$repo/pulls/$issueNumber") .appendGitHubHeaders(githubToken) .awaitResult(GithubPullRequestDeserializer) .mapClientErrorToGithubException() suspend fun getGitHubIssue( githubToken: String, issueNumber: Int, repo: String = flankRepository ): Result<GithubPullRequest, Exception> = Fuel.get("$URL_BASE/$repo/issues/$issueNumber") .appendGitHubHeaders(githubToken) .awaitResult(GithubPullRequestDeserializer) .mapClientErrorToGithubException() suspend fun getGitHubIssueList( githubToken: String, parameters: Parameters = emptyList(), repo: String = flankRepository ): Result<List<GithubPullRequest>, Exception> = Fuel.get("$URL_BASE/$repo/issues", parameters) .appendGitHubHeaders(githubToken) .awaitResult(GithubPullRequestListDeserializer) .mapClientErrorToGithubException() suspend fun getGitHubCommitList( githubToken: String, parameters: Parameters = emptyList(), repo: String = flankRepository ): Result<List<GitHubCommit>, Exception> = Fuel.get("$URL_BASE/$repo/commits", parameters) .appendGitHubHeaders(githubToken) .awaitResult(GitHubCommitListDeserializer) .mapClientErrorToGithubException() suspend fun getGitHubWorkflowRunsSummary( githubToken: String, workflow: String, parameters: Parameters = emptyList(), repo: String = flankRepository ): Result<GitHubWorkflowRunsSummary, Exception> = Fuel.get("$URL_BASE/$repo/actions/workflows/$workflow/runs", parameters) .appendGitHubHeaders(githubToken) .awaitResult(GithubWorkflowRunsSummaryDeserializer) .mapClientErrorToGithubException() suspend fun postNewIssueComment( githubToken: String, issueNumber: Int, payload: GitHubCreateIssueCommentRequest, repo: String = flankRepository ): Result<GitHubCreateIssueCommentResponse, Exception> = Fuel.post("$URL_BASE/$repo/issues/$issueNumber/comments") .appendGitHubHeaders(githubToken) .body(payload.toJson()) .awaitResult(GitHubCreateIssueCommentResponseDeserializer) .mapClientErrorToGithubException() suspend fun postNewIssue( githubToken: String, payload: GitHubCreateIssueRequest, repo: String = flankRepository ): Result<GitHubCreateIssueResponse, Exception> = Fuel.post("$URL_BASE/$repo/issues") .appendGitHubHeaders(githubToken) .body(payload.toJson()) .awaitResult(GitHubCreateIssueResponseDeserializer) .mapClientErrorToGithubException() suspend fun getLabelsFromIssue(githubToken: String, issueNumber: Int, repo: String = flankRepository) = Fuel.get("$URL_BASE/$repo/issues/$issueNumber/labels") .appendGitHubHeaders(githubToken) .awaitResult(GitHubLabelDeserializable) .mapClientErrorToGithubException() suspend fun setLabelsToPullRequest( githubToken: String, pullRequestNumber: Int, labels: List<String>, repo: String = flankRepository ) { Fuel.post("$URL_BASE/$repo/issues/$pullRequestNumber/labels") .appendGitHubHeaders(githubToken) .body(GitHubSetLabelsRequest(labels).toJson()) .awaitStringResult() .onError { println("Could not set assignees because of ${it.message}") } .success { println("$labels set to pull request #$pullRequestNumber") } } suspend fun setAssigneesToPullRequest( githubToken: String, pullRequestNumber: Int, assignees: List<String>, repo: String = flankRepository ) { Fuel.post("$URL_BASE/$repo/issues/$pullRequestNumber/assignees") .appendGitHubHeaders(githubToken) .body(GitHubSetAssigneesRequest(assignees).toJson()) .awaitStringResult() .onError { println("Could not set assignees because of ${it.message}") it.printStackTrace() } .success { println("$assignees set to pull request #$pullRequestNumber") } } fun patchIssue( githubToken: String, issueNumber: Int, payload: GitHubUpdateIssueRequest, repo: String = flankRepository ): Result<ByteArray, Exception> = Fuel.patch("$URL_BASE/$repo/issues/$issueNumber") .appendGitHubHeaders(githubToken) .body(payload.toJson()) .response() .third .mapClientErrorToGithubException() fun deleteOldTag( tag: String, username: String, password: String, repo: String = flankRepository ): Result<ByteArray, Exception> = Fuel.delete("$URL_BASE/$repo/git/refs/tags/$tag") .authentication() .basic(username, password) .response() .third .mapClientErrorToGithubException() fun Request.appendGitHubHeaders(githubToken: String, contentType: String = "application/vnd.github.v3+json") = appendHeader("Accept", contentType).also { if (githubToken.isNotBlank()) appendHeader("Authorization", "token $githubToken") } // ============= JCABI GITHUB API ============= fun githubRepo( token: String, repoPath: String ): Repo = createGitHubClient(token).repos().get(Coordinates.Simple(repoPath)) private fun createGitHubClient(gitHubToken: String) = when { gitHubToken.isEmpty() -> RtGithub() else -> RtGithub(gitHubToken) } fun Repo.getRelease(tag: String): Release.Smart? = Releases.Smart(releases()).run { if (!exists(tag)) null else Release.Smart(find(tag)) } fun Repo.getOrCreateRelease(tag: String): Release.Smart = releases().getOrCreateRelease(tag) private fun Releases.getOrCreateRelease(tag: String) = Release.Smart( try { print("* Fetching release $tag - ") Releases.Smart(this).find(tag).also { println("OK") } } catch (e: IllegalArgumentException) { println("FAILED") print("* Creating new release $tag - ") create(tag).also { println("OK") } } )
apache-2.0
e14ccf4c8ea98a73e504ebc83870a890
38.060086
120
0.73838
4.703359
false
false
false
false
SimpleMobileTools/Simple-Music-Player
app/src/main/kotlin/com/simplemobiletools/musicplayer/models/Playlist.kt
1
1164
package com.simplemobiletools.musicplayer.models import androidx.room.* import com.simplemobiletools.commons.helpers.AlphanumericComparator import com.simplemobiletools.commons.helpers.SORT_DESCENDING import com.simplemobiletools.musicplayer.helpers.PLAYER_SORT_BY_TITLE @Entity(tableName = "playlists", indices = [(Index(value = ["id"], unique = true))]) data class Playlist( @PrimaryKey(autoGenerate = true) var id: Int, @ColumnInfo(name = "title") var title: String, @Ignore var trackCount: Int = 0 ) : Comparable<Playlist> { constructor() : this(0, "", 0) companion object { var sorting = 0 } override fun compareTo(other: Playlist): Int { var result = when { sorting and PLAYER_SORT_BY_TITLE != 0 -> AlphanumericComparator().compare(title.toLowerCase(), other.title.toLowerCase()) else -> trackCount.compareTo(other.trackCount) } if (sorting and SORT_DESCENDING != 0) { result *= -1 } return result } fun getBubbleText() = when { sorting and PLAYER_SORT_BY_TITLE != 0 -> title else -> trackCount.toString() } }
gpl-3.0
3f5ffd016a3cf12679dbbe10708a9702
29.631579
133
0.654639
4.327138
false
false
false
false
code-helix/slatekit
src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Sms.kt
1
4106
/** * <slate_header> * author: Kishore Reddy * url: www.github.com/code-helix/slatekit * copyright: 2015 Kishore Reddy * license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md * desc: A tool-kit, utility library and server-backend * usage: Please refer to license on github for more info. * </slate_header> */ package slatekit.examples //<doc:import_required> import slatekit.notifications.sms.SmsMessage import slatekit.notifications.sms.SmsService import slatekit.notifications.sms.TwilioSms //</doc:import_required> //<doc:import_examples> import slatekit.common.templates.Template import slatekit.common.templates.TemplatePart import slatekit.common.templates.Templates import slatekit.common.conf.Config import slatekit.common.info.ApiLogin import slatekit.common.types.Vars import slatekit.common.ext.env import slatekit.results.Try import slatekit.results.Success import kotlinx.coroutines.runBlocking import slatekit.common.ext.orElse import slatekit.common.io.Uris import slatekit.common.types.Countries //</doc:import_examples> class Example_Sms : Command("sms") { override fun execute(request: CommandRequest): Try<Any> { //<doc:setup> // Setup 1: Getting Api key/login info from config // Load the config file from slatekit directory in user_home directory // e.g. {user_home}/myapp/conf/sms.conf // NOTE: It is safer/more secure to store config files there. val conf = Config.of("~/.slatekit/conf/sms.conf") val apiKey1 = conf.apiLogin("sms") // Setup 2: Get the api key either through conf or explicitly val apiKey2 = ApiLogin("17181234567", "ABC1234567", "password", "dev", "twilio-sms") // Setup 3a: Setup the sms service ( basic ) with api key // Note: The sms service will default to only USA ( you can customize this later ) val apiKey = apiKey1 ?: apiKey2 val sms1 = TwilioSms(apiKey.key, apiKey.pass, apiKey.account) // Setup 3b: Setup the sms service with support for templates // Template 1: With explicit text and embedded variables // Template 2: Loaded from text file val templates = Templates.build( templates = listOf( Template("sms_welcome", """ Hi @{user.name}, Welcome to @{app.name}! We have sent a welcome email and account confirmation to @{user.email}. """.trimIndent()), Template("sms_confirm", Uris.readText("~/slatekit/templates/sms_confirm.txt") ?: "") ), subs = listOf( "app.name" to { s: TemplatePart -> "My App" }, "app.from" to { s: TemplatePart -> "My App Team" } ) ) val sms2 = TwilioSms(apiKey.key, apiKey.pass, apiKey.account, templates) // Setup 3b: Setup the templates with support for different country codes val countries = Countries.filter(listOf("US", "FR")) val sms3 = TwilioSms(apiKey.key, apiKey.pass, apiKey.account, templates, countries) val sms: SmsService = sms3 //</doc:setup> //<doc:examples> runBlocking { // Sample phone number ( loaded from environment variable for test/example purposes ) val phone = "SLATEKIT_EXAMPLE_PHONE".env().orElse("1234567890") // Use case 1: Send an invitation message to phone "234567890 in the United States. sms.send("Invitation to MyApp.com 1", "us", phone) // Use case 2: Send using a constructed message object sms.sendSync(SmsMessage("Invitation to MyApp.com 2", "us", phone)) // Use case 3: Send message using one of the templates sms.sendTemplate("sms_welcome", "us", phone, Vars(listOf( "user.name" to "user1", "user.email" to "[email protected]" ))) } //</doc:examples> return Success("") } }
apache-2.0
d849f8c5f12720fbfad4e2327e1e0d21
38.104762
108
0.622747
4.281543
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/links/linkdetails/LinkDetailsActivity.kt
1
11392
package io.github.feelfreelinux.wykopmobilny.ui.modules.links.linkdetails import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.view.Menu import android.view.MenuItem import androidx.core.content.ContextCompat import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.api.WykopImageFile import io.github.feelfreelinux.wykopmobilny.api.suggest.SuggestApi import io.github.feelfreelinux.wykopmobilny.base.BaseActivity import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link import io.github.feelfreelinux.wykopmobilny.models.dataclass.LinkComment import io.github.feelfreelinux.wykopmobilny.ui.adapters.LinkDetailsAdapter import io.github.feelfreelinux.wykopmobilny.ui.fragments.linkcomments.LinkCommentViewListener import io.github.feelfreelinux.wykopmobilny.ui.modules.input.BaseInputActivity import io.github.feelfreelinux.wykopmobilny.ui.widgets.InputToolbarListener import io.github.feelfreelinux.wykopmobilny.utils.isVisible import io.github.feelfreelinux.wykopmobilny.utils.preferences.LinksPreferencesApi import io.github.feelfreelinux.wykopmobilny.utils.preferences.SettingsPreferencesApi import io.github.feelfreelinux.wykopmobilny.utils.prepare import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi import kotlinx.android.synthetic.main.activity_link_details.* import kotlinx.android.synthetic.main.toolbar.* import javax.inject.Inject class LinkDetailsActivity : BaseActivity(), LinkDetailsView, androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener, InputToolbarListener, LinkCommentViewListener { companion object { const val EXTRA_LINK = "LINK_PARCEL" const val EXTRA_LINK_ID = "EXTRA_LINKID" const val EXTRA_COMMENT_ID = "EXTRA_COMMENT_ID" fun createIntent(context: Context, link: Link) = Intent(context, LinkDetailsActivity::class.java).apply { putExtra(EXTRA_LINK, link) } fun createIntent(context: Context, linkId: Int, commentId: Int? = null) = Intent(context, LinkDetailsActivity::class.java).apply { putExtra(EXTRA_LINK_ID, linkId) putExtra(EXTRA_COMMENT_ID, commentId) } } @Inject lateinit var userManagerApi: UserManagerApi @Inject lateinit var settingsApi: SettingsPreferencesApi @Inject lateinit var suggestionsApi: SuggestApi @Inject lateinit var linkPreferences: LinksPreferencesApi @Inject lateinit var adapter: LinkDetailsAdapter @Inject lateinit var presenter: LinkDetailsPresenter lateinit var contentUri: Uri override val enableSwipeBackLayout: Boolean = true val linkId by lazy { if (intent.hasExtra(EXTRA_LINK)) link.id else intent.getIntExtra(EXTRA_LINK_ID, -1) } private val link by lazy { intent.getParcelableExtra<Link>(EXTRA_LINK) } private var replyLinkId: Int = 0 private val linkCommentId by lazy { intent.getIntExtra(EXTRA_COMMENT_ID, -1) } override fun updateLinkComment(comment: LinkComment) { adapter.updateLinkComment(comment) } override fun replyComment(comment: LinkComment) { replyLinkId = comment.id inputToolbar.addAddressant(comment.author.nick) } override fun setCollapsed(comment: LinkComment, isCollapsed: Boolean) { adapter.link?.comments?.forEach { when (comment.id) { it.id -> { it.isCollapsed = isCollapsed it.isParentCollapsed = false } it.parentId -> it.isParentCollapsed = isCollapsed } } adapter.notifyDataSetChanged() } override fun getReplyCommentId(): Int { return if (replyLinkId != 0 && inputToolbar.textBody.contains("@")) replyLinkId else -1 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_link_details) setSupportActionBar(toolbar) presenter.subscribe(this) adapter.linkCommentViewListener = this adapter.linkHeaderActionListener = presenter adapter.linkCommentActionListener = presenter supportActionBar?.apply { title = null setDisplayHomeAsUpEnabled(true) } toolbar.overflowIcon = ContextCompat.getDrawable(this, R.drawable.ic_sort) // Prepare RecyclerView recyclerView?.apply { prepare() // Set margin, adapter this.adapter = [email protected] } supportActionBar?.title = "Znalezisko" presenter.linkId = linkId if (intent.hasExtra(EXTRA_LINK)) { adapter.link = link adapter.notifyDataSetChanged() } adapter.highlightCommentId = linkCommentId // Prepare InputToolbar inputToolbar.setup(userManagerApi, suggestionsApi) inputToolbar.inputToolbarListener = this swiperefresh.setOnRefreshListener(this) presenter.sortBy = linkPreferences.linkCommentsDefaultSort ?: "best" adapter.notifyDataSetChanged() loadingView?.isVisible = true hideInputToolbar() if (adapter.link != null) { presenter.loadComments() presenter.updateLink() } else { presenter.loadLinkAndComments() } setSubtitle() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater?.inflate(R.menu.link_details_menu, menu) return true } private fun setSubtitle() { supportActionBar?.setSubtitle( when (presenter.sortBy) { "new" -> R.string.sortby_newest "old" -> R.string.sortby_oldest else -> R.string.sortby_best } ) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.refresh -> onRefresh() R.id.sortbyBest -> { presenter.sortBy = "best" linkPreferences.linkCommentsDefaultSort = "best" setSubtitle() presenter.loadComments() swiperefresh?.isRefreshing = true } R.id.sortbyNewest -> { presenter.sortBy = "new" linkPreferences.linkCommentsDefaultSort = "new" setSubtitle() presenter.loadComments() swiperefresh?.isRefreshing = true } R.id.sortbyOldest -> { presenter.sortBy = "old" linkPreferences.linkCommentsDefaultSort = "old" setSubtitle() presenter.loadComments() swiperefresh?.isRefreshing = true } android.R.id.home -> finish() } return true } override fun onRefresh() { presenter.loadComments() presenter.updateLink() adapter.notifyDataSetChanged() } override fun showLinkComments(comments: List<LinkComment>) { adapter.link?.comments = comments.toMutableList() // Auto-Collapse comments depending on settings if (settingsApi.hideLinkCommentsByDefault) { adapter.link?.comments?.forEach { if (it.parentId == it.id) { it.isCollapsed = true } else { it.isParentCollapsed = true } } } loadingView?.isVisible = false swiperefresh?.isRefreshing = false adapter.notifyDataSetChanged() inputToolbar.show() if (linkCommentId != -1 && adapter.link != null) { if (settingsApi.hideLinkCommentsByDefault) { expandAndScrollToComment(linkCommentId) } else { scrollToComment(linkCommentId) } } } private fun expandAndScrollToComment(linkCommentId: Int) { adapter.link?.comments?.let { allComments -> val parentId = allComments.find { it.id == linkCommentId }?.parentId allComments.forEach { if (it.parentId == parentId) { it.isCollapsed = false it.isParentCollapsed = false } } } adapter.notifyDataSetChanged() val comments = adapter.link!!.comments var index = 0 for (i in 0 until comments.size) { if (!comments[i].isParentCollapsed) index++ if (comments[i].id == linkCommentId) break } recyclerView?.scrollToPosition(index + 1) } override fun scrollToComment(id: Int) { val index = adapter.link!!.comments.indexOfFirst { it.id == id } recyclerView?.scrollToPosition(index + 1) } override fun updateLink(link: Link) { link.comments = adapter.link?.comments ?: mutableListOf() adapter.updateLinkHeader(link) inputToolbar.show() } override fun openGalleryImageChooser() { val intent = Intent() intent.type = "image/*" intent.action = Intent.ACTION_GET_CONTENT startActivityForResult( Intent.createChooser( intent, getString(R.string.insert_photo_galery) ), BaseInputActivity.USER_ACTION_INSERT_PHOTO ) } override fun sendPhoto(photo: String?, body: String, containsAdultContent: Boolean) { presenter.sendReply(body, photo, containsAdultContent) } override fun sendPhoto(photo: WykopImageFile, body: String, containsAdultContent: Boolean) { presenter.sendReply(body, photo, containsAdultContent) } override fun hideInputToolbar() { inputToolbar.hide() } override fun hideInputbarProgress() { inputToolbar.showProgress(false) } override fun resetInputbarState() { hideInputbarProgress() inputToolbar.resetState() replyLinkId = 0 } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK) { when (requestCode) { BaseInputActivity.USER_ACTION_INSERT_PHOTO -> { inputToolbar.setPhoto(data?.data) } BaseInputActivity.REQUEST_CODE -> { onRefresh() } BaseInputActivity.USER_ACTION_INSERT_PHOTO_CAMERA -> { inputToolbar.setPhoto(contentUri) } BaseInputActivity.EDIT_LINK_COMMENT -> { val commentId = data?.getIntExtra("commentId", -1) onRefresh() scrollToComment(commentId ?: -1) } } } } override fun openCamera(uri: Uri) { contentUri = uri val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) intent.putExtra(MediaStore.EXTRA_OUTPUT, uri) startActivityForResult(intent, BaseInputActivity.USER_ACTION_INSERT_PHOTO_CAMERA) } override fun onDestroy() { super.onDestroy() presenter.unsubscribe() } }
mit
1c84d410a930e6be82af8ef24fb2807e
34.055385
133
0.630442
5.138475
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/hints/KotlinCallChainHintsProvider.kt
1
4281
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.codeInsight.hints import com.intellij.codeInsight.hints.InlayInfo import com.intellij.codeInsight.hints.chain.AbstractCallChainHintsProvider import com.intellij.codeInsight.hints.presentation.InlayPresentation import com.intellij.codeInsight.hints.presentation.PresentationFactory import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.parameterInfo.HintsTypeRenderer import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType /** * Kotlin's analog for Java's [com.intellij.codeInsight.hints.MethodChainsInlayProvider] * * Test - [org.jetbrains.kotlin.idea.codeInsight.hints.KotlinCallChainHintsProviderTest] */ class KotlinCallChainHintsProvider : AbstractCallChainHintsProvider<KtQualifiedExpression, KotlinType, BindingContext>() { override val previewText: String get() = """ fun main() { (1..100).filter { it % 2 == 0 } .map { it * 2 } .takeIf { list -> list.all { it % 2 == 0 } } ?.map { "item: ${'$'}it" } ?.forEach { println(it) } } inline fun IntRange.filter(predicate: (Int) -> Boolean): List<Int> = TODO() inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> = TODO() inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? = TODO() inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean = TODO() inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit = TODO() inline fun println(message: Any?) = TODO() """.trimIndent() override fun KotlinType.getInlayPresentation( expression: PsiElement, factory: PresentationFactory, project: Project, context: BindingContext ): InlayPresentation { val inlayInfoDetails = HintsTypeRenderer .getInlayHintsTypeRenderer(context, expression as? KtElement ?: error("Only Kotlin psi are possible")) .renderType(this) return KotlinAbstractHintsProvider.getInlayPresentationForInlayInfoDetails( InlayInfoDetails(InlayInfo("", expression.textRange.endOffset), inlayInfoDetails), factory, project, this@KotlinCallChainHintsProvider ) } override fun getTypeComputationContext(topmostDotQualifiedExpression: KtQualifiedExpression): BindingContext { return topmostDotQualifiedExpression.analyze(BodyResolveMode.PARTIAL_NO_ADDITIONAL) } override fun PsiElement.getType(context: BindingContext): KotlinType? { return context.getType(this as? KtExpression ?: return null) } override val dotQualifiedClass: Class<KtQualifiedExpression> get() = KtQualifiedExpression::class.java override fun KtQualifiedExpression.getReceiver(): PsiElement { return receiverExpression } override fun KtQualifiedExpression.getParentDotQualifiedExpression(): KtQualifiedExpression? { var expr: PsiElement? = parent while ( expr is KtPostfixExpression || expr is KtParenthesizedExpression || expr is KtArrayAccessExpression || expr is KtCallExpression ) { expr = expr.parent } return expr as? KtQualifiedExpression } override fun PsiElement.skipParenthesesAndPostfixOperatorsDown(): PsiElement? { var expr: PsiElement? = this while (true) { expr = when (expr) { is KtPostfixExpression -> expr.baseExpression is KtParenthesizedExpression -> expr.expression is KtArrayAccessExpression -> expr.arrayExpression is KtCallExpression -> expr.calleeExpression else -> break } } return expr } }
apache-2.0
8b19ec5b25e83ca896d588841e8136c3
41.386139
158
0.661294
5.195388
false
false
false
false
Zhouzhouzhou/AndroidDemo
app/src/main/java/com/zhou/android/common/PaddingItemDecoration.kt
1
963
package com.zhou.android.common import android.content.Context import android.graphics.Rect import android.support.v7.widget.RecyclerView import android.view.View /** * 边距设置 * Created by mxz on 2020/3/23. */ class PaddingItemDecoration(context: Context, left: Int = 0, top: Int = 0, right: Int = 0, bottom: Int = 0) : RecyclerView.ItemDecoration() { private var leftPadding = 0 private var topPadding = 0 private var rightPadding = 0 private var bottomPadding = 0 init { val density = context.resources.displayMetrics.density leftPadding = (density * left).toInt() topPadding = (density * top).toInt() rightPadding = (density * right).toInt() bottomPadding = (density * bottom).toInt() } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) { outRect.set(leftPadding, topPadding, rightPadding, bottomPadding) } }
mit
f32473744b3b6b66bc9cafca877f7950
30.866667
110
0.689005
4.207048
false
false
false
false
siosio/intellij-community
platform/util-ex/src/com/intellij/openapi/progress/suspender.kt
2
3454
// 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. @file:ApiStatus.Experimental package com.intellij.openapi.progress import kotlinx.coroutines.suspendCancellableCoroutine import org.jetbrains.annotations.ApiStatus import java.util.concurrent.atomic.AtomicReference import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.Continuation import kotlin.coroutines.CoroutineContext import kotlin.coroutines.resume /** * Coroutine pause-ability is cooperative, the coroutine must periodically invoke [checkCanceled] to achieve that. * * Example: * ``` * val suspender = coroutineSuspender() * launch(Dispatchers.Default + suspender) { * for (item in data) { * checkCanceled() * // process data * } * } * * // later e.g. when user clicks the button: * suspender.pause() // after this call the coroutine (and its children) will suspend in the checkCanceled() * ``` * * @param active `true` means non-paused, while `false` creates a suspender in paused state * @return handle which can be used to pause and resume the coroutine * @see checkCanceled */ fun coroutineSuspender(active: Boolean = true): CoroutineSuspender = CoroutineSuspenderElement(active) /** * Implementation of this interface is thread-safe. */ @ApiStatus.NonExtendable interface CoroutineSuspender : CoroutineContext { fun pause() fun resume() } private val EMPTY_PAUSED_STATE: CoroutineSuspenderState = CoroutineSuspenderState.Paused(emptyArray()) private sealed class CoroutineSuspenderState { object Active : CoroutineSuspenderState() class Paused(val continuations: Array<Continuation<Unit>>) : CoroutineSuspenderState() } /** * Internal so it's not possible to access this element from the client code, * because clients must not be able to pause themselves. * The code which calls [coroutineSuspender] must store the reference somewhere, * because this code is responsible for pausing/resuming. */ internal object CoroutineSuspenderElementKey : CoroutineContext.Key<CoroutineSuspenderElement> internal class CoroutineSuspenderElement(active: Boolean) : AbstractCoroutineContextElement(CoroutineSuspenderElementKey), CoroutineSuspender { private val myState: AtomicReference<CoroutineSuspenderState> = AtomicReference( if (active) CoroutineSuspenderState.Active else EMPTY_PAUSED_STATE ) override fun pause() { myState.compareAndSet(CoroutineSuspenderState.Active, EMPTY_PAUSED_STATE) } override fun resume() { val oldState = myState.getAndSet(CoroutineSuspenderState.Active) if (oldState is CoroutineSuspenderState.Paused) { for (suspendedContinuation in oldState.continuations) { suspendedContinuation.resume(Unit) } } } suspend fun checkPaused() { while (true) { when (val state = myState.get()) { is CoroutineSuspenderState.Active -> return // don't suspend is CoroutineSuspenderState.Paused -> suspendCancellableCoroutine { continuation: Continuation<Unit> -> val newState = CoroutineSuspenderState.Paused(state.continuations + continuation) if (!myState.compareAndSet(state, newState)) { // don't suspend here; on the next loop iteration either the CAS will succeed, or the suspender will be in Active state continuation.resume(Unit) } } } } } }
apache-2.0
e846fab763fd7f36b179cc58884ae648
34.244898
140
0.748118
4.851124
false
false
false
false
jwren/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/resolve/lazy/PartialBodyResolveFilter.kt
1
25845
// 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.resolve.lazy import com.intellij.psi.PsiElement import com.intellij.psi.PsiRecursiveElementVisitor import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.StatementFilter import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.swap import java.util.* //TODO: do resolve anonymous object's body class PartialBodyResolveFilter( elementsToResolve: Collection<KtElement>, private val declaration: KtDeclaration, forCompletion: Boolean ) : StatementFilter() { private val statementMarks = StatementMarks() private val globalProbablyNothingCallableNames = ProbablyNothingCallableNames.getInstance(declaration.project) private val globalProbablyContractedCallableNames = ProbablyContractedCallableNames.getInstance(declaration.project) private val contextNothingFunctionNames = HashSet<String>() private val contextNothingVariableNames = HashSet<String>() override val filter: ((KtExpression) -> Boolean)? = { statementMarks.statementMark(it) != MarkLevel.NONE } val allStatementsToResolve: Collection<KtExpression> get() = statementMarks.allMarkedStatements() init { elementsToResolve.forEach { assert(declaration.isAncestor(it)) } assert(!KtPsiUtil.isLocal(declaration)) { "Should never be invoked on local declaration otherwise we may miss some local declarations with type Nothing" } declaration.forEachDescendantOfType<KtCallableDeclaration> { declaration -> if (declaration.typeReference.containsProbablyNothing()) { val name = declaration.name if (name != null) { if (declaration is KtNamedFunction) { contextNothingFunctionNames.add(name) } else { contextNothingVariableNames.add(name) } } } } elementsToResolve.forEach { statementMarks.mark(it, if (forCompletion) MarkLevel.NEED_COMPLETION else MarkLevel.NEED_REFERENCE_RESOLVE) } declaration.forTopLevelBlocksInside { processBlock(it) } } //TODO: do..while is special case private fun processBlock(block: KtBlockExpression): NameFilter { if (isValueNeeded(block)) { block.lastStatement()?.let { statementMarks.mark(it, MarkLevel.NEED_REFERENCE_RESOLVE) } } val nameFilter = NameFilter() val startStatement = statementMarks.lastMarkedStatement(block, MarkLevel.NEED_REFERENCE_RESOLVE) ?: return nameFilter for (statement in startStatement.siblings(forward = false)) { if (statement !is KtExpression) continue if (statement is KtNamedDeclaration) { val name = statement.getName() if (name != null && nameFilter(name)) { statementMarks.mark(statement, MarkLevel.NEED_REFERENCE_RESOLVE) } } else if (statement is KtDestructuringDeclaration) { if (statement.entries.any { val name = it.name name != null && nameFilter(name) }) { statementMarks.mark(statement, MarkLevel.NEED_REFERENCE_RESOLVE) } } fun updateNameFilter() { when (statementMarks.statementMark(statement)) { MarkLevel.NONE, MarkLevel.TAKE -> { } MarkLevel.NEED_REFERENCE_RESOLVE -> nameFilter.addUsedNames(statement) MarkLevel.NEED_COMPLETION -> nameFilter.addAllNames() } } updateNameFilter() if (!nameFilter.isEmpty) { val smartCastPlaces = potentialSmartCastPlaces(statement) { it.affectsNames(nameFilter) } if (!smartCastPlaces.isEmpty()) { //TODO: do we really need correct resolve for ALL smart cast places? smartCastPlaces.values .flatten() .forEach { statementMarks.mark(it, MarkLevel.NEED_REFERENCE_RESOLVE) } updateNameFilter() } } val level = statementMarks.statementMark(statement) if (level > MarkLevel.TAKE) { // otherwise there are no statements inside that need processBlock which only works when reference resolve needed statement.forTopLevelBlocksInside { nestedBlock -> val childFilter = processBlock(nestedBlock) nameFilter.addNamesFromFilter(childFilter) } } } return nameFilter } /** * Finds places within the given statement that may affect smart-casts after it. * That is, such places whose containing statements must be left in code to keep the smart-casts. * Returns map from smart-cast expression names (variable name or qualified variable name) to places. */ private fun potentialSmartCastPlaces( statement: KtExpression, filter: (SmartCastName) -> Boolean = { true } ): Map<SmartCastName, List<KtExpression>> { val map = HashMap<SmartCastName, ArrayList<KtExpression>>(0) fun addPlace(name: SmartCastName, place: KtExpression) { map.getOrPut(name) { ArrayList(1) }.add(place) } fun addPlaces(name: SmartCastName, places: Collection<KtExpression>) { if (places.isNotEmpty()) { map.getOrPut(name) { ArrayList(places.size) }.addAll(places) } } fun addIfCanBeSmartCast(expression: KtExpression) { val name = expression.smartCastExpressionName() ?: return if (filter(name)) { addPlace(name, expression) } } statement.accept(object : ControlFlowVisitor() { override fun visitPostfixExpression(expression: KtPostfixExpression) { expression.acceptChildren(this) if (expression.operationToken == KtTokens.EXCLEXCL) { addIfCanBeSmartCast(expression.baseExpression ?: return) } } override fun visitCallExpression(expression: KtCallExpression) { super.visitCallExpression(expression) val nameReference = expression.calleeExpression as? KtNameReferenceExpression ?: return if (!globalProbablyContractedCallableNames.isProbablyContractedCallableName(nameReference.getReferencedName())) return val mentionedSmartCastName = expression.findMentionedName(filter) if (mentionedSmartCastName != null) { addPlace(mentionedSmartCastName, expression) } } override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) { expression.acceptChildren(this) if (expression.operationReference.getReferencedNameElementType() == KtTokens.AS_KEYWORD) { addIfCanBeSmartCast(expression.left) } } override fun visitBinaryExpression(expression: KtBinaryExpression) { expression.acceptChildren(this) if (expression.operationToken == KtTokens.ELVIS) { val left = expression.left val right = expression.right if (left != null && right != null) { val smartCastName = left.smartCastExpressionName() if (smartCastName != null && filter(smartCastName)) { val exits = collectAlwaysExitPoints(right) addPlaces(smartCastName, exits) } } } } override fun visitIfExpression(expression: KtIfExpression) { val condition = expression.condition val thenBranch = expression.then val elseBranch = expression.`else` val (thenSmartCastNames, elseSmartCastNames) = possiblySmartCastInCondition(condition) fun processBranchExits(smartCastNames: Collection<SmartCastName>, branch: KtExpression?) { if (branch == null) return val filteredNames = smartCastNames.filter(filter) if (filteredNames.isNotEmpty()) { val exits = collectAlwaysExitPoints(branch) if (exits.isNotEmpty()) { for (name in filteredNames) { addPlaces(name, exits) } } } } processBranchExits(thenSmartCastNames, elseBranch) processBranchExits(elseSmartCastNames, thenBranch) condition?.accept(this) if (thenBranch != null && elseBranch != null) { val thenCasts = potentialSmartCastPlaces(thenBranch, filter) if (thenCasts.isNotEmpty()) { val elseCasts = potentialSmartCastPlaces(elseBranch) { filter(it) && thenCasts.containsKey(it) } if (elseCasts.isNotEmpty()) { for ((name, places) in thenCasts) { if (elseCasts.containsKey(name)) { // need filtering by cast names in else-branch addPlaces(name, places) } } for ((name, places) in elseCasts) { // already filtered by cast names in then-branch addPlaces(name, places) } } } } } override fun visitForExpression(expression: KtForExpression) { // analyze only the loop-range expression, do not enter the loop body expression.loopRange?.accept(this) } override fun visitWhileExpression(expression: KtWhileExpression) { val condition = expression.condition // we need to enter the body only for "while(true)" if (condition.isTrueConstant()) { expression.acceptChildren(this) } else { condition?.accept(this) } } //TODO: when }) return map } private fun KtExpression.findMentionedName(filter: (SmartCastName) -> Boolean): SmartCastName? { var foundMentionedName: SmartCastName? = null val visitor = object : PsiRecursiveElementVisitor() { override fun visitElement(element: PsiElement) { if (foundMentionedName != null) return if (element !is KtSimpleNameExpression) super.visitElement(element) if (element !is KtExpression) return element.smartCastExpressionName()?.takeIf(filter)?.let { foundMentionedName = it } } } accept(visitor) return foundMentionedName } /** * Returns names of expressions that would possibly be smart cast * in then (first component) and else (second component) * branches of an if-statement with such condition */ private fun possiblySmartCastInCondition(condition: KtExpression?): Pair<Set<SmartCastName>, Set<SmartCastName>> { val emptyResult = Pair(setOf<SmartCastName>(), setOf<SmartCastName>()) when (condition) { is KtBinaryExpression -> { val operation = condition.operationToken val left = condition.left ?: return emptyResult val right = condition.right ?: return emptyResult fun smartCastInEq(): Pair<Set<SmartCastName>, Set<SmartCastName>> = when { left.isNullLiteral() -> { Pair(setOf(), right.smartCastExpressionName().singletonOrEmptySet()) } right.isNullLiteral() -> { Pair(setOf(), left.smartCastExpressionName().singletonOrEmptySet()) } else -> { val leftName = left.smartCastExpressionName() val rightName = right.smartCastExpressionName() val names = listOfNotNull(leftName, rightName).toSet() Pair(names, setOf()) } } when (operation) { KtTokens.EQEQ, KtTokens.EQEQEQ -> return smartCastInEq() KtTokens.EXCLEQ, KtTokens.EXCLEQEQEQ -> return smartCastInEq().swap() KtTokens.ANDAND -> { val casts1 = possiblySmartCastInCondition(left) val casts2 = possiblySmartCastInCondition(right) return Pair(casts1.first.union(casts2.first), casts1.second.intersect(casts2.second)) } KtTokens.OROR -> { val casts1 = possiblySmartCastInCondition(left) val casts2 = possiblySmartCastInCondition(right) return Pair(casts1.first.intersect(casts2.first), casts1.second.union(casts2.second)) } } } is KtIsExpression -> { val cast = condition.leftHandSide.smartCastExpressionName().singletonOrEmptySet() return if (condition.isNegated) Pair(setOf(), cast) else Pair(cast, setOf()) } is KtPrefixExpression -> { if (condition.operationToken == KtTokens.EXCL) { val operand = condition.baseExpression ?: return emptyResult return possiblySmartCastInCondition(operand).swap() } } is KtParenthesizedExpression -> { val operand = condition.expression ?: return emptyResult return possiblySmartCastInCondition(operand) } } return emptyResult } /** * If it's possible that the given statement never passes the execution to the next statement (that is, always exits somewhere) * then this function returns a collection of all places in code that are necessary to be kept to preserve this behaviour. */ private fun collectAlwaysExitPoints(statement: KtExpression?): Collection<KtExpression> { val result = ArrayList<KtExpression>() statement?.accept(object : ControlFlowVisitor() { var insideLoopLevel: Int = 0 override fun visitReturnExpression(expression: KtReturnExpression) { result.add(expression) } override fun visitThrowExpression(expression: KtThrowExpression) { result.add(expression) } override fun visitIfExpression(expression: KtIfExpression) { expression.condition?.accept(this) val thenBranch = expression.then val elseBranch = expression.`else` if (thenBranch != null && elseBranch != null) { // if we have only one branch it makes no sense to search exits in it val thenExits = collectAlwaysExitPoints(thenBranch) if (thenExits.isNotEmpty()) { val elseExits = collectAlwaysExitPoints(elseBranch) if (elseExits.isNotEmpty()) { result.addAll(thenExits) result.addAll(elseExits) } } } } override fun visitForExpression(loop: KtForExpression) { loop.loopRange?.accept(this) // do not make sense to search exits inside for as not necessary enter it at all } override fun visitWhileExpression(loop: KtWhileExpression) { val condition = loop.condition ?: return if (condition.isTrueConstant()) { insideLoopLevel++ loop.body?.accept(this) insideLoopLevel-- } else { // do not make sense to search exits inside while-loop as not necessary enter it at all condition.accept(this) } } override fun visitDoWhileExpression(loop: KtDoWhileExpression) { loop.condition?.accept(this) insideLoopLevel++ loop.body?.accept(this) insideLoopLevel-- } override fun visitBreakExpression(expression: KtBreakExpression) { if (insideLoopLevel == 0 || expression.getLabelName() != null) { result.add(expression) } } override fun visitContinueExpression(expression: KtContinueExpression) { if (insideLoopLevel == 0 || expression.getLabelName() != null) { result.add(expression) } } override fun visitCallExpression(expression: KtCallExpression) { val name = (expression.calleeExpression as? KtSimpleNameExpression)?.getReferencedName() if (name != null && (name in globalProbablyNothingCallableNames.functionNames() || name in contextNothingFunctionNames)) { result.add(expression) } super.visitCallExpression(expression) } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val name = expression.getReferencedName() if (name in globalProbablyNothingCallableNames.propertyNames() || name in contextNothingVariableNames) { result.add(expression) } } override fun visitBinaryExpression(expression: KtBinaryExpression) { if (expression.operationToken == KtTokens.ELVIS) { // do not search exits after "?:" expression.left?.accept(this) } else { super.visitBinaryExpression(expression) } } }) return result } /** * Recursively visits code but does not enter constructs that may not affect smart casts/control flow */ private abstract class ControlFlowVisitor : KtVisitorVoid() { override fun visitKtElement(element: KtElement) { if (element.noControlFlowInside()) return element.acceptChildren(this) } private fun KtElement.noControlFlowInside() = this is KtFunction || this is KtClass || this is KtClassBody } private data class SmartCastName( private val receiverName: SmartCastName?, private val selectorName: String? /* null means "this" (and receiverName should be null */ ) { init { if (selectorName == null) { assert(receiverName == null) { "selectorName is allowed to be null only when receiverName is also null (which means 'this')" } } } override fun toString(): String = if (receiverName != null) "$receiverName.$selectorName" else selectorName ?: "this" fun affectsNames(nameFilter: (String) -> Boolean): Boolean { if (selectorName == null) return true if (!nameFilter(selectorName)) return false return receiverName == null || receiverName.affectsNames(nameFilter) } } private fun KtExpression.smartCastExpressionName(): SmartCastName? { return when (this) { is KtSimpleNameExpression -> SmartCastName(null, this.getReferencedName()) is KtQualifiedExpression -> { val selector = selectorExpression as? KtSimpleNameExpression ?: return null val selectorName = selector.getReferencedName() val receiver = receiverExpression if (receiver is KtThisExpression) { return SmartCastName(null, selectorName) } val receiverName = receiver.smartCastExpressionName() ?: return null return SmartCastName(receiverName, selectorName) } is KtThisExpression -> SmartCastName(null, null) else -> null } } //TODO: declarations with special names (e.g. "get") private class NameFilter : (String) -> Boolean { private var names: MutableSet<String>? = HashSet() override fun invoke(name: String) = names == null || name in names!! val isEmpty: Boolean get() = names?.isEmpty() ?: false fun addUsedNames(statement: KtExpression) { if (names != null) { statement.forEachDescendantOfType<KtSimpleNameExpression>(canGoInside = { it !is KtBlockExpression }) { names!!.add(it.getReferencedName()) } } } fun addNamesFromFilter(filter: NameFilter) { if (names == null) return if (filter.names == null) { names = null } else { names!!.addAll(filter.names!!) } } fun addAllNames() { names = null } } private enum class MarkLevel { NONE, TAKE, NEED_REFERENCE_RESOLVE, NEED_COMPLETION } companion object { fun findStatementToResolve(element: KtElement, declaration: KtDeclaration): KtExpression? { return element.parentsWithSelf.takeWhile { it != declaration }.firstOrNull { it.isStatement() } as KtExpression? } private fun KtElement.forTopLevelBlocksInside(action: (KtBlockExpression) -> Unit) { forEachDescendantOfType(canGoInside = { it !is KtBlockExpression }, action = action) } private fun KtExpression?.isNullLiteral() = this?.node?.elementType == KtNodeTypes.NULL private fun KtExpression?.isTrueConstant() = this != null && node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT && text == "true" private fun <T : Any> T?.singletonOrEmptySet(): Set<T> = if (this != null) setOf(this) else setOf() //TODO: review logic private fun isValueNeeded(expression: KtExpression): Boolean = when (val parent = expression.parent) { is KtBlockExpression -> expression == parent.lastStatement() && isValueNeeded(parent) is KtContainerNode -> { //TODO - not quite correct val pparent = parent.parent as? KtExpression pparent != null && isValueNeeded(pparent) } is KtDeclarationWithBody -> { if (expression == parent.bodyExpression) !parent.hasBlockBody() && !parent.hasDeclaredReturnType() else true } is KtAnonymousInitializer -> false else -> true } private fun KtBlockExpression.lastStatement(): KtExpression? = lastChild?.siblings(forward = false)?.firstIsInstanceOrNull<KtExpression>() private fun PsiElement.isStatement() = this is KtExpression && parent is KtBlockExpression private fun KtTypeReference?.containsProbablyNothing() = this?.typeElement?.anyDescendantOfType<KtUserType> { KotlinPsiHeuristics.isProbablyNothing(it) } ?: false } private inner class StatementMarks { private val statementMarks = HashMap<KtExpression, MarkLevel>() private val blockLevels = HashMap<KtBlockExpression, MarkLevel>() fun mark(element: PsiElement, level: MarkLevel) { var e = element while (e != declaration) { if (e.isStatement()) { markStatement(e as KtExpression, level) } e = e.parent!! } } private fun markStatement(statement: KtExpression, level: MarkLevel) { val currentLevel = statementMark(statement) if (currentLevel < level) { statementMarks[statement] = level val block = statement.parent as KtBlockExpression val currentBlockLevel = blockLevels[block] ?: MarkLevel.NONE if (currentBlockLevel < level) { blockLevels[block] = level } } } fun statementMark(statement: KtExpression): MarkLevel = statementMarks[statement] ?: MarkLevel.NONE fun allMarkedStatements(): Collection<KtExpression> = statementMarks.keys fun lastMarkedStatement(block: KtBlockExpression, minLevel: MarkLevel): KtExpression? { val level = blockLevels[block] ?: MarkLevel.NONE if (level < minLevel) return null // optimization return block.lastChild.siblings(forward = false) .filterIsInstance<KtExpression>() .first { statementMark(it) >= minLevel } } } }
apache-2.0
20b9ffb901bce5ba141783a629d057b4
40.685484
162
0.578797
5.944112
false
false
false
false
jwren/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinHighlightingSuspender.kt
1
4184
// 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.highlighter import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.EditorNotifications import com.intellij.util.Alarm import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable import java.util.concurrent.TimeUnit /** * Highlighting daemon is restarted when exception is thrown, if there is a recurred error * (e.g. within a resolve) it could lead to infinite highlighting loop. * * Do not rethrow exception too often to disable HL for a while */ class KotlinHighlightingSuspender(private val project: Project) { private val timeoutSeconds = Registry.intValue("kotlin.suspended.highlighting.timeout", 10) private val lastThrownExceptionTimestampPerFile = mutableMapOf<VirtualFile, Long>() private val suspendTimeoutMs = TimeUnit.SECONDS.toMillis(timeoutSeconds.toLong()) private val updateQueue = Alarm(Alarm.ThreadToUse.SWING_THREAD, KotlinPluginDisposable.getInstance(project)) /** * @return true, when file is suspended for the 1st time (within a timeout window) */ fun suspend(file: VirtualFile): Boolean { cleanup() if (suspendTimeoutMs <= 0) return false val timestamp = System.currentTimeMillis() // daemon is restarted when exception is thrown // if there is a recurred error (e.g. within a resolve) it could lead to infinite highlighting loop // so, do not rethrow exception too often to disable HL for a while val lastThrownExceptionTimestamp = synchronized(lastThrownExceptionTimestampPerFile) { val lastThrownExceptionTimestamp = lastThrownExceptionTimestampPerFile[file] ?: run { lastThrownExceptionTimestampPerFile[file] = timestamp 0L } lastThrownExceptionTimestamp } scheduleUpdate(file) updateNotifications(file) return timestamp - lastThrownExceptionTimestamp > suspendTimeoutMs } private fun scheduleUpdate(file: VirtualFile) { updateQueue.apply { addRequest(Runnable { updateNotifications(file) }, suspendTimeoutMs + 1) } } fun unsuspend(file: VirtualFile) { synchronized(lastThrownExceptionTimestampPerFile) { lastThrownExceptionTimestampPerFile.remove(file) } cleanup() updateNotifications(file) } fun isSuspended(file: VirtualFile): Boolean { cleanup() val timestamp = System.currentTimeMillis() val lastThrownExceptionTimestamp = synchronized(lastThrownExceptionTimestampPerFile) { lastThrownExceptionTimestampPerFile[file] ?: return false } return timestamp - lastThrownExceptionTimestamp < suspendTimeoutMs } private fun cleanup() { val timestamp = System.currentTimeMillis() val filesToUpdate = mutableListOf<VirtualFile>() val filesToUpdateLater = mutableListOf<VirtualFile>() synchronized(lastThrownExceptionTimestampPerFile) { if (lastThrownExceptionTimestampPerFile.isEmpty()) return val it = lastThrownExceptionTimestampPerFile.entries.iterator() while (it.hasNext()) { val next = it.next() if (timestamp - next.value > suspendTimeoutMs) { filesToUpdate += next.key it.remove() } } filesToUpdateLater.addAll(lastThrownExceptionTimestampPerFile.keys) } updateQueue.cancelAllRequests() filesToUpdate.forEach(::updateNotifications) filesToUpdateLater.forEach(::scheduleUpdate) } private fun updateNotifications(file: VirtualFile) { EditorNotifications.getInstance(project).updateNotifications(file) } companion object { fun getInstance(project: Project): KotlinHighlightingSuspender = project.service() } }
apache-2.0
e32f57ae56fc2772572b72244f5d5512
37.75
158
0.702438
5.723666
false
false
false
false
androidx/androidx
compose/runtime/runtime-saveable/samples/src/main/java/androidx/compose/runtime/saveable/samples/SaveableStateHolderSamples.kt
3
3528
/* * 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.runtime.saveable.samples import androidx.annotation.Sampled import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding 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.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveableStateHolder import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp @Sampled @Composable fun SimpleNavigationWithSaveableStateSample() { @Composable fun <T : Any> Navigation( currentScreen: T, modifier: Modifier = Modifier, content: @Composable (T) -> Unit ) { // create SaveableStateHolder. val saveableStateHolder = rememberSaveableStateHolder() Box(modifier) { // Wrap the content representing the `currentScreen` inside `SaveableStateProvider`. // Here you can also add a screen switch animation like Crossfade where during the // animation multiple screens will be displayed at the same time. saveableStateHolder.SaveableStateProvider(currentScreen) { content(currentScreen) } } } Column { var screen by rememberSaveable { mutableStateOf("screen1") } Row(horizontalArrangement = Arrangement.SpaceEvenly) { Button(onClick = { screen = "screen1" }) { Text("Go to screen1") } Button(onClick = { screen = "screen2" }) { Text("Go to screen2") } } Navigation(screen, Modifier.fillMaxSize()) { currentScreen -> if (currentScreen == "screen1") { Screen1() } else { Screen2() } } } } @Composable fun Screen1() { var counter by rememberSaveable { mutableStateOf(0) } Button(onClick = { counter++ }) { Text("Counter=$counter on Screen1") } } @Composable fun Screen2() { Text("Screen2") } @Composable fun Button(modifier: Modifier = Modifier, onClick: () -> Unit, content: @Composable () -> Unit) { Box( modifier .clickable(onClick = onClick) .background(Color(0xFF6200EE), RoundedCornerShape(4.dp)) .padding(horizontal = 16.dp, vertical = 8.dp) ) { content() } }
apache-2.0
cc0c783914b4eef3b5bdb07e9e5ba341
32.932692
97
0.686224
4.648221
false
false
false
false
GunoH/intellij-community
plugins/package-search/gradle/src/com/jetbrains/packagesearch/intellij/plugin/gradle/configuration/PackageSearchGradleConfiguration.kt
7
3163
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.gradle.configuration import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.util.xmlb.annotations.OptionTag import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration @State( name = "PackageSearchGradleConfiguration", storages = [(Storage(PackageSearchGeneralConfiguration.StorageFileName))], ) internal class PackageSearchGradleConfiguration : BaseState(), PersistentStateComponent<PackageSearchGradleConfiguration> { companion object { @JvmStatic fun getInstance(project: Project) = project.service<PackageSearchGradleConfiguration>() } override fun getState(): PackageSearchGradleConfiguration = this override fun loadState(state: PackageSearchGradleConfiguration) { this.copyFrom(state) } @get:OptionTag("GRADLE_SCOPES") var gradleScopes by string(PackageSearchGradleConfigurationDefaults.GradleScopes) @get:OptionTag("GRADLE_SCOPES_DEFAULT") var defaultGradleScope by string(PackageSearchGradleConfigurationDefaults.GradleDefaultScope) @get:OptionTag("UPDATE_SCOPES_ON_USE") var updateScopesOnUsage by property(true) fun determineDefaultGradleScope(): String = if (!defaultGradleScope.isNullOrEmpty()) { defaultGradleScope!! } else { PackageSearchGradleConfigurationDefaults.GradleDefaultScope } fun addGradleScope(scope: String) { val currentScopes = getGradleScopes() if (!currentScopes.contains(scope)) { gradleScopes = currentScopes.joinToString(",") + ",$scope" this.incrementModificationCount() } } fun getGradleScopes(): List<String> { var scopes = gradleScopes.orEmpty().split(",", ";", "\n") .map { it.trim() } .filter { it.isNotEmpty() } if (scopes.isEmpty()) { scopes = PackageSearchGradleConfigurationDefaults.GradleScopes.split(",", ";", "\n") .map { it.trim() } .filter { it.isNotEmpty() } } return scopes } }
apache-2.0
10e13592a4948cf7fc8d06e502c09707
37.573171
123
0.682896
5.434708
false
true
false
false
GunoH/intellij-community
plugins/ide-features-trainer/src/training/featuresSuggester/suggesters/IntroduceVariableSuggester.kt
2
5432
package training.featuresSuggester.suggesters import com.intellij.psi.PsiElement import training.featuresSuggester.FeatureSuggesterBundle import training.featuresSuggester.NoSuggestion import training.featuresSuggester.SuggesterSupport import training.featuresSuggester.Suggestion import training.featuresSuggester.actions.* import training.util.WeakReferenceDelegator class IntroduceVariableSuggester : AbstractFeatureSuggester() { override val id: String = "Introduce variable" override val suggestingActionDisplayName: String = FeatureSuggesterBundle.message("introduce.variable.name") override val message = FeatureSuggesterBundle.message("introduce.variable.message") override val suggestingActionId = "IntroduceVariable" override val suggestingTipId = suggestingActionId override val minSuggestingIntervalDays = 14 override val languages = listOf("JAVA", "kotlin", "Python", "JavaScript", "ECMAScript 6") private class ExtractedExpressionData(var exprText: String, changedStatement: PsiElement) { var changedStatement: PsiElement? by WeakReferenceDelegator(changedStatement) val changedStatementText: String var declaration: PsiElement? by WeakReferenceDelegator(null) var variableEditingFinished: Boolean = false init { val text = changedStatement.text changedStatementText = text.replaceFirst(exprText, "").trim() exprText = exprText.trim() } fun getDeclarationText(): String? { return declaration?.let { if (it.isValid) it.text else null } } } private var extractedExprData: ExtractedExpressionData? = null override fun getSuggestion(action: Action): Suggestion { val language = action.language ?: return NoSuggestion val langSupport = SuggesterSupport.getForLanguage(language) ?: return NoSuggestion when (action) { is BeforeEditorTextRemovedAction -> { with(action) { val deletedText = textFragment.text.takeIf { it.isNotBlank() }?.trim() ?: return NoSuggestion val psiFile = this.psiFile ?: return NoSuggestion val contentOffset = caretOffset + textFragment.text.indexOfFirst { it != ' ' && it != '\n' } val curElement = psiFile.findElementAt(contentOffset) ?: return NoSuggestion if (langSupport.isPartOfExpression(curElement)) { val changedStatement = langSupport.getTopmostStatementWithText(curElement, deletedText) ?: return NoSuggestion extractedExprData = ExtractedExpressionData(textFragment.text, changedStatement) } } } is EditorCutAction -> { val data = extractedExprData ?: return NoSuggestion if (data.exprText != action.text.trim()) { extractedExprData = null } } is ChildReplacedAction -> { if (extractedExprData == null) return NoSuggestion with(action) { when { langSupport.isVariableDeclarationAdded(this) -> { extractedExprData!!.declaration = newChild } newChild.text.trim() == extractedExprData!!.changedStatementText -> { extractedExprData!!.changedStatement = newChild } langSupport.isVariableInserted(this) -> { extractedExprData = null return createSuggestion() } } } } is ChildAddedAction -> { if (extractedExprData == null) return NoSuggestion with(action) { if (langSupport.isVariableDeclarationAdded(this)) { extractedExprData!!.declaration = newChild } else if (newChild.text.trim() == extractedExprData!!.changedStatementText) { extractedExprData!!.changedStatement = newChild } else if (!extractedExprData!!.variableEditingFinished && isVariableEditingFinished()) { extractedExprData!!.variableEditingFinished = true } } } is ChildrenChangedAction -> { if (extractedExprData == null) return NoSuggestion if (action.parent === extractedExprData!!.declaration && !extractedExprData!!.variableEditingFinished && isVariableEditingFinished() ) { extractedExprData!!.variableEditingFinished = true } } else -> NoSuggestion } return NoSuggestion } private fun SuggesterSupport.isVariableDeclarationAdded(action: ChildReplacedAction): Boolean { return isExpressionStatement(action.oldChild) && isVariableDeclaration(action.newChild) } private fun SuggesterSupport.isVariableDeclarationAdded(action: ChildAddedAction): Boolean { return isCodeBlock(action.parent) && isVariableDeclaration(action.newChild) } private fun isVariableEditingFinished(): Boolean { if (extractedExprData == null) return false with(extractedExprData!!) { val declarationText = getDeclarationText() ?: return false return declarationText.trim().endsWith(exprText) } } private fun SuggesterSupport.isVariableInserted(action: ChildReplacedAction): Boolean { if (extractedExprData == null) return false with(extractedExprData!!) { return variableEditingFinished && declaration.let { it != null && it.isValid && action.newChild.text == getVariableName(it) } && changedStatement === getTopmostStatementWithText(action.newChild, "") } } }
apache-2.0
b7be4634112a1df03bf6e0b2046a1574
39.237037
110
0.688144
5.594233
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/stackFrameUtils.kt
4
4898
// 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.core import com.sun.jdi.LocalVariable import com.sun.jdi.Location import com.sun.jdi.Method import org.jetbrains.kotlin.idea.debugger.base.util.DexDebugFacility import org.jetbrains.kotlin.idea.debugger.base.util.safeVariables import org.jetbrains.kotlin.idea.debugger.core.DebuggerUtils.getBorders // A pair of a [LocalVariable] with its starting [Location] and // a stable [Comparable] implementation. // // [LocalVariable.compareTo] orders variables by location and slot. // The location is unstable on dex VMs due to spilling and the slot // depends on compiler internals. This class orders variables // according to the attached location and name instead. class VariableWithLocation( val variable: LocalVariable, val location: Location, ) : Comparable<VariableWithLocation> { override fun compareTo(other: VariableWithLocation): Int = location.compareTo(other.location).takeIf { it != 0 } ?: name.compareTo(other.name) val name: String get() = variable.name() override fun toString(): String = "$name at $location" } // Returns a list of all [LocalVariable]s in the given methods with their starting // location, ordered according to start location and variable name. // // The computed start locations take variable spilling into account on a dex VM. // On a dex VM all variables are kept in registers and may have to be spilled // during register allocation. This means that the same source level variable may // correspond to several variables with different locations and slots. // This method implements a heuristic to assign each visible variable to its // actual starting location. // // --- // // This heuristic is not perfect. During register allocation we sometimes have // to insert additional move instructions in the middle of a method, which can // lead to large gaps in the scope of a local variable. Even if there is no additional // spill code, the compiler is free to reorder blocks which can also create gaps // in the variable live ranges. Unfortunately there is no way to detect this situation // based on the local variable table and we will end up with the wrong variable order. fun Method.sortedVariablesWithLocation(): List<VariableWithLocation> { val allVariables = safeVariables() ?: return emptyList() // On the JVM we can use the variable offsets directly. if (!DexDebugFacility.isDex(virtualMachine())) { return allVariables.mapNotNull { local -> local.getBorders()?.let { VariableWithLocation(local, it.start) } }.sorted() } // On dex, there are no separate slots for local variables. Instead, local variables // are kept in registers and are subject to spilling. When a variable is spilled, // its start offset is reset. In order to sort variables by introduction order, // we need to identify spilled variables. // // The heuristic we use for this is to look for pairs of variables with the same // name and type for which one begins exactly when the other ends. val startOffsets = mutableMapOf<Long, MutableList<LocalVariable>>() val replacements = mutableMapOf<LocalVariable, LocalVariable>() for (variable in allVariables) { val startOffset = variable.getBorders()?.start ?: continue startOffsets.getOrPut(startOffset.codeIndex()) { mutableListOf() } += variable } for (variable in allVariables) { val endOffset = variable.getBorders()?.endInclusive ?: continue // Note that the endOffset is inclusive - it doesn't necessarily correspond to // any bytecode index - so the variable ends exactly one index later. val otherVariables = startOffsets[endOffset.codeIndex() + 1] ?: continue for (other in otherVariables) { if (variable.name() == other.name() && variable.signature() == other.signature()) { replacements[other] = variable break } } } return allVariables.mapNotNull { variable -> var alias = variable while (true) { alias = replacements[alias] ?: break } replacements[variable] = alias alias.getBorders()?.let { VariableWithLocation(variable, it.start) } }.sorted() } // Given a list of variables returns a copy of the list without duplicate variable names, // keeping only the last occurrence for each name. // // For Java, this kind of filtering is done in [StackFrame.visibleVariables], but for // Kotlin this needs to be done separately for every (inline) stack frame. fun filterRepeatedVariables(sortedVariables: List<LocalVariable>): List<LocalVariable> = sortedVariables.associateBy { it.name() }.values.toList()
apache-2.0
14b3d9657f94e7aa8f39dab958fca1fe
45.647619
120
0.71519
4.727799
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateNextFunctionActionFactory.kt
3
1974
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable import com.intellij.psi.util.findParentOfType import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtForExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.util.OperatorNameConventions object CreateNextFunctionActionFactory : CreateCallableMemberFromUsageFactory<KtForExpression>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtForExpression? { return diagnostic.psiElement.findParentOfType(strict = false) } override fun createCallableInfo(element: KtForExpression, diagnostic: Diagnostic): CallableInfo? { val diagnosticWithParameters = DiagnosticFactory.cast(diagnostic, Errors.NEXT_MISSING, Errors.NEXT_NONE_APPLICABLE) val ownerType = TypeInfo(diagnosticWithParameters.a, Variance.IN_VARIANCE) val variableExpr = element.loopParameter ?: element.destructuringDeclaration ?: return null val returnType = TypeInfo(variableExpr as KtExpression, Variance.OUT_VARIANCE) return FunctionInfo( OperatorNameConventions.NEXT.asString(), ownerType, returnType, modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) ) } }
apache-2.0
abac93225ced5d1e70da6c774b16db62
52.351351
158
0.800405
5.140625
false
false
false
false
siosio/intellij-community
plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/CacheVersionManager.kt
1
2856
// 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.jps.incremental import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.load.kotlin.JvmBytecodeBinaryVersion import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMetadataVersion import java.io.File import java.io.IOException import java.nio.file.Path import kotlin.io.path.* /** * Manages files with actual version [loadActual] and provides expected version [expected]. * Based on that actual and expected versions [CacheStatus] can be calculated. * This can be done by constructing [CacheAttributesDiff] and calling [CacheAttributesDiff.status]. * Based on that status system may perform required actions (i.e. rebuild something, clearing caches, etc...). */ class CacheVersionManager( private val versionFile: Path, expectedOwnVersion: Int? ) : CacheAttributesManager<CacheVersion> { override val expected: CacheVersion? = if (expectedOwnVersion == null) null else CacheVersion(expectedOwnVersion, JvmBytecodeBinaryVersion.INSTANCE, JvmMetadataVersion.INSTANCE) override fun loadActual(): CacheVersion? = if (versionFile.notExists()) null else try { CacheVersion(versionFile.readText().toInt()) } catch (e: NumberFormatException) { null } catch (e: IOException) { null } override fun writeVersion(values: CacheVersion?) { if (values == null) versionFile.deleteIfExists() else { versionFile.parent.createDirectories() versionFile.writeText(values.intValue.toString()) } } @get:TestOnly val versionFileForTesting: File get() = versionFile.toFile() } fun CacheVersion(own: Int, bytecode: JvmBytecodeBinaryVersion, metadata: JvmMetadataVersion): CacheVersion { require(own in 0 until Int.MAX_VALUE / 1000000) require(bytecode.major in 0..9) require(bytecode.minor in 0..9) require(metadata.major in 0..9) require(metadata.minor in 0..99) return CacheVersion( own * 1000000 + bytecode.major * 10000 + bytecode.minor * 100 + metadata.major * 1000 + metadata.minor ) } data class CacheVersion(val intValue: Int) { val own: Int get() = intValue / 1000000 val bytecode: JvmBytecodeBinaryVersion get() = JvmBytecodeBinaryVersion( intValue / 10000 % 10, intValue / 100 % 10 ) val metadata: JvmMetadataVersion get() = JvmMetadataVersion( intValue / 1000 % 10, intValue / 1 % 100 ) override fun toString(): String = "CacheVersion(caches: $own, bytecode: $bytecode, metadata: $metadata)" }
apache-2.0
64c64a5074e97404c162fdb2824e557f
34.259259
158
0.682773
4.651466
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/data/database/queries/MangaSyncQueries.kt
2
1845
package eu.kanade.tachiyomi.data.database.queries import com.pushtorefresh.storio.sqlite.queries.DeleteQuery import com.pushtorefresh.storio.sqlite.queries.Query import eu.kanade.tachiyomi.data.database.DbProvider import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.MangaSync import eu.kanade.tachiyomi.data.database.tables.MangaSyncTable import eu.kanade.tachiyomi.data.mangasync.MangaSyncService interface MangaSyncQueries : DbProvider { fun getMangaSync(manga: Manga, sync: MangaSyncService) = db.get() .`object`(MangaSync::class.java) .withQuery(Query.builder() .table(MangaSyncTable.TABLE) .where("${MangaSyncTable.COL_MANGA_ID} = ? AND " + "${MangaSyncTable.COL_SYNC_ID} = ?") .whereArgs(manga.id, sync.id) .build()) .prepare() fun getMangasSync(manga: Manga) = db.get() .listOfObjects(MangaSync::class.java) .withQuery(Query.builder() .table(MangaSyncTable.TABLE) .where("${MangaSyncTable.COL_MANGA_ID} = ?") .whereArgs(manga.id) .build()) .prepare() fun insertMangaSync(manga: MangaSync) = db.put().`object`(manga).prepare() fun insertMangasSync(mangas: List<MangaSync>) = db.put().objects(mangas).prepare() fun deleteMangaSync(manga: MangaSync) = db.delete().`object`(manga).prepare() fun deleteMangaSyncForManga(manga: Manga) = db.delete() .byQuery(DeleteQuery.builder() .table(MangaSyncTable.TABLE) .where("${MangaSyncTable.COL_MANGA_ID} = ?") .whereArgs(manga.id) .build()) .prepare() }
gpl-3.0
dbc6e11c871581beae3f360ce8e499bc
39.130435
86
0.60813
4.467312
false
false
false
false
siosio/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/LessonStateBase.kt
1
1492
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.learn.lesson import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import training.learn.course.Lesson import training.util.trainerPluginConfigName @State(name = "LessonStateBase", storages = [Storage(value = trainerPluginConfigName)]) private class LessonStateBase : PersistentStateComponent<LessonStateBase> { override fun getState(): LessonStateBase = this override fun loadState(persistedState: LessonStateBase) { map = persistedState.map.mapKeys { it.key.toLowerCase() }.toMutableMap() } var map: MutableMap<String, LessonState> = mutableMapOf() companion object { internal val instance: LessonStateBase get() = ApplicationManager.getApplication().getService(LessonStateBase::class.java) } } internal object LessonStateManager { fun setPassed(lesson: Lesson) { LessonStateBase.instance.map[lesson.id.toLowerCase()] = LessonState.PASSED } fun resetPassedStatus() { for (lesson in LessonStateBase.instance.map) { lesson.setValue(LessonState.NOT_PASSED) } } fun getStateFromBase(lessonId: String): LessonState = LessonStateBase.instance.map.getOrPut(lessonId.toLowerCase()) { LessonState.NOT_PASSED } }
apache-2.0
c62277144c8f1f0cb86d3f78e3d219c2
34.52381
140
0.77815
4.507553
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/find/impl/TextSearchContributor.kt
1
10042
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.find.impl import com.intellij.find.FindBundle import com.intellij.find.FindManager import com.intellij.find.FindModel import com.intellij.find.FindSettings import com.intellij.find.impl.TextSearchRightActionAction.* import com.intellij.ide.actions.GotoActionBase import com.intellij.ide.actions.SearchEverywhereBaseAction import com.intellij.ide.actions.SearchEverywhereClassifier import com.intellij.ide.actions.searcheverywhere.* import com.intellij.ide.actions.searcheverywhere.AbstractGotoSEContributor.createContext import com.intellij.ide.util.RunOnceUtil import com.intellij.ide.util.scopeChooser.ScopeChooserCombo import com.intellij.ide.util.scopeChooser.ScopeDescriptor import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.observable.properties.AtomicBooleanProperty import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.Key import com.intellij.psi.SmartPointerManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.reference.SoftReference import com.intellij.usages.UsageInfo2UsageAdapter import com.intellij.usages.UsageViewPresentation import com.intellij.util.CommonProcessors import com.intellij.util.PlatformUtils import com.intellij.util.Processor import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.JBIterable import java.lang.ref.Reference import java.lang.ref.WeakReference import javax.swing.ListCellRenderer internal class TextSearchContributor( val event: AnActionEvent ) : WeightedSearchEverywhereContributor<SearchEverywhereItem>, SearchFieldActionsContributor, PossibleSlowContributor, DumbAware, ScopeSupporting, Disposable { private val project = event.getRequiredData(CommonDataKeys.PROJECT) private val model = FindManager.getInstance(project).findInProjectModel private var everywhereScope = getEverywhereScope() private var projectScope: GlobalSearchScope? private var selectedScopeDescriptor: ScopeDescriptor private var psiContext = getPsiContext() private lateinit var onDispose: () -> Unit init { val scopes = createScopes() projectScope = getProjectScope(scopes) selectedScopeDescriptor = getInitialSelectedScope(scopes) } private fun getPsiContext() = GotoActionBase.getPsiContext(event)?.let { SmartPointerManager.getInstance(project).createSmartPsiElementPointer(it) } private fun getEverywhereScope() = SearchEverywhereClassifier.EP_Manager.getEverywhereScope(project) ?: GlobalSearchScope.everythingScope(project) private fun getProjectScope(descriptors: List<ScopeDescriptor>): GlobalSearchScope? { SearchEverywhereClassifier.EP_Manager.getProjectScope(project)?.let { return it } GlobalSearchScope.projectScope(project).takeIf { it != everywhereScope }?.let { return it } val secondScope = JBIterable.from(descriptors).filter { !it.scopeEquals(everywhereScope) && !it.scopeEquals(null) }.first() return if (secondScope != null) secondScope.scope as GlobalSearchScope? else everywhereScope } override fun getSearchProviderId() = ID override fun getGroupName() = FindBundle.message("search.everywhere.group.name") override fun getSortWeight() = 1500 override fun showInFindResults() = enabled() override fun isShownInSeparateTab() = true override fun fetchWeightedElements(pattern: String, indicator: ProgressIndicator, consumer: Processor<in FoundItemDescriptor<SearchEverywhereItem>>) { FindModel.initStringToFind(model, pattern) val presentation = FindInProjectUtil.setupProcessPresentation(project, UsageViewPresentation()) val scope = GlobalSearchScope.projectScope(project) // TODO use scope from model ? val recentItemRef = ThreadLocal<Reference<SearchEverywhereItem>>() FindInProjectUtil.findUsages(model, project, indicator, presentation, emptySet()) { val usage = UsageInfo2UsageAdapter.CONVERTER.`fun`(it) as UsageInfo2UsageAdapter indicator.checkCanceled() val recentItem = SoftReference.dereference(recentItemRef.get()) val newItem = if (recentItem != null && recentItem.usage.merge(usage)) { // recompute merged presentation recentItem.withPresentation(usagePresentation(project, scope, recentItem.usage)) } else { SearchEverywhereItem(usage, usagePresentation(project, scope, usage)).also { if (!consumer.process(FoundItemDescriptor(it, 0))) return@findUsages false } } recentItemRef.set(WeakReference(newItem)) true } } override fun getElementsRenderer(): ListCellRenderer<in SearchEverywhereItem> = TextSearchRenderer() override fun processSelectedItem(selected: SearchEverywhereItem, modifiers: Int, searchText: String): Boolean { // TODO async navigation val info = selected.usage if (!info.canNavigate()) return false info.navigate(true) return true } override fun getActions(onChanged: Runnable): List<AnAction> = listOf(ScopeAction { onChanged.run() }, JComboboxAction(project) { onChanged.run() }.also { onDispose = it.saveMask }) override fun createRightActions(onChanged: Runnable): List<TextSearchRightActionAction> { lateinit var regexp: AtomicBooleanProperty val word = AtomicBooleanProperty(model.isWholeWordsOnly).apply { afterChange { model.isWholeWordsOnly = it; if (it) regexp.set(false) } } val case = AtomicBooleanProperty(model.isCaseSensitive).apply { afterChange { model.isCaseSensitive = it } } regexp = AtomicBooleanProperty(model.isRegularExpressions).apply { afterChange { model.isRegularExpressions = it; if (it) word.set(false) } } return listOf(CaseSensitiveAction(case, onChanged), WordAction(word, onChanged), RegexpAction(regexp, onChanged)) } override fun getDataForItem(element: SearchEverywhereItem, dataId: String): Any? { if (CommonDataKeys.PSI_ELEMENT.`is`(dataId)) { return element.usage.element } return null } private fun getInitialSelectedScope(scopeDescriptors: List<ScopeDescriptor>): ScopeDescriptor { val scope = SE_TEXT_SELECTED_SCOPE.get(project) ?: return ScopeDescriptor(projectScope) return scopeDescriptors.find { scope == it.displayName && !it.scopeEquals(null) } ?: ScopeDescriptor(projectScope) } private fun setSelectedScope(scope: ScopeDescriptor) { selectedScopeDescriptor = scope SE_TEXT_SELECTED_SCOPE.set(project, if (scope.scopeEquals(everywhereScope) || scope.scopeEquals(projectScope)) null else scope.displayName) FindSettings.getInstance().customScope = selectedScopeDescriptor.scope?.displayName model.customScopeName = selectedScopeDescriptor.scope?.displayName model.customScope = selectedScopeDescriptor.scope model.isCustomScope = true } private fun createScopes() = mutableListOf<ScopeDescriptor>().also { ScopeChooserCombo.processScopes(project, createContext(project, psiContext), ScopeChooserCombo.OPT_LIBRARIES or ScopeChooserCombo.OPT_EMPTY_SCOPES, CommonProcessors.CollectProcessor(it)) } override fun getScope() = selectedScopeDescriptor override fun getSupportedScopes() = createScopes() override fun setScope(scope: ScopeDescriptor) { setSelectedScope(scope) } private inner class ScopeAction(val onChanged: () -> Unit) : ScopeChooserAction() { override fun onScopeSelected(descriptor: ScopeDescriptor) { setSelectedScope(descriptor) onChanged() } override fun getSelectedScope() = selectedScopeDescriptor override fun isEverywhere() = selectedScopeDescriptor.scopeEquals(everywhereScope) override fun processScopes(processor: Processor<in ScopeDescriptor>) = ContainerUtil.process(createScopes(), processor) override fun onProjectScopeToggled() { isEverywhere = !selectedScopeDescriptor.scopeEquals(everywhereScope) } override fun setEverywhere(everywhere: Boolean) { setSelectedScope(ScopeDescriptor(if (everywhere) everywhereScope else projectScope)) onChanged() } override fun canToggleEverywhere() = if (everywhereScope == projectScope) false else selectedScopeDescriptor.scopeEquals(everywhereScope) || selectedScopeDescriptor.scopeEquals(projectScope) } override fun dispose() { if (this::onDispose.isInitialized) onDispose() } companion object { private const val ID = "TextSearchContributor" private const val ADVANCED_OPTION_ID = "se.text.search" private val SE_TEXT_SELECTED_SCOPE = Key.create<String>("SE_TEXT_SELECTED_SCOPE") private fun enabled() = AdvancedSettings.getBoolean(ADVANCED_OPTION_ID) class Factory : SearchEverywhereContributorFactory<SearchEverywhereItem> { override fun isAvailable() = enabled() override fun createContributor(event: AnActionEvent) = TextSearchContributor(event) } class TextSearchAction : SearchEverywhereBaseAction(), DumbAware { override fun update(event: AnActionEvent) { super.update(event) event.presentation.isEnabledAndVisible = enabled() } override fun actionPerformed(e: AnActionEvent) { showInSearchEverywherePopup(ID, e, true, true) } } class TextSearchActivity : StartupActivity.DumbAware { override fun runActivity(project: Project) { RunOnceUtil.runOnceForApp(ADVANCED_OPTION_ID) { AdvancedSettings.setBoolean(ADVANCED_OPTION_ID, PlatformUtils.isRider()) } } } } }
apache-2.0
ff5b407681285b04a4d97ecf1462acb6
41.918803
145
0.765186
4.93707
false
false
false
false
GunoH/intellij-community
plugins/evaluation-plugin/languages/src/com/intellij/cce/visitor/CodeFragmentFromPsiBuilder.kt
4
2079
package com.intellij.cce.visitor import com.intellij.cce.core.CodeFragment import com.intellij.cce.core.Language import com.intellij.cce.processor.EvaluationRootProcessor import com.intellij.cce.util.FilesHelper import com.intellij.cce.util.text import com.intellij.cce.visitor.exceptions.PsiConverterException import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager open class CodeFragmentFromPsiBuilder(private val project: Project, val language: Language) : CodeFragmentBuilder() { private val dumbService: DumbService = DumbService.getInstance(project) open fun getVisitors(): List<CompletionEvaluationVisitor> = CompletionEvaluationVisitor.EP_NAME.extensions.toList() override fun build(file: VirtualFile, rootProcessor: EvaluationRootProcessor): CodeFragment { val psi = dumbService.runReadActionInSmartMode<PsiFile> { PsiManager.getInstance(project).findFile(file) } ?: throw PsiConverterException("Cannot get PSI of file ${file.path}") val filePath = FilesHelper.getRelativeToProjectPath(project, file.path) val visitors = getVisitors().filter { it.language == language } if (visitors.isEmpty()) throw IllegalStateException("No suitable visitors") if (visitors.size > 1) throw IllegalStateException("More than 1 suitable visitors") val fileTokens = getFileTokens(visitors.first(), psi) fileTokens.path = filePath fileTokens.text = file.text() return findRoot(fileTokens, rootProcessor) } private fun getFileTokens(visitor: CompletionEvaluationVisitor, psi: PsiElement): CodeFragment { if (visitor !is PsiElementVisitor) throw IllegalArgumentException("Visitor must implement PsiElementVisitor") dumbService.runReadActionInSmartMode { assert(!dumbService.isDumb) { "Generating actions during indexing." } psi.accept(visitor) } return visitor.getFile() } }
apache-2.0
a7270cd1efad8130d8163a0c2d88a19d
45.2
117
0.790765
4.569231
false
false
false
false
kenyee/teamcity-graphite-stats
src/main/kotlin/com/kenyee/teamcity/util/GraphiteStats.kt
1
7918
package com.kenyee.teamcity.util import org.jetbrains.teamcity.rest.BuildLocator import org.jetbrains.teamcity.rest.BuildStatus import org.jetbrains.teamcity.rest.TeamCityInstance import org.slf4j.LoggerFactory import org.yaml.snakeyaml.Yaml import org.yaml.snakeyaml.constructor.SafeConstructor import java.io.File import java.io.FileInputStream import java.io.IOException import java.io.OutputStreamWriter import java.net.Socket import java.util.* /* * Main graphite polling loop * * Data sent to graphite: * <prefix>.queuesize * <prefix>.build.<config>.queuetime * <prefix>.build.<config>.buildtime */ class GraphiteStats { fun someLibraryMethod(): Boolean { return true } companion object { private val LOG = LoggerFactory.getLogger("GraphiteStats") @JvmStatic fun main(args: Array<String>) { val configPath = if (args.size > 0) args[0] else "config.yml" val configInfo = loadConfig(configPath) if (configInfo == null) { println("ERROR - Configuration error!") System.exit(1); } runLoop(configInfo!!) } fun runLoop(configInfo: ConfigInfo) { val tcServer = TeamCityInstance.httpAuth(configInfo.teamcityServer, configInfo.username.toString(), configInfo.password.toString()) var lastPollTime = Date() while (true) { try { val queuedBuilds = tcServer.queuedBuilds().list() LOG.debug("Queue length: ${queuedBuilds.size}") sendGraphiteStat(configInfo, configInfo.getQueueLengthMetricName(), queuedBuilds.size.toString()) if (LOG.isDebugEnabled()) { queuedBuilds.map({ it -> LOG.debug(it.toString()) }) } val successfulBuildsLocator = (tcServer.builds() .withStatus(BuildStatus.SUCCESS) .sinceDate(lastPollTime) .limitResults(configInfo.maxBuilds)) if (successfulBuildsLocator is BuildLocator) { val successfulBuilds = successfulBuildsLocator.list(); LOG.debug("Successful Build count: ${successfulBuilds.size}") successfulBuilds .map({ if (it.fetchFinishDate() > lastPollTime) { lastPollTime = it.fetchFinishDate() } }) successfulBuilds .filter({ it -> var includeBuild = true for (exclusion in configInfo.excludeProjects) { if (exclusion.toRegex().matches(it.buildConfigurationId)) { includeBuild = false break } } includeBuild }) .map({ val buildTime = (it.fetchFinishDate().time - it.fetchStartDate().time) / 1000 val queueTime = (it.fetchStartDate().time - it.fetchQueuedDate().time) / 1000 LOG.debug("$it $buildTime $queueTime") sendGraphiteStat(configInfo, configInfo.getBuildRunTimeMetricName(it.buildConfigurationId), buildTime.toString()) sendGraphiteStat(configInfo, configInfo.getBuildWaitTimeMetricName(it.buildConfigurationId), queueTime.toString()) }); } } catch (e: Exception) { LOG.error("Error reading from Teamcity: ", e) } catch (e: java.lang.Error) { LOG.error("Error connecting to Teamcity: ", e) } Thread.sleep(configInfo.pollPeriodSecs.times(1000).toLong()); } } fun loadConfig(configPath: String): ConfigInfo? { val configFile = File(configPath); println("Loading configuration from: " + configFile.absolutePath) if (!configFile.exists()) { println("ERROR - Configuration file not found!") return null } val yaml = Yaml(SafeConstructor()) val configData = yaml.load(FileInputStream(configFile)) if (configData is Map<*, *>) { val graphiteServer = configData.get("graphite").toString() if (graphiteServer.isNullOrEmpty()) { println("ERROR - Graphite server must be specified") } val prefix = configData.get("prefix").toString() val teamcityServer = configData.get("teamcity").toString() if (teamcityServer.isNullOrEmpty()) { println("ERROR - Teamcity server URL must be specified") } val username = configData.get("username").toString() val password = configData.get("password").toString() var pollPeriodSecs = configData.get("pollsecs") as Int? if (pollPeriodSecs == null) { println("Poll period not specified...defaulting to 10sec polling") pollPeriodSecs = 10 } var maxBuilds = configData.get("maxbuilds") as Int? if (maxBuilds == null) { println("Max build limit for period not specified...defaulting to 100") maxBuilds = 10 } @Suppress("UNCHECKED_CAST") var exclusions = configData.get("exclude") as List<String>? if (exclusions == null) { exclusions = ArrayList<String>() } val configInfo = ConfigInfo(graphiteServer, prefix, teamcityServer, username, password, pollPeriodSecs, maxBuilds, exclusions) return configInfo } return null } fun sendGraphiteStat(configInfo: ConfigInfo, metricName: String, metricValue: String) { val message = metricName.formatMetric(metricValue) val socket = Socket(configInfo.graphiteServer, 2003) val writer = OutputStreamWriter(socket.getOutputStream()) try { writer.write(message); writer.flush(); } catch (e: IOException) { LOG.error("Error writing to graphite: ", e) } } fun String.formatMetric(metricValue: String): String { return this + " " + metricValue + " " + Math.round(System.currentTimeMillis() / 1000.0) + "\n"; } } data class ConfigInfo( val graphiteServer: String, val prefix: String?, val teamcityServer : String, val username : String?, val password : String?, val pollPeriodSecs : Int, val maxBuilds : Int, val excludeProjects : List<String>) { fun getQueueLengthMetricName(): String { return prefix + ".queuesize" } fun getBuildWaitTimeMetricName(buildConfigurationId: String): String { return prefix + ".build." + buildConfigurationId + ".queuetime" } fun getBuildRunTimeMetricName(buildConfigurationId: String): String { return prefix + ".build." + buildConfigurationId + ".buildtime" } } }
mit
b513a4834bfc864a5cf463d3aa17543f
40.025907
150
0.520081
5.651677
false
true
false
false
intrigus/jtransc
jtransc-main/test/JsTest.kt
1
8782
/* * Copyright 2016 Carlos Ballesteros Velasco * * 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. */ import big.* import com.jtransc.BuildBackend import com.jtransc.gen.js.JsGenerator import com.jtransc.gen.js.JsTarget import com.jtransc.plugin.service.ConfigServiceLoader import issues.Issue100Double import issues.Issue105 import issues.Issue135 import issues.issue130.Issue130 import issues.issue146.Issue146 import issues.issue158.Issue158 import javatest.ExtendedCharsetsTest import javatest.MemberCollisionsTest import javatest.MessageDigestTest import javatest.misc.BenchmarkTest import javatest.misc.TryFinallyCheck import javatest.net.URLEncoderDecoderTest import javatest.utils.KotlinInheritanceTest import jtransc.ExtraKeywordsTest import jtransc.ExtraRefsTest import jtransc.ProcessTest import jtransc.bug.JTranscBug110 import jtransc.bug.JTranscBug127 import jtransc.java8.Java8Test import jtransc.java8.Java8Test2 import jtransc.jtransc.js.ScriptEngineTest import jtransc.jtransc.nativ.JTranscJsNativeMixedTest import jtransc.micro.MicroHelloWorld import jtransc.micro.NanoHelloWorldTest import jtransc.ref.MethodBodyReferencesTest import jtransc.staticinit.StaticInitTest import jtransc.staticinit.StaticInitTest2 import org.junit.Assert import org.junit.Ignore import org.junit.Test import testservice.test.ServiceLoaderTest import testservice.test.TestServiceJs2 class JsTest : _Base() { override val DEFAULT_TARGET = JsTarget() //override val TREESHAKING_TRACE = true @Test fun testBig() = testClass(Params(clazz = BigTest::class.java, minimize = false, log = false)) @Test fun testBigMin() = testClass(Params(clazz = BigTest::class.java, minimize = true, log = false)) @Test fun testBigIO() = testClass(Params(clazz = BigIOTest::class.java, minimize = true, log = false, treeShaking = true)) @Test fun testProcess() = testClass(Params(clazz = ProcessTest::class.java, minimize = true, log = false, treeShaking = true)) @Test fun testJTranscBug110() = testClass(Params(clazz = JTranscBug110::class.java, minimize = false, log = false, treeShaking = true)) @Test fun testScriptEngine() = testClass(Params(clazz = ScriptEngineTest::class.java, minimize = false, log = false, treeShaking = true)) @Test fun testJavaEightJs() = testClass(Params(clazz = Java8Test::class.java, minimize = false, log = false)) @Test fun testNanoHelloWorld() = testClass(Params(clazz = NanoHelloWorldTest::class.java, minimize = false, log = false, treeShaking = true)) @Test fun testStaticInitIssue135() = testClass(Params(clazz = Issue135::class.java, minimize = false, log = false, treeShaking = true)) @Ignore("Already included in BigTest") @Test fun testJTranscBug127() = testClass(Params(clazz = JTranscBug127::class.java, minimize = false, log = false, treeShaking = true)) @Ignore("Already included in BigTest") @Test fun testDescentIssue130() = testClass(Params(clazz = Issue130::class.java, minimize = false, log = false, treeShaking = true)) @Test fun testNanoHelloWorldShouldReferenceGetMethods() { val result = _action(Params(clazz = NanoHelloWorldTest::class.java, minimize = false, log = false, treeShaking = true), run = false) val generator = result.generator as JsGenerator val outputFile = generator.jsOutputFile val output = outputFile.readString() Assert.assertEquals(false, output.contains("getMethod")) println("OutputSize: ${outputFile.size}") Assert.assertEquals(true, outputFile.size < 220 * 1024) // Size should be < 220 KB } @Test fun testMicroHelloWorld() = testClass(Params(clazz = MicroHelloWorld::class.java, minimize = true, log = false, treeShaking = true)) @Test fun testKotlinInheritanceTestJs() = testClass(Params(clazz = KotlinInheritanceTest::class.java, minimize = false, log = false)) @Test fun testTwoJavaEightTwoJs() = testClass(Params(clazz = Java8Test2::class.java, minimize = false, log = false)) @Test fun testURLEncoderDecoder() = testClass(Params(clazz = URLEncoderDecoderTest::class.java, minimize = false, log = false, treeShaking = true)) //@Test fun testIssue100Double() = testClass<Issue100Double>(minimize = true, log = true, treeShaking = true, debug = true) @Test fun testIssue100Double() = testClass(Params(clazz = Issue100Double::class.java, minimize = true, log = false, treeShaking = true)) @Test fun testIssue105() = testClass(Params(clazz = Issue105::class.java, minimize = false, log = false, treeShaking = true)) @Test fun testExtendedCharsets() = testClass(Params(clazz = ExtendedCharsetsTest::class.java, minimize = false, log = false, treeShaking = true)) @Test fun testMessageDigestTest() = testClass(Params(clazz = MessageDigestTest::class.java, minimize = false, log = false, treeShaking = true)) //@Test fun testMicroHelloWorldAsm2() = testClass<MicroHelloWorld>(minimize = false, log = false, treeShaking = true, backend = BuildBackend.ASM2) //@Test fun testMicroHelloWorldAsm2() = testClass<MicroHelloWorld>(minimize = false, log = false, treeShaking = true, backend = BuildBackend.ASM2) //@Test fun testMicroHelloWorldAsm2() = testClass<HelloWorldTest>(minimize = false, log = false, treeShaking = true, backend = BuildBackend.ASM2) //@Test fun testMicroHelloWorldAsm2() = testClass<BenchmarkTest>(minimize = false, log = false, treeShaking = true, backend = BuildBackend.ASM2) @Test fun testMicroStaticInitTest() = testClass(Params(clazz = StaticInitTest::class.java, minimize = false, log = false, backend = BuildBackend.ASM, treeShaking = true)) @Test fun testMicroStaticInitTest2() = testClass(Params(clazz = StaticInitTest2::class.java, minimize = false, log = false, backend = BuildBackend.ASM, treeShaking = true)) @Test fun testHelloWorld() = testClass(Params(clazz = HelloWorldTest::class.java, minimize = false, log = false)) @Test fun testBenchmarkTest() = testClass(Params(clazz = BenchmarkTest::class.java, minimize = false, log = false)) @Test fun testServiceLoaderTest() = testNativeClass(""" TestServiceImpl1.test:ss TestServiceJs10 """, Params(clazz = ServiceLoaderTest::class.java, minimize = false, configureInjector = { mapInstance(ConfigServiceLoader( classesToSkip = listOf( TestServiceJs2::class.java.name ) )) })) @Test fun nativeJsTest() = testNativeClass(""" 17 -333 Services: TestServiceImpl1.test:ss /Services: 2 hello world 10 jtransc_jtransc_JTranscInternalNamesTest main([Ljava/lang/String;)V ___hello Error !(10 < 10) ok JTranscReinterpretArrays: MethodBodyReferencesTestJs:true MethodBodyReferencesTestCpp:false MethodBodyReferencesTestJvm:false OK! MixedJsKotlin.main[1] MixedJsKotlin.main[2] [ 1, 2, 3 ] <Buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f> {"a":10,"b":"c","c":[1,2,3]} .txt 1 2 0 true 1234567 1 hello 777 999 21 HELLO WORLD1demo HELLO WORLD2test Timeout! """, Params(clazz = JTranscJsNativeMixedTest::class.java, minimize = false, treeShaking = true)) @Test fun referencesTest() = testNativeClass(""" MethodBodyReferencesTestJs:true MethodBodyReferencesTestCpp:false MethodBodyReferencesTestJvm:false """, Params(clazz = MethodBodyReferencesTest::class.java, minimize = true, treeShaking = false)) @Test fun extraKeywordsJs() = testNativeClass(""" 1 2 3 4 5 6 7 8 9 """, Params(clazz = ExtraKeywordsTest::class.java, minimize = true)) @Test fun extraRefsTest() = testNativeClass(""" OK """, Params(clazz = ExtraRefsTest::class.java, minimize = true)) @Test fun testNumberFormatTest2() = testClass(Params(clazz = NumberFormatTest2::class.java, minimize = false, log = false)) @Test fun testTryFinallyCheck() = testClass(Params(clazz = TryFinallyCheck::class.java, minimize = false, log = false)) @Test fun testMemberCollisionsTest() = testClass(Params(clazz = MemberCollisionsTest::class.java, minimize = false, log = false)) @Test fun testAsyncIO() = testClass(Params(clazz = AsyncIOTest::class.java, minimize = false, log = false, treeShaking = true)) @Ignore("Must fix #146") @Test fun testIssue146() = testClass(Params(clazz = Issue146::class.java, minimize = false, log = false, treeShaking = true)) @Test fun testIssue158() = testClass(Params(clazz = Issue158::class.java, minimize = false, log = false, treeShaking = true)) }
apache-2.0
d1b63778881c72ebb8187c50d7868b11
42.696517
173
0.755181
3.800087
false
true
false
false
koma-im/koma
src/main/kotlin/koma/gui/element/control/KVirtualScrollBar.kt
1
1838
package koma.gui.element.control import javafx.scene.control.ListCell import javafx.scene.control.ScrollBar import javafx.scene.control.Skin import koma.gui.element.control.skin.KVirtualFlow import koma.gui.element.control.skin.ScrollBarSkin import mu.KotlinLogging import org.controlsfx.tools.Utils private val logger = KotlinLogging.logger {} /** * This custom ScrollBar is used to map the increment & decrement features * to pixel based scrolling rather than thumb/track based scrolling, if the * "virtual" attribute is true. */ class KVirtualScrollBar<I, T>( private val flow: KVirtualFlow<I, T>, private val isVirtual: Boolean = true ) : ScrollBar() where I: ListCell<T> { override fun decrement() { if (isVirtual) { flow.scrollPixels(-10.0) } else { super.decrement() } } override fun increment() { if (isVirtual) { flow.scrollPixels(10.0) } else { super.increment() } } fun turnPageByPos(pos: Double) { val oldValue = flow.getPosition() val newValue = (max - min) * Utils.clamp(0.0, pos, 1.0) + min if (newValue < oldValue) { pageUp() } else if (newValue > oldValue) { pageDown() } } fun pageUp(){ val cell = flow.firstVisibleCell ?: return flow.scrollToBottom(cell) } fun pageDown(){ val cell = flow.lastVisibleCell ?: return flow.scrollToTop(cell) } fun end() { val s = flow.itemsSize() if (s == null){ logger.error { "trying to get to the bottom of an empty list" } return } flow.scrollToTop( s - 1) } override fun createDefaultSkin(): Skin<*> { return ScrollBarSkin(this) } }
gpl-3.0
dd1e7e9c2a6e2865d2547f7be9bdf6a5
24.178082
75
0.597388
4.084444
false
false
false
false
aosp-mirror/platform_frameworks_support
jetifier/jetifier/core/src/main/kotlin/com/android/tools/build/jetifier/core/rule/RewriteRulesMap.kt
1
2156
/* * 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.rule import com.android.tools.build.jetifier.core.type.JavaType /** * Contains all [RewriteRule]s. */ class RewriteRulesMap(val rewriteRules: List<RewriteRule>) { companion object { private const val TAG = "RewriteRulesMap" val EMPTY = RewriteRulesMap(emptyList()) } constructor(vararg rules: RewriteRule) : this(rules.toList()) val runtimeIgnoreRules = rewriteRules.filter { it.isRuntimeIgnoreRule() }.toSet() /** * Tries to rewrite the given given type using the rules. If */ fun rewriteType(type: JavaType): JavaType? { // Try to find a rule for (rule in rewriteRules) { if (rule.isIgnoreRule()) { continue } val typeRewriteResult = rule.apply(type) if (typeRewriteResult.result == null) { continue } return typeRewriteResult.result } return null } fun reverse(): RewriteRulesMap { return RewriteRulesMap(rewriteRules .filter { !it.isIgnoreRule() } .map { it.reverse() } .toList()) } fun appendRules(rules: List<RewriteRule>): RewriteRulesMap { return RewriteRulesMap(rewriteRules + rules) } fun toJson(): JsonData { return JsonData(rewriteRules.map { it.toJson() }.toSet()) } /** * JSON data model for [RewriteRulesMap]. */ data class JsonData(val rules: Set<RewriteRule.JsonData>) }
apache-2.0
3b79bf9dda7a5e65e6105bdd55a6d3c0
28.148649
85
0.642393
4.519916
false
false
false
false
JetBrains/teamcity-azure-plugin
plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/web/VmSizesHandler.kt
1
1397
/* * 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.web import jetbrains.buildServer.clouds.azure.arm.connector.AzureApiConnector import kotlinx.coroutines.coroutineScope import org.jdom.Content import org.jdom.Element import javax.servlet.http.HttpServletRequest /** * Handles vm sizes request. */ internal class VmSizesHandler : ResourceHandler { override suspend fun handle(request: HttpServletRequest, context: ResourceHandlerContext) = coroutineScope { val region = request.getParameter("region") val sizes = context.apiConnector.getVmSizes(region) val sizesElement = Element("vmSizes") for (size in sizes) { sizesElement.addContent(Element("vmSize").apply { text = size }) } sizesElement } }
apache-2.0
5ab0e9ab880fd814c3342672f0c57365
32.261905
112
0.72083
4.420886
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/parser/GenePostgresSimilarToVisitor.kt
1
7654
package org.evomaster.core.parser import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.regex.* /** * Created by arcuri82 on 12-Jun-19. */ class GenePostgresSimilarToVisitor : PostgresSimilarToBaseVisitor<VisitResult>() { /* WARNING: lot of code here is similar/adapted from ECMA262 visitor. But, as the parser objects are different, it does not seem simple to reuse the code without avoiding copy&paste&adapt :( */ override fun visitPattern(ctx: PostgresSimilarToParser.PatternContext): VisitResult { val res = ctx.disjunction().accept(this) val disjList = DisjunctionListRxGene(res.genes.map { it as DisjunctionRxGene }) val gene = RegexGene("regex", disjList) return VisitResult(gene) } override fun visitDisjunction(ctx: PostgresSimilarToParser.DisjunctionContext): VisitResult { val altRes = ctx.alternative().accept(this) val disj = DisjunctionRxGene("disj", altRes.genes.map { it as Gene }, true, true) val res = VisitResult(disj) if(ctx.disjunction() != null){ val disjRes = ctx.disjunction().accept(this) res.genes.addAll(disjRes.genes) } return res } override fun visitAlternative(ctx: PostgresSimilarToParser.AlternativeContext): VisitResult { val res = VisitResult() for(i in 0 until ctx.term().size){ val resTerm = ctx.term()[i].accept(this) val gene = resTerm.genes.firstOrNull() if(gene != null) { res.genes.add(gene) } } return res } override fun visitTerm(ctx: PostgresSimilarToParser.TermContext): VisitResult { val res = VisitResult() val resAtom = ctx.atom().accept(this) val atom = resAtom.genes.firstOrNull() ?: return res if(ctx.quantifier() != null){ val limits = ctx.quantifier().accept(this).data as Pair<Int,Int> val q = QuantifierRxGene("q", atom, limits.first, limits.second) res.genes.add(q) } else { res.genes.add(atom) } return res } override fun visitQuantifier(ctx: PostgresSimilarToParser.QuantifierContext): VisitResult { val res = VisitResult() var min = 1 var max = 1 if(ctx.bracketQuantifier() == null){ val symbol = ctx.text when(symbol){ "*" -> {min=0; max= Int.MAX_VALUE} "+" -> {min=1; max= Int.MAX_VALUE} "?" -> {min=0; max=1} else -> throw IllegalArgumentException("Invalid quantifier symbol: $symbol") } } else { val q = ctx.bracketQuantifier() when { q.bracketQuantifierOnlyMin() != null -> { min = q.bracketQuantifierOnlyMin().decimalDigits().text.toInt() max = Int.MAX_VALUE } q.bracketQuantifierSingle() != null -> { min = q.bracketQuantifierSingle().decimalDigits().text.toInt() max = min } q.bracketQuantifierRange() != null -> { val range = q.bracketQuantifierRange() min = range.decimalDigits()[0].text.toInt() max = range.decimalDigits()[1].text.toInt() } else -> throw IllegalArgumentException("Invalid quantifier: ${ctx.text}") } } res.data = Pair(min,max) return res } override fun visitAtom(ctx: PostgresSimilarToParser.AtomContext): VisitResult { if(! ctx.patternCharacter().isEmpty()){ val block = ctx.patternCharacter().map { it.text } .joinToString("") val gene = PatternCharacterBlockGene("block", block) return VisitResult(gene) } if(ctx.disjunction() != null){ val res = ctx.disjunction().accept(this) val disjList = DisjunctionListRxGene(res.genes.map { it as DisjunctionRxGene }) //TODO tmp hack until full handling of ^$. Assume full match when nested disjunctions for(gene in disjList.disjunctions){ gene.extraPrefix = false gene.extraPostfix = false gene.matchStart = true gene.matchEnd = true } return VisitResult(disjList) } if(ctx.UNDERSCORE() != null){ return VisitResult(AnyCharacterRxGene()) } if(ctx.PERCENT() != null){ return VisitResult(QuantifierRxGene("q", AnyCharacterRxGene(), 0 , Int.MAX_VALUE)) } if(ctx.characterClass() != null){ return ctx.characterClass().accept(this) } throw IllegalStateException("No valid atom resolver for: ${ctx.text}") } override fun visitCharacterClass(ctx: PostgresSimilarToParser.CharacterClassContext): VisitResult { val negated = ctx.CARET() != null val ranges = ctx.classRanges().accept(this).data as List<Pair<Char,Char>> val gene = CharacterRangeRxGene(negated, ranges) return VisitResult(gene) } override fun visitClassRanges(ctx: PostgresSimilarToParser.ClassRangesContext): VisitResult { val res = VisitResult() val list = mutableListOf<Pair<Char,Char>>() if(ctx.nonemptyClassRanges() != null){ val ranges = ctx.nonemptyClassRanges().accept(this).data as List<Pair<Char,Char>> list.addAll(ranges) } res.data = list return res } override fun visitNonemptyClassRanges(ctx: PostgresSimilarToParser.NonemptyClassRangesContext): VisitResult { val list = mutableListOf<Pair<Char,Char>>() val startText = ctx.classAtom()[0].text assert(startText.length == 1) // single chars val start : Char = startText[0] val end = if(ctx.classAtom().size == 2){ ctx.classAtom()[1].text[0] } else { //single char, not an actual range start } list.add(Pair(start, end)) if(ctx.nonemptyClassRangesNoDash() != null){ val ranges = ctx.nonemptyClassRangesNoDash().accept(this).data as List<Pair<Char,Char>> list.addAll(ranges) } if(ctx.classRanges() != null){ val ranges = ctx.classRanges().accept(this).data as List<Pair<Char,Char>> list.addAll(ranges) } val res = VisitResult() res.data = list return res } override fun visitNonemptyClassRangesNoDash(ctx: PostgresSimilarToParser.NonemptyClassRangesNoDashContext): VisitResult { val list = mutableListOf<Pair<Char,Char>>() if(ctx.MINUS() != null){ val start = ctx.classAtomNoDash().text[0] val end = ctx.classAtom().text[0] list.add(Pair(start, end)) } else { val char = (ctx.classAtom() ?: ctx.classAtomNoDash()).text[0] list.add(Pair(char, char)) } if(ctx.nonemptyClassRangesNoDash() != null){ val ranges = ctx.nonemptyClassRangesNoDash().accept(this).data as List<Pair<Char,Char>> list.addAll(ranges) } if(ctx.classRanges() != null){ val ranges = ctx.classRanges().accept(this).data as List<Pair<Char,Char>> list.addAll(ranges) } val res = VisitResult() res.data = list return res } }
lgpl-3.0
566c081c77411b3f619ec6826f9d7bde
27.886792
125
0.57421
4.661389
false
false
false
false
JavaTrainingCourse/obog-manager
src/main/kotlin/com/github/javatrainingcourse/obogmanager/domain/model/Attendance.kt
1
2006
/* * Copyright (c) 2017-2018 mikan */ package com.github.javatrainingcourse.obogmanager.domain.model import com.github.javatrainingcourse.obogmanager.Version import java.io.Serializable import java.util.* import javax.persistence.* /** * @author mikan * @since 0.1 */ @Entity @Table(name = "attendances") class Attendance { @AttributeOverrides(AttributeOverride(name = "convocationId", column = Column(name = "convocation_id")), AttributeOverride(name = "membershipId", column = Column(name = "member_id"))) @EmbeddedId private var id: AttendanceId? = null @MapsId("convocationId") @ManyToOne var convocation: Convocation? = null @MapsId("membershipId") @ManyToOne var membership: Membership? = null @Column(nullable = false) var attend: Boolean? = null @Column(length = 256) var comment: String? = null @Column @Temporal(TemporalType.TIMESTAMP) var createdDate: Date? = null @Column @Temporal(TemporalType.TIMESTAMP) var lastUpdateDate: Date? = null companion object { fun newAttendance(convocation: Convocation, membership: Membership, comment: String): Attendance { val id = AttendanceId() id.convocationId = convocation.id id.membershipId = membership.id val attendance = Attendance() attendance.id = id attendance.convocation = convocation attendance.membership = membership attendance.comment = comment attendance.attend = true attendance.createdDate = Date() attendance.lastUpdateDate = Date() return attendance } } class AttendanceId : Serializable { var convocationId: Long? = null var membershipId: Long? = null companion object { private const val serialVersionUID = Version.OBOG_MANAGER_SERIAL_VERSION_UID } } fun isAttend(): Boolean { return attend ?: true } }
apache-2.0
b21908ea272ef9efca5836d809b59ca0
25.394737
187
0.646062
4.389497
false
false
false
false
Szewek/Minecraft-Flux
src/main/java/szewek/mcflux/items/ItemUpChip.kt
1
1845
package szewek.mcflux.items import net.minecraft.entity.EntityLivingBase import net.minecraft.entity.player.EntityPlayer import net.minecraft.entity.player.EntityPlayerMP import net.minecraft.item.EnumAction import net.minecraft.item.ItemStack import net.minecraft.network.play.server.SPacketTitle import net.minecraft.stats.StatList import net.minecraft.util.ActionResult import net.minecraft.util.EnumActionResult import net.minecraft.util.EnumHand import net.minecraft.util.text.TextComponentTranslation import net.minecraft.world.World import szewek.mcflux.fluxable.FluxableCapabilities class ItemUpChip : ItemMCFlux() { override fun getItemUseAction(stack: ItemStack?) = EnumAction.BOW override fun getMaxItemUseDuration(stack: ItemStack) = 40 override fun onItemRightClick(w: World, p: EntityPlayer, h: EnumHand): ActionResult<ItemStack> { p.activeHand = h return ActionResult(EnumActionResult.SUCCESS, p.getHeldItem(h)) } override fun onItemUseFinish(stk: ItemStack, w: World, elb: EntityLivingBase): ItemStack { if (!w.isRemote && elb is EntityPlayerMP) { val mp = elb as EntityPlayerMP? val pe = mp!!.getCapability(FluxableCapabilities.CAP_PE, null) ?: return stk val lvl = pe.updateLevel() if (lvl.toInt() == -1) return stk stk.grow(-1) mp.connection.sendPacket(SPacketTitle(SPacketTitle.Type.TITLE, textInstalled, 50, 500, 50)) mp.connection.sendPacket(SPacketTitle(SPacketTitle.Type.SUBTITLE, if (lvl.toInt() == 30) textLvlMax else TextComponentTranslation(PF + "lvlup", lvl))) val stat = StatList.getObjectUseStats(this) if (stat != null) mp.addStat(stat) } return stk } companion object { private const val PF = "mcflux.upchip." private val textInstalled = TextComponentTranslation(PF + "installed") private val textLvlMax = TextComponentTranslation(PF + "lvlmax") } }
mit
f3761f62f14a83255362a5a557ae2d32
36.653061
153
0.776152
3.646245
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/resolver/SourcePathProvider.kt
3
3348
/* * 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 org.gradle.kotlin.dsl.resolver import org.gradle.internal.classpath.ClassPath import org.gradle.kotlin.dsl.support.KotlinScriptType import org.gradle.kotlin.dsl.support.KotlinScriptTypeMatch import org.gradle.kotlin.dsl.support.filter import org.gradle.kotlin.dsl.support.isGradleKotlinDslJar import org.gradle.kotlin.dsl.support.listFilesOrdered import java.io.File const val buildSrcSourceRootsFilePath = "build/source-roots/buildSrc/source-roots.txt" object SourcePathProvider { fun sourcePathFor( classPath: ClassPath, scriptFile: File?, projectDir: File, gradleHomeDir: File?, sourceDistributionResolver: SourceDistributionProvider ): ClassPath { val gradleKotlinDslJar = classPath.filter(::isGradleKotlinDslJar) val gradleSourceRoots = gradleHomeDir?.let { sourceRootsOf(it, sourceDistributionResolver) } ?: emptyList() // If the script file is known, determine its type val scriptType = scriptFile?.let { KotlinScriptTypeMatch.forFile(it)?.scriptType } // We also add the "buildSrc" sources onto the source path. // Only exception is the "settings.gradle.kts" script, which is evaluated before "buildSrc", so it shouldn't see the sources val projectBuildSrcRoots = when (scriptType) { KotlinScriptType.SETTINGS -> emptyList() else -> buildSrcRootsOf(projectDir) } return gradleKotlinDslJar + projectBuildSrcRoots + gradleSourceRoots } /** * Returns source directories from buildSrc if any. */ private fun buildSrcRootsOf(projectRoot: File): Collection<File> = projectRoot.resolve("buildSrc/$buildSrcSourceRootsFilePath") .takeIf { it.isFile } ?.readLines() ?.map { projectRoot.resolve("buildSrc/$it") } ?: buildSrcRootsFallbackFor(projectRoot) private fun buildSrcRootsFallbackFor(projectRoot: File) = subDirsOf(File(projectRoot, "buildSrc/src/main")) private fun sourceRootsOf(gradleInstallation: File, sourceDistributionResolver: SourceDistributionProvider): Collection<File> = gradleInstallationSources(gradleInstallation) ?: downloadedSources(sourceDistributionResolver) private fun gradleInstallationSources(gradleInstallation: File) = File(gradleInstallation, "src").takeIf { it.exists() }?.let { subDirsOf(it) } private fun downloadedSources(sourceDistributionResolver: SourceDistributionProvider) = sourceDistributionResolver.sourceDirs() } internal fun subDirsOf(dir: File): Collection<File> = if (dir.isDirectory) dir.listFilesOrdered { it.isDirectory } else emptyList()
apache-2.0
6ef9b341884b545bc04f99eece441668
35.791209
132
0.720131
4.689076
false
false
false
false
honix/godot
platform/android/java/lib/src/org/godotengine/godot/vulkan/VkThread.kt
5
7115
/*************************************************************************/ /* VkThread.kt */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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. */ /*************************************************************************/ @file:JvmName("VkThread") package org.godotengine.godot.vulkan import android.util.Log import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /** * Thread implementation for the [VkSurfaceView] onto which the vulkan logic is ran. * * The implementation is modeled after [android.opengl.GLSurfaceView]'s GLThread. */ internal class VkThread(private val vkSurfaceView: VkSurfaceView, private val vkRenderer: VkRenderer) : Thread(TAG) { companion object { private val TAG = VkThread::class.java.simpleName } /** * Used to run events scheduled on the thread. */ private val eventQueue = ArrayList<Runnable>() /** * Used to synchronize interaction with other threads (e.g: main thread). */ private val lock = ReentrantLock() private val lockCondition = lock.newCondition() private var shouldExit = false private var exited = false private var rendererInitialized = false private var rendererResumed = false private var resumed = false private var surfaceChanged = false private var hasSurface = false private var width = 0 private var height = 0 /** * Determine when drawing can occur on the thread. This usually occurs after the * [android.view.Surface] is available, the app is in a resumed state. */ private val readyToDraw get() = hasSurface && resumed private fun threadExiting() { lock.withLock { exited = true lockCondition.signalAll() } } /** * Queue an event on the [VkThread]. */ fun queueEvent(event: Runnable) { lock.withLock { eventQueue.add(event) lockCondition.signalAll() } } /** * Request the thread to exit and block until it's done. */ fun blockingExit() { lock.withLock { shouldExit = true lockCondition.signalAll() while (!exited) { try { Log.i(TAG, "Waiting on exit for $name") lockCondition.await() } catch (ex: InterruptedException) { currentThread().interrupt() } } } } /** * Invoked when the app resumes. */ fun onResume() { lock.withLock { resumed = true lockCondition.signalAll() } } /** * Invoked when the app pauses. */ fun onPause() { lock.withLock { resumed = false lockCondition.signalAll() } } /** * Invoked when the [android.view.Surface] has been created. */ fun onSurfaceCreated() { // This is a no op because surface creation will always be followed by surfaceChanged() // which provide all the needed information. } /** * Invoked following structural updates to [android.view.Surface]. */ fun onSurfaceChanged(width: Int, height: Int) { lock.withLock { hasSurface = true surfaceChanged = true; this.width = width this.height = height lockCondition.signalAll() } } /** * Invoked when the [android.view.Surface] is no longer available. */ fun onSurfaceDestroyed() { lock.withLock { hasSurface = false lockCondition.signalAll() } } /** * Thread loop modeled after [android.opengl.GLSurfaceView]'s GLThread. */ override fun run() { try { while (true) { var event: Runnable? = null lock.withLock { while (true) { // Code path for exiting the thread loop. if (shouldExit) { vkRenderer.onVkDestroy() return } // Check for events and execute them outside of the loop if found to avoid // blocking the thread lifecycle by holding onto the lock. if (eventQueue.isNotEmpty()) { event = eventQueue.removeAt(0) break; } if (readyToDraw) { if (!rendererResumed) { rendererResumed = true vkRenderer.onVkResume() if (!rendererInitialized) { rendererInitialized = true vkRenderer.onVkSurfaceCreated(vkSurfaceView.holder.surface) } } if (surfaceChanged) { vkRenderer.onVkSurfaceChanged(vkSurfaceView.holder.surface, width, height) surfaceChanged = false } // Break out of the loop so drawing can occur without holding onto the lock. break; } else if (rendererResumed) { // If we aren't ready to draw but are resumed, that means we either lost a surface // or the app was paused. rendererResumed = false vkRenderer.onVkPause() } // We only reach this state if we are not ready to draw and have no queued events, so // we wait. // On state change, the thread will be awoken using the [lock] and [lockCondition], and // we will resume execution. lockCondition.await() } } // Run queued event. if (event != null) { event?.run() continue } // Draw only when there no more queued events. vkRenderer.onVkDrawFrame() } } catch (ex: InterruptedException) { Log.i(TAG, "InterruptedException", ex) } catch (ex: IllegalStateException) { Log.i(TAG, "IllegalStateException", ex) } finally { threadExiting() } } }
mit
28671df34e4536b94ffe6e02abe11cb9
29.405983
117
0.592551
4.309509
false
false
false
false
AlmasB/FXGL
fxgl-samples/src/main/kotlin/sandbox/subscene/SubSceneSampleApp.kt
1
1549
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package sandbox.subscene import com.almasb.fxgl.app.GameApplication import com.almasb.fxgl.app.GameSettings import com.almasb.fxgl.dsl.FXGL import com.almasb.fxgl.scene.SubScene import javafx.event.EventHandler import javafx.util.Duration /** * @author Serge Merzliakov ([email protected]) */ class SubSceneSampleApp : GameApplication() { override fun initSettings(settings: GameSettings) { settings.width = 700 settings.height = 400 settings.title = "SubScene Navigation Demo" settings.isMainMenuEnabled = false settings.isGameMenuEnabled = false settings.isIntroEnabled = false } override fun initGame() { val handler: EventHandler<NavigateEvent> = EventHandler { e: NavigateEvent? -> handleNavigate(e!!) } FXGL.getEventBus().addEventHandler(NAVIGATION, handler) } override fun initUI() { FXGL.run(Runnable { FXGL.getSceneService().pushSubScene(MainSubScene()) }, Duration.seconds(0.0)) } private fun handleNavigate(e: NavigateEvent) { var subScene: SubScene? = null when (e.eventType) { MAIN_VIEW -> subScene = MainSubScene() ABOUT_VIEW -> subScene = AboutSubScene() OPTIONS_VIEW -> subScene = OptionsSubScene() PLAY_VIEW -> subScene = PlaySubScene() } FXGL.getSceneService().popSubScene() FXGL.getSceneService().pushSubScene(subScene!!) } } fun main(args: Array<String>) { GameApplication.launch(SubSceneSampleApp::class.java, args) }
mit
315c197af1d2736c8d6c1054f564c60b
23.587302
80
0.733376
3.496614
false
false
false
false
timrs2998/pdf-builder
src/main/kotlin/com/github/timrs2998/pdfbuilder/KotlinBuilder.kt
1
2670
package com.github.timrs2998.pdfbuilder import org.apache.pdfbox.pdmodel.PDDocument import java.awt.image.BufferedImage /** * A DSL for Kotlin, Groovy or Java 8 consumers of this API. */ @DslMarker annotation class DocumentMarker /** * Creates the outermost [Document] [element][Element] representing the pdf, and returns * the rendered [PDDocument] that can be [saved][PDDocument.save] to a * [java.io.File] or [java.io.OutputStream]. * * @return The rendered [PDDocument]. */ fun document(init: Document.() -> Unit): PDDocument { val document = Document() document.init() return document.render() } // Workaround for Groovy disliking kotlin default parameters @DocumentMarker fun Document.text(value: String) = this.text(value) {} @DocumentMarker fun Document.text(value: String, init: TextElement.() -> Unit = {}): TextElement { val textElement = TextElement(this, value) textElement.init() this.children.add(textElement) return textElement } @DocumentMarker fun Document.image(imagePath: String) = this.image(imagePath) {} @DocumentMarker fun Document.image(imagePath: String, init: ImageElement.() -> Unit = {}): ImageElement { val imageElement = ImageElement(this, imagePath, null) imageElement.init() this.children.add(imageElement) return imageElement } @DocumentMarker fun Document.image(bufferedImage: BufferedImage): ImageElement = this.image(bufferedImage) {} @DocumentMarker fun Document.image(bufferedImage: BufferedImage, init: ImageElement.() -> Unit = {}): ImageElement { val imageElement = ImageElement(this, "", bufferedImage) imageElement.init() this.children.add(imageElement) return imageElement } @DocumentMarker fun Document.table(init: TableElement.() -> Unit): TableElement { val tableElement = TableElement(this) tableElement.init() this.children.add(tableElement) return tableElement } @DslMarker annotation class TableMarker @TableMarker fun TableElement.header(init: RowElement.() -> Unit): RowElement { val rowElement = RowElement(this) rowElement.init() this.header = rowElement return rowElement } @TableMarker fun TableElement.row(init: RowElement.() -> Unit): RowElement { val rowElement = RowElement(this) rowElement.init() this.rows.add(rowElement) return rowElement } @DslMarker annotation class RowMarker // Workaround for Groovy disliking kotlin default parameters @RowMarker fun RowElement.text(value: String) = this.text(value) {} @RowMarker fun RowElement.text(value: String, init: TextElement.() -> Unit = {}): TextElement { val textElement = TextElement(this, value) textElement.init() this.columns.add(textElement) return textElement }
gpl-3.0
9795037be7aef5805c3eefa190651f07
25.7
100
0.748689
4.033233
false
false
false
false
willowtreeapps/assertk
assertk/src/commonMain/kotlin/assertk/assertions/iterable.kt
1
9964
package assertk.assertions import assertk.Assert import assertk.all import assertk.assertions.support.appendName import assertk.assertions.support.expected import assertk.assertions.support.show /** * Asserts the iterable contains the expected element, using `in`. * @see [doesNotContain] */ fun Assert<Iterable<*>>.contains(element: Any?) = given { actual -> if (element in actual) return expected("to contain:${show(element)} but was:${show(actual)}") } /** * Asserts the iterable does not contain the expected element, using `!in`. * @see [contains] */ fun Assert<Iterable<*>>.doesNotContain(element: Any?) = given { actual -> if (element !in actual) return expected("to not contain:${show(element)} but was:${show(actual)}") } /** * Asserts the iterable does not contain any of the expected elements. * @see [containsAll] */ fun Assert<Iterable<*>>.containsNone(vararg elements: Any?) = given { actual -> val notExpected = elements.filter { it in actual } if (notExpected.isEmpty()) { return } expected("to contain none of:${show(elements)} but was:${show(actual)}\n elements not expected:${show(notExpected)}") } /** * Asserts the iterable contains all the expected elements, in any order. The collection may also * contain additional elements. * @see [containsNone] * @see [containsExactly] * @see [containsOnly] */ fun Assert<Iterable<*>>.containsAll(vararg elements: Any?) = given { actual -> val notFound = elements.filterNot { it in actual } if (notFound.isEmpty()) { return } expected("to contain all:${show(elements)} but was:${show(actual)}\n elements not found:${show(notFound)}") } /** * Asserts the iterable contains only the expected elements, in any order. Duplicate values * in the expected and actual are ignored. * * [1, 2] containsOnly [2, 1] passes * [1, 2, 2] containsOnly [2, 1] passes * [1, 2] containsOnly [2, 2, 1] passes * * @see [containsNone] * @see [containsExactly] * @see [containsAll] * @see [containsExactlyInAnyOrder] */ fun Assert<Iterable<*>>.containsOnly(vararg elements: Any?) = given { actual -> val notInActual = elements.filterNot { it in actual } val notInExpected = actual.filterNot { it in elements } if (notInExpected.isEmpty() && notInActual.isEmpty()) { return } expected(StringBuilder("to contain only:${show(elements)} but was:${show(actual)}").apply { if (notInActual.isNotEmpty()) { append("\n elements not found:${show(notInActual)}") } if (notInExpected.isNotEmpty()) { append("\n extra elements found:${show(notInExpected)}") } }.toString()) } /** * Asserts the iterable contains exactly the expected elements, in any order. Each value in expected * must correspond to a matching value in actual, and visa-versa. * * [1, 2] containsExactlyInAnyOrder [2, 1] passes * [1, 2, 2] containsExactlyInAnyOrder [2, 1] fails * [1, 2] containsExactlyInAnyOrder [2, 2, 1] fails * * @see [containsNone] * @see [containsExactly] * @see [containsAll] * @see [containsOnly] */ fun Assert<Iterable<*>>.containsExactlyInAnyOrder(vararg elements: Any?) = given { actual -> val notInActual = elements.toMutableList() val notInExpected = actual.toMutableList() elements.forEach { if (notInExpected.contains(it)) { notInExpected.removeFirst(it) notInActual.removeFirst(it) } } if (notInExpected.isEmpty() && notInActual.isEmpty()) { return } expected(StringBuilder("to contain exactly in any order:${show(elements)} but was:${show(actual)}").apply { if (notInActual.isNotEmpty()) { append("\n elements not found:${show(notInActual)}") } if (notInExpected.isNotEmpty()) { append("\n extra elements found:${show(notInExpected)}") } }.toString()) } internal fun MutableList<*>.removeFirst(value: Any?) { val index = indexOf(value) if (index > -1) removeAt(index) } /** * Asserts on each item in the iterable. The given lambda will be run for each item. * * ``` * assertThat(listOf("one", "two")).each { * it.hasLength(3) * } * ``` */ fun <E> Assert<Iterable<E>>.each(f: (Assert<E>) -> Unit) = given { actual -> all { actual.forEachIndexed { index, item -> f(assertThat(item, name = appendName(show(index, "[]")))) } } } /** * Extracts a value of from each item in the iterable, allowing you to assert on a list of those values. * * ``` * assertThat(people) * .extracting(Person::name) * .contains("Sue", "Bob") * ``` */ fun <E, R> Assert<Iterable<E>>.extracting(f1: (E) -> R): Assert<List<R>> = transform { actual -> actual.map(f1) } /** * Extracts two values of from each item in the iterable, allowing you to assert on a list of paris of those values. * * ``` * assertThat(people) * .extracting(Person::name, Person::age) * .contains("Sue" to 20, "Bob" to 22) * ``` */ fun <E, R1, R2> Assert<Iterable<E>>.extracting(f1: (E) -> R1, f2: (E) -> R2): Assert<List<Pair<R1, R2>>> = transform { actual -> actual.map { f1(it) to f2(it) } } /** * Extracts three values from each item in the iterable, allowing you to assert on a list of triples of those values. * * ``` * assertThat(people) * .extracting(Person::name, Person::age, Person::address) * .contains(Triple("Sue", 20, "123 Street"), Triple("Bob", 22, "456 Street") * ``` */ fun <E, R1, R2, R3> Assert<Iterable<E>>.extracting( f1: (E) -> R1, f2: (E) -> R2, f3: (E) -> R3 ): Assert<List<Triple<R1, R2, R3>>> = transform { actual -> actual.map { Triple(f1(it), f2(it), f3(it)) } } /** * Asserts on each item in the iterable, passing if none of the items pass. * The given lambda will be run for each item. * * ``` * assertThat(listOf("one", "two")).none { * it.hasLength(2) * } * ``` */ fun <E> Assert<Iterable<E>>.none(f: (Assert<E>) -> Unit) = given { actual -> if (actual.count() > 0) { all(message = "expected none to pass", body = { each { item -> f(item) } }, failIf = { it.isEmpty() }) } } /** * Asserts on each item in the iterable, passing if at least `times` items pass. * The given lambda will be run for each item. * * ``` * assert(listOf(-1, 1, 2)).atLeast(2) { it.isPositive() } * ``` */ fun <E, T : Iterable<E>> Assert<T>.atLeast(times: Int, f: (Assert<E>) -> Unit) { var count = 0 all(message = "expected to pass at least $times times", body = { each { item -> count++; f(item) } }, failIf = { count - it.size < times }) } /** * Asserts on each item in the iterable, passing if at most `times` items pass. * The given lambda will be run for each item. * * ``` * assert(listOf(-2, -1, 1)).atMost(2) { it.isPositive() } * ``` */ fun <E, T : Iterable<E>> Assert<T>.atMost(times: Int, f: (Assert<E>) -> Unit) { var count = 0 all(message = "expected to pass at most $times times", body = { each { item -> count++; f(item) } }, failIf = { count - it.size > times }) } /** * Asserts on each item in the iterable, passing if exactly `times` items pass. * The given lambda will be run for each item. * * ``` * assert(listOf(-1, 1, 2)).exactly(2) { it.isPositive() } * ``` */ fun <E, T : Iterable<E>> Assert<T>.exactly(times: Int, f: (Assert<E>) -> Unit) { var count = 0 all(message = "expected to pass exactly $times times", body = { each { item -> count++; f(item) } }, failIf = { count - it.size != times }) } /** * Asserts on each item in the iterable, passing if any of the items pass. * The given lambda will be run for each item. * * ``` * assert(listOf(-1, -2, 1)).any { it.isPositive() } * ``` */ fun <E, T : Iterable<E>> Assert<T>.any(f: (Assert<E>) -> Unit) { var lastFailureCount = 0 var itemPassed = false all(message = "expected any item to pass", body = { failure -> given { actual -> actual.forEachIndexed { index, item -> f(assertThat(item, name = appendName(show(index, "[]")))) if (lastFailureCount == failure.count) { itemPassed = true } lastFailureCount = failure.count } } }, failIf = { !itemPassed }) } /** * Asserts the iterable is empty. * @see [isNotEmpty] * @see [isNullOrEmpty] */ fun Assert<Iterable<*>>.isEmpty() = given { actual -> if (actual.none()) return expected("to be empty but was:${show(actual)}") } /** * Asserts the iterable is not empty. * @see [isEmpty] */ fun Assert<Iterable<*>>.isNotEmpty() = given { actual -> if (actual.any()) return expected("to not be empty") } /** * Asserts the iterable is not empty, and returns an assert on the first element. */ fun <E, T : Iterable<E>> Assert<T>.first(): Assert<E> { return transform(appendName("first", ".")) { iterable -> val iterator = iterable.iterator() if (iterator.hasNext()) { iterator.next() } else { expected("to not be empty") } } } /** * Asserts the iterable contains exactly one element, and returns an assert on that element. */ fun <E, T : Iterable<E>> Assert<T>.single(): Assert<E> { return transform(appendName("single", ".")) { iterable -> val iterator = iterable.iterator() if (iterator.hasNext()) { val single = iterator.next() if (iterator.hasNext()) { val size = if (iterable is Collection<*>) iterable.size.toString() else "multiple" expected("to have single element but has $size: ${show(iterable)}") } else { single } } else { expected("to have single element but was empty") } } }
mit
d17c4eacdc2e07f8c391593df32a269b
29.567485
121
0.599759
3.694475
false
false
false
false
alexmonthy/lttng-scope
lttng-scope/src/test/kotlin/org/lttng/scope/views/timecontrol/TimeRangeTextFieldsMinimumTest.kt
2
3045
/* * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.lttng.scope.views.timecontrol import com.efficios.jabberwocky.common.TimeRange import org.junit.jupiter.api.Test /** * Tests for [TimeRangeTextFields] specifying a minimum range duration. */ class TimeRangeTextFieldsMinimumTest : TimeRangeTextFieldsTest() { // LIMIT_START = 1000 // LIMIT_END = 2000 // INITIAL_START = 1200 // INITIAL_END = 1800 companion object { private const val MINIMUM_DURATION = 100L } override fun provideFixture() = TimeRangeTextFields(TimeRange.of(LIMIT_START, LIMIT_END), MINIMUM_DURATION) // ------------------------------------------------------------------------ // Start text field // ------------------------------------------------------------------------ @Test fun testNewStartMoveEnd() { startField.text = "1750" startField.fireEvent(ENTER_EVENT) verifyTimeRange(1750, 1850) } @Test fun testNewStarMoveBoth() { startField.text = "1950" startField.fireEvent(ENTER_EVENT) verifyTimeRange(1900, LIMIT_END) } @Test override fun testNewStartBiggerThanEnd() { startField.text = "1900" startField.fireEvent(ENTER_EVENT) verifyTimeRange(1900, LIMIT_END) } @Test override fun testNewStartBiggerThanLimit() { startField.text = "2200" startField.fireEvent(ENTER_EVENT) verifyTimeRange(1900, LIMIT_END) } // ------------------------------------------------------------------------ // End text field // ------------------------------------------------------------------------ @Test fun testNewEndMoveStart() { endField.text = "1250" endField.fireEvent(ENTER_EVENT) verifyTimeRange(1150, 1250) } @Test fun testNewEndMoveBoth() { endField.text = "1050" endField.fireEvent(ENTER_EVENT) verifyTimeRange(LIMIT_START, 1100) } @Test override fun testNewEndSmallerThanLimit() { endField.text = "800" endField.fireEvent(ENTER_EVENT) verifyTimeRange(LIMIT_START, 1100) } @Test override fun testNewEndSmallerThanStart() { endField.text = "1150" endField.fireEvent(ENTER_EVENT) verifyTimeRange(1050, 1150) } // ------------------------------------------------------------------------ // Duration text field // ------------------------------------------------------------------------ @Test fun testNewDurationTooSmall() { durationField.text = "50" durationField.fireEvent(ENTER_EVENT) verifyTimeRange(INITIAL_START, INITIAL_START + MINIMUM_DURATION) } }
epl-1.0
68ecbe81ba13febdd5ad63196291641e
27.726415
111
0.553695
4.879808
false
true
false
false
kittinunf/ReactiveAndroid
reactiveandroid-ui/src/main/kotlin/com/github/kittinunf/reactiveandroid/widget/ToolbarProperty.kt
1
1364
package com.github.kittinunf.reactiveandroid.widget import android.graphics.drawable.Drawable import android.widget.Toolbar import com.github.kittinunf.reactiveandroid.MutableProperty import com.github.kittinunf.reactiveandroid.createMainThreadMutableProperty //================================================================================ // Properties //================================================================================ val Toolbar.rx_logo: MutableProperty<Drawable> get() { val getter = { logo } val setter: (Drawable) -> Unit = { logo = it } return createMainThreadMutableProperty(getter, setter) } val Toolbar.rx_navigationIcon: MutableProperty<Drawable> get() { val getter = { navigationIcon } val setter: (Drawable) -> Unit = { navigationIcon = it } return createMainThreadMutableProperty(getter, setter) } val Toolbar.rx_subtitle: MutableProperty<CharSequence> get() { val getter = { subtitle } val setter: (CharSequence) -> Unit = { subtitle = it } return createMainThreadMutableProperty(getter, setter) } val Toolbar.rx_title: MutableProperty<CharSequence> get() { val getter = { title } val setter: (CharSequence) -> Unit = { title = it } return createMainThreadMutableProperty(getter, setter) }
mit
462121afe2eba05072b5413725dc58d8
31.47619
82
0.607038
5.328125
false
false
false
false
ajordens/clouddriver
clouddriver-event/src/main/kotlin/com/netflix/spinnaker/clouddriver/event/persistence/InMemoryEventRepository.kt
2
7168
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.clouddriver.event.persistence import com.netflix.spectator.api.Registry import com.netflix.spinnaker.clouddriver.event.Aggregate import com.netflix.spinnaker.clouddriver.event.EventMetadata import com.netflix.spinnaker.clouddriver.event.SpinnakerEvent import com.netflix.spinnaker.clouddriver.event.config.MemoryEventRepositoryConfigProperties import com.netflix.spinnaker.clouddriver.event.exceptions.AggregateChangeRejectedException import com.netflix.spinnaker.kork.exceptions.SystemException import java.time.Duration import java.time.Instant import java.util.UUID import java.util.concurrent.ConcurrentHashMap import kotlin.math.max import org.slf4j.LoggerFactory import org.springframework.context.ApplicationEventPublisher import org.springframework.scheduling.annotation.Scheduled /** * An in-memory only [EventRepository]. This implementation should only be used for testing. */ class InMemoryEventRepository( private val config: MemoryEventRepositoryConfigProperties, private val applicationEventPublisher: ApplicationEventPublisher, private val registry: Registry ) : EventRepository { private val log by lazy { LoggerFactory.getLogger(javaClass) } private val aggregateCountId = registry.createId("eventing.aggregates") private val aggregateWriteCountId = registry.createId("eventing.aggregates.writes") private val aggregateReadCountId = registry.createId("eventing.aggregates.reads") private val eventCountId = registry.createId("eventing.events") private val eventWriteCountId = registry.createId("eventing.events.writes") private val eventReadCountId = registry.createId("eventing.events.reads") private val events: MutableMap<Aggregate, MutableList<SpinnakerEvent>> = ConcurrentHashMap() override fun save( aggregateType: String, aggregateId: String, originatingVersion: Long, newEvents: List<SpinnakerEvent> ) { registry.counter(aggregateWriteCountId).increment() val aggregate = getAggregate(aggregateType, aggregateId) if (aggregate.version != originatingVersion) { // If this is being thrown, ensure that the originating process is retried on the latest aggregate version // by re-reading the newEvents list. throw AggregateChangeRejectedException(aggregate.version, originatingVersion) } events.getOrPut(aggregate) { mutableListOf() }.let { aggregateEvents -> val currentSequence = aggregateEvents.map { it.getMetadata().sequence }.max() ?: 0 newEvents.forEachIndexed { index, newEvent -> // TODO(rz): Plugin more metadata (provenance, serviceVersion, etc) newEvent.setMetadata( EventMetadata( id = UUID.randomUUID().toString(), aggregateType = aggregateType, aggregateId = aggregateId, sequence = currentSequence + (index + 1), originatingVersion = originatingVersion ) ) } registry.counter(eventWriteCountId).increment(newEvents.size.toLong()) aggregateEvents.addAll(newEvents) aggregate.version = aggregate.version + 1 } log.debug( "Saved $aggregateType/$aggregateId@${aggregate.version}: " + "[${newEvents.joinToString(",") { it.javaClass.simpleName }}]" ) newEvents.forEach { applicationEventPublisher.publishEvent(it) } } override fun list(aggregateType: String, aggregateId: String): List<SpinnakerEvent> { registry.counter(eventReadCountId).increment() return getAggregate(aggregateType, aggregateId) .let { events[it]?.toList() } ?: throw MissingAggregateEventsException(aggregateType, aggregateId) } override fun listAggregates(criteria: EventRepository.ListAggregatesCriteria): EventRepository.ListAggregatesResult { val aggregates = events.keys val result = aggregates.toList() .let { list -> criteria.aggregateType?.let { requiredType -> list.filter { it.type == requiredType } } ?: list } .let { list -> criteria.token?.let { nextPageToken -> val start = list.indexOf(list.find { "${it.type}/${it.id}" == nextPageToken }) val end = (start + criteria.perPage).let { if (it > list.size - 1) { list.size } else { criteria.perPage } } list.subList(start, end) } ?: list } return EventRepository.ListAggregatesResult( aggregates = result, nextPageToken = result.lastOrNull()?.let { "${it.type}/${it.id}" } ) } private fun getAggregate(aggregateType: String, aggregateId: String): Aggregate { registry.counter(aggregateReadCountId).increment() val aggregate = Aggregate( aggregateType, aggregateId, 0L ) events.putIfAbsent(aggregate, mutableListOf()) return events.keys.first { it == aggregate } } @Scheduled(fixedDelayString = "\${spinnaker.clouddriver.eventing.memory-repository.cleanup-job-delay-ms:60000}") private fun cleanup() { registry.counter(eventReadCountId).increment() config.maxAggregateAgeMs ?.let { Duration.ofMillis(it) } ?.let { maxAge -> val horizon = Instant.now().minus(maxAge) log.info("Cleaning up aggregates last updated earlier than $maxAge ($horizon)") events.entries .filter { it.value.any { event -> event.getMetadata().timestamp.isBefore(horizon) } } .map { it.key } .forEach { log.trace("Cleaning up $it") events.remove(it) } } config.maxAggregatesCount ?.let { maxCount -> log.info("Cleaning up aggregates to max $maxCount items, pruning by earliest updated") events.entries // Flatten into pairs of List<Aggregate, SpinnakerEvent> .flatMap { entry -> entry.value.map { Pair(entry.key, it) } } .sortedBy { it.second.getMetadata().timestamp } .subList(0, max(events.size - maxCount, 0)) .forEach { log.trace("Cleaning up ${it.first}") events.remove(it.first) } } } @Scheduled(fixedRate = 1_000) private fun recordMetrics() { registry.gauge(aggregateCountId).set(events.size.toDouble()) registry.gauge(eventCountId).set(events.flatMap { it.value }.size.toDouble()) } inner class MissingAggregateEventsException(aggregateType: String, aggregateId: String) : SystemException( "Aggregate $aggregateType/$aggregateId is missing its internal events list store" ) }
apache-2.0
4859fb8306eb20d8bc7792180e6d78a7
36.333333
119
0.696429
4.684967
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/economy/EmojiFightBetCommand.kt
1
3708
package net.perfectdreams.loritta.morenitta.commands.vanilla.economy import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.common.commands.ArgumentType import net.perfectdreams.loritta.common.commands.arguments import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase import net.perfectdreams.loritta.morenitta.utils.AccountUtils import net.perfectdreams.loritta.common.utils.Emotes import net.perfectdreams.loritta.morenitta.utils.GACampaigns import net.perfectdreams.loritta.morenitta.utils.GenericReplies import net.perfectdreams.loritta.morenitta.utils.NumberUtils import net.perfectdreams.loritta.morenitta.utils.sendStyledReply class EmojiFightBetCommand(val m: LorittaBot) : DiscordAbstractCommandBase( m, listOf("emojifight bet", "rinhadeemoji bet", "emotefight bet"), net.perfectdreams.loritta.common.commands.CommandCategory.ECONOMY ) { override fun command() = create { localizedDescription("commands.command.emojifightbet.description") localizedExamples("commands.command.emojifightbet.examples") usage { arguments { argument(ArgumentType.NUMBER) {} argument(ArgumentType.NUMBER) { optional = true } } } this.similarCommands = listOf("EmojiFightCommand") this.canUseInPrivateChannel = false executesDiscord { // Gets the first argument // If the argument is null (we just show the command explanation and exit) // If it is not null, we convert it to a Long (if it is a invalid number, it will be null) // Then, in the ".also" block, we check if it is null and, if it is, we show that the user provided a invalid number! val totalEarnings = (args.getOrNull(0) ?: explainAndExit()) .let { NumberUtils.convertShortenedNumberToLong(it) } .let { if (it == null) GenericReplies.invalidNumber(this, args[0]) it } if (0 >= totalEarnings) fail(locale["commands.command.flipcoinbet.zeroMoney"], Constants.ERROR) val selfUserProfile = lorittaUser.profile if (totalEarnings > selfUserProfile.money) { sendStyledReply { this.append { message = locale["commands.command.flipcoinbet.notEnoughMoneySelf"] prefix = Constants.ERROR } this.append { message = GACampaigns.sonhosBundlesUpsellDiscordMessage( "https://loritta.website/", // Hardcoded, woo "bet-coinflip-legacy", "bet-not-enough-sonhos" ) prefix = Emotes.LORI_RICH.asMention mentionUser = false } } return@executesDiscord } // Only allow users to participate in a emoji fight bet if the user got their daily reward today AccountUtils.getUserTodayDailyReward(loritta, lorittaUser.profile) ?: fail(locale["commands.youNeedToGetDailyRewardBeforeDoingThisAction", serverConfig.commandPrefix], Constants.ERROR) // Self user check run { val epochMillis = user.timeCreated.toEpochSecond() * 1000 // Don't allow users to bet if they are recent accounts if (epochMillis + (Constants.ONE_WEEK_IN_MILLISECONDS * 2) > System.currentTimeMillis()) // 14 dias fail( LorittaReply( locale["commands.command.pay.selfAccountIsTooNew", 14] + " ${Emotes.LORI_CRYING}", Constants.ERROR ) ) } val maxPlayersInEvent = ( (this.args.getOrNull(1) ?.toIntOrNull() ?: EmojiFight.DEFAULT_MAX_PLAYER_COUNT) .coerceIn(2, EmojiFight.DEFAULT_MAX_PLAYER_COUNT) ) val emojiFight = EmojiFight( this, totalEarnings, maxPlayersInEvent ) emojiFight.start() } } }
agpl-3.0
708fcb712745e65e072df4d3e5ca8833
33.663551
122
0.732201
3.886792
false
false
false
false
ragnraok/MovieCamera
app/src/main/java/com/ragnarok/moviecamera/ui/MainUI.kt
1
2817
package com.ragnarok.moviecamera.ui import android.os.Bundle import android.os.Handler import android.os.Looper import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import android.view.animation.OvershootInterpolator import android.widget.ImageButton import com.ragnarok.moviecamera.R /** * Created by ragnarok on 15/6/9. */ class MainUI : BaseUI() { override val TAG: String = "MovieCamera.MainUI" var imageList: RecyclerView? = null var imageListAdapter: ImageListAdapter? = null var imageLayoutManager: LinearLayoutManager? = null var createButton: ImageButton? = null var revealMaskView: CircularRevealMaskView? = null val uiHandler = Handler(Looper.getMainLooper()) var isShow = true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) createButton = findViewById(R.id.create) as ImageButton revealMaskView = findViewById(R.id.revealView) as CircularRevealMaskView revealMaskView?.setColor(0xAFF0F8FF.toInt()) val createButtonTransY = getResources().getDimension(R.dimen.fab_size) + getResources().getDimension(R.dimen.fab_bottom_margin) + 100 createButton?.setTranslationY(createButtonTransY) createButton?.setOnClickListener { v: View -> if (isShow) { var location = Array(2, { 0 }).toIntArray() createButton?.getLocationOnScreen(location) val x = location[0] + createButton!!.getWidth() / 2 val y = location[1] + createButton!!.getHeight() / 2 showRevealView(x, y) isShow = false } else { isShow = true hideRevealView() } } initImageList() } private fun showRevealView(locX: Int, locY: Int) { revealMaskView?.resetState() uiHandler.postDelayed({revealMaskView?.startShow(locX, locY)}, 50) } private fun hideRevealView() { revealMaskView?.resetState() uiHandler.postDelayed({revealMaskView?.startHide()}, 50) } private fun initImageList() { imageList = findViewById(R.id.images_list) as RecyclerView imageListAdapter = ImageListAdapter(this) imageLayoutManager = LinearLayoutManager(this) imageList?.setLayoutManager(imageLayoutManager) imageList?.setAdapter(imageListAdapter) } override fun onToolbarInitAnimFinish() { imageListAdapter?.updateItems() createButton?.animate()!!.translationY(0f).setInterpolator(OvershootInterpolator()).setDuration(300).setStartDelay(250) } }
mit
94acbad6a221589eaf619dfd5640b17f
31.022727
141
0.662407
4.758446
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/services/imgur/ImgurAuthInterceptor.kt
1
2321
package com.baulsupp.okurl.services.imgur import com.baulsupp.oksocial.output.OutputHandler import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor import com.baulsupp.okurl.authenticator.ValidatedCredentials import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token import com.baulsupp.okurl.credentials.TokenValue import com.baulsupp.okurl.kotlin.queryMap import com.baulsupp.okurl.kotlin.queryMapValue import com.baulsupp.okurl.secrets.Secrets import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response class ImgurAuthInterceptor : Oauth2AuthInterceptor() { override val serviceDefinition = Oauth2ServiceDefinition( "api.imgur.com", "Imgur API", "imgur", "https://api.imgur.com/endpoints", "https://imgur.com/account/settings/apps" ) override suspend fun authorize( client: OkHttpClient, outputHandler: OutputHandler<Response>, authArguments: List<String> ): Oauth2Token { val clientId = Secrets.prompt("Imgur Client Id", "imgur.clientId", "", false) val clientSecret = Secrets.prompt("Imgur Client Secret", "imgur.clientSecret", "", true) return ImgurAuthFlow.login(client, outputHandler, clientId, clientSecret) } override suspend fun validate( client: OkHttpClient, credentials: Oauth2Token ): ValidatedCredentials = ValidatedCredentials( client.queryMapValue<String>( "https://api.imgur.com/3/account/me", TokenValue(credentials), "data", "url" ) ) override fun canRenew(result: Response): Boolean = result.code == 403 override suspend fun renew(client: OkHttpClient, credentials: Oauth2Token): Oauth2Token { val body = FormBody.Builder().add("refresh_token", credentials.refreshToken!!) .add("client_id", credentials.clientId!!) .add("client_secret", credentials.clientSecret!!) .add("grant_type", "refresh_token") .build() val request = Request.Builder().url("https://api.imgur.com/oauth2/token") .method("POST", body) .build() val responseMap = client.queryMap<Any>(request) return Oauth2Token( responseMap["access_token"] as String, credentials.refreshToken, credentials.clientId, credentials.clientSecret ) } }
apache-2.0
5007b2199703061b77128df3134c6271
34.166667
92
0.739767
4.32216
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/ide/intentions/MoveGuardToMatchArmIntention.kt
3
1613
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsExpr import org.rust.lang.core.psi.RsIfExpr import org.rust.lang.core.psi.RsMatchArmGuard import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.ext.parentMatchArm import org.rust.lang.core.psi.ext.ancestorStrict class MoveGuardToMatchArmIntention : RsElementBaseIntentionAction<MoveGuardToMatchArmIntention.Context>() { override fun getText(): String = "Move guard inside the match arm" override fun getFamilyName(): String = text data class Context( val guard: RsMatchArmGuard, val armBody: RsExpr ) override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? { val guard = element.ancestorStrict<RsMatchArmGuard>() ?: return null val armBody = guard.parentMatchArm.expr ?: return null return Context(guard, armBody) } override fun invoke(project: Project, editor: Editor, ctx: Context) { val (guard, oldBody) = ctx val caretOffsetInGuard = editor.caretModel.offset - guard.textOffset val psiFactory = RsPsiFactory(project) var newBody = psiFactory.createIfExpression(guard.expr, oldBody) newBody = oldBody.replace(newBody) as RsIfExpr guard.delete() editor.caretModel.moveToOffset(newBody.textOffset + caretOffsetInGuard) } }
mit
94d4580837fa2265a98fdb7d7d952310
37.404762
107
0.737756
4.255937
false
false
false
false
owncloud/android
owncloudApp/src/androidTest/java/com/owncloud/android/utils/matchers/TextViewMatcher.kt
2
1549
/** * ownCloud Android client application * * @author Abel García de Prada * * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * <p> * 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. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.utils.matchers import android.view.View import android.widget.TextView import androidx.annotation.ColorRes import androidx.core.content.ContextCompat import androidx.test.espresso.matcher.BoundedMatcher import org.hamcrest.Description import org.hamcrest.Matcher fun withTextColor( @ColorRes textColor: Int ): Matcher<View> = object : BoundedMatcher<View, TextView>(TextView::class.java) { override fun describeTo(description: Description) { description.appendText("TextView with text color: $textColor") } override fun matchesSafely(view: TextView): Boolean { val expectedColor = ContextCompat.getColor(view.context, textColor) val actualColor = view.currentTextColor return actualColor == expectedColor } }
gpl-2.0
f5a2b8f8355ea9eaee24cccca73ef303
35
79
0.73062
4.539589
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/browser/webview/usecase/SelectedTextUseCase.kt
1
2896
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.browser.webview.usecase import android.content.Context import android.net.Uri import androidx.core.net.toUri import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import jp.toastkid.lib.BrowserViewModel import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.Urls import jp.toastkid.search.SearchCategory import jp.toastkid.search.UrlFactory import jp.toastkid.yobidashi.R class SelectedTextUseCase( private val urlFactory: UrlFactory = UrlFactory(), private val stringResolver: (Int, Any) -> String, private val contentViewModel: ContentViewModel, private val browserViewModel: BrowserViewModel ) { fun countCharacters(word: String) { val codePointCount = word.codePointCount(1, word.length - 1) val message = stringResolver(R.string.message_character_count, codePointCount) contentViewModel.snackShort(message) } fun search(word: String, searchEngine: String?) { val url = calculateToUri(word, searchEngine) ?: return browserViewModel.open(url) } fun searchWithPreview(word: String, searchEngine: String?) { val url = calculateToUri(word, searchEngine) ?: return browserViewModel.preview(url) } private fun calculateToUri(word: String, searchEngine: String?): Uri? { val cleaned = if (word.startsWith("\"") && word.length > 10) word.substring(1, word.length - 2) else word return if (Urls.isValidUrl(cleaned)) cleaned.toUri() else makeUrl(word, searchEngine) } private fun makeUrl(word: String, searchEngine: String?): Uri? { if (word.isEmpty() || word == "\"\"") { contentViewModel.snackShort(R.string.message_failed_query_extraction_from_web_view) return null } return urlFactory( searchEngine ?: SearchCategory.getDefaultCategoryName(), word ) } companion object { fun make(context: Context?): SelectedTextUseCase? = (context as? FragmentActivity)?.let { activity -> val viewModelProvider = ViewModelProvider(activity) return SelectedTextUseCase( stringResolver = { resource, additional -> context.getString(resource, additional) }, contentViewModel = viewModelProvider.get(ContentViewModel::class.java), browserViewModel = viewModelProvider.get(BrowserViewModel::class.java) ) } } }
epl-1.0
4b54b77c1027cf60e9344d34de88caec
34.765432
105
0.675069
4.786777
false
false
false
false
google/horologist
media-sample/src/main/java/com/google/android/horologist/mediasample/ui/debug/MediaInfoTimeText.kt
1
3297
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.mediasample.ui.debug import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.wear.compose.foundation.CurvedScope import androidx.wear.compose.foundation.CurvedTextStyle import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.TimeText import androidx.wear.compose.material.curvedText import com.google.android.horologist.media3.offload.AudioOffloadStatus import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi import com.google.android.horologist.networks.data.DataUsageReport import com.google.android.horologist.networks.data.NetworkType import com.google.android.horologist.networks.data.Networks import com.google.android.horologist.networks.ui.curveDataUsage @Composable public fun MediaInfoTimeText( mediaInfoTimeTextViewModel: MediaInfoTimeTextViewModel, modifier: Modifier = Modifier ) { val uiState by mediaInfoTimeTextViewModel.uiState.collectAsStateWithLifecycle() if (uiState.enabled) { MediaInfoTimeText( modifier = modifier, networkStatus = uiState.networks, networkUsage = uiState.dataUsageReport, offloadStatus = uiState.audioOffloadStatus, pinnedNetworks = uiState.pinnedNetworks ) } else { TimeText(modifier = modifier) } } @Composable public fun MediaInfoTimeText( networkStatus: Networks, networkUsage: DataUsageReport?, offloadStatus: AudioOffloadStatus?, pinnedNetworks: Set<NetworkType>, modifier: Modifier = Modifier ) { val style = CurvedTextStyle(MaterialTheme.typography.caption3) val context = LocalContext.current TimeText( modifier = modifier, startCurvedContent = { curveDataUsage( networkStatus = networkStatus, networkUsage = networkUsage, style = style, context = context, pinnedNetworks = pinnedNetworks ) }, endCurvedContent = { offloadDataStatus( offloadStatus = offloadStatus, style = style ) } ) } @ExperimentalHorologistNetworksApi public fun CurvedScope.offloadDataStatus( offloadStatus: AudioOffloadStatus?, style: CurvedTextStyle ) { if (offloadStatus != null) { curvedText( text = offloadStatus.trackOffloadDescription(), style = style ) } }
apache-2.0
8e5275a06233c8d194764461ab8a59f0
32.642857
83
0.718835
4.965361
false
false
false
false
amith01994/intellij-community
plugins/settings-repository/src/git/dirCacheEditor.kt
13
7968
/* * 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.jgit.dirCache import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import org.eclipse.jgit.dircache.BaseDirCacheEditor import org.eclipse.jgit.dircache.DirCache import org.eclipse.jgit.dircache.DirCacheEntry import org.eclipse.jgit.internal.JGitText import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.lib.FileMode import org.eclipse.jgit.lib.Repository import org.jetbrains.settingsRepository.byteBufferToBytes import org.jetbrains.settingsRepository.removeWithParentsIfEmpty import java.io.File import java.io.FileInputStream import java.text.MessageFormat import java.util.Comparator private val EDIT_CMP = object : Comparator<PathEdit> { override fun compare(o1: PathEdit, o2: PathEdit): Int { val a = o1.path val b = o2.path return DirCache.cmp(a, a.size(), b, b.size()) } } /** * Don't copy edits, * DeletePath (renamed to DeleteFile) accepts raw path * Pass repository to apply */ public class DirCacheEditor(edits: List<PathEdit>, private val repository: Repository, dirCache: DirCache, estimatedNumberOfEntries: Int) : BaseDirCacheEditor(dirCache, estimatedNumberOfEntries) { private val edits = edits.sortBy(EDIT_CMP) override fun commit(): Boolean { if (edits.isEmpty()) { // No changes? Don't rewrite the index. // cache.unlock() return true } return super.commit() } override fun finish() { if (!edits.isEmpty()) { applyEdits() replace() } } private fun applyEdits() { val maxIndex = cache.getEntryCount() var lastIndex = 0 for (edit in edits) { var entryIndex = cache.findEntry(edit.path, edit.path.size()) val missing = entryIndex < 0 if (entryIndex < 0) { entryIndex = -(entryIndex + 1) } val count = Math.min(entryIndex, maxIndex) - lastIndex if (count > 0) { fastKeep(lastIndex, count) } lastIndex = if (missing) entryIndex else cache.nextEntry(entryIndex) if (edit is DeleteFile) { continue } if (edit is DeleteDirectory) { lastIndex = cache.nextEntry(edit.path, edit.path.size(), entryIndex) continue } if (missing) { val entry = DirCacheEntry(edit.path) edit.apply(entry, repository) if (entry.getRawMode() == 0) { throw IllegalArgumentException(MessageFormat.format(JGitText.get().fileModeNotSetForPath, entry.getPathString())) } fastAdd(entry) } else if (edit is AddFile || edit is AddLoadedFile) { // apply to first entry and remove others var firstEntry = cache.getEntry(entryIndex) val entry: DirCacheEntry if (firstEntry.isMerged()) { entry = firstEntry } else { entry = DirCacheEntry(edit.path) entry.setCreationTime(firstEntry.getCreationTime()) } edit.apply(entry, repository) fastAdd(entry) } else { // apply to all entries of the current path (different stages) for (i in entryIndex..lastIndex - 1) { val entry = cache.getEntry(i) edit.apply(entry, repository) fastAdd(entry) } } } val count = maxIndex - lastIndex if (count > 0) { fastKeep(lastIndex, count) } } } public interface PathEdit { val path: ByteArray public fun apply(entry: DirCacheEntry, repository: Repository) } abstract class PathEditBase(override final val path: ByteArray) : PathEdit private fun encodePath(path: String): ByteArray { val bytes = byteBufferToBytes(Constants.CHARSET.encode(path)) if (SystemInfo.isWindows) { for (i in 0..bytes.size() - 1) { if (bytes[i].toChar() == '\\') { bytes[i] = '/'.toByte() } } } return bytes } class AddFile(private val pathString: String) : PathEditBase(encodePath(pathString)) { override fun apply(entry: DirCacheEntry, repository: Repository) { val file = File(repository.getWorkTree(), pathString) entry.setFileMode(FileMode.REGULAR_FILE) val length = file.length() entry.setLength(length) entry.setLastModified(file.lastModified()) val input = FileInputStream(file) val inserter = repository.newObjectInserter() try { entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, length, input)) inserter.flush() } finally { inserter.close() input.close() } } } class AddLoadedFile(path: String, private val content: ByteArray, private val size: Int = content.size(), private val lastModified: Long = System.currentTimeMillis()) : PathEditBase(encodePath(path)) { override fun apply(entry: DirCacheEntry, repository: Repository) { entry.setFileMode(FileMode.REGULAR_FILE) entry.setLength(size) entry.setLastModified(lastModified) val inserter = repository.newObjectInserter() try { entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, content, 0, size)) inserter.flush() } finally { inserter.close() } } } fun DeleteFile(path: String) = DeleteFile(encodePath(path)) public class DeleteFile(path: ByteArray) : PathEditBase(path) { override fun apply(entry: DirCacheEntry, repository: Repository) = throw UnsupportedOperationException(JGitText.get().noApplyInDelete) } public class DeleteDirectory(entryPath: String) : PathEditBase(encodePath(if (entryPath.endsWith('/') || entryPath.isEmpty()) entryPath else "$entryPath/")) { override fun apply(entry: DirCacheEntry, repository: Repository) = throw UnsupportedOperationException(JGitText.get().noApplyInDelete) } public fun Repository.edit(edit: PathEdit) { edit(listOf(edit)) } public fun Repository.edit(edits: List<PathEdit>) { if (edits.isEmpty()) { return } val dirCache = lockDirCache() try { DirCacheEditor(edits, this, dirCache, dirCache.getEntryCount() + 4).commit() } finally { dirCache.unlock() } } private class DirCacheTerminator(dirCache: DirCache) : BaseDirCacheEditor(dirCache, 0) { override fun finish() { replace() } } public fun Repository.deleteAllFiles(deletedSet: MutableSet<String>? = null, fromWorkingTree: Boolean = true) { val dirCache = lockDirCache() try { if (deletedSet != null) { for (i in 0..dirCache.getEntryCount() - 1) { val entry = dirCache.getEntry(i) if (entry.getFileMode() == FileMode.REGULAR_FILE) { deletedSet.add(entry.getPathString()) } } } DirCacheTerminator(dirCache).commit() } finally { dirCache.unlock() } if (fromWorkingTree) { val files = getWorkTree().listFiles { it.getName() != Constants.DOT_GIT } if (files != null) { for (file in files) { FileUtil.delete(file) } } } } public fun Repository.writePath(path: String, bytes: ByteArray, size: Int = bytes.size()) { edit(AddLoadedFile(path, bytes, size)) FileUtil.writeToFile(File(getWorkTree(), path), bytes, 0, size) } public fun Repository.deletePath(path: String, isFile: Boolean = true, fromWorkingTree: Boolean = true) { edit((if (isFile) DeleteFile(path) else DeleteDirectory(path))) if (fromWorkingTree) { val workTree = getWorkTree() val ioFile = File(workTree, path) if (ioFile.exists()) { ioFile.removeWithParentsIfEmpty(workTree, isFile) } } }
apache-2.0
a1a59794baaba5951c8ca4a8b36ad35d
29.30038
201
0.678464
4.077789
false
false
false
false
yshrsmz/monotweety
app2/src/main/java/net/yslibrary/monotweety/ui/splash/SplashViewModel.kt
1
3310
package net.yslibrary.monotweety.ui.splash import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import net.yslibrary.monotweety.base.CoroutineDispatchers import net.yslibrary.monotweety.data.session.Session import net.yslibrary.monotweety.domain.session.ObserveSession import net.yslibrary.monotweety.ui.arch.Action import net.yslibrary.monotweety.ui.arch.Effect import net.yslibrary.monotweety.ui.arch.GlobalAction import net.yslibrary.monotweety.ui.arch.Intent import net.yslibrary.monotweety.ui.arch.MviViewModel import net.yslibrary.monotweety.ui.arch.Processor import net.yslibrary.monotweety.ui.arch.State import net.yslibrary.monotweety.ui.arch.ULIEState import javax.inject.Inject sealed class SplashIntent : Intent { object Initialize : SplashIntent() } sealed class SplashAction : Action { object CheckSession : SplashAction() data class SessionUpdated( val session: Session?, ) : SplashAction() } sealed class SplashEffect : Effect { object ToLogin : SplashEffect() object ToMain : SplashEffect() } data class SplashState( val state: ULIEState, val hasSession: Boolean, ) : State { companion object { fun initialState(): SplashState { return SplashState( state = ULIEState.UNINITIALIZED, hasSession = false ) } } } class SplashProcessor @Inject constructor( private val observesSession: ObserveSession, dispatchers: CoroutineDispatchers, ) : Processor<SplashAction>( dispatchers = dispatchers, ) { override fun processAction(action: SplashAction) { when (action) { SplashAction.CheckSession -> { doObserveSession() } is SplashAction.SessionUpdated -> { // no-op } } } private fun doObserveSession() = launch { val session = observesSession().first() put(SplashAction.SessionUpdated(session)) } } class SplashViewModel @Inject constructor( dispatchers: CoroutineDispatchers, processor: SplashProcessor, ) : MviViewModel<SplashIntent, SplashAction, SplashState, SplashEffect>( initialState = SplashState.initialState(), dispatchers = dispatchers, processor = processor, ) { override fun intentToAction(intent: SplashIntent, state: SplashState): Action { return when (intent) { SplashIntent.Initialize -> { if (state.state == ULIEState.UNINITIALIZED) { SplashAction.CheckSession } else { GlobalAction.NoOp } } } } override fun reduce(previousState: SplashState, action: SplashAction): SplashState { return when (action) { SplashAction.CheckSession -> { previousState.copy(state = ULIEState.LOADING) } is SplashAction.SessionUpdated -> { val hasSession = action.session != null val effect = if (hasSession) SplashEffect.ToMain else SplashEffect.ToLogin sendEffect(effect) previousState.copy( state = ULIEState.IDLE, hasSession = hasSession ) } } } }
apache-2.0
0392db636212a4ed1fa5fbcf4f6c0f4b
29.090909
90
0.645619
4.932936
false
false
false
false
josesamuel/remoter
remoter/src/main/java/remoter/compiler/kbuilder/FloatParamBuilder.kt
1
3479
package remoter.compiler.kbuilder import com.squareup.kotlinpoet.FunSpec import javax.lang.model.element.Element import javax.lang.model.element.ExecutableElement import javax.lang.model.element.VariableElement import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror /** * A [ParamBuilder] for float type parameters */ internal class FloatParamBuilder(remoterInterfaceElement: Element, bindingManager: KBindingManager) : ParamBuilder(remoterInterfaceElement, bindingManager) { override fun writeParamsToProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) { if (param.asType().kind == TypeKind.ARRAY) { if (paramType == ParamType.OUT) { writeArrayOutParamsToProxy(param, methodBuilder) } else { methodBuilder.addStatement("$DATA.writeFloatArray(" + param.simpleName + ")") } } else { methodBuilder.addStatement("$DATA.writeFloat(" + param.simpleName + ")") } } override fun readResultsFromStub(methodElement: ExecutableElement, resultType: TypeMirror, methodBuilder: FunSpec.Builder) { if (resultType.kind == TypeKind.ARRAY) { methodBuilder.addStatement("$REPLY.writeFloatArray($RESULT)") } else { methodBuilder.addStatement("$REPLY.writeFloat($RESULT)") } } override fun readResultsFromProxy(methodType: ExecutableElement, methodBuilder: FunSpec.Builder) { val resultMirror = methodType.getReturnAsTypeMirror() val resultType = methodType.getReturnAsKotlinType() if (resultMirror.kind == TypeKind.ARRAY) { val suffix = if (resultType.isNullable) "" else "!!" methodBuilder.addStatement("$RESULT = $REPLY.createFloatArray()$suffix") } else { methodBuilder.addStatement("$RESULT = $REPLY.readFloat()") } } override fun readOutResultsFromStub(param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) { if (param.asType().kind == TypeKind.ARRAY) { methodBuilder.addStatement("$REPLY.writeFloatArray($paramName)") } } override fun writeParamsToStub(methodType: ExecutableElement, param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) { super.writeParamsToStub(methodType, param, paramType, paramName, methodBuilder) if (param.asType().kind == TypeKind.ARRAY) { if (paramType == ParamType.OUT) { writeOutParamsToStub(param, paramType, paramName, methodBuilder) } else { val suffix = if (param.isNullable()) "" else "!!" methodBuilder.addStatement("$paramName = $DATA.createFloatArray()$suffix") } } else { methodBuilder.addStatement("$paramName = $DATA.readFloat()") } } override fun readOutParamsFromProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) { if (param.asType().kind == TypeKind.ARRAY && paramType != ParamType.IN) { if (param.isNullable()){ methodBuilder.beginControlFlow("if (${param.simpleName} != null)") } methodBuilder.addStatement("$REPLY.readFloatArray(" + param.simpleName + ")") if (param.isNullable()){ methodBuilder.endControlFlow() } } } }
apache-2.0
92da6474b9f6461bb28f0dcff818bfe9
43.602564
164
0.65881
5.108664
false
false
false
false
bachhuberdesign/deck-builder-gwent
app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/deckbuild/Deck.kt
1
4038
package com.bachhuberdesign.deckbuildergwent.features.deckbuild import android.database.Cursor import com.bachhuberdesign.deckbuildergwent.features.shared.model.Card import com.bachhuberdesign.deckbuildergwent.features.shared.model.CardType import com.bachhuberdesign.deckbuildergwent.features.shared.model.Faction import com.bachhuberdesign.deckbuildergwent.util.getBooleanFromColumn import com.bachhuberdesign.deckbuildergwent.util.getIntFromColumn import com.bachhuberdesign.deckbuildergwent.util.getLongFromColumn import com.bachhuberdesign.deckbuildergwent.util.getStringFromColumn import io.reactivex.functions.Function import rx.functions.Func1 import java.util.Date import kotlin.collections.ArrayList /** * @author Eric Bachhuber * @version 1.0.0 * @since 1.0.0 */ data class Deck(var id: Int = 0, var name: String = "", var faction: Int = 0, var leader: Card? = null, var leaderId: Int = 0, var cards: MutableList<Card> = ArrayList(), var isFavorited: Boolean = false, var createdDate: Date = Date(), var lastUpdate: Date? = Date()) { companion object { const val TABLE = "user_decks" const val JOIN_CARD_TABLE = "user_decks_cards" const val ID = "_id" const val NAME = "name" const val LEADER_ID = "leader_id" const val FACTION = "faction" const val FAVORITED = "favorited" const val CREATED_DATE = "created_date" const val LAST_UPDATE = "last_update" const val MAX_NUM_CARDS = 40 val MAP1 = Func1<Cursor, Deck> { cursor -> val deck = Deck() deck.id = cursor.getIntFromColumn(Deck.ID) deck.name = cursor.getStringFromColumn(Deck.NAME) deck.faction = cursor.getIntFromColumn(Deck.FACTION) deck.leaderId = cursor.getIntFromColumn(Deck.LEADER_ID) deck.isFavorited = cursor.getBooleanFromColumn(Deck.FAVORITED) deck.createdDate = Date(cursor.getLongFromColumn(Deck.CREATED_DATE)) deck.lastUpdate = Date(cursor.getLongFromColumn(Deck.LAST_UPDATE)) deck } val MAPPER = Function<Cursor, Deck> { cursor -> val deck = Deck() deck.id = cursor.getIntFromColumn(Deck.ID) deck.name = cursor.getStringFromColumn(Deck.NAME) deck.faction = cursor.getIntFromColumn(Deck.FACTION) deck.leaderId = cursor.getIntFromColumn(Deck.LEADER_ID) deck.isFavorited = cursor.getBooleanFromColumn(Deck.FAVORITED) deck.createdDate = Date(cursor.getLongFromColumn(Deck.CREATED_DATE)) deck.lastUpdate = Date(cursor.getLongFromColumn(Deck.LAST_UPDATE)) deck } fun isCardAddableToDeck(deck: Deck, card: Card): Boolean { // Check that deck is not full if (deck.cards.size >= MAX_NUM_CARDS) { return false } // Check that card is neutral or same faction as deck if (card.faction != Faction.NEUTRAL) { if (deck.faction != card.faction) { return false } } val filteredByCardType = deck.cards.filter { it.cardType == card.cardType } val filteredById = deck.cards.filter { it.cardId == card.cardId } if (card.cardType == CardType.LEADER) return false if (card.cardType == CardType.BRONZE && filteredById.size >= 3) return false if (card.cardType == CardType.SILVER && filteredById.isNotEmpty()) return false if (card.cardType == CardType.SILVER && filteredByCardType.size >= 6) return false if (card.cardType == CardType.GOLD && filteredById.isNotEmpty()) return false if (card.cardType == CardType.GOLD && filteredByCardType.size >= 4) return false return true } } }
apache-2.0
a74f5463632cf976ca3c133868a5468f
38.598039
94
0.623576
4.641379
false
false
false
false
dushmis/dagger
java/dagger/hilt/android/plugin/src/test/kotlin/GradleTestRunner.kt
1
7452
/* * Copyright (C) 2020 The Dagger 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. */ import java.io.File import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.BuildTask import org.gradle.testkit.runner.GradleRunner import org.junit.rules.TemporaryFolder /** * Testing utility class that sets up a simple Android project that applies the Hilt plugin. */ class GradleTestRunner(val tempFolder: TemporaryFolder) { private val dependencies = mutableListOf<String>() private val activities = mutableListOf<String>() private val additionalAndroidOptions = mutableListOf<String>() private val hiltOptions = mutableListOf<String>() private var appClassName: String? = null private var buildFile: File? = null private var gradlePropertiesFile: File? = null private var manifestFile: File? = null private var additionalTasks = mutableListOf<String>() init { tempFolder.newFolder("src", "main", "java", "minimal") tempFolder.newFolder("src", "test", "java", "minimal") tempFolder.newFolder("src", "main", "res") } // Adds project dependencies, e.g. "implementation <group>:<id>:<version>" fun addDependencies(vararg deps: String) { dependencies.addAll(deps) } // Adds an <activity> tag in the project's Android Manifest, e.g. "<activity name=".Foo"/> fun addActivities(vararg activityElements: String) { activities.addAll(activityElements) } // Adds 'android' options to the project's build.gradle, e.g. "lintOptions.checkReleaseBuilds = false" fun addAndroidOption(vararg options: String) { additionalAndroidOptions.addAll(options) } // Adds 'hilt' options to the project's build.gradle, e.g. "enableExperimentalClasspathAggregation = true" fun addHiltOption(vararg options: String) { hiltOptions.addAll(options) } // Adds a source package to the project. The package path is relative to 'src/main/java'. fun addSrcPackage(packagePath: String) { File(tempFolder.root, "src/main/java/$packagePath").mkdirs() } // Adds a source file to the project. The source path is relative to 'src/main/java'. fun addSrc(srcPath: String, srcContent: String): File { File(tempFolder.root, "src/main/java/${srcPath.substringBeforeLast(File.separator)}").mkdirs() return tempFolder.newFile("/src/main/java/$srcPath").apply { writeText(srcContent) } } // Adds a test source file to the project. The source path is relative to 'src/test/java'. fun addTestSrc(srcPath: String, srcContent: String): File { File(tempFolder.root, "src/test/java/${srcPath.substringBeforeLast(File.separator)}").mkdirs() return tempFolder.newFile("/src/test/java/$srcPath").apply { writeText(srcContent) } } // Adds a resource file to the project. The source path is relative to 'src/main/res'. fun addRes(resPath: String, resContent: String): File { File(tempFolder.root, "src/main/res/${resPath.substringBeforeLast(File.separator)}").mkdirs() return tempFolder.newFile("/src/main/res/$resPath").apply { writeText(resContent) } } fun setAppClassName(name: String) { appClassName = name } fun runAdditionalTasks(taskName: String) { additionalTasks.add(taskName) } // Executes a Gradle builds and expects it to succeed. fun build(): Result { setupFiles() return Result(tempFolder.root, createRunner().build()) } // Executes a Gradle build and expects it to fail. fun buildAndFail(): Result { setupFiles() return Result(tempFolder.root, createRunner().buildAndFail()) } private fun setupFiles() { writeBuildFile() writeGradleProperties() writeAndroidManifest() } private fun writeBuildFile() { buildFile?.delete() buildFile = tempFolder.newFile("build.gradle").apply { writeText( """ buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:4.2.0' } } plugins { id 'com.android.application' id 'dagger.hilt.android.plugin' } android { compileSdkVersion 30 buildToolsVersion "30.0.2" defaultConfig { applicationId "plugin.test" minSdkVersion 21 targetSdkVersion 30 } compileOptions { sourceCompatibility 1.8 targetCompatibility 1.8 } ${additionalAndroidOptions.joinToString(separator = "\n")} } allprojects { repositories { mavenLocal() google() jcenter() } } dependencies { ${dependencies.joinToString(separator = "\n")} } hilt { ${hiltOptions.joinToString(separator = "\n")} } """.trimIndent() ) } } private fun writeGradleProperties() { gradlePropertiesFile?.delete() gradlePropertiesFile = tempFolder.newFile("gradle.properties").apply { writeText( """ android.useAndroidX=true """.trimIndent() ) } } private fun writeAndroidManifest() { manifestFile?.delete() manifestFile = tempFolder.newFile("/src/main/AndroidManifest.xml").apply { writeText( """ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="minimal"> <application android:name="${appClassName ?: "android.app.Application"}" android:theme="@style/Theme.AppCompat.Light.DarkActionBar"> ${activities.joinToString(separator = "\n")} </application> </manifest> """.trimIndent() ) } } private fun createRunner() = GradleRunner.create() .withProjectDir(tempFolder.root) .withArguments(listOf("--stacktrace", "assembleDebug") + additionalTasks) .withPluginClasspath() // .withDebug(true) // Add this line to enable attaching a debugger to the gradle test invocation .forwardOutput() // Data class representing a Gradle Test run result. data class Result( private val projectRoot: File, private val buildResult: BuildResult ) { val tasks: List<BuildTask> get() = buildResult.tasks // Finds a task by name. fun getTask(name: String) = buildResult.task(name) ?: error("Task '$name' not found.") // Gets the full build output. fun getOutput() = buildResult.output // Finds a transformed file. The srcFilePath is relative to the app's package. fun getTransformedFile(srcFilePath: String): File { val parentDir = File(projectRoot, "build/intermediates/asm_instrumented_project_classes/debug") return File(parentDir, srcFilePath).also { if (!it.exists()) { error("Unable to find transformed class ${it.path}") } } } } }
apache-2.0
ed5da510c5e2ed785ce2fc6d69c41906
31.4
108
0.659554
4.489157
false
true
false
false
noties/Markwon
app-sample/src/main/java/io/noties/markwon/app/samples/ToastSample.kt
1
1167
package io.noties.markwon.app.samples import android.widget.Toast import io.noties.markwon.Markwon import io.noties.markwon.app.sample.ui.MarkwonTextViewSample import io.noties.markwon.sample.annotations.MarkwonArtifact import io.noties.markwon.sample.annotations.MarkwonSampleInfo import io.noties.markwon.sample.annotations.Tag @MarkwonSampleInfo( id = "20200627072642", title = "Markdown in Toast", description = "Display _static_ markdown content in a `android.widget.Toast`", artifacts = [MarkwonArtifact.CORE], tags = [Tag.toast] ) class ToastSample : MarkwonTextViewSample() { override fun render() { // NB! only _static_ content is going to be displayed, // so, no images, tables or latex in a Toast val md = """ # Heading is fine > Even quote if **fine** ``` finally code works; ``` _italic_ to put an end to it """.trimIndent() val markwon = Markwon.create(context) // render raw input to styled markdown val markdown = markwon.toMarkdown(md) // Toast accepts CharSequence and allows styling via spans Toast.makeText(context, markdown, Toast.LENGTH_LONG).show() } }
apache-2.0
6ee35e2d0777fd1892a35112cea88083
29.736842
80
0.708655
4.094737
false
false
false
false
letroll/githubbookmarkmanager
app/src/main/kotlin/fr/letroll/githubbookmarkmanager/data/model/RepoAuthorization.kt
1
756
package fr.letroll.githubbookmarkmanager.data.model import java.util.* /** * Created by jquievreux on 05/12/14. */ public data class RepoAuthorization( var id: Int, var url: String, var app: App, var token: String, var note: String, var note_url: String, var created_at: String, var updated_at: String, var scopes: List<String>) // public var id: kotlin.Int = -1 // // public var url: String = "" // // public var app: App = App() // // public var token: String = "" // // public var note: String = "" // // public var note_url: String = "" // // public var created_at: String = "" // // public var updated_at: String = "" // // public var scopes: List<String> = ArrayList<String>() //}
apache-2.0
0af8bc9666a2ae6aac7668abe002f10a
18.921053
59
0.597884
3.189873
false
false
false
false
danfma/kodando
kodando-react-router-dom/src/main/kotlin/kodando/react/router/dom/Extensions.kt
1
612
@file:Suppress("unused") package kodando.react.router.dom /** * Created by danfma on 04/04/17. */ inline var RouteTo.toUrl: String get() = this.to as String set(value) { this.to = value } inline var RouteTo.toLocation: Location get() = this.to as Location set(value) { this.to = value } inline var PromptProps.messageText: String get() = this.message as String set(value) { this.message = value } inline var PromptProps.messageFunc: (Location) -> String get() = this.message.unsafeCast<(Location) -> String>() set(value) { this.message = value.unsafeCast<Any>() }
mit
73e4fc8993321fe5ac4c4d038f856eff
18.741935
57
0.665033
3.290323
false
false
false
false
alashow/music-android
modules/base-android/src/main/java/tm/alashow/base/ui/base/delegate/AuthenticationActivity.kt
1
6684
/* * Copyright (C) 2018, Alashov Berkeli * All rights reserved. */ package tm.alashow.base.ui.base.delegate import android.accounts.Account import android.accounts.AccountAuthenticatorResponse import android.accounts.AccountManager import android.app.Activity import android.content.Intent import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import com.andretietz.retroauth.* /** * Copied from https://github.com/andretietz/retroauth/blob/master/retroauth-android/src/main/java/com/andretietz/retroauth/AuthenticationActivity.kt * To extend custom classes */ /** * Your activity that's supposed to create the account (i.e. Login{@link android.app.Activity}) has to implement this. * It'll provide functionality to {@link #storeCredentials(Account, String, String)} and * {@link #storeUserData(Account, String, String)} when logging in. In case your service is providing a refresh token, * use {@link #storeCredentials(Account, String, String, String)}. This will additionally store a refresh token that * can be used in {@link Authenticator#validateResponse(int, okhttp3.Response, TokenStorage, Object, Object, Object)} * to update the access-token */ abstract class AuthenticationActivity : ComponentActivity() { private var accountAuthenticatorResponse: AccountAuthenticatorResponse? = null private lateinit var accountType: String private lateinit var accountManager: AccountManager private var credentialType: String? = null private lateinit var resultBundle: Bundle private lateinit var credentialStorage: AndroidCredentialStorage protected val ownerManager by lazy { AndroidOwnerStorage(application) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) accountManager = AccountManager.get(application) credentialStorage = AndroidCredentialStorage(application) accountAuthenticatorResponse = intent.getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE) accountAuthenticatorResponse?.onRequestContinued() val accountType = intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE) if (accountType == null) { accountAuthenticatorResponse?.onError(AccountManager.ERROR_CODE_CANCELED, "canceled") throw IllegalStateException( String.format( "This Activity cannot be started without the \"%s\" extra in the intent! " + "Use the \"createAccount\"-Method of the \"%s\" for opening the Login manually.", AccountManager.KEY_ACCOUNT_TYPE, OwnerStorage::class.java.simpleName ) ) } this.accountType = accountType credentialType = intent.getStringExtra("account_credential_type") resultBundle = Bundle() resultBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType) } /** * This method stores an authentication Token to a specific account. * * @param account Account you want to store the credentials for * @param credentialType type of the credentials you want to store * @param credentials the AndroidToken */ fun storeCredentials(account: Account, credentialType: AndroidCredentialType, credentials: AndroidCredentials) { credentialStorage.storeCredentials(account, credentialType, credentials) } /** * With this you can store some additional userdata in key-value-pairs to the account. * * @param account Account you want to store information for * @param key the key for the data * @param value the actual data you want to store */ fun storeUserData(account: Account, key: String, value: String?) { accountManager.setUserData(account, key, value) } /** * This method will finish the login process. Depending on the finishActivity flag, the activity * will be finished or not. The account which is reached into this method will be set as * "current" account. * * @param account Account you want to set as current active * @param finishActivity when `true`, the activity will be finished after finalization. */ @JvmOverloads fun finalizeAuthentication(account: Account, finishActivity: Boolean = true) { resultBundle.putString(AccountManager.KEY_ACCOUNT_NAME, account.name) ownerManager.switchActiveOwner(account.type, account) if (finishActivity) finish() } /** * Tries finding an existing account with the given name. * It creates a new Account if it couldn't find it * * @param accountName Name of the account you're searching for * @return The account if found, or a newly created one */ fun createOrGetAccount(accountName: String): Account { // if this is a relogin val accountList = accountManager.getAccountsByType(accountType) for (account in accountList) { if (account.name == accountName) return account } val account = Account(accountName, accountType) accountManager.addAccountExplicitly(account, null, null) return account } /** * If for some reason an account was created already and the login couldn't complete successfully, you can user this * method to remove this account * * @param account to remove */ @Suppress("DEPRECATION") fun removeAccount(account: Account) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { accountManager.removeAccount(account, null, null, null) } else { accountManager.removeAccount(account, null, null) } } /** * Sends the result or a Constants.ERROR_CODE_CANCELED error if a result isn't present. */ override fun finish() { if (accountAuthenticatorResponse != null) { accountAuthenticatorResponse?.onResult(resultBundle) accountAuthenticatorResponse = null } else { if (resultBundle.containsKey(AccountManager.KEY_ACCOUNT_NAME)) { val intent = Intent() intent.putExtras(resultBundle) setResult(Activity.RESULT_OK, intent) } else { setResult(Activity.RESULT_CANCELED) } } super.finish() } /** * @return The requested account type if available. otherwise `null` */ fun getRequestedAccountType() = accountType /** * @return The requested token type if available. otherwise `null` */ fun getRequestedCredentialType() = credentialType }
apache-2.0
1d25821c0633cefd6e80db951c5a31cf
39.756098
149
0.688809
5.033133
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/user/AchievementInfoFragment.kt
1
14103
package de.westnordost.streetcomplete.user import android.animation.LayoutTransition import android.animation.LayoutTransition.APPEARING import android.animation.LayoutTransition.DISAPPEARING import android.animation.TimeAnimator import android.content.Intent import android.os.Bundle import android.view.View import android.view.ViewGroup import android.view.ViewPropertyAnimator import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator import android.view.animation.OvershootInterpolator import androidx.core.net.toUri import androidx.core.view.isGone import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import de.westnordost.streetcomplete.HandlesOnBackPressed import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.user.achievements.Achievement import de.westnordost.streetcomplete.databinding.FragmentAchievementInfoBinding import de.westnordost.streetcomplete.ktx.tryStartActivity import de.westnordost.streetcomplete.ktx.viewBinding import de.westnordost.streetcomplete.util.Transforms import de.westnordost.streetcomplete.util.animateFrom import de.westnordost.streetcomplete.util.animateTo import de.westnordost.streetcomplete.util.applyTransforms /** Shows details for a certain level of one achievement as a fake-dialog. * There are two modes: * * 1. Show details of a newly achieved achievement. The achievement icon animates in in a fancy way * and some shining animation is played. The unlocked links are shown. * * 2. Show details of an already achieved achievement. The achievement icon animates from another * view to its current position, no shining animation is played. Also, the unlocked links are * not shown because they can be looked at in the links screen. * * It is not a real dialog because a real dialog has its own window, or in other words, has a * different root view than the rest of the UI. However, for the calculation to animate the icon * from another view to the position in the "dialog", there must be a common root view. * */ class AchievementInfoFragment : Fragment(R.layout.fragment_achievement_info), HandlesOnBackPressed { private val binding by viewBinding(FragmentAchievementInfoBinding::bind) /** View from which the achievement icon is animated from (and back on dismissal)*/ private var achievementIconBubble: View? = null var isShowing: Boolean = false private set // need to keep the animators here to be able to clear them on cancel private val currentAnimators: MutableList<ViewPropertyAnimator> = mutableListOf() private var shineAnimation: TimeAnimator? = null private val layoutTransition: LayoutTransition = LayoutTransition() /* ---------------------------------------- Lifecycle --------------------------------------- */ init { layoutTransition.disableTransitionType(APPEARING) layoutTransition.disableTransitionType(DISAPPEARING) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.dialogAndBackgroundContainer.setOnClickListener { dismiss() } // in order to not show the scroll indicators binding.unlockedLinksList.isNestedScrollingEnabled = false binding.unlockedLinksList.layoutManager = object : LinearLayoutManager(requireContext(), VERTICAL, false) { override fun canScrollVertically() = false } } override fun onBackPressed(): Boolean { if (isShowing) { dismiss() return true } return false } override fun onDestroyView() { super.onDestroyView() achievementIconBubble = null clearAnimators() shineAnimation?.cancel() shineAnimation = null } /* ---------------------------------------- Interface --------------------------------------- */ /** Show as details of a tapped view */ fun show(achievement: Achievement, level: Int, achievementBubbleView: View): Boolean { if (currentAnimators.isNotEmpty()) return false isShowing = true this.achievementIconBubble = achievementBubbleView bind(achievement, level, false) animateInFromView(achievementBubbleView) return true } /** Show as new achievement achieved/unlocked */ fun showNew(achievement: Achievement, level: Int): Boolean { if (currentAnimators.isNotEmpty()) return false isShowing = true bind(achievement, level, true) animateIn() return true } fun dismiss(): Boolean { if (currentAnimators.isNotEmpty()) return false isShowing = false animateOut(achievementIconBubble) return true } /* ----------------------------------- Animating in and out --------------------------------- */ private fun bind(achievement: Achievement, level: Int, showLinks: Boolean) { binding.achievementIconView.icon = context?.getDrawable(achievement.icon) binding.achievementIconView.level = level binding.achievementTitleText.setText(achievement.title) binding.achievementDescriptionText.isGone = achievement.description == null if (achievement.description != null) { val arg = achievement.getPointThreshold(level) binding.achievementDescriptionText.text = resources.getString(achievement.description, arg) } else { binding.achievementDescriptionText.text = "" } val unlockedLinks = achievement.unlockedLinks[level].orEmpty() val hasNoUnlockedLinks = unlockedLinks.isEmpty() || !showLinks binding.unlockedLinkTitleText.isGone = hasNoUnlockedLinks binding.unlockedLinksList.isGone = hasNoUnlockedLinks if (hasNoUnlockedLinks) { binding.unlockedLinksList.adapter = null } else { binding.unlockedLinkTitleText.setText( if (unlockedLinks.size == 1) R.string.achievements_unlocked_link else R.string.achievements_unlocked_links ) binding.unlockedLinksList.adapter = LinksAdapter(unlockedLinks, this::openUrl) } } private fun animateIn() { binding.dialogAndBackgroundContainer.visibility = View.VISIBLE shineAnimation?.cancel() val anim = TimeAnimator() anim.setTimeListener { _, _, deltaTime -> binding.shineView1.rotation += deltaTime / 50f binding.shineView2.rotation -= deltaTime / 100f } anim.start() shineAnimation = anim clearAnimators() currentAnimators.addAll( createShineFadeInAnimations() + createDialogPopInAnimations(DIALOG_APPEAR_DELAY_IN_MS) + listOf( createFadeInBackgroundAnimation(), createAchievementIconPopInAnimation() ) ) currentAnimators.forEach { it.start() } } private fun animateInFromView(questBubbleView: View) { questBubbleView.visibility = View.INVISIBLE binding.dialogAndBackgroundContainer.visibility = View.VISIBLE binding.shineView1.visibility = View.GONE binding.shineView2.visibility = View.GONE currentAnimators.addAll(createDialogPopInAnimations() + listOf( createFadeInBackgroundAnimation(), createAchievementIconFlingInAnimation(questBubbleView) )) currentAnimators.forEach { it.start() } } private fun animateOut(questBubbleView: View?) { binding.dialogContainer.layoutTransition = null val iconAnimator = if (questBubbleView != null) { createAchievementIconFlingOutAnimation(questBubbleView) } else { createAchievementIconPopOutAnimation() } currentAnimators.addAll( createDialogPopOutAnimations() + createShineFadeOutAnimations() + listOf( createFadeOutBackgroundAnimation(), iconAnimator ) ) currentAnimators.forEach { it.start() } } private fun createAchievementIconFlingInAnimation(sourceView: View): ViewPropertyAnimator { sourceView.visibility = View.INVISIBLE val root = sourceView.rootView as ViewGroup binding.achievementIconView.applyTransforms(Transforms.IDENTITY) binding.achievementIconView.alpha = 1f return binding.achievementIconView.animateFrom(sourceView, root) .setDuration(ANIMATION_TIME_IN_MS) .setInterpolator(OvershootInterpolator()) } private fun createAchievementIconFlingOutAnimation(targetView: View): ViewPropertyAnimator { val root = targetView.rootView as ViewGroup return binding.achievementIconView.animateTo(targetView, root) .setDuration(ANIMATION_TIME_OUT_MS) .setInterpolator(AccelerateDecelerateInterpolator()) .withEndAction { targetView.visibility = View.VISIBLE achievementIconBubble = null } } private fun createShineFadeInAnimations(): List<ViewPropertyAnimator> { return listOf(binding.shineView1, binding.shineView2).map { it.visibility = View.VISIBLE it.alpha = 0f it.animate() .alpha(1f) .setDuration(ANIMATION_TIME_IN_MS) .setInterpolator(DecelerateInterpolator()) } } private fun createShineFadeOutAnimations(): List<ViewPropertyAnimator> { return listOf(binding.shineView1, binding.shineView2).map { it.animate() .alpha(0f) .setDuration(ANIMATION_TIME_OUT_MS) .setInterpolator(AccelerateInterpolator()) .withEndAction { shineAnimation?.cancel() shineAnimation = null it.visibility = View.GONE } } } private fun createAchievementIconPopInAnimation(): ViewPropertyAnimator { binding.achievementIconView.alpha = 0f binding.achievementIconView.scaleX = 0f binding.achievementIconView.scaleY = 0f binding.achievementIconView.rotationY = -180f return binding.achievementIconView.animate() .alpha(1f) .scaleX(1f).scaleY(1f) .rotationY(360f) .setDuration(ANIMATION_TIME_NEW_ACHIEVEMENT_IN_MS) .setInterpolator(DecelerateInterpolator()) } private fun createAchievementIconPopOutAnimation(): ViewPropertyAnimator { return binding.achievementIconView.animate() .alpha(0f) .scaleX(0.5f).scaleY(0.5f) .setDuration(ANIMATION_TIME_OUT_MS) .setInterpolator(AccelerateInterpolator()) } private fun createDialogPopInAnimations(startDelay: Long = 0): List<ViewPropertyAnimator> { return listOf(binding.dialogContentContainer, binding.dialogBubbleBackground).map { it.alpha = 0f it.scaleX = 0.5f it.scaleY = 0.5f it.translationY = 0f /* For the "show new achievement" mode, only the icon is shown first and only after a * delay, the dialog with the description etc. * This icon is in the center at first and should animate up while the dialog becomes * visible. This movement is solved via a (default) layout transition here for which the * APPEARING transition type is disabled because we animate the alpha ourselves. */ it.isGone = startDelay > 0 it.animate() .setStartDelay(startDelay) .withStartAction { if (startDelay > 0) { binding.dialogContainer.layoutTransition = layoutTransition it.visibility = View.VISIBLE } } .alpha(1f) .scaleX(1f).scaleY(1f) .setDuration(ANIMATION_TIME_IN_MS) .setInterpolator(OvershootInterpolator()) } } private fun createDialogPopOutAnimations(): List<ViewPropertyAnimator> { return listOf(binding.dialogContentContainer, binding.dialogBubbleBackground).map { it.animate() .alpha(0f) .setStartDelay(0) .scaleX(0.5f).scaleY(0.5f) .translationYBy(it.height * 0.2f) .setDuration(ANIMATION_TIME_OUT_MS) .setInterpolator(AccelerateInterpolator()) } } private fun createFadeInBackgroundAnimation(): ViewPropertyAnimator { binding.dialogBackground.alpha = 0f return binding.dialogBackground.animate() .alpha(1f) .setDuration(ANIMATION_TIME_IN_MS) .setInterpolator(DecelerateInterpolator()) .withEndAction { currentAnimators.clear() } } private fun createFadeOutBackgroundAnimation(): ViewPropertyAnimator { return binding.dialogBackground.animate() .alpha(0f) .setDuration(ANIMATION_TIME_OUT_MS) .setInterpolator(AccelerateInterpolator()) .withEndAction { binding.dialogAndBackgroundContainer.visibility = View.INVISIBLE currentAnimators.clear() } } private fun clearAnimators() { for (anim in currentAnimators) { anim.cancel() } currentAnimators.clear() } private fun openUrl(url: String) { val intent = Intent(Intent.ACTION_VIEW, url.toUri()) tryStartActivity(intent) } companion object { const val ANIMATION_TIME_NEW_ACHIEVEMENT_IN_MS = 1000L const val ANIMATION_TIME_IN_MS = 400L const val DIALOG_APPEAR_DELAY_IN_MS = 1600L const val ANIMATION_TIME_OUT_MS = 300L } }
gpl-3.0
94c0bb8e50d8e417f4783a39190933e1
38.175
115
0.6544
5.462045
false
false
false
false
tomatrocho/insapp-android
app/src/main/java/fr/insapp/insapp/notifications/MyFirebaseMessagingService.kt
2
11058
package fr.insapp.insapp.notifications import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Color import android.media.RingtoneManager import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import androidx.preference.PreferenceManager import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import fr.insapp.insapp.R import fr.insapp.insapp.http.ServiceGenerator import fr.insapp.insapp.models.NotificationUser import fr.insapp.insapp.utility.Utils import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* /** * Created by thomas on 18/07/2017. */ class MyFirebaseMessagingService : FirebaseMessagingService() { /** * Called if InstanceID token is updated. This may occur if the security of * the previous token had been compromised. Note that this is called when the InstanceID token * is initially generated so this is where you would retrieve the token. */ override fun onNewToken(token: String) { Log.d(TAG, "Refreshed token: $token") sendRegistrationTokenToServer(token) } /** * Called when message is received. * * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. */ override fun onMessageReceived(remoteMessage: RemoteMessage) { Log.d(TAG, "From: ${remoteMessage.from}") remoteMessage.data.isNotEmpty().let { Log.d(TAG, "Data: " + remoteMessage.data) val notification = remoteMessage.notification sendNotification(notification?.title, notification?.body, notification?.clickAction, remoteMessage.data) } } private fun sendNotification(title: String?, body: String?, clickAction: String?, data: Map<String, String>?) { val intent = Intent(clickAction) if (data != null) { for ((key, value) in data) { intent.putExtra(key, value) } } var channel = "others" if(body?.contains("news")!!){ channel = "posts" } else if(body.contains("invite")){ channel = "events" } if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("notifications_$channel", true)){ val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT) val builder: NotificationCompat.Builder = NotificationCompat.Builder(this, channel) builder .setDefaults(Notification.DEFAULT_ALL) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setSmallIcon(R.drawable.ic_stat_notify) .setAutoCancel(true) .setLights(Color.RED, 500, 1000) .setColor(ContextCompat.getColor(this, R.color.colorPrimary)) .setContentTitle(title) .setContentText(body) .setContentIntent(pendingIntent) val manager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager manager.notify(randomNotificationId, builder.build()) } } private val randomNotificationId: Int get() = Random().nextInt(9999 - 1000) + 1000 companion object { const val TAG = "FA_DEBUG" private val topics = arrayOf( "posts-android", "posts-unknown-class", "posts-1STPI", "posts-2STPI", "posts-3CDTI", "posts-4CDTI", "posts-5CDTI", "posts-3EII", "posts-4EII", "posts-5EII", "posts-3GM", "posts-4GM", "posts-5GM", "posts-3GMA", "posts-4GMA", "posts-5GMA", "posts-3GCU", "posts-4GCU", "posts-5GCU", "posts-3INFO", "posts-4INFO", "posts-5INFO", "posts-3SGM", "posts-4SGM", "posts-5SGM", "posts-3SRC", "posts-4SRC", "posts-5SRC", "posts-STAFF", "events-android", "events-unknown-class", "events-1STPI", "events-2STPI", "events-3CDTI", "events-4CDTI", "events-5CDTI", "events-3EII", "events-4EII", "events-5EII", "events-3GM", "events-4GM", "events-5GM", "events-3GMA", "events-4GMA", "events-5GMA", "events-3GCU", "events-4GCU", "events-5GCU", "events-3INFO", "events-4INFO", "events-5INFO", "events-3SGM", "events-4SGM", "events-5SGM", "events-3SRC", "events-4SRC", "events-5SRC", "events-STAFF" ) fun subscribeToTopic(topic: String, flag: Boolean = true) { if (flag) { Log.d(TAG, "Subscribing to topic $topic..") FirebaseMessaging.getInstance().subscribeToTopic(topic).addOnCompleteListener { task -> var msg = "Successfully subscribed to topic $topic" if (!task.isSuccessful) { msg = "Failed to subscribe to topic $topic" } Log.d(TAG, msg) } } else { Log.d(TAG, "Unsubscribing from topic $topic..") FirebaseMessaging.getInstance().unsubscribeFromTopic(topic).addOnCompleteListener { task -> var msg = "Successfully unsubscribed from topic $topic" if (!task.isSuccessful) { msg = "Failed to unsubscribe from topic $topic" } Log.d(TAG, msg) } } } /** * Persist token to the server. * * Modify this method to associate the user's FCM InstanceID token with any server-side account * maintained by the application. * * @param token The new token. */ fun sendRegistrationTokenToServer(token: String) { val user = Utils.user if (user != null) { val notificationUser = NotificationUser(null, user.id, token, "android") val call = ServiceGenerator.client.registerNotification(notificationUser) call.enqueue(object : Callback<NotificationUser> { override fun onResponse(call: Call<NotificationUser>, response: Response<NotificationUser>) { var msg = "Firebase token successfully registered on server: $token" if (!response.isSuccessful) { msg = "Failed to register Firebase token on server" } Log.d(TAG, msg) } override fun onFailure(call: Call<NotificationUser>, t: Throwable) { Log.d(TAG, "Failed to register Firebase token on server: network failure") } }) } else { Log.d(TAG, "Failed to register Firebase token on server: user is null") } } } /* when (notification.type) { "eventTag", "tag" -> { val call1 = ServiceGenerator.create().getUserFromId(notification.sender) call1.enqueue(object : Callback<User> { override fun onResponse(call: Call<User>, response: Response<User>) { if (response.isSuccessful) { val user = response.body() val id = resources.getIdentifier(Utils.drawableProfileName(user!!.promotion, user.gender), "drawable", App.getAppContext().packageName) Glide .with(App.getAppContext()) .asBitmap() .load(id) .into(notificationTarget) } else { Toast.makeText(App.getAppContext(), "FirebaseMessaging", Toast.LENGTH_LONG).show() } } override fun onFailure(call: Call<User>, t: Throwable) { Toast.makeText(App.getAppContext(), "FirebaseMessaging", Toast.LENGTH_LONG).show() } }) } "post" -> { val call2 = ServiceGenerator.create().getAssociationFromId(notification.post.association) call2.enqueue(object : Callback<Association> { override fun onResponse(call: Call<Association>, response: Response<Association>) { if (response.isSuccessful) { val club = response.body() Glide .with(App.getAppContext()) .asBitmap() .load(ServiceGenerator.CDN_URL + club!!.profilePicture) .into(notificationTarget) } else { Toast.makeText(App.getAppContext(), "FirebaseMessaging", Toast.LENGTH_LONG).show() } } override fun onFailure(call: Call<Association>, t: Throwable) { Toast.makeText(App.getAppContext(), "FirebaseMessaging", Toast.LENGTH_LONG).show() } }) } "event" -> { val call3 = ServiceGenerator.create().getAssociationFromId(notification.event.association) call3.enqueue(object : Callback<Association> { override fun onResponse(call: Call<Association>, response: Response<Association>) { if (response.isSuccessful) { val club = response.body() Glide .with(App.getAppContext()) .asBitmap() .load(ServiceGenerator.CDN_URL + club!!.profilePicture) .into(notificationTarget) } else { Toast.makeText(App.getAppContext(), "FirebaseMessaging", Toast.LENGTH_LONG).show() } } override fun onFailure(call: Call<Association>, t: Throwable) { Toast.makeText(App.getAppContext(), "FirebaseMessaging", Toast.LENGTH_LONG).show() } }) } else -> { } } */ }
mit
b2fb9712feeecf0476d6337c97c26027
36.612245
159
0.533912
5.100554
false
false
false
false
binaryfoo/emv-bertlv
src/test/java/io/github/binaryfoo/decoders/apdu/GetProcessingOptionsCommandAPDUDecoderTest.kt
1
1829
package io.github.binaryfoo.decoders.apdu import io.github.binaryfoo.DecodedData import io.github.binaryfoo.EmvTags import io.github.binaryfoo.QVsdcTags import io.github.binaryfoo.decoders.DecodeSession import io.github.binaryfoo.decoders.annotator.backgroundOf import io.github.binaryfoo.tlv.Tag import org.hamcrest.core.Is.`is` import org.junit.Assert.assertThat import org.junit.Test class GetProcessingOptionsCommandAPDUDecoderTest { @Test fun testDecodeVisaWithPDOL() { val session = DecodeSession() session.tagMetaData = QVsdcTags.METADATA session.put(EmvTags.PDOL, "9F66049F02069F03069F1A0295055F2A029A039C019F3704") val input = "80A8000023832136000000000000001000000000000000003600000000000036120315000008E4C800" val decoded = GetProcessingOptionsCommandAPDUDecoder().decode(input, 0, session) assertThat(decoded.rawData, `is`("C-APDU: GPO")) val children = decoded.children val expectedDecodedTTQ = QVsdcTags.METADATA.get(QVsdcTags.TERMINAL_TX_QUALIFIERS).decoder.decode("36000000", 7, DecodeSession()) assertThat(children.first(), `is`(DecodedData(Tag.fromHex("9F66"), "9F66 (TTQ - Terminal transaction qualifiers)", "36000000", 7, 11, expectedDecodedTTQ))) assertThat(children.last(), `is`(DecodedData(EmvTags.UNPREDICTABLE_NUMBER, "9F37 (unpredictable number)", "0008E4C8", 36, 40, backgroundReading = backgroundOf("A nonce generated by the terminal for replay attack prevention")))) } @Test fun testDecodeMastercardWithoutPDOL() { val session = DecodeSession() val input = "80A8000002830000" val decoded = GetProcessingOptionsCommandAPDUDecoder().decode(input, 0, session) assertThat(decoded.rawData, `is`("C-APDU: GPO")) assertThat(decoded.getDecodedData(), `is`("No PDOL included")) assertThat(decoded.isComposite(), `is`(false)) } }
mit
6f66b47b2fbff6430c9f0dd63726ac9c
47.131579
231
0.774194
3.702429
false
true
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/registry/type/text/ChatVisibilityRegistry.kt
1
1558
/* * 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.registry.type.text import org.lanternpowered.api.audience.MessageType import org.lanternpowered.api.entity.player.chat.ChatVisibility import org.lanternpowered.api.key.NamespacedKey import org.lanternpowered.api.text.Text import org.lanternpowered.api.text.TextRepresentable import org.lanternpowered.api.text.translatableTextOf import org.lanternpowered.server.catalog.DefaultCatalogType import org.lanternpowered.server.registry.internalCatalogTypeRegistry val ChatVisibilityRegistry = internalCatalogTypeRegistry<ChatVisibility> { fun register(id: String, isChatVisible: (MessageType) -> Boolean) = register(LanternChatVisibility(NamespacedKey.minecraft(id), translatableTextOf("options.chat.visibility.$id"), isChatVisible)) register("full") { true } register("system") { type -> type == MessageType.SYSTEM } register("hidden") { false } } private class LanternChatVisibility( key: NamespacedKey, text: Text, private val chatTypePredicate: (MessageType) -> Boolean ) : DefaultCatalogType(key), ChatVisibility, TextRepresentable by text { override fun isVisible(type: net.kyori.adventure.audience.MessageType): Boolean = this.chatTypePredicate(type) }
mit
cfbe99ddceb9163abe2abdb4e9ff7ae1
42.277778
138
0.777279
4.364146
false
false
false
false
simo-andreev/Colourizmus
app/src/main/java/bg/o/sim/colourizmus/view/ColourDetailsActivity.kt
1
3102
package bg.o.sim.colourizmus.view import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.provider.MediaStore import android.widget.LinearLayout import androidx.annotation.ColorInt import androidx.appcompat.app.AppCompatActivity import androidx.cardview.widget.CardView import androidx.palette.graphics.Palette import bg.o.sim.colourizmus.R import bg.o.sim.colourizmus.databinding.ActivityColourDetailsBinding import bg.o.sim.colourizmus.model.CustomColour import bg.o.sim.colourizmus.model.LIVE_COLOUR import bg.o.sim.colourizmus.utils.* class ColourDetailsActivity : AppCompatActivity() { private lateinit var binding: ActivityColourDetailsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityColourDetailsBinding.inflate(layoutInflater) setContentView(binding.root) val dominantCol: CustomColour = when { intent.hasExtra(EXTRA_COLOUR) -> intent.getSerializableExtra(EXTRA_COLOUR) as CustomColour intent.hasExtra(EXTRA_PICTURE_URI) -> loadPassedPhoto(intent) else -> CustomColour(LIVE_COLOUR.value!!, "") } // show the 'dominant' colour at top bind(binding.colourPreview.root, dominantCol) // complimentary second bind(binding.complimentaryPreview.root, getComplimentaryColour(dominantCol)) // and the rest -> bind(binding.paletteA.root, *getSaturationSwatch(dominantCol)) bind(binding.paletteB.root, *getValueSwatch(dominantCol)) bind(binding.paletteC.root, *getColourTriade(dominantCol)) bind(binding.paletteD.root, *getHueSwatch(dominantCol)) } private fun loadPassedPhoto(intent: Intent): CustomColour { val bitmap: Bitmap = MediaStore.Images.Media.getBitmap(contentResolver, intent.getParcelableExtra(EXTRA_PICTURE_URI)!!) val palette = Palette.Builder(bitmap).generate() binding.photoPreview.setImageBitmap(bitmap) @ColorInt val default = -1 bind( binding.photoSwatchDefault.root, CustomColour(palette.getMutedColor(default), ""), CustomColour(palette.getDominantColor(default), ""), CustomColour(palette.getVibrantColor(default), ""), ) bind( binding.photoSwatchLight.root, CustomColour(palette.getLightMutedColor(default), ""), CustomColour(palette.getDominantColor(default), ""), CustomColour(palette.getLightVibrantColor(default), ""), ) bind( binding.photoSwatchDark.root, CustomColour(palette.getDarkMutedColor(default), ""), CustomColour(palette.getDominantColor(default), ""), CustomColour(palette.getDarkVibrantColor(default), ""), ) return CustomColour(palette.getDominantColor(default), "prime") } private fun bind(view: CardView, vararg colours: CustomColour) { view.findViewById<LinearLayout>(R.id.palette_row).bindColourList(*colours) } }
apache-2.0
48515c54007f3605111ce154dcf3ce56
38.782051
127
0.705029
4.69289
false
false
false
false
jonninja/node.kt
src/main/kotlin/node/express/middleware/UrlEncodedBodyParser.kt
1
3027
package node.express.middleware import node.express.Response import node.express.Request import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder import node.express.Body import io.netty.handler.codec.http.multipart.Attribute import io.netty.handler.codec.http.multipart.InterfaceHttpData import java.util.HashSet import node.express.RouteHandler /** * Body parser for URL encoded data */ public fun urlEncodedBodyParser(): RouteHandler.()->Unit { return { if (req.body == null) { try { val decoder = HttpPostRequestDecoder(DefaultHttpDataFactory(false), req.request) val data = decoder.getBodyHttpDatas()!! if (data.size() > 0) { req.attributes.put("body", UrlEncodedBody(decoder)) } } catch (e: Throwable) { // ignored } } next() } } private class UrlEncodedBody(decoder: HttpPostRequestDecoder): Body { val decoder = decoder private fun getAttribute(key: String): Attribute? { return decoder.getBodyHttpData(key) as? Attribute } override fun get(key: String): Any? { return getAttribute(key)?.getString() } override fun asInt(key: String): Int? { return getAttribute(key)?.getString()?.toInt() } override fun asString(key: String): String? { return getAttribute(key)?.getString() } override fun asDouble(key: String): Double? { return getAttribute(key)?.getString()?.toDouble() } override fun asInt(index: Int): Int? { throw UnsupportedOperationException() } override fun asString(index: Int): String? { throw UnsupportedOperationException() } override fun asNative(): Any { return decoder } public override fun size(): Int { return decoder.getBodyHttpDatas()!!.size() } public override fun isEmpty(): Boolean { return size() == 0 } public override fun containsKey(key: Any?): Boolean { return decoder.getBodyHttpDatas()!!.find { it.getName() == key } != null } public override fun containsValue(value: Any?): Boolean { throw UnsupportedOperationException() } public override fun get(key: Any?): Any? { return this.get(key as String) } public override fun keySet(): Set<String> { return HashSet(decoder.getBodyHttpDatas()!!.map { it.getName()!! }) } public override fun values(): Collection<Any?> { return decoder.getBodyHttpDatas()!!.map { (it as Attribute).getValue() } } public override fun entrySet(): Set<Map.Entry<String, Any?>> { return HashSet(decoder.getBodyHttpDatas()!!.map { BodyEntry(it as Attribute) }) } private data class BodyEntry(val att: Attribute): Map.Entry<String, Any?> { public override fun hashCode(): Int { return att.hashCode() } public override fun equals(other: Any?): Boolean { return att.equals(other) } public override fun getKey(): String { return att.getName()!! } public override fun getValue(): Any? { return att.getValue() } } }
mit
e56eb31b6817dd100419b5fafbf650e7
29.897959
88
0.681533
4.269394
false
false
false
false
ursjoss/scipamato
core/core-web/src/main/java/ch/difty/scipamato/core/web/sync/RefDataSyncPage.kt
1
2946
package ch.difty.scipamato.core.web.sync import ch.difty.scipamato.core.ScipamatoCoreApplication import ch.difty.scipamato.core.ScipamatoSession import ch.difty.scipamato.core.auth.Roles import ch.difty.scipamato.core.sync.launcher.SyncJobLauncher import ch.difty.scipamato.core.web.common.BasePage import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapAjaxButton import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons import de.agilecoders.wicket.core.markup.html.bootstrap.form.BootstrapForm import org.apache.wicket.ajax.AjaxRequestTarget import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation import org.apache.wicket.event.Broadcast import org.apache.wicket.event.IEvent import org.apache.wicket.model.StringResourceModel import org.apache.wicket.request.mapper.parameter.PageParameters import org.apache.wicket.spring.injection.annot.SpringBean import java.time.Duration @Suppress("serial") @AuthorizeInstantiation(Roles.USER, Roles.ADMIN) class RefDataSyncPage(parameters: PageParameters) : BasePage<Void>(parameters) { @SpringBean private lateinit var jobLauncher: SyncJobLauncher override fun onInitialize() { super.onInitialize() queue(BootstrapForm<Void>("synchForm")) queue(newButton("synchronize")) queue(SyncResultListPanel("syncResults")) } private fun newButton(id: String): BootstrapAjaxButton { val labelModel = StringResourceModel("button.$id.label", this, null) return object : BootstrapAjaxButton(id, labelModel, Buttons.Type.Primary) { override fun onSubmit(target: AjaxRequestTarget) { super.onSubmit(target) ScipamatoCoreApplication.getApplication().launchSyncTask(SyncBatchTask(jobLauncher)) page.send(page, Broadcast.DEPTH, BatchJobLaunchedEvent(target)) info(StringResourceModel("feedback.msg.started", this, null).string) target.add(this) } override fun onConfigure() { super.onConfigure() if (ScipamatoSession.get().syncJobResult.isRunning) { isEnabled = false label = StringResourceModel("button.$id-wip.label", this, null) } else { isEnabled = true label = StringResourceModel("button.$id.label", this, null) } } } } @Suppress("MagicNumber") override fun onEvent(event: IEvent<*>) { (event.payload as? BatchJobLaunchedEvent)?.let { jobLaunchedEvent -> [email protected](AjaxSelfUpdatingTimerBehavior(Duration.ofSeconds(5))) jobLaunchedEvent.target.add(this@RefDataSyncPage) } } companion object { private const val serialVersionUID = 1L } }
bsd-3-clause
914362781773f5c8490fd6dfc8288c1f
41.085714
100
0.704684
4.560372
false
false
false
false
DSolyom/ViolinDS
ViolinDS/app/src/main/java/ds/violin/v1/util/common/Bitmaps.kt
1
23065
/* Copyright 2013 Dániel Sólyom 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 ds.violin.v1.util.common import java.io.ByteArrayOutputStream import java.io.File import java.io.FileInputStream import java.io.FilterInputStream import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import android.app.Activity import android.content.Context import android.database.Cursor import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Point import android.net.Uri import android.provider.MediaStore object Bitmaps { /** * * @param url * @return * @throws IOException * @throws OutOfMemoryError */ @Throws(IOException::class, OutOfMemoryError::class) fun downloadImage(url: URL): Bitmap { var stream: InputStream? = null try { stream = getFlushedHttpStream(url) return BitmapFactory.decodeStream(stream) } catch (e: IOException) { throw e } catch (e: OutOfMemoryError) { throw e } finally { if (stream != null) { stream.close() } } } /** * * @param url * @return * @throws IOException * @throws OutOfMemoryError */ @Throws(IOException::class, OutOfMemoryError::class) fun downloadImageAsByteArray(url: URL): ByteArray { var stream: InputStream? = null try { stream = getFlushedHttpStream(url) return Files.getFileAsByteArray(stream) } catch (e: IOException) { throw e } catch (e: OutOfMemoryError) { throw e } finally { if (stream != null) { stream.close() } } } /** * * @param bytes * @return */ fun createBitmap(bytes: ByteArray): Bitmap { return BitmapFactory.decodeByteArray(bytes, 0, bytes.size) } /** * create a thumbnail (png, 100 quality) from byte array * this first creates a bitmap from the byte array, then scales that bitmap * !please note: this does not checks if the input byteArray is 'small' enough to create the bitmap * * @param byteArray * @param width * @param height * @throws OutOfMemoryError * @return */ @Throws(OutOfMemoryError::class) fun createThumbnail(byteArray: ByteArray, width: Int, height: Int): Bitmap { val tmp = createBitmap(byteArray) val result = Bitmap.createScaledBitmap(tmp, width, height, false) tmp.recycle() return result } /** * create a thumbnail's byte array * this first creates a bitmap from the byte array, then scales that bitmap and converts that to byte array * !please note: this does not checks if the input byteArray is 'small' enough to create the bitmap(s) * * @param byteArray * @param maxWidth * @param maxHeight * @throws OutOfMemoryError * @return */ @Throws(OutOfMemoryError::class) @JvmOverloads fun createThumbnailByteArray(byteArray: ByteArray, maxWidth: Int, maxHeight: Int, format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG, quality: Int = 100): ByteArray { var thumbnailByteArray = byteArray val point = findNewBitmapSize(thumbnailByteArray, maxWidth, maxHeight) ?: return thumbnailByteArray val tmp = createThumbnail(thumbnailByteArray, point.x, point.y) thumbnailByteArray = compressBitmapToByteArray(tmp, format, quality) tmp.recycle() return thumbnailByteArray } /** * gives back another bitmap resized so size is inside maxWidth and maxHeight * !note: does not recycle the input bitmap and may return the original bitmap (if no scaling was necessary) * * @param bmp * @param maxWidth * @param maxHeight * @return */ fun resizeBitmap(bmp: Bitmap, maxWidth: Int, maxHeight: Int): Bitmap { val point = findNewBitmapSize(bmp.width, bmp.height, maxWidth, maxHeight) return Bitmap.createScaledBitmap(bmp, point.x, point.y, true) } /** * gives back another bitmap resized so size is inside maxWidth and maxHeight * !note: may return the original bitmap (if no scaling was necessary) * * @param bmp * @param maxWidth * @param maxHeight * @param recycle * @return */ fun resizeBitmap(bmp: Bitmap, maxWidth: Int, maxHeight: Int, recycle: Boolean): Bitmap { val bw = bmp.width val bh = bmp.height val point = findNewBitmapSize(bw, bh, maxWidth, maxHeight) if (bw == point.x && bh == point.y) { return bmp } val ret = Bitmap.createScaledBitmap(bmp, point.x, point.y, true) if (recycle) { bmp.recycle() } return ret } /** * * @param byteArray * @param maxWidth * @param maxHeight * @return */ fun findNewBitmapSize(byteArray: ByteArray, maxWidth: Int, maxHeight: Int): Point? { //Decode image size from byte array val o = BitmapFactory.Options() o.inJustDecodeBounds = true BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size, o) return findNewBitmapSize(o.outWidth, o.outHeight, maxWidth, maxHeight) } /** * * @param oWidth * @param oHeight * @param maxWidth * @param maxHeight * @return */ fun findNewBitmapSize(oWidth: Int, oHeight: Int, maxWidth: Int, maxHeight: Int): Point { // use image size ratio to find out real width and height if (oWidth > maxWidth || oHeight > maxHeight) { var nw = maxWidth var nh = maxHeight val rw = maxWidth.toDouble() / oWidth val rh = maxHeight.toDouble() / oHeight if (rw > rh) { nw = (oWidth * rh).toInt() } else { nh = (oHeight * rw).toInt() } return Point(nw, nh) } else { return if (maxWidth > maxHeight) Point(maxHeight, maxHeight) else Point(maxWidth, maxWidth) } } /** * * @param byteArray * @param approxWidth * @param approxHeight * @return */ fun createThumbnailApprox(byteArray: ByteArray, approxWidth: Int, approxHeight: Int): Bitmap? { try { //Decode image size val o = BitmapFactory.Options() o.inJustDecodeBounds = true BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size, o) var bmp: Bitmap? var scale = 1 if (o.outHeight > approxHeight || o.outWidth > approxWidth) { scale = Math.max(Math.pow(2.0, Math.ceil(Math.log(approxHeight.toDouble() / o.outHeight.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt(), Math.pow(2.0, Math.ceil(Math.log(approxWidth.toDouble() / o.outWidth.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt()) } //Decode with inSampleSize val o2 = BitmapFactory.Options() o2.inSampleSize = scale bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size, o2) return bmp } catch (e: Throwable) { e.printStackTrace() return null } } /** * @param bmp * @return */ fun compressBitmapToByteArray(bmp: Bitmap): ByteArray { val stream = ByteArrayOutputStream() bmp.compress(Bitmap.CompressFormat.PNG, 100, stream) return stream.toByteArray() } /** * * @param bmp * @param format * @param quality * @return */ fun compressBitmapToByteArray(bmp: Bitmap, format: Bitmap.CompressFormat, quality: Int): ByteArray { val stream = ByteArrayOutputStream() bmp.compress(format, quality, stream) return stream.toByteArray() } /** * * @param context * @param uri * @param approxWidth * @param approxHeight * @return */ fun getThumbnailInternal(context: Context, uri: Uri, approxWidth: Int, approxHeight: Int): Bitmap? { try { var `is`: InputStream = context.contentResolver.openInputStream(uri) //Decode image size val o = BitmapFactory.Options() o.inJustDecodeBounds = true BitmapFactory.decodeStream(`is`, null, o) `is`.close() var bmp: Bitmap? var scale = 1 if (o.outHeight > approxHeight || o.outWidth > approxWidth) { scale = Math.max(Math.pow(2.0, Math.ceil(Math.log(approxHeight.toDouble() / o.outHeight.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt(), Math.pow(2.0, Math.ceil(Math.log(approxWidth.toDouble() / o.outWidth.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt()) } //Decode with inSampleSize val o2 = BitmapFactory.Options() o2.inSampleSize = scale `is` = context.contentResolver.openInputStream(uri) bmp = BitmapFactory.decodeStream(`is`, null, o2) `is`.close() return bmp } catch (e: Throwable) { e.printStackTrace() return null } } /** * * @param imageFileName * @param approxWidth * @param approxHeight * @return */ fun getThumbnail(imageFileName: String, approxWidth: Int, approxHeight: Int): Bitmap? { val f = File(imageFileName) if (!f.exists()) { return null } try { //Decode image size val o = BitmapFactory.Options() o.inJustDecodeBounds = true var fis = FileInputStream(f) BitmapFactory.decodeStream(fis, null, o) fis.close() var bmp: Bitmap? var scale = 1 if (o.outHeight > approxHeight || o.outWidth > approxWidth) { scale = Math.max(Math.pow(2.0, Math.floor(Math.log(approxHeight.toDouble() / o.outHeight.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt(), Math.pow(2.0, Math.floor(Math.log(approxWidth.toDouble() / o.outWidth.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt()) } //Decode with inSampleSize val o2 = BitmapFactory.Options() o2.inSampleSize = scale fis = FileInputStream(f) bmp = BitmapFactory.decodeStream(fis, null, o2) fis.close() return bmp } catch (e: Throwable) { throw e } } /** * * @param url * @param approxWidth * @param approxHeight * @return */ @Throws(IOException::class) fun getResizedImageFromHttpStream(url: URL, approxWidth: Int, approxHeight: Int): Bitmap { var stream: InputStream? = null try { //Decode image size val o = BitmapFactory.Options() o.inJustDecodeBounds = true stream = getFlushedHttpStream(url) BitmapFactory.decodeStream(stream, null, o) Debug.logD("Bitmaps", "original size: " + o.outWidth + "x" + o.outHeight + " ") var bmp: Bitmap? var scale = 1 if (o.outHeight > approxHeight || o.outWidth > approxWidth) { scale = Math.max(Math.pow(2.0, Math.ceil(Math.log(approxHeight.toDouble() / o.outHeight.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt(), Math.pow(2.0, Math.ceil(Math.log(approxWidth.toDouble() / o.outWidth.toDouble()) / Math.log(0.5)).toInt().toDouble()).toInt()) } //Decode with inSampleSize val o2 = BitmapFactory.Options() o2.inSampleSize = scale stream = getFlushedHttpStream(url) bmp = BitmapFactory.decodeStream(stream, null, o2) Debug.logD("Bitmaps", "new size: " + bmp!!.width + "x" + bmp.height + " ") return bmp } catch (e: IOException) { e.printStackTrace() throw e } finally { if (stream != null) { stream.close() } } } /** * * @param activity * @param uri * @return */ fun getImageFileNameFromUri(activity: Activity, uri: Uri): String? { val ret: String? try { val proj = arrayOf(MediaStore.Images.Media.DATA) val cursor = activity.contentResolver.query(uri, proj, null, null, null) val index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) cursor.moveToFirst() ret = cursor.getString(index) cursor.close() } catch (e: Exception) { ret = null } return ret } /** * @param url * @return * @throws IOException */ @Throws(IOException::class) fun getFlushedHttpStream(url: URL): FlushedInputStream { val conn = url.openConnection() as HttpURLConnection conn.doInput = true conn.useCaches = false conn.connect() val stream = conn.inputStream try { stream.reset() } catch (e: Throwable) { } return FlushedInputStream(stream) } // manipulations fun fastBlur(sentBitmap: Bitmap, radius: Int, fromX: Int, fromY: Int, width: Int, height: Int, brightnessMod: Float, scale: Float): Bitmap? { var usedradius = radius // Stack Blur v1.0 from // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html // // Java Author: Mario Klingemann <mario at quasimondo.com> // http://incubator.quasimondo.com // created Feburary 29, 2004 // Android port : Yahel Bouaziz <yahel at kayenko.com> // http://www.kayenko.com // ported april 5th, 2012 // This is a compromise between Gaussian Blur and Box blur // It creates much better looking blurs than Box Blur, but is // 7x faster than my Gaussian Blur implementation. // // I called it Stack Blur because this describes best how this // filter works internally: it creates a kind of moving stack // of colors whilst scanning through the image. Thereby it // just has to add one new block of color to the right side // of the stack and remove the leftmost color. The remaining // colors on the topmost layer of the stack are either added on // or reduced by one, depending on if they are on the right or // on the left side of the stack. // // If you are using this algorithm in your code please add // the following line: // // Stack Blur Algorithm by Mario Klingemann <[email protected]> // added brightness modification by DS (january 7th, 2013) // implemented for kotlin by DS (2016) val bitmap: Bitmap if (scale == 1.0f) { bitmap = sentBitmap.copy(sentBitmap.config, true) } else { bitmap = Bitmap.createScaledBitmap(sentBitmap, (sentBitmap.width * scale).toInt(), (sentBitmap.height * scale).toInt(), false) } if (usedradius < 1) { return null } val w = (width * scale).toInt() val h = (height * scale).toInt() val pix = IntArray(w * h) bitmap.getPixels(pix, 0, w, fromX, fromY, w, h) val wm = w - 1 val hm = h - 1 val wh = w * h val div = usedradius + usedradius + 1 val r = IntArray(wh) val g = IntArray(wh) val b = IntArray(wh) var rsum: Int var gsum: Int var bsum: Int var x: Int var y: Int var i: Int var p: Int var yp: Int var yi: Int var yw: Int val vmin = IntArray(Math.max(w, h)) var divsum = div + 1 shr 1 divsum *= divsum val dv = IntArray(256 * divsum) i = 0 while (i < 256 * divsum) { dv[i] = i / divsum i++ } yi = 0 yw = yi val stack = Array(div) { IntArray(3) } var stackpointer: Int var stackstart: Int var sir: IntArray var rbs: Int val r1 = usedradius + 1 var routsum: Int var goutsum: Int var boutsum: Int var rinsum: Int var ginsum: Int var binsum: Int val originRadius = usedradius y = 0 while (y < h) { bsum = 0 gsum = 0 rsum = 0 boutsum = 0 goutsum = 0 routsum = 0 binsum = 0 ginsum = 0 rinsum = 0 i = -usedradius while (i <= usedradius) { p = pix[yi + Math.min(wm, Math.max(i, 0))] sir = stack[i + usedradius] sir[0] = p and 0xff0000 shr 16 sir[1] = p and 0x00ff00 shr 8 sir[2] = p and 0x0000ff rbs = r1 - Math.abs(i) rsum += sir[0] * rbs gsum += sir[1] * rbs bsum += sir[2] * rbs if (i > 0) { rinsum += sir[0] ginsum += sir[1] binsum += sir[2] } else { routsum += sir[0] goutsum += sir[1] boutsum += sir[2] } i++ } stackpointer = usedradius x = 0 while (x < w) { r[yi] = dv[rsum] g[yi] = dv[gsum] b[yi] = dv[bsum] rsum -= routsum gsum -= goutsum bsum -= boutsum stackstart = stackpointer - usedradius + div sir = stack[stackstart % div] routsum -= sir[0] goutsum -= sir[1] boutsum -= sir[2] if (y == 0) { vmin[x] = Math.min(x + usedradius + 1, wm) } p = pix[yw + vmin[x]] sir[0] = p and 0xff0000 shr 16 sir[1] = p and 0x00ff00 shr 8 sir[2] = p and 0x0000ff rinsum += sir[0] ginsum += sir[1] binsum += sir[2] rsum += rinsum gsum += ginsum bsum += binsum stackpointer = (stackpointer + 1) % div sir = stack[stackpointer % div] routsum += sir[0] goutsum += sir[1] boutsum += sir[2] rinsum -= sir[0] ginsum -= sir[1] binsum -= sir[2] yi++ x++ } yw += w y++ } usedradius = originRadius x = 0 while (x < w) { bsum = 0 gsum = 0 rsum = 0 boutsum = 0 goutsum = 0 routsum = 0 binsum = 0 ginsum = 0 rinsum = 0 yp = -usedradius * w i = -usedradius while (i <= usedradius) { yi = Math.max(0, yp) + x sir = stack[i + usedradius] sir[0] = r[yi] sir[1] = g[yi] sir[2] = b[yi] rbs = r1 - Math.abs(i) rsum += r[yi] * rbs gsum += g[yi] * rbs bsum += b[yi] * rbs if (i > 0) { rinsum += sir[0] ginsum += sir[1] binsum += sir[2] } else { routsum += sir[0] goutsum += sir[1] boutsum += sir[2] } if (i < hm) { yp += w } i++ } yi = x stackpointer = usedradius y = 0 while (y < h) { pix[yi] = 0xff000000.toInt() or ((dv[rsum] * brightnessMod).toInt() shl 16) or ((dv[gsum] * brightnessMod).toInt() shl 8) or (dv[bsum] * brightnessMod).toInt() rsum -= routsum gsum -= goutsum bsum -= boutsum stackstart = stackpointer - usedradius + div sir = stack[stackstart % div] routsum -= sir[0] goutsum -= sir[1] boutsum -= sir[2] if (x == 0) { vmin[y] = Math.min(y + r1, hm) * w } p = x + vmin[y] sir[0] = r[p] sir[1] = g[p] sir[2] = b[p] rinsum += sir[0] ginsum += sir[1] binsum += sir[2] rsum += rinsum gsum += ginsum bsum += binsum stackpointer = (stackpointer + 1) % div sir = stack[stackpointer] routsum += sir[0] goutsum += sir[1] boutsum += sir[2] rinsum -= sir[0] ginsum -= sir[1] binsum -= sir[2] yi += w y++ } x++ } bitmap.setPixels(pix, 0, w, fromX, fromY, w, h) return bitmap } // for jpegs class FlushedInputStream(inputStream: InputStream) : FilterInputStream(inputStream) { @Throws(IOException::class) override fun skip(n: Long): Long { var totalBytesSkipped = 0L while (totalBytesSkipped < n) { var bytesSkipped = `in`.skip(n - totalBytesSkipped) if (bytesSkipped == 0L) { val byteSkipped = read() if (byteSkipped < 0) { break // we reached EOF } else { bytesSkipped = 1 // we read one byte } } totalBytesSkipped += bytesSkipped } return totalBytesSkipped } } }
apache-2.0
4e92734e94614f9d8627f9fff0e2fc7a
29.108355
175
0.516368
4.523044
false
false
false
false
SpineEventEngine/core-java
buildSrc/src/main/kotlin/io/spine/internal/gradle/VersionWriter.kt
2
5330
/* * Copyright 2022, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.internal.gradle import java.util.* import org.gradle.api.DefaultTask import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.file.DirectoryProperty import org.gradle.api.provider.MapProperty import org.gradle.api.tasks.Input import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.TaskAction /** * A task that generates a dependency versions `.properties` file. */ abstract class WriteVersions : DefaultTask() { /** * Versions to add to the file. * * The map key is a string in the format of `<group ID>_<artifact name>`, and the value * is the version corresponding to those group ID and artifact name. * * @see WriteVersions.version */ @get:Input abstract val versions: MapProperty<String, String> /** * The directory that hosts the generated file. */ @get:OutputDirectory abstract val versionsFileLocation: DirectoryProperty /** * Adds a dependency version to write into the file. * * The given dependency notation is a Gradle artifact string of format: * `"<group ID>:<artifact name>:<version>"`. * * @see WriteVersions.versions * @see WriteVersions.includeOwnVersion */ fun version(dependencyNotation: String) { val parts = dependencyNotation.split(":") check(parts.size == 3) { "Invalid dependency notation: `$dependencyNotation`." } versions.put("${parts[0]}_${parts[1]}", parts[2]) } /** * Enables the versions file to include the version of the project that owns this task. * * @see WriteVersions.version * @see WriteVersions.versions */ fun includeOwnVersion() { val groupId = project.group.toString() val artifactId = project.artifactId val version = project.version.toString() versions.put("${groupId}_${artifactId}", version) } /** * Creates a `.properties` file with versions, named after the value * of [Project.artifactId] property. * * The name of the file would be: `versions-<artifactId>.properties`. * * By default, value of [Project.artifactId] property is a project's name with "spine-" prefix. * For example, if a project's name is "tools", then the name of the file would be: * `versions-spine-tools.properties`. */ @TaskAction fun writeFile() { versions.finalizeValue() versionsFileLocation.finalizeValue() val values = versions.get() val properties = Properties() properties.putAll(values) val outputDir = versionsFileLocation.get().asFile outputDir.mkdirs() val fileName = resourceFileName() val file = outputDir.resolve(fileName) file.createNewFile() file.writer().use { properties.store(it, "Dependency versions supplied by the `$path` task.") } } private fun resourceFileName(): String { val artifactId = project.artifactId return "versions-${artifactId}.properties" } } /** * A plugin that enables storing dependency versions into a resource file. * * Dependency version may be used by Gradle plugins at runtime. * * The plugin adds one task — `writeVersions`, which generates a `.properties` file with some * dependency versions. * * The generated file will be available in classpath of the target project under the name: * `versions-<project name>.properties`, where `<project name>` is the name of the target * Gradle project. */ @Suppress("unused") class VersionWriter : Plugin<Project> { override fun apply(target: Project): Unit = with (target.tasks) { val task = register("writeVersions", WriteVersions::class.java) { versionsFileLocation.convention(project.layout.buildDirectory.dir(name)) includeOwnVersion() project.sourceSets .getByName("main") .resources .srcDir(versionsFileLocation) } getByName("processResources").dependsOn(task) } }
apache-2.0
5f747c9aaaf97f663e07d5865c4c063b
34.758389
99
0.681682
4.557742
false
false
false
false
bailuk/AAT
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/menu/provider/MapMenu.kt
1
1992
package ch.bailu.aat_gtk.view.menu.provider import ch.bailu.aat_gtk.lib.menu.MenuModelBuilder import ch.bailu.aat_gtk.solid.GtkMapDirectories import ch.bailu.aat_gtk.view.UiController import ch.bailu.aat_lib.map.MapContext import ch.bailu.aat_lib.preferences.map.SolidMapTileStack import ch.bailu.aat_lib.preferences.map.SolidOverlayFileList import ch.bailu.aat_lib.resources.Res import ch.bailu.foc.FocFactory import ch.bailu.gtk.gtk.Window class MapMenu( private val uiController: UiController, private val mapContext: MapContext, mapDirectories: GtkMapDirectories, focFactory: FocFactory, window: Window ) : MenuProvider { private val srender = mapDirectories.createSolidRenderTheme() private val renderMenu = SolidFileSelectorMenu(srender, window) private val soverlay = SolidOverlayFileList(srender.storage, focFactory) private val overlayMenu = SolidCheckMenu(soverlay) private val soffline = mapDirectories.createSolidFile() private val offlineMenu = SolidFileSelectorMenu(soffline, window) private val stiles = SolidMapTileStack(srender) private val tilesMenu = SolidCheckMenu(stiles) override fun createMenu(): MenuModelBuilder { return MenuModelBuilder() .submenu(stiles.label, tilesMenu.createMenu()) .submenu(soverlay.label, overlayMenu.createMenu()) .submenu(soffline.label, offlineMenu.createMenu()) .submenu(srender.label, renderMenu.createMenu()) .label(Res.str().intro_settings()) { uiController.showPreferencesMap() } .label(Res.str().tt_info_reload()) { mapContext.mapView.reDownloadTiles() } } override fun createCustomWidgets(): Array<CustomWidget> { return tilesMenu.createCustomWidgets() + overlayMenu.createCustomWidgets() + offlineMenu.createCustomWidgets() + renderMenu.createCustomWidgets() } }
gpl-3.0
458924573aa9c9e507615a5d68574e87
35.218182
76
0.708835
4.176101
false
false
false
false
cbeust/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/UnversionedDep.kt
3
1328
package com.beust.kobalt.maven import java.io.File /** * Represents a dependency that doesn't have a version: "org.testng:testng:". Such dependencies * eventually resolve to the latest version of the artifact. */ open class UnversionedDep(open val groupId: String, open val artifactId: String) { open fun toMetadataXmlPath(fileSystem: Boolean = true, isLocal: Boolean, version: String? = null) : String { var result = toDirectory("", fileSystem) + if (isLocal) "maven-metadata-local.xml" else "maven-metadata.xml" if (! File(result).exists() && version != null) { result = toDirectory("", fileSystem) + version + File.separator + if (isLocal) "maven-metadata-local.xml" else "maven-metadata.xml" } return result } /** * Turn this dependency to a directory. If fileSystem is true, use the file system * dependent path separator, otherwise, use '/' (used to create URL's). */ fun toDirectory(v: String, fileSystem: Boolean = true, trailingSlash: Boolean = true): String { val sep = if (fileSystem) File.separator else "/" val l = listOf(groupId.replace(".", sep), artifactId, v) val result = l.joinToString(sep) return if (trailingSlash && ! result.endsWith(sep)) result + sep else result } }
apache-2.0
e2f5c503d3082628b3919dbdda3d364f
44.793103
116
0.655873
4.202532
false
true
false
false
cbeust/kobalt
src/test/kotlin/com/beust/kobalt/TestModule.kt
1
1920
package com.beust.kobalt import com.beust.kobalt.api.KobaltContext import com.beust.kobalt.app.MainModule import com.beust.kobalt.internal.ILogger import com.beust.kobalt.internal.KobaltSettings import com.beust.kobalt.internal.KobaltSettingsXml import com.beust.kobalt.maven.LocalRepo import com.beust.kobalt.maven.aether.KobaltMavenResolver import com.beust.kobalt.misc.kobaltLog import com.google.common.eventbus.EventBus import com.google.inject.Provider import com.google.inject.Scopes import java.io.File import java.util.concurrent.ExecutorService val LOCAL_CACHE = File(SystemProperties.homeDir + File.separatorChar + ".kobalt-test") val TEST_KOBALT_SETTINGS = KobaltSettings(KobaltSettingsXml()).apply { localCache = LOCAL_CACHE } class TestLocalRepo: LocalRepo(TEST_KOBALT_SETTINGS) class TestModule : MainModule(Args(), TEST_KOBALT_SETTINGS) { override fun configureTest() { val localRepo = TestLocalRepo() bind(LocalRepo::class.java).toInstance(localRepo) // val localAether = Aether(LOCAL_CACHE, TEST_KOBALT_SETTINGS, EventBus()) val testResolver = KobaltMavenResolver(KobaltSettings(KobaltSettingsXml()), Args(), TestLocalRepo(), EventBus()) bind(KobaltMavenResolver::class.java).to(testResolver) bind(KobaltContext::class.java).toProvider(Provider<KobaltContext> { KobaltContext(args).apply { resolver = testResolver logger = object: ILogger { override fun log(tag: CharSequence, level: Int, message: CharSequence, newLine: Boolean) { kobaltLog(1, "TestLog: [$tag $level] " + message) } } } }).`in`(Scopes.SINGLETON) } override fun bindExecutors() { // in tests do nothing to bind new executors for each tests // this avoids tests submitting tasks after pool shutdown } }
apache-2.0
56f19d6373dee2be7322ada01552527d
39
120
0.702604
4.324324
false
true
false
false
jupf/staticlog
src/main/kotlin/de/jupf/staticlog/Log.kt
1
10872
//@file:JvmName("Log") package de.jupf.staticlog import de.jupf.staticlog.core.Logger import de.jupf.staticlog.core.LogLevel import de.jupf.staticlog.format.Builder import de.jupf.staticlog.format.Indent import de.jupf.staticlog.format.Line import de.jupf.staticlog.format.LogFormat import de.jupf.staticlog.printer.AndroidPrinter import de.jupf.staticlog.printer.DesktopPrinter import de.jupf.staticlog.printer.Printer import java.util.* /** * The StaticLog main logging interface object * * @author J.Pfeifer * @created on 03.02.2016. */ object Log { internal val logInstance = Logger(4) @JvmStatic var logLevel: LogLevel get() = logInstance.logLevel set(value) { logInstance.logLevel = value } var filterTag: String get() = logInstance.filterTag set(value) { logInstance.filterTag = value } @JvmStatic val slf4jLogInstancesMap: Map<String,Logger> = LinkedHashMap() @JvmStatic var slf4jLogLevel: LogLevel get() = SLF4JBindingFacade.logLevel set(value) { SLF4JBindingFacade.logLevel = value } /** * Returns a logger instance for Java */ @JvmStatic fun javaInstance(): Logger { return Logger(4) } /** * Returns a logger instance for kotlin */ @JvmStatic fun kotlinInstance(): Logger { return Logger(3) } /** * Adding the given [printer] to the printers used by this [Logger] */ @JvmStatic fun addPrinter(printer: Printer) { logInstance.addPrinter(printer) } /** * Resets the [Printer] of this [Logger] to the default. */ @JvmStatic fun setDefaultPrinter() { logInstance.setDefaultPrinter() } /** * Sets the given [printer] as the new and only printer for this [Logger]. */ @JvmStatic fun setPrinter(printer: Printer) { logInstance.setPrinter(printer) } /** * Logs a debug message. * * @param message The log message * @param tag The tag the message is logged under * @param throwable The log-related throwable */ @JvmStatic fun debug(message: String, tag: String, throwable: Throwable) { logInstance.debug(message, tag, throwable) } /** * Logs a debug message. * The tag will default to the class name the log is created from. * * @param message The log message * @param throwable The log-related throwable */ @JvmStatic fun debug(message: String, throwable: Throwable) { logInstance.debug(message, throwable) } /** * Logs a debug message. * * @param message The log message * @param tag The tag the message is logged under */ @JvmStatic fun debug(message: String, tag: String) { logInstance.debug(message, tag) } /** * Logs a debug message. * The tag will default to the class name the log is created from. * * @param message The log message */ @JvmStatic fun debug(message: String) { logInstance.debug(message) } /** * Logs an info message. * * @param message The log message * @param tag The tag the message is logged under * @param throwable The log-related throwable */ @JvmStatic fun info(message: String, tag: String, throwable: Throwable) { logInstance.info(message, tag, throwable) } /** * Logs an info message. * The tag will default to the class name the log is created from. * * @param message The log message * @param throwable The log-related throwable */ @JvmStatic fun info(message: String, throwable: Throwable) { logInstance.info(message, throwable) } /** * Logs an info message. * * @param message The log message * @param tag The tag the message is logged under */ @JvmStatic fun info(message: String, tag: String) { logInstance.info(message, tag) } /** * Logs an info message. * The tag will default to the class name the log is created from. * * @param message The log message */ @JvmStatic fun info(message: String) { logInstance.info(message) } /** * Logs a warning message. * * @param message The log message * @param tag The tag the message is logged under * @param throwable The log-related throwable */ @JvmStatic fun warn(message: String, tag: String, throwable: Throwable) { logInstance.warn(message, tag, throwable) } /** * Logs a warning message. * The tag will default to the class name the log is created from. * * @param message The log message * @param throwable The log-related throwable */ @JvmStatic fun warn(message: String, throwable: Throwable) { logInstance.warn(message, throwable) } /** * Logs a warning message. * * @param message The log message * @param tag The tag the message is logged under */ @JvmStatic fun warn(message: String, tag: String) { logInstance.warn(message, tag) } /** * Logs a warning message. * The tag will default to the class name the log is created from. * * @param message The log message */ @JvmStatic fun warn(message: String) { logInstance.warn(message) } /** * Logs an error message. * * @param message The log message * @param tag The tag the message is logged under * @param throwable The log-related throwable */ @JvmStatic fun error(message: String, tag: String, throwable: Throwable) { logInstance.error(message, tag, throwable) } /** * Logs an error message. * The tag will default to the class name the log is created from. * * @param message The log message * @param throwable The log-related throwable */ @JvmStatic fun error(message: String, throwable: Throwable) { logInstance.error(message, throwable) } /** * Logs an error message. * * @param message The log message * @param tag The tag the message is logged under */ @JvmStatic fun error(message: String, tag: String) { logInstance.error(message, tag) } /** * Logs an error message. * The tag will default to the class name the log is created from. * * @param message The log message */ @JvmStatic fun error(message: String) { logInstance.error(message) } /** * This method deletes the old [LogFormat] and * returns a handle to create the new format with. * * @return log format handle */ @JvmStatic fun newFormat(): LogFormat { return logInstance.newFormat() } /** * Sets a tag filter for this Logger. * Only messages with this tag will be printed. * * @param filterTag */ @JvmStatic fun setTagFilter(filterTag: String) { logInstance.filterTag = filterTag } /** * Deletes a previously set tag filter. */ @JvmStatic fun deleteTagFilter() { logInstance.deleteTagFilter() } fun newFormat(buildFun: LogFormat.() -> Unit) { logInstance.newFormat(buildFun) } object FormatOperations { /** * Creates a space [Builder] which prints [times] spaces. * * @param times number of spaces to print * * @return [Builder] for spaces */ @JvmStatic fun space(times: Int): Builder { return Log.logInstance.logFormat.space(times) } /** * Creates a tab [Builder] which prints [times] tabs. * @param times number of tabs to print * * @return [Builder] for tabs */ @JvmStatic fun tab(times: Int): Builder { return Log.logInstance.logFormat.tab(times) } /** * Creates a date [Builder] which prints the actual date/time in the given [format]. * @param format String in a [SimpleDateFormat](http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html) * * @return [Builder] for spaces */ @JvmStatic fun date(format: String): Builder { return Log.logInstance.logFormat.date(format) } /** * Creates a [Builder] which prints the current time in milliseconds. * * @return [Builder] for time since epoch */ @JvmStatic fun epoch(): Builder { return Log.logInstance.logFormat.epoch } /** * Creates a [Builder] which prints the [LogLevel] of the log. * * @return [Builder] for current [LogLevel] */ @JvmStatic fun level(): Builder { return Log.logInstance.logFormat.level } /** * Creates a [Builder] which prints the log message itself. * * @return [Builder] for the message */ @JvmStatic fun message(): Builder { return Log.logInstance.logFormat.message } /** * Creates a [Builder] which prints the tag of the log. * * @return [Builder] for the tag */ @JvmStatic fun tag(): Builder { return Log.logInstance.logFormat.tag } /** * Creates a [Builder] which prints the fully qualified name of the occurrence of the log. * * @return [Builder] for the occurrence */ @JvmStatic fun occurrence(): Builder { return Log.logInstance.logFormat.occurrence } /** * Creates a Builder which prints the given [text] * * @param text the text to print * * @return [Builder] for [text] */ @JvmStatic fun text(text: String): Builder { return Log.logInstance.logFormat.text(text) } /** * Creates a [Builder] which prints all added Builders. * * @return [Builder] for current [LogLevel] */ @JvmStatic fun line(vararg builders: Builder): Builder { val line = Line() for (i in builders.indices) { line.children.add(builders[i]) } return line } @JvmStatic fun indent(vararg builders: Builder): Builder { val indent = Indent() for (i in builders.indices) { indent.children.add(builders[i]) } return indent } } }
mit
d08f2e5ca8f9fa6eb991383cc0985fd0
24.461358
129
0.575883
4.466721
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/sponge/util/SpongeUtils.kt
1
1653
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.sponge.util import com.demonwav.mcdev.util.constantStringValue import com.demonwav.mcdev.util.findContainingClass import com.intellij.lang.jvm.annotation.JvmAnnotationConstantValue import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember import com.intellij.psi.PsiModifierListOwner fun PsiMember.isInSpongePluginClass(): Boolean = this.containingClass?.isSpongePluginClass() == true fun PsiClass.isSpongePluginClass(): Boolean = this.hasAnnotation(SpongeConstants.PLUGIN_ANNOTATION) || this.hasAnnotation(SpongeConstants.JVM_PLUGIN_ANNOTATION) fun PsiElement.spongePluginClassId(): String? { val clazz = this.findContainingClass() ?: return null val annotation = clazz.getAnnotation(SpongeConstants.PLUGIN_ANNOTATION) ?: clazz.getAnnotation(SpongeConstants.JVM_PLUGIN_ANNOTATION) return annotation?.findAttributeValue("id")?.constantStringValue } fun isInjected(element: PsiModifierListOwner, optionalSensitive: Boolean): Boolean { val annotation = element.getAnnotation(SpongeConstants.INJECT_ANNOTATION) ?: return false if (!optionalSensitive) { return true } return !isInjectOptional(annotation) } fun isInjectOptional(annotation: PsiAnnotation): Boolean { val optional = annotation.findAttribute("optional") ?: return false val value = optional.attributeValue return value is JvmAnnotationConstantValue && value.constantValue == true }
mit
2f9b730ab4036dd5a065a0d88b7eb59f
34.170213
102
0.784029
4.604457
false
false
false
false
is00hcw/anko
dsl/testData/functional/appcompat-v7/ViewTest.kt
2
13610
public object `$$Anko$Factories$AppcompatV7View` { public val TINTED_AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatAutoCompleteTextView(ctx) else AutoCompleteTextView(ctx) } public val TINTED_BUTTON = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatButton(ctx) else Button(ctx) } public val TINTED_CHECK_BOX = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatCheckBox(ctx) else CheckBox(ctx) } public val TINTED_CHECKED_TEXT_VIEW = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatCheckedTextView(ctx) else CheckedTextView(ctx) } public val TINTED_EDIT_TEXT = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatEditText(ctx) else EditText(ctx) } public val TINTED_MULTI_AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatMultiAutoCompleteTextView(ctx) else MultiAutoCompleteTextView(ctx) } public val TINTED_RADIO_BUTTON = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatRadioButton(ctx) else RadioButton(ctx) } public val TINTED_RATING_BAR = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatRatingBar(ctx) else RatingBar(ctx) } public val TINTED_SPINNER = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatSpinner(ctx) else Spinner(ctx) } public val TINTED_TEXT_VIEW = { ctx: Context -> if (Build.VERSION.SDK_INT < 21) android.support.v7.widget.AppCompatTextView(ctx) else TextView(ctx) } public val SEARCH_VIEW = { ctx: Context -> android.support.v7.widget.SearchView(ctx) } public val SWITCH_COMPAT = { ctx: Context -> android.support.v7.widget.SwitchCompat(ctx) } } public inline fun ViewManager.tintedAutoCompleteTextView(): AutoCompleteTextView = tintedAutoCompleteTextView({}) public inline fun ViewManager.tintedAutoCompleteTextView(init: AutoCompleteTextView.() -> Unit): AutoCompleteTextView { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_AUTO_COMPLETE_TEXT_VIEW) { init() } } public inline fun ViewManager.tintedButton(): Button = tintedButton({}) public inline fun ViewManager.tintedButton(init: Button.() -> Unit): Button { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_BUTTON) { init() } } public inline fun ViewManager.tintedButton(text: CharSequence?): Button { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_BUTTON) { setText(text) } } public inline fun ViewManager.tintedButton(text: CharSequence?, init: Button.() -> Unit): Button { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_BUTTON) { init() setText(text) } } public inline fun ViewManager.tintedButton(text: Int): Button { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_BUTTON) { setText(text) } } public inline fun ViewManager.tintedButton(text: Int, init: Button.() -> Unit): Button { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_BUTTON) { init() setText(text) } } public inline fun ViewManager.tintedCheckBox(): CheckBox = tintedCheckBox({}) public inline fun ViewManager.tintedCheckBox(init: CheckBox.() -> Unit): CheckBox { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) { init() } } public inline fun ViewManager.tintedCheckBox(text: CharSequence?): CheckBox { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) { setText(text) } } public inline fun ViewManager.tintedCheckBox(text: CharSequence?, init: CheckBox.() -> Unit): CheckBox { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) { init() setText(text) } } public inline fun ViewManager.tintedCheckBox(text: Int): CheckBox { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) { setText(text) } } public inline fun ViewManager.tintedCheckBox(text: Int, init: CheckBox.() -> Unit): CheckBox { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) { init() setText(text) } } public inline fun ViewManager.tintedCheckBox(text: CharSequence?, checked: Boolean): CheckBox { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) { setText(text) setChecked(checked) } } public inline fun ViewManager.tintedCheckBox(text: CharSequence?, checked: Boolean, init: CheckBox.() -> Unit): CheckBox { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) { init() setText(text) setChecked(checked) } } public inline fun ViewManager.tintedCheckBox(text: Int, checked: Boolean): CheckBox { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) { setText(text) setChecked(checked) } } public inline fun ViewManager.tintedCheckBox(text: Int, checked: Boolean, init: CheckBox.() -> Unit): CheckBox { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECK_BOX) { init() setText(text) setChecked(checked) } } public inline fun ViewManager.tintedCheckedTextView(): CheckedTextView = tintedCheckedTextView({}) public inline fun ViewManager.tintedCheckedTextView(init: CheckedTextView.() -> Unit): CheckedTextView { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_CHECKED_TEXT_VIEW) { init() } } public inline fun ViewManager.tintedEditText(): EditText = tintedEditText({}) public inline fun ViewManager.tintedEditText(init: EditText.() -> Unit): EditText { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_EDIT_TEXT) { init() } } public inline fun ViewManager.tintedEditText(text: CharSequence?): EditText { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_EDIT_TEXT) { setText(text) } } public inline fun ViewManager.tintedEditText(text: CharSequence?, init: EditText.() -> Unit): EditText { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_EDIT_TEXT) { init() setText(text) } } public inline fun ViewManager.tintedEditText(text: Int): EditText { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_EDIT_TEXT) { setText(text) } } public inline fun ViewManager.tintedEditText(text: Int, init: EditText.() -> Unit): EditText { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_EDIT_TEXT) { init() setText(text) } } public inline fun ViewManager.tintedMultiAutoCompleteTextView(): MultiAutoCompleteTextView = tintedMultiAutoCompleteTextView({}) public inline fun ViewManager.tintedMultiAutoCompleteTextView(init: MultiAutoCompleteTextView.() -> Unit): MultiAutoCompleteTextView { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_MULTI_AUTO_COMPLETE_TEXT_VIEW) { init() } } public inline fun ViewManager.tintedRadioButton(): RadioButton = tintedRadioButton({}) public inline fun ViewManager.tintedRadioButton(init: RadioButton.() -> Unit): RadioButton { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_RADIO_BUTTON) { init() } } public inline fun ViewManager.tintedRatingBar(): RatingBar = tintedRatingBar({}) public inline fun ViewManager.tintedRatingBar(init: RatingBar.() -> Unit): RatingBar { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_RATING_BAR) { init() } } public inline fun ViewManager.tintedSpinner(): Spinner = tintedSpinner({}) public inline fun ViewManager.tintedSpinner(init: Spinner.() -> Unit): Spinner { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_SPINNER) { init() } } public inline fun Context.tintedSpinner(): Spinner = tintedSpinner({}) public inline fun Context.tintedSpinner(init: Spinner.() -> Unit): Spinner { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_SPINNER) { init() } } public inline fun Activity.tintedSpinner(): Spinner = tintedSpinner({}) public inline fun Activity.tintedSpinner(init: Spinner.() -> Unit): Spinner { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_SPINNER) { init() } } public inline fun ViewManager.tintedTextView(): TextView = tintedTextView({}) public inline fun ViewManager.tintedTextView(init: TextView.() -> Unit): TextView { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_TEXT_VIEW) { init() } } public inline fun ViewManager.tintedTextView(text: CharSequence?): TextView { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_TEXT_VIEW) { setText(text) } } public inline fun ViewManager.tintedTextView(text: CharSequence?, init: TextView.() -> Unit): TextView { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_TEXT_VIEW) { init() setText(text) } } public inline fun ViewManager.tintedTextView(text: Int): TextView { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_TEXT_VIEW) { setText(text) } } public inline fun ViewManager.tintedTextView(text: Int, init: TextView.() -> Unit): TextView { return ankoView(`$$Anko$Factories$AppcompatV7View`.TINTED_TEXT_VIEW) { init() setText(text) } } public inline fun ViewManager.searchView(): android.support.v7.widget.SearchView = searchView({}) public inline fun ViewManager.searchView(init: android.support.v7.widget.SearchView.() -> Unit): android.support.v7.widget.SearchView { return ankoView(`$$Anko$Factories$AppcompatV7View`.SEARCH_VIEW) { init() } } public inline fun Context.searchView(): android.support.v7.widget.SearchView = searchView({}) public inline fun Context.searchView(init: android.support.v7.widget.SearchView.() -> Unit): android.support.v7.widget.SearchView { return ankoView(`$$Anko$Factories$AppcompatV7View`.SEARCH_VIEW) { init() } } public inline fun Activity.searchView(): android.support.v7.widget.SearchView = searchView({}) public inline fun Activity.searchView(init: android.support.v7.widget.SearchView.() -> Unit): android.support.v7.widget.SearchView { return ankoView(`$$Anko$Factories$AppcompatV7View`.SEARCH_VIEW) { init() } } public inline fun ViewManager.switchCompat(): android.support.v7.widget.SwitchCompat = switchCompat({}) public inline fun ViewManager.switchCompat(init: android.support.v7.widget.SwitchCompat.() -> Unit): android.support.v7.widget.SwitchCompat { return ankoView(`$$Anko$Factories$AppcompatV7View`.SWITCH_COMPAT) { init() } } public object `$$Anko$Factories$AppcompatV7ViewGroup` { public val ACTION_MENU_VIEW = { ctx: Context -> _ActionMenuView(ctx) } public val LINEAR_LAYOUT_COMPAT = { ctx: Context -> _LinearLayoutCompat(ctx) } public val TOOLBAR = { ctx: Context -> _Toolbar(ctx) } } public inline fun ViewManager.actionMenuView(): android.support.v7.widget.ActionMenuView = actionMenuView({}) public inline fun ViewManager.actionMenuView(init: _ActionMenuView.() -> Unit): android.support.v7.widget.ActionMenuView { return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.ACTION_MENU_VIEW) { init() } } public inline fun Context.actionMenuView(): android.support.v7.widget.ActionMenuView = actionMenuView({}) public inline fun Context.actionMenuView(init: _ActionMenuView.() -> Unit): android.support.v7.widget.ActionMenuView { return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.ACTION_MENU_VIEW) { init() } } public inline fun Activity.actionMenuView(): android.support.v7.widget.ActionMenuView = actionMenuView({}) public inline fun Activity.actionMenuView(init: _ActionMenuView.() -> Unit): android.support.v7.widget.ActionMenuView { return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.ACTION_MENU_VIEW) { init() } } public inline fun ViewManager.linearLayoutCompat(): android.support.v7.widget.LinearLayoutCompat = linearLayoutCompat({}) public inline fun ViewManager.linearLayoutCompat(init: _LinearLayoutCompat.() -> Unit): android.support.v7.widget.LinearLayoutCompat { return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.LINEAR_LAYOUT_COMPAT) { init() } } public inline fun Context.linearLayoutCompat(): android.support.v7.widget.LinearLayoutCompat = linearLayoutCompat({}) public inline fun Context.linearLayoutCompat(init: _LinearLayoutCompat.() -> Unit): android.support.v7.widget.LinearLayoutCompat { return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.LINEAR_LAYOUT_COMPAT) { init() } } public inline fun Activity.linearLayoutCompat(): android.support.v7.widget.LinearLayoutCompat = linearLayoutCompat({}) public inline fun Activity.linearLayoutCompat(init: _LinearLayoutCompat.() -> Unit): android.support.v7.widget.LinearLayoutCompat { return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.LINEAR_LAYOUT_COMPAT) { init() } } public inline fun ViewManager.toolbar(): android.support.v7.widget.Toolbar = toolbar({}) public inline fun ViewManager.toolbar(init: _Toolbar.() -> Unit): android.support.v7.widget.Toolbar { return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.TOOLBAR) { init() } } public inline fun Context.toolbar(): android.support.v7.widget.Toolbar = toolbar({}) public inline fun Context.toolbar(init: _Toolbar.() -> Unit): android.support.v7.widget.Toolbar { return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.TOOLBAR) { init() } } public inline fun Activity.toolbar(): android.support.v7.widget.Toolbar = toolbar({}) public inline fun Activity.toolbar(init: _Toolbar.() -> Unit): android.support.v7.widget.Toolbar { return ankoView(`$$Anko$Factories$AppcompatV7ViewGroup`.TOOLBAR) { init() } }
apache-2.0
953afdbef58caa7be9f373b1dd223e99
49.598513
207
0.736297
4.226708
false
false
false
false
Ztiany/Repository
Kotlin/Kotlin-coroutineSample/src/main/java/com/bennyhuo/coroutines/sample/Ex11_RetrofitDemo.kt
2
4247
package com.bennyhuo.coroutines.sample import com.bennyhuo.coroutines.utils.log import com.jakewharton.retrofit2.adapter.kotlin.coroutines.experimental.CoroutineCallAdapterFactory import kotlinx.coroutines.experimental.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Path import kotlin.coroutines.experimental.suspendCoroutine //region common private val gitHubServiceApi by lazy { val retrofit = retrofit2.Retrofit.Builder() .baseUrl("https://api.github.com") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .build() retrofit.create(GitHubServiceApi::class.java) } interface GitHubServiceApi { @GET("users/{login}") fun getUserCallback(@Path("login") login: String): Call<User> @GET("users/{login}") fun getUserCoroutine(@Path("login") login: String): Deferred<User> } data class User(val id: String, val name: String, val url: String) fun showUser(user: User) { println(user) } fun showError(t: Throwable) { t.printStackTrace() } //endregion fun main(args: Array<String>) = runBlocking { //useCallback() //wrappedInSuspendFunction() //useCoroutine() //useTraditionalForLoop() //useExtensionForEach() //timeCost() } fun useCallback() { gitHubServiceApi.getUserCallback("bennyhuo").enqueue(object : Callback<User> { override fun onFailure(call: Call<User>, t: Throwable) { showError(t) } override fun onResponse(call: Call<User>, response: Response<User>) { response.body()?.let(::showUser) ?: showError(NullPointerException()) } }) } suspend fun wrappedInSuspendFunction() { launch { try { showUser(async { getUser("bennyhuo") }.await()) } catch (e: Exception) { showError(e) } }.join() } suspend fun getUser(login: String) = suspendCoroutine<User> { continuation -> gitHubServiceApi.getUserCallback(login).enqueue(object : Callback<User> { override fun onFailure(call: Call<User>, t: Throwable) { continuation.resumeWithException(t) } override fun onResponse(call: Call<User>, response: Response<User>) { response.body()?.let(continuation::resume) ?: continuation.resumeWithException(NullPointerException()) } }) } suspend fun useCoroutine() { launch { try { showUser(gitHubServiceApi.getUserCoroutine("bennyhuo").await()) } catch (e: Exception) { showError(e) } }.join() } suspend fun useTraditionalForLoop() { launch { for (login in listOf("JakeWharton", "abreslav", "yole", "elizarov")) { try { showUser(gitHubServiceApi.getUserCoroutine(login).await()) } catch (e: Exception) { showError(e) } delay(1000) } }.join() } suspend fun useExtensionForEach() { launch { listOf("JakeWharton", "abreslav", "yole", "elizarov") .forEach { try { showUser(gitHubServiceApi.getUserCoroutine(it).await()) } catch (e: Exception) { showError(e) } delay(1000) } }.join() } suspend fun timeCost() { launch { cost { listOf("JakeWharton", "abreslav", "yole", "elizarov") .forEach { cost { try { showUser(gitHubServiceApi.getUserCoroutine(it).await()) } catch (e: Exception) { showError(e) } delay(1000) } } } }.join() } inline fun <T> cost(block: () -> T): T { val start = System.currentTimeMillis() val result = block() val cost = System.currentTimeMillis() - start log("Time Cost: ${cost}ms") return result }
apache-2.0
3d7ecb91f6c1469ff20305e125939dbe
27.32
114
0.580645
4.6013
false
false
false
false
pokk/KotlinKnifer
kotlinshaver/src/main/java/com/devrapid/kotlinshaver/Kits.kt
1
980
@file:Suppress("NOTHING_TO_INLINE") package com.devrapid.kotlinshaver import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract inline infix fun (() -> Unit).iff(condition: Any?): Any? { return when (condition) { is Boolean -> if (condition) this() else null is Float, Double, Int, Long -> this() is String -> if (condition.isNotBlank()) this() else null is Collection<*> -> if (condition.isNotEmpty()) this() else null else -> condition?.let { this() } } } inline fun Any?.isNull() = null == this inline fun Any?.isNotNull() = null != this @OptIn(ExperimentalContracts::class) inline fun Any?.isNullExp(): Boolean { contract { returns(false) implies (this@isNullExp == null) } return null == this } @OptIn(ExperimentalContracts::class) inline fun Any?.isNotNullExp(): Boolean { contract { returns(true) implies (this@isNotNullExp != null) } return null != this }
apache-2.0
37f096c6123c85e8881e4e5026f4ae05
26.222222
72
0.652041
4.032922
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/org/mariotaku/ktextension/StreamExtensions.kt
1
1251
package org.mariotaku.ktextension import java.io.InputStream import java.io.OutputStream import java.nio.charset.Charset import java.util.* /** * Created by mariotaku on 2016/12/7. */ fun InputStream.toString(charset: Charset, close: Boolean = false): String { val r = bufferedReader(charset) if (close) return r.use { it.readText() } return r.readText() } fun OutputStream.writeLine(string: String = "", charset: Charset = Charset.defaultCharset(), crlf: Boolean = false) { write(string.toByteArray(charset)) if (crlf) { write("\r\n".toByteArray(charset)) } else { write("\n".toByteArray(charset)) } } fun InputStream.expectLine(string: String = "", charset: Charset = Charset.defaultCharset(), crlf: Boolean = false): Boolean { if (!expectBytes(string.toByteArray(charset))) return false if (crlf) { if (!expectBytes("\r\n".toByteArray(charset))) return false } else { if (!expectBytes("\n".toByteArray(charset))) return false } return true } fun InputStream.expectBytes(bytes: ByteArray): Boolean { val readBytes = ByteArray(bytes.size) read(readBytes) return Arrays.equals(readBytes, bytes) }
gpl-3.0
45a61d823df16174801a54d100b5639c
27.454545
92
0.652278
4.061688
false
false
false
false
GlimpseFramework/glimpse-framework-android
android/src/main/kotlin/glimpse/android/gles/GLES.kt
1
8361
package glimpse.android.gles import android.graphics.BitmapFactory import android.opengl.GLES20 import android.opengl.GLUtils import glimpse.Color import glimpse.android.gles.delegates.EnableDisableDelegate import glimpse.gles.* import glimpse.gles.GLES import glimpse.gles.delegates.EnumPairSetAndRememberDelegate import glimpse.gles.delegates.EnumSetAndRememberDelegate import glimpse.gles.delegates.SetAndRememberDelegate import glimpse.shaders.ProgramHandle import glimpse.shaders.ShaderHandle import glimpse.shaders.ShaderType import glimpse.textures.TextureHandle import glimpse.textures.TextureMagnificationFilter import glimpse.textures.TextureMinificationFilter import glimpse.textures.TextureWrapping import java.io.InputStream import java.nio.Buffer import java.nio.FloatBuffer import java.nio.IntBuffer /** * Android implementation of GLES facade. */ object GLES : GLES { override var viewport: Viewport by SetAndRememberDelegate(Viewport(1, 1)) { GLES20.glViewport(0, 0, it.width, it.height) } override var clearColor: Color by SetAndRememberDelegate(Color.Companion.BLACK) { GLES20.glClearColor(it.red, it.green, it.blue, it.alpha) } override var clearDepth: Float by SetAndRememberDelegate(1f) { GLES20.glClearDepthf(it) } override var isDepthTest: Boolean by EnableDisableDelegate(GLES20.GL_DEPTH_TEST) override var depthTestFunction: DepthTestFunction by EnumSetAndRememberDelegate(DepthTestFunction.LESS, depthTestFunctionMapping) { GLES20.glDepthFunc(it) } override var isBlend: Boolean by EnableDisableDelegate(GLES20.GL_BLEND) override var blendFunction: Pair<BlendFactor, BlendFactor> by EnumPairSetAndRememberDelegate(BlendFactor.ZERO to BlendFactor.ONE, blendFactorMapping) { GLES20.glBlendFunc(it.first, it.second) } override var isCullFace: Boolean by EnableDisableDelegate(GLES20.GL_CULL_FACE) override var cullFaceMode: CullFaceMode by EnumSetAndRememberDelegate(CullFaceMode.BACK, cullFaceModeMapping) { GLES20.glCullFace(it) } override fun clearDepthBuffer() { GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT) } override fun clearColorBuffer() { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) } override fun createShader(shaderType: ShaderType) = ShaderHandle(GLES20.glCreateShader(shaderTypeMapping[shaderType]!!)) override fun compileShader(shaderHandle: ShaderHandle, source: String) { GLES20.glShaderSource(shaderHandle.value, source) GLES20.glCompileShader(shaderHandle.value) } override fun deleteShader(shaderHandle: ShaderHandle) { GLES20.glDeleteShader(shaderHandle.value) } override fun getShaderCompileStatus(shaderHandle: ShaderHandle) = getShaderProperty(shaderHandle, GLES20.GL_COMPILE_STATUS) == GLES20.GL_TRUE private fun getShaderProperty(shaderHandle: ShaderHandle, property: Int): Int { val result = IntBuffer.allocate(1) GLES20.glGetShaderiv(shaderHandle.value, property, result) return result[0] } override fun getShaderLog(shaderHandle: ShaderHandle): String = GLES20.glGetShaderInfoLog(shaderHandle.value) override fun createProgram() = ProgramHandle(GLES20.glCreateProgram()) override fun attachShader(programHandle: ProgramHandle, shaderHandle: ShaderHandle) { GLES20.glAttachShader(programHandle.value, shaderHandle.value) } override fun linkProgram(programHandle: ProgramHandle) { GLES20.glLinkProgram(programHandle.value) } override fun useProgram(programHandle: ProgramHandle) { GLES20.glUseProgram(programHandle.value) } override fun deleteProgram(programHandle: ProgramHandle) { GLES20.glDeleteProgram(programHandle.value) } override fun getProgramLinkStatus(programHandle: ProgramHandle) = getProgramProperty(programHandle, GLES20.GL_LINK_STATUS) == GLES20.GL_TRUE private fun getProgramProperty(programHandle: ProgramHandle, property: Int): Int { val result = IntBuffer.allocate(1) GLES20.glGetProgramiv(programHandle.value, property, result) return result[0] } override fun getProgramLog(programHandle: ProgramHandle): String = GLES20.glGetProgramInfoLog(programHandle.value) override fun getUniformLocation(handle: ProgramHandle, name: String) = UniformLocation(GLES20.glGetUniformLocation(handle.value, name)) override fun getAttributeLocation(handle: ProgramHandle, name: String) = AttributeLocation(GLES20.glGetAttribLocation(handle.value, name)) override fun uniformFloat(location: UniformLocation, float: Float) { GLES20.glUniform1f(location.value, float) } override fun uniformFloats(location: UniformLocation, floats: FloatArray) { GLES20.glUniform1fv(location.value, floats.size, floats, 0) } override fun uniformInt(location: UniformLocation, int: Int) { GLES20.glUniform1i(location.value, int) } override fun uniformInts(location: UniformLocation, ints: IntArray) { GLES20.glUniform1iv(location.value, ints.size, ints, 0) } override fun uniformMatrix16f(location: UniformLocation, _16f: Array<Float>) { GLES20.glUniformMatrix4fv(location.value, 1, false, _16f.toFloatArray(), 0) } override fun uniform4f(location: UniformLocation, _4f: Array<Float>, count: Int) { GLES20.glUniform4fv(location.value, count, _4f.toFloatArray(), 0) } override fun createAttributeFloatArray(location: AttributeLocation, buffer: FloatBuffer, vectorSize: Int) = createAttributeArray(location, buffer, vectorSize, GLES20.GL_FLOAT, 4) override fun createAttributeIntArray(location: AttributeLocation, buffer: IntBuffer, vectorSize: Int) = createAttributeArray(location, buffer, vectorSize, GLES20.GL_INT, 4) private fun createAttributeArray(location: AttributeLocation, buffer: Buffer, vectorSize: Int, type: Int, typeSize: Int): BufferHandle { buffer.rewind() val handles = IntArray(1) GLES20.glGenBuffers(1, handles, 0) GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, handles[0]) GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, buffer.limit() * typeSize, buffer, GLES20.GL_STATIC_DRAW) GLES20.glVertexAttribPointer(location.value, vectorSize, type, false, 0, 0) return BufferHandle(handles[0]) } override fun deleteAttributeArray(handle: BufferHandle) { GLES20.glDeleteBuffers(1, arrayOf(handle.value).toIntArray(), 0) } override fun enableAttributeArray(location: AttributeLocation) { GLES20.glEnableVertexAttribArray(location.value) } override fun disableAttributeArray(location: AttributeLocation) { GLES20.glDisableVertexAttribArray(location.value) } override var textureMinificationFilter: TextureMinificationFilter by EnumSetAndRememberDelegate(TextureMinificationFilter.NEAREST_MIPMAP_LINEAR, textureMinificationFilterMapping) { GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, it) } override var textureMagnificationFilter: TextureMagnificationFilter by EnumSetAndRememberDelegate(TextureMagnificationFilter.LINEAR, textureMagnificationFilterMapping) { GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, it) } override var textureWrapping: Pair<TextureWrapping, TextureWrapping> by EnumPairSetAndRememberDelegate(TextureWrapping.REPEAT to TextureWrapping.REPEAT, textureWrappingMapping) { GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, it.first) GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, it.second) } override fun generateTextures(count: Int): Array<TextureHandle> { val handles = IntArray(count) GLES20.glGenTextures(count, handles, 0) return handles.map { TextureHandle(it) }.toTypedArray() } override fun deleteTextures(count: Int, handles: Array<TextureHandle>) { GLES20.glDeleteTextures(count, handles.map { it.value }.toIntArray(), 0) } override fun bindTexture2D(handle: TextureHandle) { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, handle.value) } override fun textureImage2D(inputStream: InputStream, fileName: String, withMipmap: Boolean) { val bitmap = BitmapFactory.decodeStream(inputStream) GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, bitmap, 0) if (withMipmap) GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D) bitmap.recycle() } override fun activeTexture(index: Int) { require(index in 0..31) { "Texture index out of bounds: $index" } GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + index) } override fun drawTriangles(verticesCount: Int) { GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, verticesCount) } }
apache-2.0
a4b705e81eeaa2a402b0501f68155aa4
36.832579
152
0.797512
3.791837
false
false
false
false
manhong2112/kflang
kotlin/src/me/mnahong2112/kf/Parser.kt
1
3440
import java.util.* /* * 參照某天跟冰封提起的方法嘗試實現的一個解釋器 * 用VSCode寫的...鬼知道能不能用(攤手 */ // parser str to list, kotlin version /* def parse_value(buffer): if is_quote_by(buffer, '"'): return String(parse_string(buffer[1:-1])) s = ''.join(buffer) if s.startswith("0x"): return Number(int(s, 16)) if s.startswith("0b") and "." not in s: return Number(int(s, 2)) if s.startswith("0o") and "." not in s: return Number(int(s, 8)) try: return Number(int(s)) except Exception: pass try: return Number(float(s)) except Exception: pass return Symbol(s) */ class Reader<T>(val arr: Collection<T>): Iterable<T>, Iterator<T> { override fun hasNext(): Boolean { return index < length } override fun iterator(): Iterator<T> { return this } val length = arr.size var index = 0 override fun next(): T { index += 1 if (index < length) { return arr.elementAt(index) } else { throw IndexOutOfBoundsException() } } fun next(n: Int): ArrayList<T> { if (index < length) { val r = ArrayList<T>(n) var k = 0 for(i in index .. Math.min(index+n, length) - 1) { r[k++] = arr.elementAt(i) } index += n index = Math.min(index, length) return r } else { throw IndexOutOfBoundsException() } } } class Parser() { sealed class Token { data class String(val value: kotlin.String) : Token() data class Symbol(val value: kotlin.String) : Token() data class Number(val value: kotlin.Number) : Token() object OpenBracket : Token() object CloseBracket : Token() } fun valueParser(buffer: StringBuilder): Token { if (isQuoteBy(buffer, '"')) { return stringParser(buffer.substring(1, buffer.length - 1)) } val s = buffer.toString() when (true) { s.startsWith("0x") -> { return Token.Number(Integer.valueOf(s, 16)) } s.startsWith("0b") -> { return Token.Number(Integer.valueOf(s, 2)) } s.startsWith("0o") -> { return Token.Number(Integer.valueOf(s, 8)) } s[0].isDigit() -> { return Token.Number(Integer.valueOf(s)) } else -> { return Token.Symbol(s) } } } fun stringParser(s: String): Token.String { } fun isQuoteBy(buffer: StringBuilder, c: Char): Boolean { return buffer.length > 1 && buffer[0] == c && buffer[buffer.length - 1] == c } val FLAG_DEFAULT = 0 val FLAG_STRING = 1 val FLAG_ESCAPING_STRING = 2 val FLAG_COMMENT = 3 fun preProcess(expr: String): Stack<Token> { } fun parse(expr: String): Stack<Token> { val res = Expr() val last = Stack<Expr>() val R = Reader(preProcess(expr)) for(i in R) { when(i) { is Token.OpenBracket -> { val new = Stack<Token>() last.peek().push(new) last.push(new) } } } if type(obj) is str: if obj in "([{": new = [] last[-1].append(new) last.append(new) elif obj in ")]}": l = last.pop() else: last[-1].append(obj) else: last[-1].append(obj) return res } }
gpl-3.0
2a31584c6ed6361c6670712f48e02cec
22.746479
82
0.529953
3.549474
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/localization/LocalizationUtils.kt
2
1038
package abi44_0_0.expo.modules.localization import android.text.TextUtils import java.util.* import kotlin.collections.ArrayList val USES_IMPERIAL = listOf("US", "LR", "MM") val iSOCurrencyCodes: ArrayList<String> by lazy { Currency.getAvailableCurrencies().map { it.currencyCode as String } as ArrayList<String> } fun getLocaleNames(locales: ArrayList<Locale>) = locales.map { it.toLanguageTag() } as ArrayList fun getCountryCode(locale: Locale): String? { return runCatching { val country = locale.country if (TextUtils.isEmpty(country)) null else country }.getOrNull() } fun getSystemProperty(key: String): String { return runCatching { val systemProperties = Class.forName("android.os.SystemProperties") val get = systemProperties.getMethod("get", String::class.java) get.invoke(systemProperties, key) as String }.getOrNull() ?: "" } fun getCurrencyCode(locale: Locale): String? { return runCatching { val currency = Currency.getInstance(locale) currency?.currencyCode }.getOrNull() }
bsd-3-clause
402d16936abee00a70d52a87a163967b
28.657143
96
0.738921
4.038911
false
false
false
false
Prokky/AsciiPanelView
asciipanelview/src/main/java/com/prokkypew/asciipanelview/AsciiPanelView.kt
1
25196
package com.prokkypew.asciipanelview import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.MotionEvent import android.view.View import com.prokkypew.asciipanelview.AsciiPanelView.ColoredChar import com.prokkypew.asciipanelview.AsciiPanelView.OnCharClickedListener /** * An implementation of terminal view for old-school games. * Initially ported from JPanel AsciiPanel https://github.com/trystan/AsciiPanel to Android View * * @author Alexander Roman * * @property chars matrix of [ColoredChar] to be drawn on the panel * @property panelWidth width of panel in chars * @property panelHeight height of panel in chars * @property charColor color of chars to be drawn if not specified * @property bgColor color of char background to be drawn if not specified * @property cursorX position X of cursor to draw next char at * @property cursorY position Y of cursor to draw next char at * @property fontFamily font file name to use for drawing chars * @property onCharClickedListener interface of [OnCharClickedListener] to be called on panel char click */ class AsciiPanelView : View { companion object { /** * Default panel width in chars = 64 */ const val DEFAULT_PANEL_WIDTH: Int = 64 /** * Default panel height in chars = 27 */ const val DEFAULT_PANEL_HEIGHT: Int = 27 /** * Default char color = [Color.BLACK] */ const val DEFAULT_CHAR_COLOR: Int = Color.BLACK /** * Default char background color = [Color.WHITE] */ const val DEFAULT_BG_COLOR: Int = Color.WHITE /** * Default font */ const val DEFAULT_FONT: String = "font.ttf" private const val CLICK_ACTION_THRESHOLD: Int = 200 } private var tileWidth: Float = 0f private var tileHeight: Float = 0f private var textPaint: Paint = Paint() private var textBgPaint: Paint = Paint() private var widthCompensation: Float = 0f private var lastTouchDown: Long = 0 lateinit var chars: Array<Array<ColoredChar>> var onCharClickedListener: OnCharClickedListener? = null var panelWidth: Int = DEFAULT_PANEL_WIDTH var panelHeight: Int = DEFAULT_PANEL_HEIGHT var charColor: Int = DEFAULT_CHAR_COLOR var bgColor: Int = DEFAULT_BG_COLOR var cursorX: Int = 0 var cursorY: Int = 0 var fontFamily: String = DEFAULT_FONT /** *@constructor Default View constructors by context */ constructor(context: Context) : super(context) { init() } /** *@constructor Default View constructors by context and attributes */ constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { readAttributes(attrs) init() } /** *@constructor Default View constructors by context, attributes and default style */ constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { readAttributes(attrs) init() } private fun readAttributes(attrs: AttributeSet) { val ta = context.obtainStyledAttributes(attrs, R.styleable.AsciiPanelView) try { panelWidth = ta.getInt(R.styleable.AsciiPanelView_panelWidth, DEFAULT_PANEL_WIDTH) panelHeight = ta.getInt(R.styleable.AsciiPanelView_panelHeight, DEFAULT_PANEL_HEIGHT) charColor = ta.getColor(R.styleable.AsciiPanelView_defaultCharColor, DEFAULT_CHAR_COLOR) bgColor = ta.getColor(R.styleable.AsciiPanelView_defaultBackgroundColor, DEFAULT_BG_COLOR) if (ta.hasValue(R.styleable.AsciiPanelView_fontFamily)) fontFamily = ta.getString(R.styleable.AsciiPanelView_fontFamily) } finally { ta.recycle() } } private fun init() { chars = Array(panelWidth) { Array(panelHeight) { ColoredChar(' ', charColor, bgColor) } } val font = Typeface.create(Typeface.createFromAsset(context.assets, fontFamily), Typeface.BOLD) textPaint.typeface = font } override fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> lastTouchDown = System.currentTimeMillis() MotionEvent.ACTION_UP -> if (System.currentTimeMillis() - lastTouchDown < CLICK_ACTION_THRESHOLD) { val x = event.x.div(tileWidth).toInt() val y = event.y.div(tileHeight).toInt() onCharClickedListener?.onCharClicked(x, y, chars[x][y]) } } return true } override fun onSizeChanged(xNew: Int, yNew: Int, xOld: Int, yOld: Int) { super.onSizeChanged(xNew, yNew, xOld, yOld) tileWidth = xNew.toFloat() / panelWidth.toFloat() tileHeight = (yNew.toFloat()) / panelHeight.toFloat() textPaint.textSize = tileHeight val bounds = Rect() textPaint.getTextBounds("W", 0, 1, bounds) widthCompensation = (tileWidth - bounds.width()) / 2 } /** * @exclude */ override fun onDraw(canvas: Canvas) { for (w in 0 until panelWidth) { val posX = tileWidth * w for (h in 0 until panelHeight) { textBgPaint.color = chars[w][h].bgColor canvas.drawRect(posX, tileHeight * h, posX + tileWidth, tileHeight * h + tileHeight, textBgPaint) } } for (w in 0 until panelWidth) { val posX = tileWidth * w for (h in 0 until panelHeight) { textPaint.color = chars[w][h].charColor val posY = tileHeight * (h + 1) - textPaint.descent() canvas.drawText(chars[w][h].char.toString(), posX + widthCompensation, posY, textPaint) } } } /** * Sets the distance from the left new text will be written to. * @param cursorX the distance from the left new text should be written to * @return this for convenient chaining of method calls */ fun setCursorPosX(cursorX: Int): AsciiPanelView { if (cursorX < 0 || cursorX >= panelWidth) throw IllegalArgumentException("cursorX $cursorX must be in range [0,$panelWidth).") this.cursorX = cursorX return this } /** * Sets the distance from the top new text will be written to. * @param cursorY the distance from the top new text should be written to * @return this for convenient chaining of method calls */ fun setCursorPosY(cursorY: Int): AsciiPanelView { if (cursorY < 0 || cursorY >= panelHeight) throw IllegalArgumentException("cursorY $cursorY must be in range [0,$panelHeight).") this.cursorY = cursorY return this } /** * Sets the x and y position of where new text will be written to. The origin (0,0) is the upper left corner. * @param x the distance from the left new text should be written to * @param y the distance from the top new text should be written to * @return this for convenient chaining of method calls */ fun setCursorPosition(x: Int, y: Int): AsciiPanelView { setCursorPosX(x) setCursorPosY(y) return this } /** * Write a character to the cursor's position. * This updates the cursor's position. * @param character the character to write * @return this for convenient chaining of method calls */ fun writeChar(character: Char): AsciiPanelView { return writeChar(character, cursorX, cursorY, charColor, bgColor) } /** * Write a character to the cursor's position with the specified foreground color. * This updates the cursor's position but not the default foreground color. * @param character the character to write * @param charColor the foreground color or null to use the default * @return this for convenient chaining of method calls */ fun writeChar(character: Char, charColor: Int): AsciiPanelView { return writeChar(character, cursorX, cursorY, charColor, bgColor) } /** * Write a character to the cursor's position with the specified foreground and background colors. * This updates the cursor's position but not the default foreground or background colors. * @param character the character to write * @param charColor the foreground color or null to use the default * @param bgColor the background color or null to use the default * @return this for convenient chaining of method calls */ fun writeCharWithColor(character: Char, charColor: Int, bgColor: Int): AsciiPanelView { return writeChar(character, cursorX, cursorY, charColor, bgColor) } /** * Write a character to the specified position. * This updates the cursor's position. * @param character the character to write * @param x the distance from the left to begin writing from * @param y the distance from the top to begin writing from * @return this for convenient chaining of method calls */ fun writeCharWithPos(character: Char, x: Int, y: Int): AsciiPanelView { if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth)") if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)") return writeChar(character, x, y, charColor, bgColor) } /** * Write a character to the specified position with the specified foreground color. * This updates the cursor's position but not the default foreground color. * @param character the character to write * @param x the distance from the left to begin writing from * @param y the distance from the top to begin writing from * @param charColor the foreground color or null to use the default * @return this for convenient chaining of method calls */ fun writeChar(character: Char, x: Int, y: Int, charColor: Int): AsciiPanelView { if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth)") if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)") return writeChar(character, x, y, charColor, bgColor) } /** * Write a character to the specified position with the specified foreground and background colors. * This updates the cursor's position but not the default foreground or background colors. * @param character the character to write * @param x the distance from the left to begin writing from * @param y the distance from the top to begin writing from * @param charColor the foreground color or null to use the default * @param bgColor the background color or null to use the default * @return this for convenient chaining of method calls */ fun writeChar(character: Char, x: Int, y: Int, charColor: Int?, bgColor: Int?): AsciiPanelView { if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth)") if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)") var gColor = charColor var bColor = bgColor if (gColor == null) gColor = this.charColor if (bColor == null) bColor = this.bgColor chars[x][y] = ColoredChar(character, gColor, bColor) cursorX = x + 1 cursorY = y invalidate() return this } /** * Write a string to the cursor's position. * This updates the cursor's position. * @param string the string to write * @return this for convenient chaining of method calls */ fun writeString(string: String): AsciiPanelView { if (cursorX + string.length > panelWidth) throw IllegalArgumentException("cursorX + string.length() " + (cursorX + string.length) + " must be less than " + panelWidth + ".") return writeString(string, cursorX, cursorY, charColor, bgColor) } /** * Write a string to the cursor's position with the specified foreground color. * This updates the cursor's position but not the default foreground color. * @param string the string to write * @param charColor the foreground color or null to use the default * @return this for convenient chaining of method calls */ fun writeString(string: String, charColor: Int): AsciiPanelView { if (cursorX + string.length > panelWidth) throw IllegalArgumentException("cursorX + string.length() " + (cursorX + string.length) + " must be less than " + panelWidth + ".") return writeString(string, cursorX, cursorY, charColor, bgColor) } /** * Write a string to the cursor's position with the specified foreground and background colors. * This updates the cursor's position but not the default foreground or background colors. * @param string the string to write * @param charColor the foreground color or null to use the default * @param bgColor the background color or null to use the default * @return this for convenient chaining of method calls */ fun writeStringWithColor(string: String, charColor: Int, bgColor: Int): AsciiPanelView { if (cursorX + string.length > panelWidth) throw IllegalArgumentException("cursorX + string.length() " + (cursorX + string.length) + " must be less than " + panelWidth + ".") return writeString(string, cursorX, cursorY, charColor, bgColor) } /** * Write a string to the specified position. * This updates the cursor's position. * @param string the string to write * @param x the distance from the left to begin writing from * @param y the distance from the top to begin writing from * @return this for convenient chaining of method calls */ fun writeStringWithPos(string: String, x: Int, y: Int): AsciiPanelView { if (x + string.length > panelWidth) throw IllegalArgumentException("x + string.length() " + (x + string.length) + " must be less than " + panelWidth + ".") if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth)") if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)") return writeString(string, x, y, charColor, bgColor) } /** * Write a string to the specified position with the specified foreground color. * This updates the cursor's position but not the default foreground color. * @param string the string to write * @param x the distance from the left to begin writing from * @param y the distance from the top to begin writing from * @param charColor the foreground color or null to use the default * @return this for convenient chaining of method calls */ fun writeString(string: String, x: Int, y: Int, charColor: Int): AsciiPanelView { if (x + string.length > panelWidth) throw IllegalArgumentException("x + string.length() " + (x + string.length) + " must be less than " + panelWidth + ".") if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth)") if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)") return writeString(string, x, y, charColor, bgColor) } /** * Write a string to the specified position with the specified foreground and background colors. * This updates the cursor's position but not the default foreground or background colors. * @param string the string to write * @param x the distance from the left to begin writing from * @param y the distance from the top to begin writing from * @param charColor the foreground color or null to use the default * @param bgColor the background color or null to use the default * @return this for convenient chaining of method calls */ fun writeString(string: String, x: Int, y: Int, charColor: Int?, bgColor: Int?): AsciiPanelView { if (x + string.length > panelWidth) throw IllegalArgumentException("x + string.length() " + (x + string.length) + " must be less than " + panelWidth + ".") if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth).") if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight).") var gColor = charColor var bColor = bgColor if (gColor == null) gColor = this.charColor if (bColor == null) bColor = this.bgColor for (i in 0 until string.length) { writeChar(string[i], x + i, y, gColor, bColor) } return this } /** * Clear the entire screen to whatever the default background color is. * @return this for convenient chaining of method calls */ fun clear(): AsciiPanelView { return clearRect(' ', 0, 0, panelWidth, panelHeight, charColor, bgColor) } /** * Clear the entire screen with the specified character and whatever the default foreground and background colors are. * @param character the character to write * @return this for convenient chaining of method calls */ fun clear(character: Char): AsciiPanelView { return clearRect(character, 0, 0, panelWidth, panelHeight, charColor, bgColor) } /** * Clear the entire screen with the specified character and whatever the specified foreground and background colors are. * @param character the character to write * @param charColor the foreground color or null to use the default * @param bgColor the background color or null to use the default * @return this for convenient chaining of method calls */ fun clear(character: Char, charColor: Int, bgColor: Int): AsciiPanelView { return clearRect(character, 0, 0, panelWidth, panelHeight, charColor, bgColor) } /** * Clear the section of the screen with the specified character and whatever the default foreground and background colors are. * The cursor position will not be modified. * @param character the character to write * @param x the distance from the left to begin writing from * @param y the distance from the top to begin writing from * @param width the height of the section to clear * @param height the width of the section to clear * @return this for convenient chaining of method calls */ fun clearRect(character: Char, x: Int, y: Int, width: Int, height: Int): AsciiPanelView { if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth).") if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight).") if (width < 1) throw IllegalArgumentException("width $width must be greater than 0.") if (height < 1) throw IllegalArgumentException("height $height must be greater than 0.") if (x + width > panelWidth) throw IllegalArgumentException("x + width " + (x + width) + " must be less than " + (panelWidth + 1) + ".") if (y + height > panelHeight) throw IllegalArgumentException("y + height " + (y + height) + " must be less than " + (panelHeight + 1) + ".") return clearRect(character, x, y, width, height, charColor, bgColor) } /** * Clear the section of the screen with the specified character and whatever the specified foreground and background colors are. * @param character the character to write * @param x the distance from the left to begin writing from * @param y the distance from the top to begin writing from * @param width the height of the section to clear * @param height the width of the section to clear * @param charColor the foreground color or null to use the default * @param bgColor the background color or null to use the default * @return this for convenient chaining of method calls */ fun clearRect(character: Char, x: Int, y: Int, width: Int, height: Int, charColor: Int, bgColor: Int): AsciiPanelView { if (x < 0 || x >= panelWidth) throw IllegalArgumentException("x $x must be in range [0,$panelWidth)") if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)") if (width < 1) throw IllegalArgumentException("width $width must be greater than 0.") if (height < 1) throw IllegalArgumentException("height $height must be greater than 0.") if (x + width > panelWidth) throw IllegalArgumentException("x + width " + (x + width) + " must be less than " + (panelWidth + 1) + ".") if (y + height > panelHeight) throw IllegalArgumentException("y + height " + (y + height) + " must be less than " + (panelHeight + 1) + ".") val originalCursorX = cursorX val originalCursorY = cursorY for (xo in x until x + width) { for (yo in y until y + height) { writeChar(character, xo, yo, charColor, bgColor) } } cursorX = originalCursorX cursorY = originalCursorY return this } /** * Write a string to the center of the panel at the specified y position. * This updates the cursor's position. * @param string the string to write * @param y the distance from the top to begin writing from * @return this for convenient chaining of method calls */ fun writeCenter(string: String, y: Int): AsciiPanelView { if (string.length > panelWidth) throw IllegalArgumentException("string.length() " + string.length + " must be less than " + panelWidth + ".") if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)") val x = (panelWidth - string.length) / 2 return writeString(string, x, y, charColor, bgColor) } /** * Write a string to the center of the panel at the specified y position with the specified foreground color. * This updates the cursor's position but not the default foreground color. * @param string the string to write * @param y the distance from the top to begin writing from * @param charColor the foreground color or null to use the default * @return this for convenient chaining of method calls */ fun writeCenter(string: String, y: Int, charColor: Int): AsciiPanelView { if (string.length > panelWidth) throw IllegalArgumentException("string.length() " + string.length + " must be less than " + panelWidth + ".") if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight)") val x = (panelWidth - string.length) / 2 return writeString(string, x, y, charColor, bgColor) } /** * Write a string to the center of the panel at the specified y position with the specified foreground and background colors. * This updates the cursor's position but not the default foreground or background colors. * @param string the string to write * @param y the distance from the top to begin writing from * @param charColor the foreground color or null to use the default * @param bgColor the background color or null to use the default * @return this for convenient chaining of method calls */ fun writeCenter(string: String, y: Int, charColor: Int?, bgColor: Int?): AsciiPanelView { if (string.length > panelWidth) throw IllegalArgumentException("string.length() " + string.length + " must be less than " + panelWidth + ".") if (y < 0 || y >= panelHeight) throw IllegalArgumentException("y $y must be in range [0,$panelHeight).") var gColor = charColor var bColor = bgColor val x = (panelWidth - string.length) / 2 if (gColor == null) gColor = this.charColor if (bColor == null) bColor = this.bgColor for (i in 0 until string.length) { writeChar(string[i], x + i, y, gColor, bColor) } return this } /** * Interface to be called on panel character click */ interface OnCharClickedListener { /** * Callback, which is called when panel is clicked * @param x position of char clicked * @param y position of char clicked * @param char object of [ColoredChar] clicked */ fun onCharClicked(x: Int?, y: Int?, char: ColoredChar) } /** * Object for chars to print on the panel * @property char char to print * @property charColor color of the char * @property bgColor color of background of the char */ class ColoredChar(var char: Char, var charColor: Int, var bgColor: Int) }
apache-2.0
5f7630ce8d25cc415e0a0be7d3a6a4e7
44.646739
181
0.653913
4.653001
false
false
false
false
kiruto/debug-bottle
components/src/main/kotlin/com/exyui/android/debugbottle/components/crash/CrashBlock.kt
1
6853
package com.exyui.android.debugbottle.components.crash import android.util.Log import com.exyui.android.debugbottle.components.okhttp.HttpBlock import java.io.* import java.text.SimpleDateFormat import java.util.* /** * Created by yuriel on 9/13/16. */ internal data class CrashBlock( val time: String = "", val threadName: String = "", val threadId: String = "", val threadPriority: String = "", val threadGroup: String = "", val message: String = "", val cause: String = "", val stacktrace: String = "", val file: File? = null) { private val threadSb = StringBuilder() private val stacktraceSb = StringBuilder() val threadString: String get() = threadSb.toString() val stacktraceString: String get() = stacktraceSb.toString() init { flushString() } private fun flushString() { threadSb + KEY_TIME + KV + time + SEPARATOR threadSb + KEY_THREAD_NAME + KV + threadName + SEPARATOR threadSb + KEY_THREAD_ID + KV + threadId + SEPARATOR threadSb + KEY_THREAD_PRIORITY + KV + threadPriority + SEPARATOR threadSb + KEY_THREAD_GROUP + KV + threadGroup + SEPARATOR stacktraceSb + KEY_MESSAGE + KV + message + SEPARATOR if (cause.isNotEmpty()) { stacktraceSb + KEY_CAUSE + KV + cause + SEPARATOR } stacktraceSb + KEY_STACKTRACE + KV + stacktrace + SEPARATOR } private operator fun StringBuilder.plus(any: Any): StringBuilder = this.append(any) override fun toString(): String { return threadSb.toString() + stacktraceSb } companion object { internal val TAG = "CrashBlock" internal val NEW_INSTANCE = "newInstance: " internal val SEPARATOR = "\r\n" internal val KV = " = " internal val KEY_TIME = "time" internal val KEY_THREAD_NAME = "threadName" internal val KEY_THREAD_ID = "threadId" internal val KEY_THREAD_PRIORITY = "threadPriority" internal val KEY_THREAD_GROUP = "threadGroup" internal val KEY_MESSAGE = "message" internal val KEY_CAUSE = "cause" internal val KEY_STACKTRACE = "stacktrace" private val TIME_FORMATTER = SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.getDefault()) fun newInstance(thread: Thread, ex: Throwable): CrashBlock { val writer = StringWriter() val printer = PrintWriter(writer) ex.printStackTrace(printer) return CrashBlock( time = TIME_FORMATTER.format(System.currentTimeMillis()), threadId = "${thread.id}", threadName = thread.name, threadPriority = "${thread.priority}", threadGroup = thread.threadGroup.name, message = ex.message?: "", cause = ex.cause?.message?: "", stacktrace = writer.toString() ) } fun newInstance(file: File): CrashBlock { var reader: BufferedReader? = null var time: String = "" var threadName: String = "" var threadId: String = "" var threadPriority: String = "" var threadGroup: String = "" var message: String = "" var cause: String = "" var stacktrace: String = "" try { val input = InputStreamReader(FileInputStream(file), "UTF-8") reader = BufferedReader(input) var line: String? = reader.readLine() fun getStringInfo(): String { if (null == line || null == reader) return "" val split = line!!.split(HttpBlock.KV.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() if (split.size > 1) { val sb = StringBuilder(split[1]) sb/*.append(line!!.getValue())*/.append(HttpBlock.SEPARATOR) line = reader!!.readLine() // read until SEPARATOR appears while (line != null) { if (line != "") { sb.append(line).append(HttpBlock.SEPARATOR) } else { break } line = reader!!.readLine() } return sb.toString() } else return "" } while(line != null) { if (line!!.startsWith(KEY_TIME)) { time = line!!.getValue() } else if (line!!.startsWith(KEY_THREAD_NAME)) { threadName = line!!.getValue() } else if (line!!.startsWith(KEY_THREAD_ID)) { threadId = line!!.getValue() } else if (line!!.startsWith(KEY_THREAD_PRIORITY)) { threadPriority = line!!.getValue() } else if (line!!.startsWith(KEY_THREAD_GROUP)) { threadGroup = line!!.getValue() } else if (line!!.startsWith(KEY_MESSAGE)) { message = line!!.getValue() } else if (line!!.startsWith(KEY_CAUSE)) { cause = line!!.getValue() } else if (line!!.startsWith(KEY_STACKTRACE)) { stacktrace = getStringInfo() } line = reader.readLine() } reader.close() reader = null } catch(e: Exception) { Log.e(TAG, NEW_INSTANCE, e) } finally { try { if (reader != null) { reader.close() } } catch (e: Exception) { Log.e(TAG, NEW_INSTANCE, e) } } return CrashBlock( time = time, threadName = threadName, threadId = threadId, threadPriority = threadPriority, threadGroup = threadGroup, message = message, cause = cause, stacktrace = stacktrace, file = file ) } private fun String.getValue(): String { val kv = this.split(KV.toRegex()).dropLastWhile(String::isEmpty).toTypedArray() if (kv.size > 1) { return kv[1] } else { return "" } } } }
apache-2.0
93e7e2b23765e856eb9ceb69db716d84
35.457447
114
0.482416
5.391817
false
false
false
false