repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
DemonWav/IntelliJBukkitSupport
src/test/kotlin/platform/forge/ModsTomlValidationInspectionTest.kt
1
2477
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge import com.demonwav.mcdev.toml.platform.forge.inspections.ModsTomlValidationInspection import com.intellij.testFramework.fixtures.BasePlatformTestCase import org.intellij.lang.annotations.Language import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test @DisplayName("Mods Toml Validation Inspection Tests") class ModsTomlValidationInspectionTest : BasePlatformTestCase() { @BeforeEach override fun setUp() { super.setUp() } @AfterEach override fun tearDown() { super.tearDown() } private fun doTest(@Language("TOML") text: String) { myFixture.configureByText("mods.toml", text) myFixture.enableInspections(ModsTomlValidationInspection::class.java) myFixture.checkHighlighting() } @Test @DisplayName("Invalid Mod ID") fun invalidModId() { doTest( """ [[mods]] modId="<error descr="Mod ID is invalid">invalid id</error>" """ ) } @Test @DisplayName("Invalid Value Type") fun invalidValueType() { doTest( """ modLoader="javafml" showAsResourcePack=<error descr="Wrong value type, expected boolean">"true"</error> [[mods]] modId="examplemod" version=<error descr="Wrong value type, expected string">10</error> logoBlur=<error descr="Wrong value type, expected boolean">"true"</error> [[dependencies.examplemod]] modId="forge" versionRange=<error descr="Wrong value type, expected string">35</error> mandatory=true """ ) } @Test @DisplayName("Invalid Enum Value") fun invalidEnumValue() { doTest( """ [[mods]] modId="examplemod" [[dependencies.examplemod]] modId="forge" ordering="<error descr="Order BEFO does not exist">BEFO</error>" side="CLIENT" modId="minecraft" ordering="NONE" side="<error descr="Side UP does not exist">UP</error>" """ ) } @Test @DisplayName("Dependency For Undeclared Mod") fun dependencyForUndeclaredMod() { doTest( """ [[mods]] modId="examplemod1" [[mods]] modId="examplemod2" [[dependencies.<error descr="Mod examplemod3 is not declared in this file">examplemod3</error>]] """ ) } }
mit
equeim/tremotesf-android
app/src/main/kotlin/org/equeim/tremotesf/ui/utils/FabUtils.kt
1
1488
package org.equeim.tremotesf.ui.utils import android.view.Gravity import androidx.appcompat.widget.TooltipCompat import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.WindowInsetsCompat import androidx.core.view.updateLayoutParams import androidx.lifecycle.LifecycleOwner import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import org.equeim.tremotesf.R fun ExtendedFloatingActionButton.extendWhenImeIsHidden(insets: Flow<WindowInsetsCompat>, lifecycleOwner: LifecycleOwner) { val marginEndWhenImeIsVisible = resources.getDimensionPixelSize(R.dimen.fab_margin) insets .map { it.isVisible(WindowInsetsCompat.Type.ime()) } .distinctUntilChanged() .launchAndCollectWhenStarted(lifecycleOwner) { imeVisible -> isExtended = !imeVisible TooltipCompat.setTooltipText(this, if (imeVisible) text else null) updateLayoutParams<CoordinatorLayout.LayoutParams> { gravity = if (imeVisible) { Gravity.BOTTOM or Gravity.END } else { Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL } marginEnd = if (imeVisible) { marginEndWhenImeIsVisible } else { 0 } } } }
gpl-3.0
AngrySoundTech/CouponCodes3
core/src/main/kotlin/tech/feldman/couponcodes/core/permission/SimplePermissionHandler.kt
2
1767
/** * The MIT License * Copyright (c) 2015 Nicholas Feldman (AngrySoundTech) * <p/> * 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: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * 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 tech.feldman.couponcodes.core.permission import tech.feldman.couponcodes.core.entity.SimplePlayer import tech.feldman.couponcodes.core.util.LocaleHandler class SimplePermissionHandler { val name: String get() = "Nope" val isEnabled: Boolean get() = false fun hasPermission(player: SimplePlayer, node: String): Boolean { throw UnsupportedOperationException("No permission handler") } fun getGroups(player: SimplePlayer): Set<String> { throw UnsupportedOperationException(LocaleHandler.getString("No permission handler")) } }
mit
bozaro/git-as-svn
src/main/kotlin/svnserver/repository/VcsSupplier.kt
1
578
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.repository import java.io.IOException /** * Consumer with VCS exceptions. * * @author a.navrotskiy */ fun interface VcsSupplier<T> { @Throws(IOException::class) fun get(): T }
gpl-2.0
googlearchive/android-dynamic-features
features/native/src/androidTest/java/com/google/android/samples/dynamicfeatures/ondemand/NativeSampleActivityTest.kt
2
1444
/* * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.samples.dynamicfeatures.ondemand import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.android.samples.dynamicfeatures.ondemand.ccode.R import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class NativeSampleActivityTest { @get:Rule val rule = ActivityScenarioRule<NativeSampleActivity>(NativeSampleActivity::class.java) @Test fun launchNativeSampleActivity() { onView(withId(R.id.hello_textview)).check(matches(isDisplayed())) } }
apache-2.0
Ztiany/Repository
Kotlin/Kotlin-coroutineSample/src/main/java/com/bennyhuo/coroutines/sample/Ex09_CallbackToCoroutine.kt
2
1476
package com.bennyhuo.coroutines.sample import com.bennyhuo.coroutines.utils.log import kotlinx.coroutines.experimental.CompletableDeferred import kotlinx.coroutines.experimental.launch import kotlinx.coroutines.experimental.runBlocking import kotlin.concurrent.thread interface Callback { fun onSuccess(result: String) fun onError(e: Throwable) } /*传统异步编程如果重构为协程*/ fun loadAsync(callback: Callback) { thread { try { Thread.sleep(1000) if (Math.random() > 0.5f) { callback.onSuccess("HelloWorld") } else { throw IllegalStateException("This is a Demonstration Error.") } } catch (e: Throwable) { callback.onError(e) } } } suspend fun load(): String { val completableDeferred = CompletableDeferred<String>() loadAsync(object : Callback { override fun onSuccess(result: String) { completableDeferred.complete(result) } override fun onError(e: Throwable) { completableDeferred.completeExceptionally(e) } }) return completableDeferred.await() } fun main(args: Array<String>) = runBlocking { log(-1) launch { log(1) try { val result = load() log(2.1) log(result) } catch (e: Exception) { log(2.2) log(e) } log(3) }.join() log(-2) }
apache-2.0
Pixelhash/SignColors
src/main/kotlin/de/codehat/signcolors/daos/SignLocationDao.kt
1
2137
package de.codehat.signcolors.daos import com.j256.ormlite.jdbc.JdbcConnectionSource import de.codehat.signcolors.SignColors import de.codehat.signcolors.dao.Dao import de.codehat.signcolors.database.model.SignLocation import org.bukkit.Location import org.bukkit.block.Block class SignLocationDao(connectionSource: JdbcConnectionSource): Dao<SignLocation, Void>(connectionSource, SignLocation::class.java) { fun exists(block: Block): Boolean { return exists(block.location) } fun exists(location: Location): Boolean { with(location) { return exists(this.world.name, this.blockX, this.blockY, this.blockZ) } } fun exists(world: String, x: Int, y: Int, z: Int): Boolean { val queryBuilder = dao.queryBuilder() val where = queryBuilder.where() with(where) { eq("world", world) and() eq("x", x) and() eq("y", y) and() eq("z", z) } return dao.query(queryBuilder.prepare()).size >= 1 } fun create(block: Block) { create(block.location) } fun create(location: Location) { with(location) { create(this.world.name, this.blockX, this.blockY, this.blockZ) } } fun create(world: String, x: Int, y: Int, z: Int) { SignLocation(world, x, y, z).apply { dao.create(this) } } fun delete(block: Block) { delete(block.location) } fun delete(location: Location) { with(location) { delete(this.world.name, this.blockX, this.blockY, this.blockZ) } } fun delete(world: String, x: Int, y: Int, z: Int) { if (exists(world, x, y, z)) { val deleteBuilder = dao.deleteBuilder() val where = deleteBuilder.where() with(where) { eq("world", world) and() eq("x", x) and() eq("y", y) and() eq("z", z) } deleteBuilder.delete() } } }
gpl-3.0
vanita5/twittnuker
twittnuker/src/androidTest/kotlin/de/vanita5/twittnuker/util/TestCommons.kt
1
1138
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.util import android.content.res.Resources import android.support.annotation.RawRes inline fun <reified T> Resources.getJsonResource(@RawRes id: Int) = openRawResource(id).use { JsonSerializer.parse(it, T::class.java) }
gpl-3.0
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/gallery/ImageInfo.kt
1
1402
package org.wikipedia.gallery import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable class ImageInfo { var source = "" var captions = emptyMap<String, String>() @SerialName("short_name") private val shortName: String? = null @SerialName("descriptionshorturl") private val descriptionShortUrl: String? = null private val derivatives = emptyList<Derivative>() // Fields specific to video files: private val codecs: List<String>? = null private val name: String? = null @SerialName("descriptionurl") val commonsUrl = "" @SerialName("thumburl") val thumbUrl = "" @SerialName("thumbwidth") val thumbWidth = 0 @SerialName("thumbheight") val thumbHeight = 0 @SerialName("url") val originalUrl = "" val mime = "*/*" @SerialName("extmetadata") val metadata: ExtMetadata? = null val user = "" val timestamp = "" val size = 0 val width = 0 val height = 0 val bestDerivative get() = derivatives.lastOrNull() // TODO: make this smarter. @Serializable class Derivative { val src = "" private val type: String? = null private val title: String? = null private val shorttitle: String? = null private val width = 0 private val height = 0 private val bandwidth: Long = 0 } }
apache-2.0
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/SetupIntentResult.kt
1
543
package com.stripe.android import com.stripe.android.model.SetupIntent import kotlinx.parcelize.Parcelize /** * A model representing the result of a [SetupIntent] confirmation via [Stripe.confirmSetupIntent] * or handling of next actions via [Stripe.handleNextActionForSetupIntent]. */ @Parcelize data class SetupIntentResult internal constructor( override val intent: SetupIntent, @Outcome private val outcomeFromFlow: Int = 0, override val failureMessage: String? = null ) : StripeIntentResult<SetupIntent>(outcomeFromFlow)
mit
Xenoage/Zong
utils-kotlin/src/com/xenoage/utils/math/Math.kt
1
5483
package com.xenoage.utils.math import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin import kotlin.math.sqrt /** PI in float precision. */ val pi = PI.toFloat() /** Returns max, if this > max, min, if this < min, else this. */ fun Int.clamp(min: Int, max: Int): Int = when { this < min -> min this > max -> max else -> this } /** * Returns this, if this < min, else this. */ fun Int.clampMin(min: Int): Int = when { this < min -> min else -> this } /** Returns max, if this > max, min, if this < min, else this. */ fun Int.clampMax(max: Int): Int = when { this > max -> max else -> this } /** * Returns min, if x < min, else x. */ fun clampMin(x: Float, min: Float): Float { return if (x < min) min else x } /** * Returns max, if x > max, min, if x < min, else x. */ fun clamp(x: Double, min: Double, max: Double): Double { return if (x < min) min else if (x > max) max else x } /** * Returns min, if x < min, else x. */ fun clampMin(x: Double, min: Double): Double { return if (x < min) min else x } /** * Returns the greatest common divisor of the given numbers. */ fun gcd(n1: Int, n2: Int): Int { return if (n2 == 0) n1 else gcd(n2, n1 % n2) } /** * Returns the least common multiple of the given numbers. */ fun lcm(n1: Int, n2: Int): Int { var ret = gcd(n1, n2) ret = n1 * n2 / ret return ret } /** * Like the % operator, but also returns positive results for negative numbers. * E.g. -3 mod 4 = 1. */ fun mod(n: Int, mod: Int): Int { return (n % mod + mod) % mod } /** * Returns the lowest result of n modulo mod, where the result is still * greater or equal than min. Also negative values are allowed, and n may be * smaller than min. */ fun modMin(n: Int, mod: Int, min: Int): Int { var n = n if (mod < 1) throw IllegalArgumentException("mod must be > 0") while (n < min) n += mod while (n - mod >= min) n -= mod return n } /** * Rotates the given point by the given angle in degrees in counter * clockwise order around the origin and returnes the rotated point. */ fun rotate(p: Point2f, angle: Float): Point2f { if (angle == 0f) return p val rot = angle * PI / 180 val cos = cos(rot) val sin = sin(rot) val x = (p.x * +cos + p.y * +sin).toFloat() val y = (p.x * -sin + p.y * +cos).toFloat() return Point2f(x, y) } /** * Returns the position of the given cubic Bézier curve at the given t value * between 0 and 1. The Bézier curve is defined by the start and end point * (named p1 and p2) and two control points (named c1 and c2). */ fun bezier(p1: Point2f, p2: Point2f, c1: Point2f, c2: Point2f, t: Float) = Point2f((-p1.x + 3 * c1.x - 3 * c2.x + p2.x) * t * t * t + (3 * p1.x - 6 * c1.x + 3 * c2.x) * t * t + (-3 * p1.x + 3 * c1.x) * t + p1.x, (-p1.y + 3 * c1.y - 3 * c2.y + p2.y) * t * t * t + (3 * p1.y - 6 * c1.y + 3 * c2.y) * t * t + (-3 * p1.y + 3 * c1.y) * t + p1.y) /** * Linear interpolation between p1 and p2, at position t between t1 and t2, * where t1 is the coordinate of p1 and t2 is the coordinate of p2. */ fun interpolateLinear(p1: Float, p2: Float, t1: Float, t2: Float, t: Float): Float { return p1 + (p2 - p1) * (t - t1) / (t2 - t1) } /** * Linear interpolation between p1 and p2, at position t between t1 and t2, * where t1 is the coordinate of p1 and t2 is the coordinate of p2. */ fun interpolateLinear(points: LinearInterpolationPoints, t: Float): Float { return interpolateLinear(points.p1, points.p2, points.t1, points.t2, t) } class LinearInterpolationPoints(val p1: Float, val p2: Float, val t1: Float, val t2: Float) fun lowestPrimeNumber(number: Int): Int { var i = 2 while (i <= sqrt(number.toDouble())) { if (number % i == 0) return i i++ } return number } /** * Computes and returns a rotated rectangle, that encloses the given two * points with the given width. * This is shown here: * * <pre> * [0]---___ * / ---___ * p1 ---[1] _ _ * / / / * [3]---___ p2 / width * ---___ / / * ---[2] _/_ </pre> * * * The result is returned as four Point2f values as shown on the above * sketch. */ fun computeRectangleFromTo(p1: Point2f, p2: Point2f, width: Float): Array<Point2f> { // compute the line from p1 to p2 val p1Top2 = p2.sub(p1) // compute the line from p1 to [0] val p1To0 = Point2f(p1Top2.y, -p1Top2.x).normalize().scale(width / 2) // compute return values return arrayOf<Point2f>(p1.add(p1To0), p2.add(p1To0), p2.sub(p1To0), p1.sub(p1To0)) } /** * Returns -1 if the given value is negative, 1 if the given value is * positive, 0 otherwise. */ fun sign(v: Float) = if (v < 0) -1f else if (v > 0) 1f else 0f /** * Returns the minimum element of the given [Comparable]s. * If any element is null or if no element is given, null is returned. * If more then one element qualifies, the first one is returned. */ fun <T : Comparable<T>> minOrNull(vararg ts: T?): T? { var ret: T? = null for (t in ts) if (t == null) return null else if (ret == null || t < ret) ret = t return ret } /** * For 2 ^ x = number, returns x. For example. 2 ^ x = 8 returns 3. * When there is no integer solution, the next smaller integer is returned, * for example 2 ^ x = 5 returns 2. */ fun log2(number: Long): Int { if (number < 1) throw IllegalArgumentException("log2(x) = n for n < 1 not possible") var n: Long = 1 var ret = 0 while (n <= number) { n *= 2 ret++ } return ret - 1 }
agpl-3.0
sksamuel/scrimage
scrimage-tests/src/test/kotlin/com/sksamuel/scrimage/core/X11ColorlistGenerator.kt
1
532
package com.sksamuel.scrimage.core import java.nio.file.Files import java.nio.file.Paths fun main() { val file = "/etc/X11/rgb.txt" Files.newInputStream(Paths.get(file)).bufferedReader().readLines().map { line -> val tokens = line.replace("\\s{2,}".toRegex(), " ").trim().split(' ') val red = tokens[0] val green = tokens[1] val blue = tokens[2] val name = tokens.drop(3).joinToString(" ").trim() if (!name.contains(" ")) println("val $name = Color($red, $green, $blue)") } }
apache-2.0
AndroidX/androidx
room/room-runtime/src/main/java/androidx/room/util/FtsTableInfo.kt
3
6780
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.util import android.annotation.SuppressLint import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import androidx.sqlite.db.SupportSQLiteDatabase import java.util.ArrayDeque /** * A data class that holds the information about an FTS table. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) class FtsTableInfo( /** * The table name */ @JvmField val name: String, /** * The column names */ @JvmField val columns: Set<String>, /** * The set of options. Each value in the set contains the option in the following format: * <key, value>. */ @JvmField val options: Set<String> ) { constructor(name: String, columns: Set<String>, createSql: String) : this(name, columns, parseOptions(createSql)) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is FtsTableInfo) return false val that = other if (name != that.name) return false if (columns != that.columns) return false return options == that.options } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + (columns.hashCode()) result = 31 * result + (options.hashCode()) return result } override fun toString(): String { return ("FtsTableInfo{name='$name', columns=$columns, options=$options'}") } companion object { // A set of valid FTS Options private val FTS_OPTIONS = arrayOf( "tokenize=", "compress=", "content=", "languageid=", "matchinfo=", "notindexed=", "order=", "prefix=", "uncompress=" ) /** * Reads the table information from the given database. * * @param database The database to read the information from. * @param tableName The table name. * @return A FtsTableInfo containing the columns and options for the provided table name. */ @SuppressLint("SyntheticAccessor") @JvmStatic fun read(database: SupportSQLiteDatabase, tableName: String): FtsTableInfo { val columns = readColumns(database, tableName) val options = readOptions(database, tableName) return FtsTableInfo(tableName, columns, options) } private fun readColumns(database: SupportSQLiteDatabase, tableName: String): Set<String> { return buildSet { database.query("PRAGMA table_info(`$tableName`)").useCursor { cursor -> if (cursor.columnCount > 0) { val nameIndex = cursor.getColumnIndex("name") while (cursor.moveToNext()) { add(cursor.getString(nameIndex)) } } } } } private fun readOptions(database: SupportSQLiteDatabase, tableName: String): Set<String> { val sql = database.query( "SELECT * FROM sqlite_master WHERE `name` = '$tableName'" ).useCursor { cursor -> if (cursor.moveToFirst()) { cursor.getString(cursor.getColumnIndexOrThrow("sql")) } else { "" } } return parseOptions(sql) } /** * Parses FTS options from the create statement of an FTS table. * * This method assumes the given create statement is a valid well-formed SQLite statement as * defined in the [CREATE VIRTUAL TABLE * syntax diagram](https://www.sqlite.org/lang_createvtab.html). * * @param createStatement the "CREATE VIRTUAL TABLE" statement. * @return the set of FTS option key and values in the create statement. */ @VisibleForTesting @JvmStatic fun parseOptions(createStatement: String): Set<String> { if (createStatement.isEmpty()) { return emptySet() } // Module arguments are within the parenthesis followed by the module name. val argsString = createStatement.substring( createStatement.indexOf('(') + 1, createStatement.lastIndexOf(')') ) // Split the module argument string by the comma delimiter, keeping track of quotation // so that if the delimiter is found within a string literal we don't substring at the // wrong index. SQLite supports four ways of quoting keywords, see: // https://www.sqlite.org/lang_keywords.html val args = mutableListOf<String>() val quoteStack = ArrayDeque<Char>() var lastDelimiterIndex = -1 argsString.forEachIndexed { i, value -> when (value) { '\'', '"', '`' -> if (quoteStack.isEmpty()) { quoteStack.push(value) } else if (quoteStack.peek() == value) { quoteStack.pop() } '[' -> if (quoteStack.isEmpty()) { quoteStack.push(value) } ']' -> if (!quoteStack.isEmpty() && quoteStack.peek() == '[') { quoteStack.pop() } ',' -> if (quoteStack.isEmpty()) { args.add(argsString.substring(lastDelimiterIndex + 1, i).trim { it <= ' ' }) lastDelimiterIndex = i } } } // Add final argument. args.add(argsString.substring(lastDelimiterIndex + 1).trim()) // Match args against valid options, otherwise they are column definitions. val options = args.filter { arg -> FTS_OPTIONS.any { validOption -> arg.startsWith(validOption) } }.toSet() return options } } }
apache-2.0
mvarnagiris/expensius
billing/src/main/kotlin/com/mvcoding/billing/Security.kt
1
2746
/* * Copyright (C) 2016 Mantas Varnagiris. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package com.mvcoding.billing import android.util.Base64 import android.util.Log import java.security.* import java.security.spec.InvalidKeySpecException import java.security.spec.X509EncodedKeySpec object Security { private val TAG = "Billing/Security" private val KEY_FACTORY_ALGORITHM = "RSA" private val SIGNATURE_ALGORITHM = "SHA1withRSA" fun verifyPurchase(base64PublicKey: String, signedData: String, signature: String): Boolean { if (base64PublicKey.isEmpty() || signedData.isEmpty() || signature.isEmpty()) return false val key = generatePublicKey(base64PublicKey) return verify(key, signedData, signature) } private fun generatePublicKey(base64PublicKey: String): PublicKey { return try { val decodedKey = Base64.decode(base64PublicKey, Base64.DEFAULT) val keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM) keyFactory.generatePublic(X509EncodedKeySpec(decodedKey)) } catch (e: NoSuchAlgorithmException) { throw RuntimeException(e); } catch (e: InvalidKeySpecException) { throw IllegalArgumentException(e) } } private fun verify(publicKey: PublicKey, signedData: String, signature: String): Boolean { val signatureBytes: ByteArray try { signatureBytes = Base64.decode(signature, Base64.DEFAULT) } catch (e: IllegalArgumentException) { Log.e(TAG, "Base64 decoding failed.") return false } try { val sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey) sig.update(signedData.toByteArray()) if (!sig.verify(signatureBytes)) { Log.e(TAG, "Signature verification failed.") return false } return true } catch (e: NoSuchAlgorithmException) { Log.e(TAG, "NoSuchAlgorithmException.") } catch (e: InvalidKeyException) { Log.e(TAG, "Invalid key specification.") } catch (e: SignatureException) { Log.e(TAG, "Signature exception.") } return false } }
gpl-3.0
TeamWizardry/LibrarianLib
modules/albedo/src/main/kotlin/com/teamwizardry/librarianlib/albedo/shader/uniform/DoubleMatrices.kt
1
18961
package com.teamwizardry.librarianlib.albedo.shader.uniform import com.teamwizardry.librarianlib.core.bridge.IMatrix3f import com.teamwizardry.librarianlib.core.bridge.IMatrix4f import com.teamwizardry.librarianlib.core.util.mixinCast import com.teamwizardry.librarianlib.math.Matrix3d import com.teamwizardry.librarianlib.math.Matrix4d import net.minecraft.util.math.Matrix3f import net.minecraft.util.math.Matrix4f import org.lwjgl.opengl.GL40 /** * All the matrix uniform APIs represent the matrix in *row* major order. Internally they're transformed to column major * order, but this doesn't matter to you. * * The only time the major order matters is when you're asked to turn a flat array like `[a, b, c, d, e, f, g, h, i]` * into a matrix. The matrix itself *doesn't rotate.* The only difference is the order you string the values together * when you make them into a flat array. With that out of the way, here's what that looks like for a 3x3 matrix. * Keep in mind that these letters have nothing to do with the math, the only significance is the order they're stored * in memory. * * ``` * "Row major" * ⎡ a b c ⎤ * ⎢ d e f ⎥ * ⎣ g h i ⎦ * * "Column major" * ⎡ a d g ⎤ * ⎢ b e h ⎥ * ⎣ c f i ⎦ * ``` */ public sealed class DoubleMatrixUniform(name: String, glConstant: Int, public val columns: Int, public val rows: Int) : Uniform(name, glConstant) { protected var values: DoubleArray = DoubleArray(columns * rows) protected operator fun get(row: Int, column: Int): Double { return values[column * rows + row] } protected operator fun set(row: Int, column: Int, value: Double) { values[column * rows + row] = value } } public sealed class DoubleMatrixArrayUniform( name: String, glConstant: Int, length: Int, public val columns: Int, public val rows: Int ) : ArrayUniform(name, glConstant, length) { private val stride = columns * rows protected val values: DoubleArray = DoubleArray(length * stride) protected operator fun get(index: Int, row: Int, column: Int): Double { return values[index * stride + column * rows + row] } protected operator fun set(index: Int, row: Int, column: Int, value: Double) { values[index * stride + column * rows + row] = value } } public class DoubleMat2x2Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT2, columns = 2, rows = 2) { /** * ``` * ⎡ m00 m01 ⎤ * ⎣ m10 m11 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m10: Double, m11: Double, ) { this[0, 0] = m00; this[0, 1] = m01 this[1, 0] = m10; this[1, 1] = m11 } override fun push() { GL40.glUniformMatrix2dv(location, true, values) } } public class DoubleMat2x2ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT2, length, columns = 2, rows = 2) { /** * ``` * ⎡ m00 m01 ⎤ * ⎣ m10 m11 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m10: Double, m11: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01 this[index, 1, 0] = m10; this[index, 1, 1] = m11 } override fun push() { GL40.glUniformMatrix2dv(location, true, values) } } public class DoubleMat3x3Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT3, columns = 3, rows = 3) { /** * ``` * ⎡ m00 m01 m02 ⎤ * ⎢ m10 m11 m12 ⎥ * ⎣ m20 m21 m22 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m02: Double, m10: Double, m11: Double, m12: Double, m20: Double, m21: Double, m22: Double, ) { this[0, 0] = m00; this[0, 1] = m01; this[0, 2] = m02 this[1, 0] = m10; this[1, 1] = m11; this[1, 2] = m12 this[2, 0] = m20; this[2, 1] = m21; this[2, 2] = m22 } public fun set(matrix: Matrix3d) { this.set( matrix.m00, matrix.m01, matrix.m02, matrix.m10, matrix.m11, matrix.m12, matrix.m20, matrix.m21, matrix.m22, ) } public fun set(matrix: Matrix3f) { val imatrix = mixinCast<IMatrix3f>(matrix) this.set( imatrix.m00.toDouble(), imatrix.m01.toDouble(), imatrix.m02.toDouble(), imatrix.m10.toDouble(), imatrix.m11.toDouble(), imatrix.m12.toDouble(), imatrix.m20.toDouble(), imatrix.m21.toDouble(), imatrix.m22.toDouble(), ) } override fun push() { GL40.glUniformMatrix3dv(location, true, values) } } public class DoubleMat3x3ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT3, length, columns = 3, rows = 3) { /** * ``` * ⎡ m00 m01 m02 ⎤ * ⎢ m10 m11 m12 ⎥ * ⎣ m20 m21 m22 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m02: Double, m10: Double, m11: Double, m12: Double, m20: Double, m21: Double, m22: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01; this[index, 0, 2] = m02 this[index, 1, 0] = m10; this[index, 1, 1] = m11; this[index, 1, 2] = m12 this[index, 2, 0] = m20; this[index, 2, 1] = m21; this[index, 2, 2] = m22 } public fun set(index: Int, matrix: Matrix3d) { this.set( index, matrix.m00, matrix.m01, matrix.m02, matrix.m10, matrix.m11, matrix.m12, matrix.m20, matrix.m21, matrix.m22, ) } public fun set(index: Int, matrix: Matrix3f) { @Suppress("CAST_NEVER_SUCCEEDS") val imatrix = matrix as IMatrix3f this.set( index, imatrix.m00.toDouble(), imatrix.m01.toDouble(), imatrix.m02.toDouble(), imatrix.m10.toDouble(), imatrix.m11.toDouble(), imatrix.m12.toDouble(), imatrix.m20.toDouble(), imatrix.m21.toDouble(), imatrix.m22.toDouble(), ) } override fun push() { GL40.glUniformMatrix3dv(location, true, values) } } public class DoubleMat4x4Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT4, columns = 4, rows = 4) { /** * ``` * ⎡ m00 m01 m02 m03 ⎤ * ⎢ m10 m11 m12 m13 ⎥ * ⎢ m20 m21 m22 m23 ⎥ * ⎣ m30 m31 m32 m33 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m02: Double, m03: Double, m10: Double, m11: Double, m12: Double, m13: Double, m20: Double, m21: Double, m22: Double, m23: Double, m30: Double, m31: Double, m32: Double, m33: Double, ) { this[0, 0] = m00; this[0, 1] = m01; this[0, 2] = m02; this[0, 3] = m03 this[1, 0] = m10; this[1, 1] = m11; this[1, 2] = m12; this[1, 3] = m13 this[2, 0] = m20; this[2, 1] = m21; this[2, 2] = m22; this[2, 3] = m23 this[3, 0] = m30; this[3, 1] = m31; this[3, 2] = m32; this[3, 3] = m33 } public fun set(matrix: Matrix4d) { this.set( matrix.m00, matrix.m01, matrix.m02, matrix.m03, matrix.m10, matrix.m11, matrix.m12, matrix.m13, matrix.m20, matrix.m21, matrix.m22, matrix.m23, matrix.m30, matrix.m31, matrix.m32, matrix.m33, ) } public fun set(matrix: Matrix4f) { @Suppress("CAST_NEVER_SUCCEEDS") val imatrix = matrix as IMatrix4f this.set( imatrix.m00.toDouble(), imatrix.m01.toDouble(), imatrix.m02.toDouble(), imatrix.m03.toDouble(), imatrix.m10.toDouble(), imatrix.m11.toDouble(), imatrix.m12.toDouble(), imatrix.m13.toDouble(), imatrix.m20.toDouble(), imatrix.m21.toDouble(), imatrix.m22.toDouble(), imatrix.m23.toDouble(), imatrix.m30.toDouble(), imatrix.m31.toDouble(), imatrix.m32.toDouble(), imatrix.m33.toDouble(), ) } override fun push() { GL40.glUniformMatrix4dv(location, true, values) } } public class DoubleMat4x4ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT4, length, columns = 4, rows = 4) { /** * ``` * ⎡ m00 m01 m02 m03 ⎤ * ⎢ m10 m11 m12 m13 ⎥ * ⎢ m20 m21 m22 m23 ⎥ * ⎣ m30 m31 m32 m33 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m02: Double, m03: Double, m10: Double, m11: Double, m12: Double, m13: Double, m20: Double, m21: Double, m22: Double, m23: Double, m30: Double, m31: Double, m32: Double, m33: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01; this[index, 0, 2] = m02; this[index, 0, 3] = m03 this[index, 1, 0] = m10; this[index, 1, 1] = m11; this[index, 1, 2] = m12; this[index, 1, 3] = m13 this[index, 2, 0] = m20; this[index, 2, 1] = m21; this[index, 2, 2] = m22; this[index, 2, 3] = m23 this[index, 3, 0] = m30; this[index, 3, 1] = m31; this[index, 3, 2] = m32; this[index, 3, 3] = m33 } public fun set(index: Int, matrix: Matrix4d) { this.set( index, matrix.m00, matrix.m01, matrix.m02, matrix.m03, matrix.m10, matrix.m11, matrix.m12, matrix.m13, matrix.m20, matrix.m21, matrix.m22, matrix.m23, matrix.m30, matrix.m31, matrix.m32, matrix.m33, ) } public fun set(index: Int, matrix: Matrix4f) { val imatrix = mixinCast<IMatrix4f>(matrix) this.set( index, imatrix.m00.toDouble(), imatrix.m01.toDouble(), imatrix.m02.toDouble(), imatrix.m03.toDouble(), imatrix.m10.toDouble(), imatrix.m11.toDouble(), imatrix.m12.toDouble(), imatrix.m13.toDouble(), imatrix.m20.toDouble(), imatrix.m21.toDouble(), imatrix.m22.toDouble(), imatrix.m23.toDouble(), imatrix.m30.toDouble(), imatrix.m31.toDouble(), imatrix.m32.toDouble(), imatrix.m33.toDouble(), ) } override fun push() { GL40.glUniformMatrix4dv(location, true, values) } } public class DoubleMat2x3Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT2x3, columns = 2, rows = 3) { /** * ``` * ⎡ m00 m01 ⎤ * ⎢ m10 m11 ⎥ * ⎣ m20 m21 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m10: Double, m11: Double, m20: Double, m21: Double, ) { this[0, 0] = m00; this[0, 1] = m01 this[1, 0] = m10; this[1, 1] = m11 this[2, 0] = m20; this[2, 1] = m21 } override fun push() { GL40.glUniformMatrix2x3dv(location, true, values) } } public class DoubleMat2x3ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT2x3, length, columns = 2, rows = 3) { /** * ``` * ⎡ m00 m01 ⎤ * ⎢ m10 m11 ⎥ * ⎣ m20 m21 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m10: Double, m11: Double, m20: Double, m21: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01 this[index, 1, 0] = m10; this[index, 1, 1] = m11 this[index, 2, 0] = m20; this[index, 2, 1] = m21 } override fun push() { GL40.glUniformMatrix2x3dv(location, true, values) } } public class DoubleMat2x4Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT2x4, columns = 2, rows = 4) { /** * ``` * ⎡ m00 m01 ⎤ * ⎢ m10 m11 ⎥ * ⎢ m20 m21 ⎥ * ⎣ m30 m31 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m10: Double, m11: Double, m20: Double, m21: Double, m30: Double, m31: Double, ) { this[0, 0] = m00; this[0, 1] = m01 this[1, 0] = m10; this[1, 1] = m11 this[2, 0] = m20; this[2, 1] = m21 this[3, 0] = m30; this[3, 1] = m31 } override fun push() { GL40.glUniformMatrix2x4dv(location, true, values) } } public class DoubleMat2x4ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT2x4, length, columns = 2, rows = 4) { /** * ``` * ⎡ m00 m01 ⎤ * ⎢ m10 m11 ⎥ * ⎢ m20 m21 ⎥ * ⎣ m30 m31 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m10: Double, m11: Double, m20: Double, m21: Double, m30: Double, m31: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01 this[index, 1, 0] = m10; this[index, 1, 1] = m11 this[index, 2, 0] = m20; this[index, 2, 1] = m21 this[index, 3, 0] = m30; this[index, 3, 1] = m31 } override fun push() { GL40.glUniformMatrix2x4dv(location, true, values) } } public class DoubleMat3x2Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT3x2, columns = 3, rows = 2) { /** * ``` * ⎡ m00 m01 m02 ⎤ * ⎣ m10 m11 m12 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m02: Double, m10: Double, m11: Double, m12: Double, ) { this[0, 0] = m00; this[0, 1] = m01; this[0, 2] = m02; this[1, 0] = m10; this[1, 1] = m11; this[1, 2] = m12; } override fun push() { GL40.glUniformMatrix3x2dv(location, true, values) } } public class DoubleMat3x2ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT3x2, length, columns = 3, rows = 2) { /** * ``` * ⎡ m00 m01 m02 ⎤ * ⎢ m10 m11 m12 ⎥ * ⎣ m30 m31 m32 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m02: Double, m10: Double, m11: Double, m12: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01; this[index, 0, 2] = m02 this[index, 1, 0] = m10; this[index, 1, 1] = m11; this[index, 1, 2] = m12 } override fun push() { GL40.glUniformMatrix3x2dv(location, true, values) } } public class DoubleMat3x4Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT3x4, columns = 3, rows = 4) { /** * ``` * ⎡ m00 m01 m02 ⎤ * ⎢ m10 m11 m12 ⎥ * ⎢ m20 m21 m22 ⎥ * ⎣ m30 m31 m32 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m02: Double, m10: Double, m11: Double, m12: Double, m20: Double, m21: Double, m22: Double, m30: Double, m31: Double, m32: Double, ) { this[0, 0] = m00; this[0, 1] = m01; this[0, 2] = m02 this[1, 0] = m10; this[1, 1] = m11; this[1, 2] = m12 this[2, 0] = m20; this[2, 1] = m21; this[2, 2] = m22 this[3, 0] = m30; this[3, 1] = m31; this[3, 2] = m32 } override fun push() { GL40.glUniformMatrix3x4dv(location, true, values) } } public class DoubleMat3x4ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT3x4, length, columns = 3, rows = 4) { /** * ``` * ⎡ m00 m01 m02 ⎤ * ⎢ m10 m11 m12 ⎥ * ⎢ m20 m21 m22 ⎥ * ⎣ m30 m31 m32 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m02: Double, m10: Double, m11: Double, m12: Double, m20: Double, m21: Double, m22: Double, m30: Double, m31: Double, m32: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01; this[index, 0, 2] = m02 this[index, 1, 0] = m10; this[index, 1, 1] = m11; this[index, 1, 2] = m12 this[index, 2, 0] = m20; this[index, 2, 1] = m21; this[index, 2, 2] = m22 this[index, 3, 0] = m30; this[index, 3, 1] = m31; this[index, 3, 2] = m32 } override fun push() { GL40.glUniformMatrix3x4dv(location, true, values) } } public class DoubleMat4x2Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT4x2, columns = 4, rows = 2) { /** * ``` * ⎡ m00 m01 m02 m03 ⎤ * ⎣ m10 m11 m12 m13 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m02: Double, m03: Double, m10: Double, m11: Double, m12: Double, m13: Double, ) { this[0, 0] = m00; this[0, 1] = m01; this[0, 2] = m02; this[0, 3] = m03 this[1, 0] = m10; this[1, 1] = m11; this[1, 2] = m12; this[1, 3] = m13 } override fun push() { GL40.glUniformMatrix4x2dv(location, true, values) } } public class DoubleMat4x2ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT4x2, length, columns = 4, rows = 2) { /** * ``` * ⎡ m00 m01 m02 m03 ⎤ * ⎣ m10 m11 m12 m13 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m02: Double, m03: Double, m10: Double, m11: Double, m12: Double, m13: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01; this[index, 0, 2] = m02; this[index, 0, 3] = m03 this[index, 1, 0] = m10; this[index, 1, 1] = m11; this[index, 1, 2] = m12; this[index, 1, 3] = m13 } override fun push() { GL40.glUniformMatrix4x2dv(location, true, values) } } public class DoubleMat4x3Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT4x3, columns = 4, rows = 3) { /** * ``` * ⎡ m00 m01 m02 m03 ⎤ * ⎢ m10 m11 m12 m13 ⎥ * ⎣ m20 m21 m22 m23 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m02: Double, m03: Double, m10: Double, m11: Double, m12: Double, m13: Double, m20: Double, m21: Double, m22: Double, m23: Double, ) { this[0, 0] = m00; this[0, 1] = m01; this[0, 2] = m02; this[0, 3] = m03 this[1, 0] = m10; this[1, 1] = m11; this[1, 2] = m12; this[1, 3] = m13 this[2, 0] = m20; this[2, 1] = m21; this[2, 2] = m22; this[2, 3] = m23 } override fun push() { GL40.glUniformMatrix4x3dv(location, true, values) } } public class DoubleMat4x3ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT4x3, length, columns = 4, rows = 3) { /** * ``` * ⎡ m00 m01 m02 m03 ⎤ * ⎢ m10 m11 m12 m13 ⎥ * ⎣ m20 m21 m22 m23 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m02: Double, m03: Double, m10: Double, m11: Double, m12: Double, m13: Double, m20: Double, m21: Double, m22: Double, m23: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01; this[index, 0, 2] = m02; this[index, 0, 3] = m03 this[index, 1, 0] = m10; this[index, 1, 1] = m11; this[index, 1, 2] = m12; this[index, 1, 3] = m13 this[index, 2, 0] = m20; this[index, 2, 1] = m21; this[index, 2, 2] = m22; this[index, 2, 3] = m23 } override fun push() { GL40.glUniformMatrix4x3dv(location, true, values) } }
lgpl-3.0
Undin/intellij-rust
src/test/kotlin/org/rust/ide/refactoring/RsPromoteModuleToDirectoryActionTest.kt
3
4182
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.psi.PsiElement import org.rust.FileTree import org.rust.RsTestBase import org.rust.fileTree import org.rust.launchAction class RsPromoteModuleToDirectoryActionTest : RsTestBase() { fun `test works on file`() = checkAvailable( "foo.rs", fileTree { rust("foo.rs", "fn hello() {}") }, fileTree { dir("foo") { rust("mod.rs", "fn hello() {}") } } ) fun `test not available on mod rs`() = checkNotAvailable( "foo/mod.rs", fileTree { dir("foo") { rust("mod.rs", "") } } ) fun `test not available on library crate root`() = checkNotAvailable("lib.rs", fileTree { rust("lib.rs", "") } ) fun `test not available on main binary crate root`() = checkNotAvailable("main.rs", fileTree { rust("main.rs", "") } ) fun `test binary crate root 1`() = checkAvailable("bin/a.rs", fileTree { dir("bin") { rust("a.rs", "") } }, fileTree { dir("bin") { dir("a") { rust("main.rs", "") } } } ) fun `test binary crate root 2`() = checkNotAvailable("bin/a/main.rs", fileTree { dir("bin") { dir("a") { rust("main.rs", "") } } } ) fun `test bench crate root 1`() = checkAvailable("bench/a.rs", fileTree { dir("bench") { rust("a.rs", "") } }, fileTree { dir("bench") { dir("a") { rust("main.rs", "") } } } ) fun `test bench crate root 2`() = checkNotAvailable("bench/a/main.rs", fileTree { dir("bench") { dir("a") { rust("main.rs", "") } } } ) fun `test example crate root 1`() = checkAvailable("example/a.rs", fileTree { dir("example") { rust("a.rs", "") } }, fileTree { dir("example") { dir("a") { rust("main.rs", "") } } } ) fun `test example crate root 2`() = checkNotAvailable("example/a/main.rs", fileTree { dir("example") { dir("a") { rust("main.rs", "") } } } ) fun `test test crate root 1`() = checkAvailable("tests/a.rs", fileTree { dir("tests") { rust("a.rs", "") } }, fileTree { dir("tests") { dir("a") { rust("main.rs", "") } } } ) fun `test test crate root 2`() = checkNotAvailable("tests/a/main.rs", fileTree { dir("tests") { dir("a") { rust("main.rs", "") } } } ) private fun checkAvailable(target: String, before: FileTree, after: FileTree) { val file = before.create().psiFile(target) testActionOnElement(file, shouldBeEnabled = true) after.assertEquals(myFixture.findFileInTempDir(".")) } private fun checkNotAvailable(target: String, before: FileTree) { val file = before.create().psiFile(target) testActionOnElement(file, shouldBeEnabled = false) } private fun testActionOnElement(element: PsiElement, shouldBeEnabled: Boolean) { myFixture.launchAction( "Rust.RsPromoteModuleToDirectoryAction", CommonDataKeys.PSI_ELEMENT to element, shouldBeEnabled = shouldBeEnabled ) } }
mit
TeamWizardry/LibrarianLib
testcore/src/main/kotlin/com/teamwizardry/librarianlib/testcore/content/impl/TestEntityImpl.kt
1
3664
package com.teamwizardry.librarianlib.testcore.content.impl import com.teamwizardry.librarianlib.core.util.Client import com.teamwizardry.librarianlib.core.util.kotlin.threadLocal import com.teamwizardry.librarianlib.testcore.content.TestEntity import net.minecraft.entity.Entity import net.minecraft.entity.EntityDimensions import net.minecraft.entity.EntityPose import net.minecraft.entity.EntityType import net.minecraft.entity.player.PlayerEntity import net.minecraft.item.ItemStack import net.minecraft.nbt.NbtCompound import net.minecraft.network.Packet import net.minecraft.network.packet.s2c.play.EntitySpawnS2CPacket import net.minecraft.util.ActionResult import net.minecraft.util.Hand import net.minecraft.util.math.Box import net.minecraft.util.math.Vec3d import net.minecraft.world.World public open class TestEntityImpl(public val config: TestEntity, type: EntityType<TestEntityImpl>, world: World): Entity(type, world) { override fun collides(): Boolean { return true } override fun handleAttack(attacker: Entity): Boolean { val context = TestEntity.HitContext(this, attacker, attacker is PlayerEntity) config.hit.run(world.isClient, context) if (context.kill) { this.remove(RemovalReason.KILLED) return true } return false } override fun onPlayerCollision(player: PlayerEntity) { super.onPlayerCollision(player) } override fun hasNoGravity(): Boolean { return super.hasNoGravity() } override fun isGlowing(): Boolean { return config.enableGlow || (world.isClient && isClientHoldingItem()) || super.isGlowing() } private fun isClientHoldingItem(): Boolean { return false // return Client.minecraft.player?.getStackInHand(Hand.MAIN_HAND)?.item == config.spawnerItem || // Client.minecraft.player?.getStackInHand(Hand.OFF_HAND)?.item == config.spawnerItem } override fun tick() { super.tick() config.tick.run(this.world.isClient, TestEntity.TickContext(this)) } // TODO: forge patch? // override fun attackEntityFrom(source: DamageSource, amount: Float): Boolean { // config.attack.run(this.world.isClient, TestEntity.AttackContext(this, source, amount)) // return false // } override fun interactAt(player: PlayerEntity, hitPos: Vec3d, hand: Hand): ActionResult { config.rightClick.run(this.world.isClient, TestEntity.RightClickContext(this, player, hand, hitPos)) if (config.rightClick.exists) return ActionResult.SUCCESS return super.interactAt(player, hitPos, hand) } // miscellaneous boilerplate ======================================================================================= override fun createSpawnPacket(): Packet<*> { return EntitySpawnS2CPacket(this) } override fun readCustomDataFromNbt(tag: NbtCompound?) { } override fun writeCustomDataToNbt(tag: NbtCompound?) { } override fun initDataTracker() { } override fun getEyeHeight(pose: EntityPose?, dimensions: EntityDimensions?): Float { return 0f } public val relativeBoundingBox: Box get() { val size = this.getDimensions(EntityPose.STANDING) val width = size.width.toDouble() val height = size.height.toDouble() return Box( -width / 2, -height / 2, -width / 2, +width / 2, +height / 2, +width / 2 ) } override fun calculateBoundingBox(): Box { return relativeBoundingBox.offset(this.x, this.y, this.z) } }
lgpl-3.0
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/project/model/impl/UserDisabledFeaturesHolder.kt
3
3103
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.model.impl import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.util.io.systemIndependentPath import org.jdom.Element import org.rust.cargo.project.model.cargoProjects import org.rust.stdext.mapNotNullToSet import java.nio.file.Path import java.nio.file.Paths /** * A service needed to store [UserDisabledFeatures] separately from [CargoProjectsServiceImpl]. * Needed to make it possible to store them in different XML files ([Storage]s) */ @State(name = "CargoProjectFeatures", storages = [ Storage(StoragePathMacros.WORKSPACE_FILE, roamingType = RoamingType.DISABLED) ]) @Service class UserDisabledFeaturesHolder(private val project: Project) : PersistentStateComponent<Element> { private var loadedUserDisabledFeatures: Map<Path, UserDisabledFeatures> = emptyMap() fun takeLoadedUserDisabledFeatures(): Map<Path, UserDisabledFeatures> { val result = loadedUserDisabledFeatures loadedUserDisabledFeatures = emptyMap() return result } override fun getState(): Element { val state = Element("state") for (cargoProject in project.cargoProjects.allProjects) { val pkgToFeatures = cargoProject.userDisabledFeatures if (!pkgToFeatures.isEmpty()) { val cargoProjectElement = Element("cargoProject") cargoProjectElement.setAttribute("file", cargoProject.manifest.systemIndependentPath) for ((pkg, features) in pkgToFeatures.pkgRootToDisabledFeatures) { if (features.isNotEmpty()) { val packageElement = Element("package") packageElement.setAttribute("file", pkg.systemIndependentPath) for (feature in features) { val featureElement = Element("feature") featureElement.setAttribute("name", feature) packageElement.addContent(featureElement) } cargoProjectElement.addContent(packageElement) } } state.addContent(cargoProjectElement) } } return state } override fun loadState(state: Element) { val cargoProjects = state.getChildren("cargoProject") loadedUserDisabledFeatures = cargoProjects.associate { cargoProject -> val projectFile = cargoProject.getAttributeValue("file").orEmpty() val features = UserDisabledFeatures.of(cargoProject.getChildren("package").associate { pkg -> val packageFile = pkg.getAttributeValue("file").orEmpty() val features = pkg.getChildren("feature").mapNotNullToSet { it.getAttributeValue("name") } Paths.get(packageFile) to features }) Paths.get(projectFile) to features } } }
mit
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/alarm/AlarmActivity.kt
1
1717
package de.tum.`in`.tumcampusapp.component.ui.alarm import android.content.Intent import android.graphics.Color import android.os.Bundle import android.webkit.WebView import android.widget.TextView import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.other.generic.activity.BaseActivity import de.tum.`in`.tumcampusapp.component.ui.alarm.model.FcmNotification import de.tum.`in`.tumcampusapp.utils.DateTimeUtils import de.tum.`in`.tumcampusapp.utils.Utils /** * Activity to show any alarms */ class AlarmActivity : BaseActivity(R.layout.activity_alarmdetails) { private lateinit var mTitle: TextView private lateinit var mDescription: WebView private lateinit var mDate: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.mTitle = findViewById(R.id.alarm_title) this.mDescription = findViewById(R.id.alarm_description) this.mDate = findViewById(R.id.alarm_date) this.processIntent(intent) } override fun onNewIntent(intent: Intent) = this.processIntent(intent) private fun processIntent(intent: Intent) { val notification = intent.getSerializableExtra("info") as FcmNotification //FcmAlert alert = (FcmAlert) intent.getSerializableExtra("alert"); //Currently only has the silent flag, don't need it atm Utils.log(notification.toString()) this.mTitle.text = notification.title this.mDescription.loadDataWithBaseURL(null, notification.description, "text/html", "utf-8", null) this.mDescription.setBackgroundColor(Color.TRANSPARENT) this.mDate.text = DateTimeUtils.getDateString(notification.created) } }
gpl-3.0
google/dokka
core/testdata/format/java-layout-html/genericExtension.kt
2
174
package p class Some fun <T : Some> T.extFun() = "" val <T : Some> T.extVal get() = "" fun <T : Some?> T.nullableExtFun() = "" val <T : Some?> T.nullableExtVal get() = ""
apache-2.0
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/window/AwtWindow.desktop.kt
3
4838
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.window import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.node.Ref import androidx.compose.ui.util.UpdateEffect import androidx.compose.ui.util.makeDisplayable import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.swing.Swing import java.awt.Window /** * Compose [Window] obtained from [create]. The [create] block will be called * exactly once to obtain the [Window] to be composed, and it is also guaranteed to be invoked on * the UI thread (Event Dispatch Thread). * * Once [AwtWindow] leaves the composition, [dispose] will be called to free resources that * obtained by the [Window]. * * The [update] block can be run multiple times (on the UI thread as well) due to recomposition, * and it is the right place to set [Window] properties depending on state. * When state changes, the block will be reexecuted to set the new properties. * Note the block will also be ran once right after the [create] block completes. * * [AwtWindow] is needed for creating window's / dialog's that still can't be created with * the default Compose functions [androidx.compose.ui.window.Window] or * [androidx.compose.ui.window.Dialog]. * * @param visible Is [Window] visible to user. * Note that if we set `false` - native resources will not be released. They will be released * only when [Window] will leave the composition. * @param create The block creating the [Window] to be composed. * @param dispose The block to dispose [Window] and free native resources. Usually it is simple * `Window::dispose` * @param update The callback to be invoked after the layout is inflated. */ @OptIn(DelicateCoroutinesApi::class) @Suppress("unused") @Composable fun <T : Window> AwtWindow( visible: Boolean = true, create: () -> T, dispose: (T) -> Unit, update: (T) -> Unit = {} ) { val currentVisible by rememberUpdatedState(visible) val windowRef = remember { Ref<T>() } fun window() = windowRef.value!! DisposableEffect(Unit) { windowRef.value = create() onDispose { dispose(window()) } } UpdateEffect { val window = window() update(window) if (!window.isDisplayable) { window.makeDisplayable() } } val showJob = Ref<Job?>() SideEffect { // Why we dispatch showing in the next AWT tick: // // 1. // window.isVisible = true can be a blocking operation. // So we have to schedule it when we will be outside of Compose render frame. // // This happens in the when we create a modal dialog. // When we call `window.isVisible = true`, internally will be created a new AWT event loop, // which will handle all the future Swing events while dialog is visible. // // We can't use LaunchedEffect or rememberCoroutineScope, because they have a dispatcher // which is controlled by the Compose rendering loop (ComposeScene.dispatcher) and we // will block coroutine. // // 2. // We achieve the correct order when we open nested // window at the same time when we open the parent window. If we would show the window // immediately we will have this sequence in case of nested Window's: // // 1. window1.setContent // 2. window2.setContent // 3. window2.isVisible = true // 4. window1.isVisible = true // // So we will have a wrong active window (window1). showJob.value?.cancel() showJob.value = GlobalScope.launch(Dispatchers.Swing) { window().isVisible = currentVisible } } DisposableEffect(Unit) { onDispose { showJob.value?.cancel() window().isVisible = false } } }
apache-2.0
taigua/exercism
kotlin/pig-latin/src/main/kotlin/PigLatin.kt
1
651
/** * Created by Corwin on 2017/2/1. */ object PigLatin { private val rVowel = Regex("^([aeiou]|xr|yt)(.*)$") private val rConsonant = Regex("^([^aeiou]*qu|y|[^aeiou]+)(.*)$") fun translate(input: String) = input.trim().split(Regex("\\s+")).map { translateWord(it) }.joinToString(" ") private fun translateWord(input: String) : String { val mv = rVowel.matchEntire(input) val mc = rConsonant.matchEntire(input) return when { mv != null -> mv.groupValues[1] + mv.groupValues[2] + "ay" mc != null -> mc.groupValues[2] + mc.groupValues[1] + "ay" else -> "" } } }
mit
klazuka/intellij-elm
src/main/kotlin/org/elm/ide/structure/ElmBreadcrumbsProvider.kt
1
2062
package org.elm.ide.structure import com.intellij.lang.Language import com.intellij.psi.PsiElement import com.intellij.ui.breadcrumbs.BreadcrumbsProvider import org.elm.lang.core.ElmLanguage import org.elm.lang.core.psi.ElmPsiElement import org.elm.lang.core.psi.elements.* class ElmBreadcrumbsProvider : BreadcrumbsProvider { override fun getLanguages(): Array<Language> = LANGUAGES override fun acceptElement(element: PsiElement): Boolean { return element is ElmPsiElement && breadcrumbName(element) != null } override fun getElementInfo(element: PsiElement): String { return breadcrumbName(element as ElmPsiElement)!! } companion object { private val LANGUAGES: Array<Language> = arrayOf(ElmLanguage) fun breadcrumbName(e: ElmPsiElement): String? { return when (e) { is ElmLetInExpr -> "let … in" is ElmIfElseExpr -> "if ${e.expressionList.firstOrNull()?.text.truncate()} then" is ElmTypeAliasDeclaration -> e.name is ElmTypeDeclaration -> e.name is ElmTypeAnnotation -> "${e.referenceName} :" is ElmValueDeclaration -> when (val assignee = e.assignee) { is ElmFunctionDeclarationLeft -> assignee.name else -> assignee?.text?.truncate() } is ElmAnonymousFunctionExpr -> e.patternList.joinToString(" ", prefix = "\\") { it.text }.truncate() + " ->" is ElmFieldType -> e.name is ElmUnionVariant -> e.name is ElmCaseOfExpr -> "case ${e.expression?.text.truncate()} of" is ElmCaseOfBranch -> "${e.pattern.text.truncate()} ->" is ElmRecordExpr -> e.baseRecordIdentifier?.let { "{${it.text} | …}" } else -> null } } private fun String?.truncate(len: Int = 20) = when { this == null -> "…" length > len -> take(len) + "…" else -> this } } }
mit
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/system/libc/templates/errno.kt
1
3355
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.system.libc.templates import org.lwjgl.generator.* import org.lwjgl.system.libc.* val errno = "Errno".nativeClass(packageName = LIBC_PACKAGE) { nativeImport ( "<errno.h>" ) documentation = "Native bindings to errno.h." EnumConstant( "Standard error codes.", "EPERM".enum("Operation not permitted", 1), "ENOENT" enum "No such file or directory", "ESRCH" enum "No such process", "EINTR" enum "Interrupted function", "EIO" enum "I/O error", "ENXIO" enum "No such device or address", "E2BIG" enum "Argument list too long", "ENOEXEC" enum "Exec format error", "EBADF" enum "Bad file number", "ECHILD" enum "No spawned processes", "EAGAIN" enum "No more processes or not enough memory or maximum nesting level reached", "ENOMEM" enum "Not enough memory", "EACCES" enum "Permission denied", "EFAULT" enum "Bad address", "EBUSY".enum("Device or resource busy", 16), "EEXIST" enum "File exists", "EXDEV" enum "Cross-device link", "ENODEV" enum "No such device", "ENOTDIR" enum "Not a directory", "EISDIR" enum "Is a directory", "EINVAL" enum "Invalid argument", "ENFILE" enum "Too many files open in system", "EMFILE" enum "Too many open files", "ENOTTY" enum "Inappropriate I/O control operation", "EFBIG".enum("File too large", 27), "ENOSPC" enum "No space left on device", "ESPIPE" enum "Invalid seek", "EROFS" enum "Read-only file system", "EMLINK" enum "Too many links", "EPIPE" enum "Broken pipe", "EDOM" enum "Math argument", "ERANGE" enum "Result too large", "EDEADLK".enum("Resource deadlock would occur", 36), "EDEADLOCK".enum("Same as EDEADLK for compatibility with older Microsoft C versions", 36), "ENAMETOOLONG".enum("Filename too long", 38), "ENOLCK" enum "No locks available", "ENOSYS" enum "Function not supported", "ENOTEMPTY" enum "Directory not empty", "EILSEQ" enum "Illegal byte sequence", "STRUNCATE".enum("String was truncated", 80) ) macro(variable = true)..int( "errno", """ Returns the integer variable {@code errno}, which is set by system calls and some library functions in the event of an error to indicate what went wrong. Its value is significant only when the return value of the call indicated an error (i.e., -1 from most system calls; -1 or $NULL from most library functions); a function that succeeds is allowed to change errno. <b>LWJGL note</b>: This function cannot be used after another JNI call to a function, because the last error resets before that call returns. For this reason, LWJGL stores the last error in thread-local storage, you can use #getErrno() to access it. """ ) int( "getErrno", """ Returns the integer variable {@code errno}, which is set by system calls and some library functions in the event of an error to indicate what went wrong. Its value is significant only when the return value of the call indicated an error (i.e., -1 from most system calls; -1 or $NULL from most library functions); a function that succeeds is allowed to change errno. <b>LWJGL note</b>: This method has a meaningful value only after another LWJGL JNI call. It does not return {@code errno} from errno.h, but the thread-local error code stored by a previous JNI call. """ ) }
bsd-3-clause
noemus/kotlin-eclipse
kotlin-eclipse-ui-test/testData/wordSelection/selectPrevious/NonTraversableElement/0.kt
2
52
val property: String <caret>= "Non-traversable test"
apache-2.0
darkpaw/boss_roobot
src/org/darkpaw/ld33/Audio.kt
1
755
package org.darkpaw.ld33 import jquery.jq import org.w3c.dom.HTMLElement import org.w3c.dom.HTMLAudioElement import java.util.* import kotlin.browser.window import org.w3c.xhr.XMLHttpRequest class Audio(val world : GameWorld) { val sounds = HashMap<String, HTMLAudioElement>() init { } fun loadSample(name : String, path: String): HTMLAudioElement { val sound = window.document.createElement("audio") as HTMLAudioElement sound.src = path sound.loop = false sounds.set(name, sound) return sound } fun play(name : String){ val sound = sounds.get(name) as HTMLAudioElement //sound.pause() //sound.play() println("audio is muted - ${name}") } }
agpl-3.0
jrgonzalezg/OpenLibraryApp
app/src/main/kotlin/com/github/jrgonzalezg/openlibrary/features/books/data/database/BookEntity.kt
1
1022
/* * Copyright (C) 2017 Juan Ramón González González (https://github.com/jrgonzalezg) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jrgonzalezg.openlibrary.features.books.data.database import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey @Entity(tableName = "books") data class BookEntity(@PrimaryKey val key: String, val title: String, val description: String?, val covers: List<Int>?, val numberOfPages: Int?, val physicalFormat: String?)
apache-2.0
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt
1
3284
package com.baeldung.kotlin import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFalse class StructuralJumpUnitTest { @Test fun givenLoop_whenBreak_thenComplete() { var value = "" for (i in "hello_world") { if (i == '_') break value += i.toString() } assertEquals("hello", value) } @Test fun givenLoop_whenBreakWithLabel_thenComplete() { var value = "" outer_loop@ for (i in 'a'..'d') { for (j in 1..3) { value += "" + i + j if (i == 'b' && j == 1) break@outer_loop } } assertEquals("a1a2a3b1", value) } @Test fun givenLoop_whenContinue_thenComplete() { var result = "" for (i in "hello_world") { if (i == '_') continue result += i } assertEquals("helloworld", result) } @Test fun givenLoop_whenContinueWithLabel_thenComplete() { var result = "" outer_loop@ for (i in 'a'..'c') { for (j in 1..3) { if (i == 'b') continue@outer_loop result += "" + i + j } } assertEquals("a1a2a3c1c2c3", result) } @Test fun givenLambda_whenReturn_thenComplete() { var result = returnInLambda(); assertEquals("hello", result) } private fun returnInLambda(): String { var result = "" "hello_world".forEach { // non-local return directly to the caller if (it == '_') return result result += it.toString() } //this line won't be reached return result; } @Test fun givenLambda_whenReturnWithExplicitLabel_thenComplete() { var result = "" "hello_world".forEach lit@{ if (it == '_') { // local return to the caller of the lambda, i.e. the forEach loop return@lit } result += it.toString() } assertEquals("helloworld", result) } @Test fun givenLambda_whenReturnWithImplicitLabel_thenComplete() { var result = "" "hello_world".forEach { if (it == '_') { // local return to the caller of the lambda, i.e. the forEach loop return@forEach } result += it.toString() } assertEquals("helloworld", result) } @Test fun givenAnonymousFunction_return_thenComplete() { var result = "" "hello_world".forEach(fun(element) { // local return to the caller of the anonymous fun, i.e. the forEach loop if (element == '_') return result += element.toString() }) assertEquals("helloworld", result) } @Test fun givenAnonymousFunction_returnToLabel_thenComplete() { var result = "" run loop@{ "hello_world".forEach { // non-local return from the lambda passed to run if (it == '_') return@loop result += it.toString() } } assertEquals("hello", result) } }
gpl-3.0
google-developer-training/basic-android-kotlin-compose-training-lunch-tray
app/src/main/java/com/example/lunchtray/ui/EntreeMenuScreen.kt
1
1616
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.lunchtray.datasource.DataSource import com.example.lunchtray.model.MenuItem import com.example.lunchtray.model.MenuItem.EntreeItem @Composable fun EntreeMenuScreen( options: List<EntreeItem>, onCancelButtonClicked: () -> Unit, onNextButtonClicked: () -> Unit, onSelectionChanged: (EntreeItem) -> Unit, modifier: Modifier = Modifier ) { BaseMenuScreen( options = options, onCancelButtonClicked = onCancelButtonClicked, onNextButtonClicked = onNextButtonClicked, onSelectionChanged = onSelectionChanged as (MenuItem) -> Unit ) } @Preview @Composable fun EntreeMenuPreview(){ EntreeMenuScreen( options = DataSource.entreeMenuItems, onCancelButtonClicked = {}, onNextButtonClicked = {}, onSelectionChanged = {} ) }
apache-2.0
dropbox/Store
filesystem/src/main/java/com/dropbox/android/external/fs3/RecordPersister.kt
1
744
package com.dropbox.android.external.fs3 import com.dropbox.android.external.fs3.filesystem.FileSystem import kotlin.time.Duration import kotlin.time.ExperimentalTime @ExperimentalTime class RecordPersister( fileSystem: FileSystem, private val expirationDuration: Duration ) : SourcePersister(fileSystem), RecordProvider<Pair<String, String>> { override fun getRecordState(key: Pair<String, String>): RecordState { return sourceFileReader.getRecordState(key, expirationDuration) } companion object { fun create( fileSystem: FileSystem, expirationDuration: Duration ): RecordPersister { return RecordPersister(fileSystem, expirationDuration) } } }
apache-2.0
pdvrieze/darwinlib
src/main/java/nl/adaptivity/android/kotlin/bundle.kt
1
2994
@file:Suppress("NOTHING_TO_INLINE") package nl.adaptivity.android.kotlin import android.os.Build import android.os.Bundle import android.os.IBinder import android.os.Parcelable import android.support.annotation.RequiresApi import android.util.Size import android.util.SizeF import android.util.SparseArray import java.io.Serializable import java.util.ArrayList inline fun bundle(capacity:Int, configurator: (Bundle) -> Unit) = Bundle(capacity).apply(configurator) inline fun bundle(configurator: (Bundle) -> Unit) = Bundle().apply(configurator) operator fun Bundle.set(key:String, value: String) = putString(key, value) operator fun Bundle.set(key:String, value: Int) = putInt(key, value) @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2) inline operator fun Bundle.set(key:String, value: IBinder) = putBinder(key, value) inline operator fun Bundle.set(key:String, value: Bundle) = putBundle(key, value) inline operator fun Bundle.set(key:String, value: Byte) = putByte(key, value) inline operator fun Bundle.set(key:String, value: ByteArray) = putByteArray(key, value) inline operator fun Bundle.set(key:String, value: Char) = putChar(key, value) inline operator fun Bundle.set(key:String, value: CharArray) = putCharArray(key, value) inline operator fun Bundle.set(key:String, value: CharSequence) = putCharSequence(key, value) inline operator fun Bundle.set(key:String, value: Array<CharSequence>) = putCharSequenceArray(key, value) @JvmName("setCharsequenceArrayList") inline operator fun Bundle.set(key:String, value: ArrayList<CharSequence>) = putCharSequenceArrayList(key, value) inline operator fun Bundle.set(key:String, value: Float) = putFloat(key, value) inline operator fun Bundle.set(key:String, value: FloatArray) = putFloatArray(key, value) @JvmName("setIntegerArrayList") inline operator fun Bundle.set(key:String, value: ArrayList<Int>) = putIntegerArrayList(key, value) inline operator fun Bundle.set(key:String, value: Parcelable) = putParcelable(key, value) inline operator fun Bundle.set(key:String, value: Array<Parcelable>) = putParcelableArray(key, value) @JvmName("setParcelableArrayList") inline operator fun Bundle.set(key:String, value: ArrayList<out Parcelable>) = putParcelableArrayList(key, value) inline operator fun Bundle.set(key:String, value: Serializable) = putSerializable(key, value) inline operator fun Bundle.set(key:String, value: Short) = putShort(key, value) inline operator fun Bundle.set(key:String, value: ShortArray) = putShortArray(key, value) @RequiresApi(Build.VERSION_CODES.LOLLIPOP) inline operator fun Bundle.set(key:String, value: Size) = putSize(key, value) @RequiresApi(Build.VERSION_CODES.LOLLIPOP) inline operator fun Bundle.set(key:String, value: SizeF) = putSizeF(key, value) inline operator fun Bundle.set(key:String, value: SparseArray<out Parcelable>) = putSparseParcelableArray(key, value) @JvmName("setStringArrayList") inline operator fun Bundle.set(key:String, value: ArrayList<String>) = putStringArrayList(key, value)
lgpl-2.1
minecraft-dev/MinecraftDev
src/main/kotlin/platform/forge/creator/ForgeProjectCreator.kt
1
11580
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge.creator import com.demonwav.mcdev.creator.BaseProjectCreator import com.demonwav.mcdev.creator.BasicJavaClassStep import com.demonwav.mcdev.creator.CreatorStep import com.demonwav.mcdev.creator.LicenseStep import com.demonwav.mcdev.creator.buildsystem.BuildSystem import com.demonwav.mcdev.creator.buildsystem.gradle.BasicGradleFinalizerStep import com.demonwav.mcdev.creator.buildsystem.gradle.GradleBuildSystem import com.demonwav.mcdev.creator.buildsystem.gradle.GradleFiles import com.demonwav.mcdev.creator.buildsystem.gradle.GradleGitignoreStep import com.demonwav.mcdev.creator.buildsystem.gradle.GradleWrapperStep import com.demonwav.mcdev.creator.buildsystem.gradle.SimpleGradleSetupStep import com.demonwav.mcdev.platform.forge.util.ForgeConstants import com.demonwav.mcdev.platform.forge.util.ForgePackAdditionalData import com.demonwav.mcdev.platform.forge.util.ForgePackDescriptor import com.demonwav.mcdev.util.MinecraftVersions import com.demonwav.mcdev.util.SemanticVersion import com.demonwav.mcdev.util.runGradleTaskAndWait import com.demonwav.mcdev.util.runWriteTask import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption.CREATE import java.nio.file.StandardOpenOption.TRUNCATE_EXISTING import java.nio.file.StandardOpenOption.WRITE import java.util.Locale class Fg2ProjectCreator( private val rootDirectory: Path, private val rootModule: Module, private val buildSystem: GradleBuildSystem, private val config: ForgeProjectConfig, private val mcVersion: SemanticVersion ) : BaseProjectCreator(rootModule, buildSystem) { private fun setupMainClassStep(): BasicJavaClassStep { return createJavaClassStep(config.mainClass) { packageName, className -> Fg2Template.applyMainClass(project, buildSystem, config, packageName, className) } } override fun getSteps(): Iterable<CreatorStep> { val buildText = Fg2Template.applyBuildGradle(project, buildSystem, mcVersion) val propText = Fg2Template.applyGradleProp(project, config) val settingsText = Fg2Template.applySettingsGradle(project, buildSystem.artifactId) val files = GradleFiles(buildText, propText, settingsText) return listOf( SimpleGradleSetupStep( project, rootDirectory, buildSystem, files ), setupMainClassStep(), GradleWrapperStep(project, rootDirectory, buildSystem), McmodInfoStep(project, buildSystem, config), SetupDecompWorkspaceStep(project, rootDirectory), GradleGitignoreStep(project, rootDirectory), BasicGradleFinalizerStep(rootModule, rootDirectory, buildSystem), ForgeRunConfigsStep(buildSystem, rootDirectory, config, CreatedModuleType.SINGLE) ) } companion object { val FG_WRAPPER_VERSION = SemanticVersion.release(4, 10, 3) } } open class Fg3ProjectCreator( protected val rootDirectory: Path, protected val rootModule: Module, protected val buildSystem: GradleBuildSystem, protected val config: ForgeProjectConfig ) : BaseProjectCreator(rootModule, buildSystem) { private fun setupMainClassStep(): BasicJavaClassStep { return createJavaClassStep(config.mainClass) { packageName, className -> if (config.mcVersion >= MinecraftVersions.MC1_19) { Fg3Template.apply1_19MainClass(project, buildSystem, config, packageName, className) } else if (config.mcVersion >= MinecraftVersions.MC1_18) { Fg3Template.apply1_18MainClass(project, buildSystem, config, packageName, className) } else if (config.mcVersion >= MinecraftVersions.MC1_17) { Fg3Template.apply1_17MainClass(project, buildSystem, config, packageName, className) } else { Fg3Template.applyMainClass(project, buildSystem, config, packageName, className) } } } protected fun transformModName(modName: String?): String { modName ?: return "examplemod" return modName.lowercase(Locale.ENGLISH).replace(" ", "") } protected fun createGradleFiles(hasData: Boolean): GradleFiles<String> { val modName = transformModName(config.pluginName) val buildText = Fg3Template.applyBuildGradle(project, buildSystem, config, modName, hasData) val propText = Fg3Template.applyGradleProp(project) val settingsText = Fg3Template.applySettingsGradle(project, buildSystem.artifactId) return GradleFiles(buildText, propText, settingsText) } override fun getSteps(): Iterable<CreatorStep> { val files = createGradleFiles(hasData = true) val steps = mutableListOf( SimpleGradleSetupStep( project, rootDirectory, buildSystem, files ), setupMainClassStep(), GradleWrapperStep(project, rootDirectory, buildSystem), Fg3ProjectFilesStep(project, buildSystem, config), Fg3CompileJavaStep(project, rootDirectory), GradleGitignoreStep(project, rootDirectory), LicenseStep(project, rootDirectory, config.license, config.authors.joinToString(", ")), BasicGradleFinalizerStep(rootModule, rootDirectory, buildSystem), ForgeRunConfigsStep(buildSystem, rootDirectory, config, CreatedModuleType.SINGLE) ) if (config.mixins) { steps += MixinConfigStep(project, buildSystem) } return steps } companion object { val FG5_WRAPPER_VERSION = SemanticVersion.release(7, 4, 2) } } class Fg3Mc112ProjectCreator( rootDirectory: Path, rootModule: Module, buildSystem: GradleBuildSystem, config: ForgeProjectConfig ) : Fg3ProjectCreator(rootDirectory, rootModule, buildSystem, config) { private fun setupMainClassStep(): BasicJavaClassStep { return createJavaClassStep(config.mainClass) { packageName, className -> Fg2Template.applyMainClass(project, buildSystem, config, packageName, className) } } override fun getSteps(): Iterable<CreatorStep> { val files = createGradleFiles(hasData = false) return listOf( SimpleGradleSetupStep( project, rootDirectory, buildSystem, files ), setupMainClassStep(), GradleWrapperStep(project, rootDirectory, buildSystem), McmodInfoStep(project, buildSystem, config), Fg3CompileJavaStep(project, rootDirectory), GradleGitignoreStep(project, rootDirectory), BasicGradleFinalizerStep(rootModule, rootDirectory, buildSystem), ForgeRunConfigsStep(buildSystem, rootDirectory, config, CreatedModuleType.SINGLE) ) } } class SetupDecompWorkspaceStep( private val project: Project, private val rootDirectory: Path ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { indicator.text = "Setting up project" indicator.text2 = "Running Gradle task: 'setupDecompWorkspace'" runGradleTaskAndWait(project, rootDirectory) { settings -> settings.taskNames = listOf("setupDecompWorkspace") settings.vmOptions = "-Xmx2G" } indicator.text2 = null } } class McmodInfoStep( private val project: Project, private val buildSystem: BuildSystem, private val config: ForgeProjectConfig ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { val text = Fg2Template.applyMcmodInfo(project, buildSystem, config) val dir = buildSystem.dirsOrError.resourceDirectory runWriteTask { CreatorStep.writeTextToFile(project, dir, ForgeConstants.MCMOD_INFO, text) } } } class Fg3ProjectFilesStep( private val project: Project, private val buildSystem: BuildSystem, private val config: ForgeProjectConfig ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { val modsTomlText = Fg3Template.applyModsToml(project, buildSystem, config) val packDescriptor = ForgePackDescriptor.forMcVersion(config.mcVersion) ?: ForgePackDescriptor.FORMAT_3 val additionalData = ForgePackAdditionalData.forMcVersion(config.mcVersion) val packMcmetaText = Fg3Template.applyPackMcmeta(project, buildSystem.artifactId, packDescriptor, additionalData) val dir = buildSystem.dirsOrError.resourceDirectory runWriteTask { CreatorStep.writeTextToFile(project, dir, ForgeConstants.PACK_MCMETA, packMcmetaText) val meta = dir.resolve("META-INF") Files.createDirectories(meta) CreatorStep.writeTextToFile(project, meta, ForgeConstants.MODS_TOML, modsTomlText) } } } class Fg3CompileJavaStep( private val project: Project, private val rootDirectory: Path ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { indicator.text = "Setting up classpath" indicator.text2 = "Running Gradle task: 'compileJava'" runGradleTaskAndWait(project, rootDirectory) { settings -> settings.taskNames = listOf("compileJava") } indicator.text2 = null } } class MixinConfigStep( private val project: Project, private val buildSystem: BuildSystem ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { val text = Fg3Template.applyMixinConfigTemplate(project, buildSystem) val dir = buildSystem.dirsOrError.resourceDirectory runWriteTask { CreatorStep.writeTextToFile(project, dir, "${buildSystem.artifactId}.mixins.json", text) } } } enum class CreatedModuleType { SINGLE, MULTI } class ForgeRunConfigsStep( private val buildSystem: BuildSystem, private val rootDirectory: Path, private val config: ForgeProjectConfig, private val createdModuleType: CreatedModuleType ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { val gradleDir = rootDirectory.resolve(".gradle") Files.createDirectories(gradleDir) val hello = gradleDir.resolve(HELLO) val task = if (createdModuleType == CreatedModuleType.MULTI) { ":${buildSystem.artifactId}:genIntellijRuns" } else { "genIntellijRuns" } // We don't use `rootModule.name` here because Gradle will change the name of the module to match // what was set as the artifactId once it imports the project val moduleName = if (createdModuleType == CreatedModuleType.MULTI) { "${buildSystem.parentOrError.artifactId}.${buildSystem.artifactId}" } else { buildSystem.artifactId } val fileContents = moduleName + "\n" + config.mcVersion + "\n" + config.forgeVersion + "\n" + task Files.write(hello, fileContents.toByteArray(Charsets.UTF_8), CREATE, TRUNCATE_EXISTING, WRITE) } companion object { const val HELLO = ".hello_from_mcdev" } }
mit
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/net/social/ActorEndpoints.kt
1
5864
/* * Copyright (C) 2018 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.net.social import android.content.ContentValues import android.database.Cursor import android.net.Uri import org.andstatus.app.context.MyContext import org.andstatus.app.data.DbUtils import org.andstatus.app.data.MyProvider import org.andstatus.app.data.MyQuery import org.andstatus.app.database.table.ActorEndpointTable import org.andstatus.app.os.AsyncUtil import org.andstatus.app.util.UriUtils import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import java.util.function.Function class ActorEndpoints private constructor(private val myContext: MyContext, private val actorId: Long) { enum class State { EMPTY, ADDING, LAZYLOAD, LOADED } private val initialized: AtomicBoolean = AtomicBoolean() private val state: AtomicReference<State> = AtomicReference(if (actorId == 0L) State.EMPTY else State.LAZYLOAD) @Volatile private var map: Map<ActorEndpointType, List<Uri>> = emptyMap() fun add(type: ActorEndpointType, value: String?): ActorEndpoints { return add(type, UriUtils.fromString(value)) } fun add(type: ActorEndpointType, uri: Uri): ActorEndpoints { if (initialize().state.get() == State.ADDING) { map = add(map.toMutableMap(), type, uri) } return this } fun findFirst(type: ActorEndpointType?): Optional<Uri> { return if (type == ActorEndpointType.EMPTY) Optional.empty() else initialize().map.getOrDefault(type, emptyList()).stream().findFirst() } fun initialize(): ActorEndpoints { while (state.get() == State.EMPTY) { if (initialized.compareAndSet(false, true)) { map = ConcurrentHashMap() state.set(State.ADDING) } } while (state.get() == State.LAZYLOAD && myContext.isReady && AsyncUtil.nonUiThread) { if (initialized.compareAndSet(false, true)) { return load() } } return this } override fun toString(): String { return map.toString() } private fun load(): ActorEndpoints { val map: MutableMap<ActorEndpointType, List<Uri>> = ConcurrentHashMap() val sql = "SELECT " + ActorEndpointTable.ENDPOINT_TYPE + "," + ActorEndpointTable.ENDPOINT_INDEX + "," + ActorEndpointTable.ENDPOINT_URI + " FROM " + ActorEndpointTable.TABLE_NAME + " WHERE " + ActorEndpointTable.ACTOR_ID + "=" + actorId + " ORDER BY " + ActorEndpointTable.ENDPOINT_TYPE + "," + ActorEndpointTable.ENDPOINT_INDEX MyQuery.foldLeft(myContext, sql, map, { m: MutableMap<ActorEndpointType, List<Uri>> -> Function { cursor: Cursor -> add(m, ActorEndpointType.fromId(DbUtils.getLong(cursor, ActorEndpointTable.ENDPOINT_TYPE)), UriUtils.fromString(DbUtils.getString(cursor, ActorEndpointTable.ENDPOINT_URI))) } }) this.map = map state.set(State.LOADED) return this } fun save(actorId: Long) { if (actorId == 0L || !state.compareAndSet(State.ADDING, State.LOADED)) return val old = from(myContext, actorId).initialize() if (this == old) return MyProvider.delete(myContext, ActorEndpointTable.TABLE_NAME, ActorEndpointTable.ACTOR_ID, actorId) map.forEach { (key: ActorEndpointType, list: List<Uri>) -> for ((index, uri) in list.withIndex()) { val contentValues = ContentValues() contentValues.put(ActorEndpointTable.ACTOR_ID, actorId) contentValues.put(ActorEndpointTable.ENDPOINT_TYPE, key.id) contentValues.put(ActorEndpointTable.ENDPOINT_INDEX, index) contentValues.put(ActorEndpointTable.ENDPOINT_URI, uri.toString()) MyProvider.insert(myContext, ActorEndpointTable.TABLE_NAME, contentValues) } } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val endpoints = other as ActorEndpoints return map == endpoints.map } override fun hashCode(): Int { return Objects.hash(map) } companion object { fun from(myContext: MyContext, actorId: Long): ActorEndpoints { return ActorEndpoints(myContext, actorId) } private fun add(map: MutableMap<ActorEndpointType, List<Uri>>, type: ActorEndpointType, uri: Uri): MutableMap<ActorEndpointType, List<Uri>> { if (UriUtils.isEmpty(uri) || type == ActorEndpointType.EMPTY) return map val urisOld = map[type] if (urisOld == null) { map[type] = listOf(uri) } else { val uris: MutableList<Uri> = ArrayList(urisOld) if (!uris.contains(uri)) { uris.add(uri) map[type] = uris } } return map } } }
apache-2.0
esofthead/mycollab
mycollab-services/src/main/java/com/mycollab/module/file/service/AccountLogoService.kt
3
1011
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.file.service import com.mycollab.db.persistence.service.IService import java.awt.image.BufferedImage /** * @author MyCollab Ltd. * @since 4.1.2 */ interface AccountLogoService : IService { fun upload(uploadedUser: String, logo: BufferedImage, sAccountId: Int): String }
agpl-3.0
ajordens/lalas
jvm/sleepybaby-api-core/src/main/kotlin/org/jordens/sleepybaby/Model.kt
2
2254
/* * Copyright 2017 Adam Jordens * * 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.jordens.sleepybaby data class Feeding(val date: String, val time: String, val nursingDurationMinutes: Int, val milkType: String, val milkVolumeMilliliters: Int, val bodyTemperature: Double?, val diaperTypes: Collection<String>, val notes: String, val milkVolumeAverageMilliliters: Int? = null) // this is a hack data class FeedingSummaryByDay(val date: String, val numberOfFeedings: Int, val milkVolumeTotalMilliliters: Int, val diaperCount: Int, val nursingDurationMinutes: Int) { val milkVolumeAverageMilliliters = Math.round(milkVolumeTotalMilliliters / numberOfFeedings.toFloat()) // ounces are rounded to one decimal val milkVolumeAverageOunces = Math.round(milkVolumeAverageMilliliters / 29.5735 * 10) / 10.0 val milkVolumeTotalOunces = Math.round(milkVolumeTotalMilliliters / 29.5735 * 10) / 10.0 } data class FeedingSummaryByTime(val feeding: Int, val feedings: MutableList<Feeding>, val summaries: MutableMap<String, Summary>, var current: Boolean = false) data class Summary(val milkVolumeAverageMilliliters: Int, val timesOfDay: Collection<String>) data class Diaper(val date: String, val time: String, val diaperType: String) data class DiaperSummaryByDay(val date: String, val diaperCount: Int)
apache-2.0
esofthead/mycollab
mycollab-config/src/main/java/com/mycollab/configuration/EnDecryptHelper.kt
3
3017
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.configuration import com.mycollab.core.MyCollabException import org.jasypt.exceptions.EncryptionOperationNotPossibleException import org.jasypt.util.password.StrongPasswordEncryptor import org.jasypt.util.text.BasicTextEncryptor import java.io.UnsupportedEncodingException import java.net.URLDecoder import java.net.URLEncoder /** * Utility class to make encrypt and decrypt text * * @author MyCollab Ltd. * @since 1.0 */ object EnDecryptHelper { private val strongEncryptor = StrongPasswordEncryptor() private var basicTextEncryptor = BasicTextEncryptor() init { basicTextEncryptor.setPassword(SiteConfiguration.getEnDecryptPassword()) } /** * Encrypt password * * @param password * @return */ @JvmStatic fun encryptSaltPassword(password: String): String = strongEncryptor.encryptPassword(password) @JvmStatic fun encryptText(text: String): String = basicTextEncryptor.encrypt(text) @JvmStatic fun encryptTextWithEncodeFriendly(text: String): String = try { URLEncoder.encode(basicTextEncryptor.encrypt(text), "ASCII") } catch (e: UnsupportedEncodingException) { throw MyCollabException(e) } @JvmStatic fun decryptText(text: String): String = try { basicTextEncryptor.decrypt(text) } catch (e: EncryptionOperationNotPossibleException) { throw MyCollabException("Can not decrypt the text--$text---") } @JvmStatic fun decryptTextWithEncodeFriendly(text: String): String = try { basicTextEncryptor.decrypt(URLDecoder.decode(text, "ASCII")) } catch (e: Exception) { throw MyCollabException("Can not decrypt the text--$text---", e) } /** * Check password `inputPassword` match with * `expectedPassword` in case `inputPassword` encrypt * or not * * @param inputPassword * @param expectedPassword * @param isPasswordEncrypt flag to denote `inputPassword` is encrypted or not * @return */ @JvmStatic fun checkPassword(inputPassword: String, expectedPassword: String, isPasswordEncrypt: Boolean): Boolean = when { isPasswordEncrypt -> inputPassword == expectedPassword else -> strongEncryptor.checkPassword(inputPassword, expectedPassword) } }
agpl-3.0
world-federation-of-advertisers/panel-exchange-client
src/test/kotlin/org/wfanet/panelmatch/integration/DoubleBlindWorkflowTest.kt
1
2436
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.integration import com.google.common.truth.Truth.assertThat import com.google.protobuf.ByteString import com.google.protobuf.kotlin.toByteStringUtf8 import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.api.v2alpha.ExchangeWorkflow import org.wfanet.panelmatch.client.common.joinKeyAndIdOf import org.wfanet.panelmatch.client.exchangetasks.JoinKeyAndIdCollection import org.wfanet.panelmatch.client.exchangetasks.joinKeyAndIdCollection private val PLAINTEXT_JOIN_KEYS = joinKeyAndIdCollection { joinKeyAndIds += joinKeyAndIdOf("join-key-1".toByteStringUtf8(), "join-key-id-1".toByteStringUtf8()) joinKeyAndIds += joinKeyAndIdOf("join-key-2".toByteStringUtf8(), "join-key-id-2".toByteStringUtf8()) } private val EDP_COMMUTATIVE_DETERMINISTIC_KEY = "some-key".toByteStringUtf8() @RunWith(JUnit4::class) class DoubleBlindWorkflowTest : AbstractInProcessPanelMatchIntegrationTest() { override val exchangeWorkflowResourcePath: String = "config/double_blind_exchange_workflow.textproto" override val workflow: ExchangeWorkflow by lazy { readExchangeWorkflowTextProto(exchangeWorkflowResourcePath) } override val initialDataProviderInputs: Map<String, ByteString> = mapOf("edp-commutative-deterministic-key" to EDP_COMMUTATIVE_DETERMINISTIC_KEY) override val initialModelProviderInputs: Map<String, ByteString> = mapOf("mp-plaintext-join-keys" to PLAINTEXT_JOIN_KEYS.toByteString()) override fun validateFinalState( dataProviderDaemon: ExchangeWorkflowDaemonForTest, modelProviderDaemon: ExchangeWorkflowDaemonForTest ) { val blob = modelProviderDaemon.readPrivateBlob("mp-decrypted-join-keys") assertThat(blob).isNotNull() JoinKeyAndIdCollection.parseFrom(blob) // Does not throw. } }
apache-2.0
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/ads/dto/AdsLinkStatus.kt
1
1805
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.ads.dto import com.google.gson.annotations.SerializedName import kotlin.String /** * @param description - Reject reason * @param redirectUrl - URL * @param status - Link status */ data class AdsLinkStatus( @SerializedName("description") val description: String, @SerializedName("redirect_url") val redirectUrl: String, @SerializedName("status") val status: String )
mit
inorichi/tachiyomi-extensions
multisrc/overrides/madara/darkyurealm/src/DarkYueRealm.kt
1
1980
package eu.kanade.tachiyomi.extension.pt.darkyurealm import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.multisrc.madara.Madara import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.SManga import okhttp3.OkHttpClient import okhttp3.Request import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit class DarkYueRealm : Madara( "DarkYue Realm", "https://darkyuerealm.site/web", "pt-BR", SimpleDateFormat("dd 'de' MMMMM, yyyy", Locale("pt", "BR")) ) { // Override the id because the name was wrong. override val id: Long = 593455310609863709 override val client: OkHttpClient = super.client.newBuilder() .addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS)) .build() override fun mangaDetailsRequest(manga: SManga): Request { return GET(baseUrl + manga.url.removePrefix("/web"), headers) } override fun chapterListRequest(manga: SManga): Request { return GET(baseUrl + manga.url.removePrefix("/web"), headers) } // [...document.querySelectorAll('input[name="genre[]"]')] // .map(x => `Genre("${document.querySelector('label[for=' + x.id + ']').innerHTML.trim()}", "${x.value}")`) // .join(',\n') override fun getGenreList(): List<Genre> = listOf( Genre("Ação", "acao"), Genre("Aventura", "aventura"), Genre("Comédia", "comedia"), Genre("Drama", "drama"), Genre("Ecchi", "ecchi"), Genre("Escolar", "escolar"), Genre("Fantasia", "fantasia"), Genre("Harém", "harem"), Genre("Isekai", "isekai"), Genre("Romance", "romance"), Genre("School Life", "school-life"), Genre("Seinen", "seinen"), Genre("Shounen", "shounen"), Genre("Slice of Life", "slice-of-life"), Genre("Sobrenatural", "sobrenatural"), Genre("Vida Escolar", "vida-escolar") ) }
apache-2.0
ohmae/DmsExplorer
mobile/src/main/java/net/mm2d/dmsexplorer/settings/theme/PaletteUtils.kt
1
1016
/* * Copyright (c) 2018 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.settings.theme import android.graphics.Bitmap import androidx.palette.graphics.Palette import androidx.palette.graphics.Palette.Swatch /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ object PaletteUtils { fun selectLightSwatch(palette: Palette): Swatch? { return palette.vibrantSwatch ?: palette.mutedSwatch ?: palette.dominantSwatch } fun selectDarkSwatch(palette: Palette): Swatch? { return palette.darkVibrantSwatch ?: palette.darkMutedSwatch ?: palette.vibrantSwatch ?: palette.mutedSwatch ?: palette.dominantSwatch } } fun Bitmap.generatePalette(): Palette = Palette.Builder(this).generate() fun Bitmap.generatePalette(listener: (Palette?) -> Unit) { Palette.Builder(this).generate(listener) }
mit
Jire/Arrowhead
src/main/kotlin/org/jire/arrowhead/windows/User32.kt
1
1649
/* * Copyright 2016 Thomas Nappo * * 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.jire.arrowhead.windows import com.sun.jna.Native /** * Provides zero-garbage fast access to [GetKeyState]. */ object User32 { /** * Retrieves the status of the specified virtual key. * * The status specifies whether the key is up, down, or toggled * (on, off—alternating each time the key is pressed). * * @param nVirtKey A virtual key. If the desired virtual key is a letter or digit * (_A_ through _Z_, _a_ through _z_, or _0_ through _9_), `nVirtKey` must be set to the ASCII value * of that character. For other keys, it must be a virtual-key code. * * If a non-English keyboard layout is used, virtual keys with values in the range ASCII * _A_ through _Z_ and _0_ through _9_ are used to specify most of the character keys. For example, * for the German keyboard layout, the virtual key of value ASCII _O_ (_0x4F_) refers to the "o" key, * whereas _VK_OEM_1_ refers to the "o with umlaut" key. */ @JvmStatic external fun GetKeyState(nVirtKey: Int): Short init { Native.register("user32") } }
apache-2.0
JavaEden/Orchid
plugins/OrchidSourceDoc/src/main/kotlin/com/eden/orchid/sourcedoc/options/SourcedocConfigArchetype.kt
2
3324
package com.eden.orchid.sourcedoc.options import com.eden.common.util.EdenUtils import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.OptionArchetype import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.archetypes.ConfigArchetype import com.eden.orchid.sourcedoc.model.SourceDocModuleConfig import com.eden.orchid.sourcedoc.page.SourceDocModuleHomePage import com.eden.orchid.sourcedoc.page.SourceDocPage import javax.inject.Inject @Description( value = "Configure this item with additional options merged in from `config.yml`, from the object at " + "the archetype key. Dots in the key indicate sub-objects within the site config.", name = "Site Config" ) open class SourcedocPageConfigArchetype @Inject constructor( protected val context: OrchidContext ) : OptionArchetype { private val configArchetype = ConfigArchetype(context) override fun getOptions(target: Any, archetypeKey: String): Map<String, Any> { val actualArchetypeKeys = mutableListOf<String>() when (target) { is SourceDocModuleHomePage -> { actualArchetypeKeys.add("sourcedoc.$archetypeKey") actualArchetypeKeys.add("sourcedoc.moduleHome${archetypeKey.capitalize()}") actualArchetypeKeys.add("${target.moduleType}.$archetypeKey") actualArchetypeKeys.add("${target.moduleType}.moduleHome${archetypeKey.capitalize()}") if (target.moduleGroup.isNotBlank()) { actualArchetypeKeys.add("${target.moduleType}.${target.moduleGroup}${archetypeKey.capitalize()}") actualArchetypeKeys.add("${target.moduleType}.${target.moduleGroup}ModuleHome${archetypeKey.capitalize()}") } } is SourceDocPage<*> -> { actualArchetypeKeys.add("sourcedoc.$archetypeKey") actualArchetypeKeys.add("sourcedoc.source${archetypeKey.capitalize()}") actualArchetypeKeys.add("${target.moduleType}.$archetypeKey") actualArchetypeKeys.add("${target.moduleType}.source${archetypeKey.capitalize()}") actualArchetypeKeys.add("${target.moduleType}.${target.key}${archetypeKey.capitalize()}") if (target.moduleGroup.isNotBlank()) { actualArchetypeKeys.add("${target.moduleType}.${target.moduleGroup}${archetypeKey.capitalize()}") actualArchetypeKeys.add("${target.moduleType}.${target.moduleGroup}Source${archetypeKey.capitalize()}") actualArchetypeKeys.add("${target.moduleType}.${target.moduleGroup}${target.key.capitalize()}${archetypeKey.capitalize()}") } } is SourceDocModuleConfig -> { actualArchetypeKeys.add("sourcedoc") actualArchetypeKeys.add("sourcedoc.$archetypeKey") actualArchetypeKeys.add(target.moduleType) actualArchetypeKeys.add("${target.moduleType}.$archetypeKey") } else -> throw IllegalArgumentException("target of SourcedocPageConfigArchetype must be a Sourcedoc page or module") } return EdenUtils.merge(*actualArchetypeKeys.map { configArchetype.getOptions(target, it) }.toTypedArray()) } }
lgpl-3.0
alorma/TimelineView
timeline/src/main/java/com/alorma/timeline/painter/line/DashedLinePainter.kt
1
409
package com.alorma.timeline.painter.line import android.graphics.DashPathEffect import android.graphics.Paint class DashedLinePainter : LineStylePainter() { override fun paintLineStyle(paint: Paint) { paint.apply { val dashIntervals = floatArrayOf(25f, 20f) val dashPathEffect = DashPathEffect(dashIntervals, 1f) pathEffect = dashPathEffect } } }
apache-2.0
mitallast/netty-queue
src/main/java/org/mitallast/queue/transport/TransportController.kt
1
1193
package org.mitallast.queue.transport import com.google.inject.Inject import io.vavr.collection.HashMap import io.vavr.collection.Map import org.mitallast.queue.common.codec.Message import org.mitallast.queue.common.logging.LoggingService @Suppress("UNCHECKED_CAST") class TransportController @Inject constructor(logging: LoggingService) { private val logger = logging.logger() @Volatile private var handlerMap: Map<Class<*>, (Message) -> Unit> = HashMap.empty() @Synchronized fun <T : Message> registerMessageHandler( requestClass: Class<T>, handler: (T) -> Unit ) { handlerMap = handlerMap.put(requestClass, handler as ((Message) -> Unit)) } @Synchronized fun <T : Message> registerMessagesHandler( requestClass: Class<T>, handler: (Message) -> Unit ) { handlerMap = handlerMap.put(requestClass, handler) } fun <T : Message> dispatch(message: T) { val handler = handlerMap.getOrElse(message.javaClass, null) if (handler != null) { handler.invoke(message) } else { logger.error("handler not found for {}", message.javaClass) } } }
mit
luanalbineli/popularmovies
app/src/main/java/com/themovielist/home/HomeFragment.kt
1
5023
package com.themovielist.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.themovielist.R import com.themovielist.base.BaseFragment import com.themovielist.base.BasePresenter import com.themovielist.enums.RequestStatusDescriptor import com.themovielist.event.FavoriteMovieEvent import com.themovielist.home.fulllist.HomeFullMovieListActivity import com.themovielist.home.partiallist.HomeMovieListFragment import com.themovielist.injector.components.ApplicationComponent import com.themovielist.injector.components.DaggerFragmentComponent import com.themovielist.model.MovieModel import com.themovielist.model.view.HomeViewModel import com.themovielist.util.setDisplay import kotlinx.android.synthetic.main.home_fragment.* import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import timber.log.Timber import javax.inject.Inject class HomeFragment : BaseFragment<HomeContract.View>(), HomeContract.View { override val presenterImplementation: BasePresenter<HomeContract.View> get() = mPresenter override val viewImplementation: HomeContract.View get() = this @Inject lateinit var mPresenter: HomePresenter private lateinit var mPopularMovieListFragment: HomeMovieListFragment private lateinit var mTopRatedMovieListFragment: HomeMovieListFragment override fun onInjectDependencies(applicationComponent: ApplicationComponent) { DaggerFragmentComponent.builder() .applicationComponent(applicationComponent) .build() .inject(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) EventBus.getDefault().register(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.home_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) activity.setTitle(R.string.home) mPopularMovieListFragment = addFragmentIfNotExists(childFragmentManager, R.id.flHomePopularMovieContainer, POPULAR_MOVIE_LIST_TAG) { HomeMovieListFragment.getInstance() } mTopRatedMovieListFragment = addFragmentIfNotExists(childFragmentManager, R.id.flHomeTopRatedMovieContainer, RATING_MOVIE_LIST_TAG) { HomeMovieListFragment.getInstance() } rsvHomeMovieRequestStatus.setTryAgainClickListener { mPresenter.tryToLoadMoviesAgain() } tvHomeSeeMovieCast.setOnClickListener { mPresenter.seeAllPopularMovieList() } tvHomeSeeMovieListByRating.setOnClickListener { mPresenter.sellAllRatingMovieList() } val homeViewModel = savedInstanceState?.getParcelable(HOME_VIEW_MODEL_BUNDLE_KEY) ?: HomeViewModel() mPresenter.start(homeViewModel) } override fun showTopRatedMovies(topRatedList: List<MovieModel>) { mTopRatedMovieListFragment.addMovies(topRatedList) } override fun showErrorLoadingMovies(error: Throwable) { Timber.i(error, "An error occurred while tried to fecth the movies from HOME") rsvHomeMovieRequestStatus.setRequestStatus(RequestStatusDescriptor.ERROR, true) } override fun showLoadingIndicator() { rsvHomeMovieRequestStatus.setRequestStatus(RequestStatusDescriptor.LOADING, true) } override fun hideLoadingIndicatorAndShowMovies() { rsvHomeMovieRequestStatus.setRequestStatus(RequestStatusDescriptor.HIDDEN) rsvHomeMovieRequestStatus.setDisplay(false) flHomeMovieContainer.setDisplay(true) } override fun showPopularMovies(popularList: List<MovieModel>) { mPopularMovieListFragment.addMovies(popularList) } override fun seeAllMoviesSortedBy(homeMovieSort: Int) { val intent = HomeFullMovieListActivity.getIntent(activity, homeMovieSort) startActivity(intent) } override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) outState?.putParcelable(HOME_VIEW_MODEL_BUNDLE_KEY, mPresenter.viewModel) } override fun onStop() { super.onStop() mPresenter.onStop() EventBus.getDefault().unregister(this) } @Subscribe(threadMode = ThreadMode.MAIN) fun onFavoriteMovieEvent(favoriteMovieEvent: FavoriteMovieEvent) { mPresenter.onFavoriteMovieEvent(favoriteMovieEvent.movie, favoriteMovieEvent.favorite) } companion object { private const val POPULAR_MOVIE_LIST_TAG = "popular_movie_list_fragment" private const val RATING_MOVIE_LIST_TAG = "rating_movie_list_fragment" private const val HOME_VIEW_MODEL_BUNDLE_KEY = "home_view_model_bundle_key" fun getInstance(): HomeFragment { return HomeFragment() } } }
apache-2.0
jiaminglu/kotlin-native
backend.native/tests/codegen/controlflow/break1.kt
1
123
fun main(args: Array<String>) { loop@ while (true) { println("Body") break } println("Done") }
apache-2.0
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/cache/user/structure/DbStructureUser.kt
2
1986
package org.stepik.android.cache.user.structure import androidx.sqlite.db.SupportSQLiteDatabase object DbStructureUser { const val TABLE_NAME = "users" object Columns { const val ID = "id" const val PROFILE = "profile" const val FIRST_NAME = "first_name" const val LAST_NAME = "last_name" const val FULL_NAME = "full_name" const val SHORT_BIO = "short_bio" const val DETAILS = "details" const val AVATAR = "avatar" const val COVER = "cover" const val IS_PRIVATE = "is_private" const val IS_GUEST = "is_guest" const val IS_ORGANIZATION = "is_organization" const val SOCIAL_PROFILES = "social_profiles" const val KNOWLEDGE = "knowledge" const val KNOWLEDGE_RANK = "knowledge_rank" const val REPUTATION = "reputation" const val REPUTATION_RANK = "reputation_rank" const val CREATED_COURSES_COUNT = "created_courses_count" const val FOLLOWERS_COUNT = "followers_count" const val ISSUED_CERTIFICATES_COUNT = "issued_certificates_count" const val JOIN_DATE = "join_date" } fun createTable(db: SupportSQLiteDatabase) { db.execSQL(""" CREATE TABLE IF NOT EXISTS $TABLE_NAME ( ${DbStructureUser.Columns.ID} LONG PRIMARY KEY, ${DbStructureUser.Columns.PROFILE} LONG, ${DbStructureUser.Columns.FIRST_NAME} TEXT, ${DbStructureUser.Columns.LAST_NAME} TEXT, ${DbStructureUser.Columns.FULL_NAME} TEXT, ${DbStructureUser.Columns.SHORT_BIO} TEXT, ${DbStructureUser.Columns.DETAILS} TEXT, ${DbStructureUser.Columns.AVATAR} TEXT, ${DbStructureUser.Columns.IS_PRIVATE} INTEGER, ${DbStructureUser.Columns.IS_ORGANIZATION} INTEGER, ${DbStructureUser.Columns.JOIN_DATE} LONG ) """.trimIndent()) } }
apache-2.0
android/performance-samples
JankStatsSample/app/src/main/java/com/example/jankstats/JankAggregatorActivity.kt
1
4467
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jankstats import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.metrics.performance.PerformanceMetricsState import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import com.example.jankstats.databinding.ActivityJankLoggingBinding /** * This activity shows how to use JankStatsAggregator, a class in this test directory layered * on top of JankStats which aggregates the per-frame data. Instead of receiving jank data * per frame (which would happen by using JankStats directly), the report listener only * receives data when a report is issued, either when the activity goes into the background * or if JankStatsAggregator issues the report itself. */ // [START aggregator_activity_init] class JankAggregatorActivity : AppCompatActivity() { private lateinit var jankStatsAggregator: JankStatsAggregator // [START_EXCLUDE silent] private lateinit var binding: ActivityJankLoggingBinding private lateinit var navController: NavController private lateinit var appBarConfiguration: AppBarConfiguration // [START jank_aggregator_listener] private val jankReportListener = JankStatsAggregator.OnJankReportListener { reason, totalFrames, jankFrameData -> // A real app could do something more interesting, like writing the info to local storage and later on report it. Log.v( "JankStatsSample", "*** Jank Report ($reason), " + "totalFrames = $totalFrames, " + "jankFrames = ${jankFrameData.size}" ) jankFrameData.forEach { frameData -> Log.v("JankStatsSample", frameData.toString()) } } // [END jank_aggregator_listener] // [END_EXCLUDE] override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // [START_EXCLUDE] binding = ActivityJankLoggingBinding.inflate(layoutInflater) setContentView(binding.root) setupUi() // [END_EXCLUDE] // Metrics state holder can be retrieved regardless of JankStats initialization. val metricsStateHolder = PerformanceMetricsState.getHolderForHierarchy(binding.root) // Initialize JankStats with an aggregator for the current window. jankStatsAggregator = JankStatsAggregator(window, jankReportListener) // Add the Activity name as state. metricsStateHolder.state?.putState("Activity", javaClass.simpleName) } // [END aggregator_activity_init] // [START aggregator_tracking_enabled] override fun onResume() { super.onResume() jankStatsAggregator.jankStats.isTrackingEnabled = true } override fun onPause() { super.onPause() // Before disabling tracking, issue the report with (optionally) specified reason. jankStatsAggregator.issueJankReport("Activity paused") jankStatsAggregator.jankStats.isTrackingEnabled = false } // [END aggregator_tracking_enabled] override fun onSupportNavigateUp(): Boolean { return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } private fun setupUi() { setSupportActionBar(binding.toolbar) val navHostFragment = supportFragmentManager.findFragmentById(R.id.navigation_container) as NavHostFragment navController = navHostFragment.navController appBarConfiguration = AppBarConfiguration(navController.graph) setupActionBarWithNavController(navController, appBarConfiguration) } }
apache-2.0
hitoshura25/Media-Player-Omega-Android
auth_framework/src/main/java/com/vmenon/mpo/auth/framework/di/dagger/BiometricsModule.kt
1
524
package com.vmenon.mpo.auth.framework.di.dagger import android.app.Application import com.vmenon.mpo.auth.domain.biometrics.BiometricsManager import com.vmenon.mpo.auth.framework.biometrics.AndroidBiometricsManager import com.vmenon.mpo.system.domain.Logger import dagger.Module import dagger.Provides @Module object BiometricsModule { @Provides @BiometricsScope fun provideBiometricsManager(application: Application, logger: Logger): BiometricsManager = AndroidBiometricsManager(application, logger) }
apache-2.0
spkingr/50-android-kotlin-projects-in-100-days
ProjectSimpleViewGroup/app/src/main/java/me/liuqingwen/android/projectsimpleviewgroup/SimpleViewGroup.kt
1
16251
package me.liuqingwen.android.projectsimpleviewgroup import android.annotation.SuppressLint import android.annotation.TargetApi import android.content.Context import android.graphics.Rect import android.os.Build import android.util.AttributeSet import android.view.* import android.widget.Scroller import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.error import org.jetbrains.anko.info import org.jetbrains.anko.px2dip import kotlin.math.absoluteValue import kotlin.math.roundToInt /** * Created by Qingwen on 2018-1-25, project: ProjectSimpleViewGroup. * * @Author: Qingwen * @DateTime: 2018-1-25 * @Package: me.liuqingwen.android.projectsimpleviewgroup in project: ProjectSimpleViewGroup * * Notice: If you are using this class or file, check it and do some modification. */ fun View.rect2dipString(rect: Rect) = "Rect[left:${px2dip(rect.left)}, top:${px2dip(rect.top)}, right:${px2dip(rect.right)}, bottom:${px2dip(rect.bottom)} ]" class SimpleViewGroup:ViewGroup, AnkoLogger { constructor(context: Context):super(context) constructor(context: Context, attrs:AttributeSet):this(context, attrs, 0) constructor(context: Context, attrs:AttributeSet, defStyleAttr:Int):super(context, attrs, defStyleAttr) { this.setUp(attrs, defStyleAttr, 0) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs:AttributeSet, defStyleAttr:Int, defStyleRes:Int):super(context, attrs, defStyleAttr, defStyleRes) { this.setUp(attrs, defStyleAttr, defStyleRes) } private var pointerX = 0.0f private var pageCount = 0 private var pageSize = 0 private var pageHeight = 0 //For constrains in Y, if not set the y of the children(big size) will not be correctly positioned private val childRect by lazy(LazyThreadSafetyMode.NONE) { Rect() } private val containerRect by lazy(LazyThreadSafetyMode.NONE) { Rect() } private val scroller by lazy(LazyThreadSafetyMode.NONE) { Scroller(this.context)} private fun setUp(attrs:AttributeSet, defStyleAttr:Int, defStyleRes:Int) { /*val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SimpleViewGroup, defStyleAttr, defStyleRes) typedArray.recycle()*/ } override fun performClick(): Boolean { super.performClick() return true } override fun performLongClick(): Boolean { super.performLongClick() return true } override fun computeScroll() { super.computeScroll() if (this.scroller.computeScrollOffset()) { this.scrollTo(this.scroller.currX, 0) postInvalidate() } } private var interceptEventY = 0.0f private var interceptEventX = 0.0f override fun onInterceptTouchEvent(event: MotionEvent?): Boolean { if (event?.action == MotionEvent.ACTION_DOWN && event.edgeFlags != 0) { return false } //------------------------------------------------------------------------------------------ info("""--------------------------------------->onInterceptTouchEvent |Event: (x:${event?.x}, y:${event?.y}) |Type: (${event?.action}) """.trimMargin()) var isIntercepted = false when(event?.action) { MotionEvent.ACTION_DOWN -> { this.interceptEventX = event.x this.interceptEventY = event.y isIntercepted = ! this.scroller.isFinished } MotionEvent.ACTION_MOVE -> { if ((event.x - this.interceptEventX).absoluteValue >= ViewConfiguration.get(this.context).scaledTouchSlop.toFloat()) { isIntercepted = true //Important! Event loops: [InterceptEventDown->InterceptEventMove->TouchEventMove->TouchEventDown!!!] //So must update the x and y for touch event! //If here no updates, then you will jump when try to drag a button or other clickable ones to scroll! this.pointerX = event.x } } /*MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { error("----------------this only happens when event is intercepted--------------->onInterceptTouchEvent(Cancel? = ${event.action == MotionEvent.ACTION_CANCEL})") this.checkPerformClicks(event) } //event is intercepted!*/ else -> this.error("Not correctly handled yet!") } return isIntercepted } private fun checkPerformClicks(event: MotionEvent) { val touchSlop = ViewConfiguration.get(this.context).scaledTouchSlop.toFloat() val clickable = this.isClickable or this.isLongClickable if (event.action == MotionEvent.ACTION_UP && clickable && (event.x - this.interceptEventX).absoluteValue < touchSlop && (event.y - this.interceptEventY).absoluteValue < touchSlop) { if (this.isFocusable && this.isFocusableInTouchMode && ! this.isFocused) { this.requestFocus() } val longTouchSlop = ViewConfiguration.getLongPressTimeout() if (event.eventTime - event.downTime >= longTouchSlop && this.isLongClickable) { this.performLongClick() } else { this.performClick() } } } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent?): Boolean { //------------------------------------------------------------------------------------------ info("""--------------------------------------->onTouchEvent |Event: (x:${event?.x}, y:${event?.y}) |Type: (${event?.action}) """.trimMargin()) when(event?.action) { MotionEvent.ACTION_DOWN -> { error("-----------------this only happens when no children consume event------------->onTouchEvent") this.pointerX = event.x if (! this.scroller.isFinished) { this.scroller.abortAnimation() } return true //True for accepting touch events } MotionEvent.ACTION_MOVE -> { this.scrollBy((this.pointerX - event.x).roundToInt(), 0) this.pointerX = event.x } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { val delta = this.pointerX - event.x + this.scrollX when { delta < 0 -> this.scroller.startScroll(this.scrollX, this.scrollY, - this.scrollX, 0) delta > (this.pageCount - 1) * this.pageSize -> this.scroller.startScroll(this.scrollX, this.scrollY, (this.pageCount - 1) * this.pageSize - this.scrollX, 0) else -> { val isNext = delta.roundToInt() % this.pageSize >= this.pageSize / 2 val pageNumber = delta.roundToInt() / this.pageSize + if (isNext) 1 else 0 this.scroller.startScroll(this.scrollX, this.scrollY, pageNumber * this.pageSize - this.scrollX, 0) } } this.invalidate() //------------------------------------------------------------------------------------------ info("""---------------------------------------> |Group: [Padding: ($paddingLeft, $paddingTop, $paddingRight, $paddingBottom)] |Page:[PageCount: $pageCount, PageSize: $pageSize] |Scroll:[ScrollXY: ($scrollX, $scrollY)] """.trimMargin()) this.checkPerformClicks(event) } else -> { this.error("Not correctly handled yet!") } } return super.onTouchEvent(event) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { //Max width and height is used only for AT_MOST(WRAP_CONTENT) layout parameters var maxWidth = 0 var maxHeight = 0 for(index in 0 until this.childCount) { val child = this.getChildAt(index) if (child.visibility == View.GONE) { continue } super.measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0) //Must add the margins to the child space rect val layoutParams = child.layoutParams as MarginLayoutParams val childWidth = child.measuredWidth + layoutParams.leftMargin + layoutParams.rightMargin val childHeight = child.measuredHeight + layoutParams.topMargin + layoutParams.bottomMargin if (childHeight > maxHeight) { maxHeight = childHeight } if (childWidth > maxWidth) { maxWidth = childWidth } //------------------------------------------------------------------------------------------ info("""--------------------------------------->onMeasure |Child[$index]: [Margin: (${px2dip(layoutParams.leftMargin)}, ${px2dip(layoutParams.topMargin)}, ${px2dip(layoutParams.rightMargin)}, ${px2dip(layoutParams.bottomMargin)})] |Child[$index]: [Padding: (${px2dip(child.paddingLeft)}, ${px2dip(child.paddingTop)}, ${px2dip(child.paddingRight)}, ${px2dip(child.paddingBottom)})] |Child[$index]: [Width&Height: (${px2dip(child.width)} = ${px2dip(child.measuredWidth)}, ${px2dip(child.height)} = ${px2dip(child.measuredHeight)})] |Child[$index]: [Position: (${rect2dipString(childRect)})] """.trimMargin()) } maxWidth += this.paddingLeft + this.paddingRight maxHeight += this.paddingTop + this.paddingBottom //Check the mode of the ViewGroup size measurement val widthMode = MeasureSpec.getMode(widthMeasureSpec) val heightMode = MeasureSpec.getMode(widthMeasureSpec) var widthMeasured = MeasureSpec.getSize(widthMeasureSpec) var heightMeasured = MeasureSpec.getSize(widthMeasureSpec) //------------------------------------------------------------------------------------------ info("""--------------------------------------->onMeasure Result-> |MaxWidth: ${px2dip(maxWidth)}, MaxHeight: ${px2dip(maxHeight)} |MeasuredWidth: ${px2dip(widthMeasured)}, MeasuredHeight: ${px2dip(heightMeasured)} |WidthMode=$widthMode, HeightMode=$heightMode """.trimMargin()) if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) { widthMeasured = maxOf(maxWidth, widthMeasured, super.getSuggestedMinimumWidth()) heightMeasured = maxOf(maxHeight, heightMeasured, super.getSuggestedMinimumHeight()) } else if (widthMode == MeasureSpec.AT_MOST) { widthMeasured = maxOf(maxWidth, widthMeasured, super.getSuggestedMinimumWidth()) } else if (heightMode == MeasureSpec.AT_MOST) { heightMeasured = maxOf(maxHeight, heightMeasured, super.getSuggestedMinimumHeight()) } //Here the widthMeasured is the max one and is the page size(width) this.pageSize = widthMeasured this.pageHeight = heightMeasured widthMeasured = View.resolveSizeAndState(widthMeasured, widthMeasureSpec, 0) heightMeasured = View.resolveSizeAndState(heightMeasured, heightMeasureSpec, 0) super.setMeasuredDimension(widthMeasured, heightMeasured) } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { with(this.containerRect) { this.left = [email protected] this.top = [email protected] this.right = right - left - [email protected] this.bottom = bottom - top - [email protected] //------------------------------------------------------------------------------------------ info("--------------------------------------->Height:${px2dip(this.bottom)}-${px2dip(this.top)}=${px2dip(this.bottom - this.top)},Padding[$paddingLeft,$paddingTop,$paddingRight,$paddingBottom]") } this.pageCount = 0 for (index in 0 until this.childCount) { val child = this.getChildAt(index) if (child.visibility == View.GONE) { continue } val layoutParams = child.layoutParams as LayoutParams val gravity = layoutParams.gravity val childWidth = minOf(child.measuredWidth + layoutParams.leftMargin + layoutParams.rightMargin, this.pageSize) //Cannot overflow the page width! val childHeight = minOf(child.measuredHeight + layoutParams.topMargin + layoutParams.bottomMargin, this.pageHeight) Gravity.apply(gravity, childWidth, childHeight, this.containerRect, this.childRect) val l = this.childRect.left + layoutParams.leftMargin + this.pageCount * this.pageSize val t = this.childRect.top + layoutParams.topMargin val r = this.childRect.right - layoutParams.rightMargin + this.pageCount * this.pageSize val b = this.childRect.bottom - layoutParams.bottomMargin child.layout(l, t, r, b) //------------------------------------------------------------------------------------------ info("""--------------------------------------->OnLayout |Child[$index]: [Gravity: $gravity = ${gravity.toString(16)}] |Child[$index]: [Margin: (${px2dip(layoutParams.leftMargin)}, ${px2dip(layoutParams.topMargin)}, ${px2dip(layoutParams.rightMargin)}, ${px2dip(layoutParams.bottomMargin)})] |Child[$index]: [Padding: (${px2dip(child.paddingLeft)}, ${px2dip(child.paddingTop)}, ${px2dip(child.paddingRight)}, ${px2dip(child.paddingBottom)})] |Child[$index]: [Width: (${px2dip(child.width)} = ${px2dip(child.measuredWidth)}, ${px2dip(child.height)} = ${px2dip(child.measuredHeight)})] |Child[$index]: [Position: (${rect2dipString(childRect)})] """.trimMargin()) this.pageCount ++ } } //Add custom layout parameters for all children override fun generateDefaultLayoutParams() = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) override fun generateLayoutParams(attrs: AttributeSet?) = LayoutParams(this.context, attrs) override fun generateLayoutParams(p: ViewGroup.LayoutParams?) = LayoutParams(p) override fun checkLayoutParams(p: ViewGroup.LayoutParams?) = p is LayoutParams //The custom class name can be the same with ViewGroup.LayoutParams inner class LayoutParams:MarginLayoutParams { var gravity = -1 constructor(context: Context, attrs: AttributeSet?):super(context, attrs) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SimpleViewGroup_Layout) this.gravity = typedArray.getInt(R.styleable.SimpleViewGroup_Layout_android_layout_gravity, -1) typedArray.recycle() } constructor(width: Int, height: Int):super(width, height) constructor(source: MarginLayoutParams):super(source) constructor(source: ViewGroup.LayoutParams?):super(source) constructor(source: LayoutParams):super(source) { this.gravity = source.gravity } constructor(width: Int, height: Int, gravity: Int):super(width, height) { this.gravity = gravity } } }
mit
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/widget/MaterialSpinnerView.kt
1
5831
package eu.kanade.tachiyomi.widget import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.view.LayoutInflater import android.view.MenuItem import android.widget.FrameLayout import androidx.annotation.ArrayRes import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.view.menu.MenuBuilder import androidx.appcompat.widget.PopupMenu import androidx.core.content.withStyledAttributes import androidx.core.view.forEach import androidx.core.view.get import androidx.core.view.size import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.core.preference.Preference import eu.kanade.tachiyomi.databinding.PrefSpinnerBinding import eu.kanade.tachiyomi.util.system.getResourceColor class MaterialSpinnerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) { private var entries = emptyList<String>() private var selectedPosition = 0 private var popup: PopupMenu? = null var onItemSelectedListener: ((Int) -> Unit)? = null set(value) { field = value if (value != null) { popup = makeSettingsPopup() setOnTouchListener(popup?.dragToOpenListener) setOnClickListener { popup?.show() } } } private val emptyIcon by lazy { AppCompatResources.getDrawable(context, R.drawable.ic_blank_24dp) } private val checkmarkIcon by lazy { AppCompatResources.getDrawable(context, R.drawable.ic_check_24dp)?.mutate()?.apply { setTint(context.getResourceColor(android.R.attr.textColorPrimary)) } } private val binding = PrefSpinnerBinding.inflate(LayoutInflater.from(context), this, false) init { addView(binding.root) context.withStyledAttributes(set = attrs, attrs = R.styleable.MaterialSpinnerView) { val title = getString(R.styleable.MaterialSpinnerView_title).orEmpty() binding.title.text = title val viewEntries = ( getTextArray(R.styleable.MaterialSpinnerView_android_entries) ?: emptyArray() ).map { it.toString() } entries = viewEntries binding.details.text = viewEntries.firstOrNull().orEmpty() } } fun setSelection(selection: Int) { if (selectedPosition < (popup?.menu?.size ?: 0)) { popup?.menu?.getItem(selectedPosition)?.let { it.icon = emptyIcon } } selectedPosition = selection popup?.menu?.getItem(selectedPosition)?.let { it.icon = checkmarkIcon } binding.details.text = entries.getOrNull(selection).orEmpty() } fun bindToPreference(pref: Preference<Int>, offset: Int = 0, block: ((Int) -> Unit)? = null) { setSelection(pref.get() - offset) popup = makeSettingsPopup(pref, offset, block) setOnTouchListener(popup?.dragToOpenListener) setOnClickListener { popup?.show() } } inline fun <reified T : Enum<T>> bindToPreference(pref: Preference<T>) { val enumConstants = T::class.java.enumConstants enumConstants?.indexOf(pref.get())?.let { setSelection(it) } val popup = makeSettingsPopup(pref) setOnTouchListener(popup.dragToOpenListener) setOnClickListener { popup.show() } } fun bindToIntPreference(pref: Preference<Int>, @ArrayRes intValuesResource: Int, block: ((Int) -> Unit)? = null) { val intValues = resources.getStringArray(intValuesResource).map { it.toIntOrNull() } setSelection(intValues.indexOf(pref.get())) popup = makeSettingsPopup(pref, intValues, block) setOnTouchListener(popup?.dragToOpenListener) setOnClickListener { popup?.show() } } inline fun <reified T : Enum<T>> makeSettingsPopup(preference: Preference<T>): PopupMenu { return createPopupMenu { pos -> onItemSelectedListener?.invoke(pos) val enumConstants = T::class.java.enumConstants enumConstants?.get(pos)?.let { enumValue -> preference.set(enumValue) } } } private fun makeSettingsPopup(preference: Preference<Int>, intValues: List<Int?>, block: ((Int) -> Unit)? = null): PopupMenu { return createPopupMenu { pos -> preference.set(intValues[pos] ?: 0) block?.invoke(pos) } } private fun makeSettingsPopup(preference: Preference<Int>, offset: Int = 0, block: ((Int) -> Unit)? = null): PopupMenu { return createPopupMenu { pos -> preference.set(pos + offset) block?.invoke(pos) } } private fun makeSettingsPopup(): PopupMenu { return createPopupMenu { pos -> onItemSelectedListener?.invoke(pos) } } private fun menuClicked(menuItem: MenuItem): Int { val pos = menuItem.itemId setSelection(pos) return pos } @SuppressLint("RestrictedApi") fun createPopupMenu(onItemClick: (Int) -> Unit): PopupMenu { val popup = PopupMenu(context, this, Gravity.END, R.attr.actionOverflowMenuStyle, 0) entries.forEachIndexed { index, entry -> popup.menu.add(0, index, 0, entry) } (popup.menu as? MenuBuilder)?.setOptionalIconsVisible(true) popup.menu.forEach { it.icon = emptyIcon } popup.menu[selectedPosition].icon = checkmarkIcon popup.setOnMenuItemClickListener { menuItem -> val pos = menuClicked(menuItem) onItemClick(pos) true } return popup } }
apache-2.0
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/domain/category/interactor/SetSortModeForCategory.kt
1
1292
package eu.kanade.domain.category.interactor import eu.kanade.domain.category.model.Category import eu.kanade.domain.category.model.CategoryUpdate import eu.kanade.domain.category.repository.CategoryRepository import eu.kanade.domain.library.model.LibrarySort import eu.kanade.domain.library.model.plus import eu.kanade.domain.library.service.LibraryPreferences class SetSortModeForCategory( private val preferences: LibraryPreferences, private val categoryRepository: CategoryRepository, ) { suspend fun await(categoryId: Long, type: LibrarySort.Type, direction: LibrarySort.Direction) { val category = categoryRepository.get(categoryId) ?: return val flags = category.flags + type + direction if (preferences.categorizedDisplaySettings().get()) { categoryRepository.updatePartial( CategoryUpdate( id = category.id, flags = flags, ), ) } else { preferences.librarySortingMode().set(LibrarySort(type, direction)) categoryRepository.updateAllFlags(flags) } } suspend fun await(category: Category, type: LibrarySort.Type, direction: LibrarySort.Direction) { await(category.id, type, direction) } }
apache-2.0
da1z/intellij-community
plugins/stream-debugger/src/com/intellij/debugger/streams/trace/impl/handler/unified/PeekTraceHandler.kt
4
2006
// Copyright 2000-2017 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.debugger.streams.trace.impl.handler.unified import com.intellij.debugger.streams.trace.dsl.CodeBlock import com.intellij.debugger.streams.trace.dsl.Dsl import com.intellij.debugger.streams.trace.dsl.Expression import com.intellij.debugger.streams.trace.dsl.VariableDeclaration import com.intellij.debugger.streams.trace.dsl.impl.TextExpression import com.intellij.debugger.streams.trace.impl.handler.type.GenericType import com.intellij.debugger.streams.wrapper.IntermediateStreamCall /** * @author Vitaliy.Bibaev */ open class PeekTraceHandler(num: Int, callName: String, private val myTypeBefore: GenericType, typeAfter: GenericType, dsl: Dsl) : HandlerBase.Intermediate(dsl) { val beforeMap = dsl.linkedMap(dsl.types.INT, myTypeBefore, "${callName}Peek${num}Before") val afterMap = dsl.linkedMap(dsl.types.INT, typeAfter, "${callName}Peek${num}After") override fun additionalVariablesDeclaration(): List<VariableDeclaration> = listOf(beforeMap.defaultDeclaration(), afterMap.defaultDeclaration()) override fun prepareResult(): CodeBlock { return dsl.block { add(beforeMap.convertToArray(this, "beforeArray")) add(afterMap.convertToArray(this, "afterArray")) } } override fun getResultExpression(): Expression = dsl.newArray(dsl.types.ANY, TextExpression("beforeArray"), TextExpression("afterArray")) override fun additionalCallsBefore(): List<IntermediateStreamCall> { val lambda = dsl.lambda("x") { doReturn(beforeMap.set(dsl.currentTime(), lambdaArg)) }.toCode() return listOf(dsl.createPeekCall(myTypeBefore, lambda)) } override fun additionalCallsAfter(): List<IntermediateStreamCall> { val lambda = dsl.lambda("x") { doReturn(afterMap.set(dsl.currentTime(), lambdaArg)) }.toCode() return listOf(dsl.createPeekCall(myTypeBefore, lambda)) } }
apache-2.0
square/wire
wire-library/wire-moshi-adapter/src/main/java/com/squareup/wire/WireJsonAdapterFactory.kt
1
3715
/* * Copyright 2018 Square 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.squareup.wire import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.Types import com.squareup.wire.internal.EnumJsonFormatter import com.squareup.wire.internal.createRuntimeMessageAdapter import java.lang.reflect.Type /** * A [JsonAdapter.Factory] that allows Wire messages to be serialized and deserialized using the * Moshi Json library. * * ``` * Moshi moshi = new Moshi.Builder() * .add(new WireJsonAdapterFactory()) * .build(); * ``` * * The resulting [Moshi] instance will be able to serialize and deserialize Wire [Message] types, * including extensions. It ignores unknown field values. The JSON encoding is intended to be * compatible with the [protobuf-java-format](https://code.google.com/p/protobuf-java-format/) * library. * * In Proto3, if a field is set to its default (or identity) value, it will be omitted in the * JSON-encoded data. Set [writeIdentityValues] to true if you want Wire to always write values, * including default ones. */ class WireJsonAdapterFactory @JvmOverloads constructor( private val typeUrlToAdapter: Map<String, ProtoAdapter<*>> = mapOf(), private val writeIdentityValues: Boolean = false, ) : JsonAdapter.Factory { /** * Returns a new WireJsonAdapterFactory that can encode the messages for [adapters] if they're * used with [AnyMessage]. */ fun plus(adapters: List<ProtoAdapter<*>>): WireJsonAdapterFactory { val newMap = typeUrlToAdapter.toMutableMap() for (adapter in adapters) { val key = adapter.typeUrl ?: throw IllegalArgumentException( "recompile ${adapter.type} to use it with WireJsonAdapterFactory" ) newMap[key] = adapter } return WireJsonAdapterFactory(newMap, writeIdentityValues) } /** * Returns a new WireJsonAdapterFactory that can encode the messages for [adapter] if they're * used with [AnyMessage]. */ fun plus(adapter: ProtoAdapter<*>): WireJsonAdapterFactory { return plus(listOf(adapter)) } override fun create( type: Type, annotations: Set<Annotation>, moshi: Moshi ): JsonAdapter<*>? { val rawType = Types.getRawType(type) return when { annotations.isNotEmpty() -> null rawType == AnyMessage::class.java -> AnyMessageJsonAdapter(moshi, typeUrlToAdapter) Message::class.java.isAssignableFrom(rawType) -> { val messageAdapter = createRuntimeMessageAdapter<Nothing, Nothing>(type as Class<Nothing>, writeIdentityValues) val jsonAdapters = MoshiJsonIntegration.jsonAdapters(messageAdapter, moshi) val redactedFieldsAdapter = moshi.adapter<List<String>>( Types.newParameterizedType(List::class.java, String::class.java) ) MessageJsonAdapter(messageAdapter, jsonAdapters, redactedFieldsAdapter).nullSafe() } WireEnum::class.java.isAssignableFrom(rawType) -> { val enumAdapter = RuntimeEnumAdapter.create(type as Class<Nothing>) val enumJsonFormatter = EnumJsonFormatter(enumAdapter) EnumJsonAdapter(enumJsonFormatter).nullSafe() } else -> null } } }
apache-2.0
notsyncing/lightfur
lightfur-ql/src/test/kotlin/io/github/notsyncing/lightfur/ql/tests/toys/UserModel.kt
2
504
package io.github.notsyncing.lightfur.ql.tests.toys import io.github.notsyncing.lightfur.entity.EntityModel import java.time.LocalDateTime class UserModel : EntityModel(table = "users") { var id: Long by field("id", primaryKey = true, autoGenerated = true) var username: String by field("username") var mobile: String? by field("mobile") var email: String? by field("email") var lastLoginTime: LocalDateTime? by field("last_login_time") var status: Int by field("status") }
gpl-3.0
treelzebub/zinepress
app/src/main/java/net/treelzebub/zinepress/net/api/model/PocketArticlesResponse.kt
1
274
package net.treelzebub.zinepress.net.api.model import com.google.gson.annotations.SerializedName /** * Created by Tre Murillo on 1/31/16 */ data class PocketArticleResponse(@SerializedName("list") val articles: Map<Long, PocketArticle>)
gpl-2.0
PolymerLabs/arcs
java/arcs/core/crdt/CrdtSingleton.kt
1
7662
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.crdt import arcs.core.common.Referencable import arcs.core.common.ReferenceId import arcs.core.crdt.CrdtSet.Operation.Add import arcs.core.crdt.CrdtSet.Operation.Remove import arcs.core.crdt.CrdtSingleton.Data import arcs.core.data.util.ReferencablePrimitive /** A [CrdtModel] capable of managing a mutable reference. */ class CrdtSingleton<T : Referencable>( initialVersion: VersionMap = VersionMap(), initialData: T? = null, singletonToCopy: CrdtSingleton<T>? = null ) : CrdtModel<Data<T>, CrdtSingleton.IOperation<T>, T?> { override val versionMap: VersionMap get() = set._data.versionMap.copy() private var set: CrdtSet<T> override val data: Data<T> get() { val setData = set._data return DataImpl(setData.versionMap, setData.values) } override val consumerView: T? // Get any value, or null if no value is present. get() = set.consumerView.minByOrNull { it.id } init { CrdtException.require(initialData == null || singletonToCopy == null) { "Cannot instantiate CrdtSingleton by supplying both initialData AND singletonToCopy" } set = when { initialData != null -> CrdtSet( CrdtSet.DataImpl( initialVersion, mutableMapOf(initialData.id to CrdtSet.DataValue(initialVersion, initialData)) ) ) singletonToCopy != null -> singletonToCopy.set.copy() else -> CrdtSet(CrdtSet.DataImpl(initialVersion)) } } /** * Simple constructor to build a [CrdtSingleton] from an initial value and starting at a given * [VersionMap]. */ constructor(versionMap: VersionMap, data: T?) : this( initialVersion = versionMap, initialData = data ) override fun merge(other: Data<T>): MergeChanges<Data<T>, IOperation<T>> { if (data == other) { return MergeChanges(CrdtChange.Operations(), CrdtChange.Operations()) } val result = set.merge(other.asCrdtSetData()) // Always return CrdtChange.Data change record for the local update, since we cannot perform // an op-based change. val modelChange: CrdtChange<Data<T>, IOperation<T>> = CrdtChange.Data(data) // If the other changes were empty, we should actually just return empty changes, rather // than the model.. val otherChange: CrdtChange<Data<T>, IOperation<T>> = if (result.otherChange.isEmpty()) { CrdtChange.Operations() } else { CrdtChange.Data(data) } return MergeChanges(modelChange, otherChange) } override fun applyOperation(op: IOperation<T>): Boolean = op.applyTo(set) /** Makes a deep copy of this [CrdtSingleton]. */ /* internal */ fun copy(): CrdtSingleton<T> = CrdtSingleton(singletonToCopy = this) override fun toString(): String = "CrdtSingleton(data=${set.data})" override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false if (this::class != other::class) return false other as CrdtSingleton<*> if (set != other.set) return false return true } override fun hashCode(): Int = set.hashCode() /** Abstract representation of the data stored by a [CrdtSingleton]. */ interface Data<T : Referencable> : CrdtData { val values: MutableMap<ReferenceId, CrdtSet.DataValue<T>> /** Constructs a deep copy of this [Data]. */ fun copy(): Data<T> /** * Converts this instance into an equivalent instance of [CrdtSet.Data]. * * CrdtSingleton is implemented via a backing CrdtSet, and their [Data] types are trivially * convertible from one to the other. */ fun asCrdtSetData(): CrdtSet.Data<T> } /** Concrete representation of the data stored by a [CrdtSingleton]. */ data class DataImpl<T : Referencable>( override var versionMap: VersionMap = VersionMap(), override val values: MutableMap<ReferenceId, CrdtSet.DataValue<T>> = mutableMapOf() ) : Data<T> { override fun asCrdtSetData() = CrdtSet.DataImpl(versionMap, values) override fun copy() = DataImpl( versionMap = VersionMap(versionMap), values = HashMap(values) ) override fun toString(): String = "CrdtSingleton.Data(versionMap=$versionMap, values=${values.toStringRepr()})" private fun <T : Referencable> Map<ReferenceId, CrdtSet.DataValue<T>>.toStringRepr() = entries.joinToString(prefix = "{", postfix = "}") { (id, value) -> "${ReferencablePrimitive.unwrap(id) ?: id}=$value" } } /** General representation of an operation which can be applied to a [CrdtSingleton]. */ interface IOperation<T : Referencable> : CrdtOperation { val actor: Actor /** Mutates [data] based on the implementation of the [Operation]. */ fun applyTo(set: CrdtSet<T>): Boolean } sealed class Operation<T : Referencable>( override val actor: Actor, override val versionMap: VersionMap ) : IOperation<T> { /** An [Operation] to update the value stored by the [CrdtSingleton]. */ open class Update<T : Referencable>( override val actor: Actor, override val versionMap: VersionMap, val value: T ) : Operation<T>(actor, versionMap) { override fun applyTo(set: CrdtSet<T>): Boolean { // If the update does not increment actors clock we reject it. if (set.versionMap[actor] >= versionMap[actor]) return false // Remove does not require an increment, but the caller of this method will have // incremented its version, so we hack a version with t-1 for this actor. val removeVersionMap = VersionMap(versionMap) removeVersionMap[actor]-- // Clear all the values inserted before this update. Clear<T>(actor, removeVersionMap).applyTo(set) // After removal of all existing values, we simply need to add the new value. return set.applyOperation(Add(actor, versionMap, value)) } override fun equals(other: Any?): Boolean = other is Update<*> && other.versionMap == versionMap && other.actor == actor && other.value == value override fun hashCode(): Int = toString().hashCode() override fun toString(): String = "CrdtSingleton.Operation.Update($versionMap, $actor, $value)" } /** An [Operation] to clear the value stored by the [CrdtSingleton]. */ open class Clear<T : Referencable>( override val actor: Actor, override val versionMap: VersionMap ) : Operation<T>(actor, versionMap) { override fun applyTo(set: CrdtSet<T>): Boolean { // Clear all existing values if our versionMap allows it. val removeOps = set.data.values.map { (id, _) -> Remove<T>(actor, versionMap, id) } // Clear succeeds if all values are removed. return removeOps.map { set.applyOperation(it) }.all { it } } override fun equals(other: Any?): Boolean = other is Clear<*> && other.versionMap == versionMap && other.actor == actor override fun hashCode(): Int = toString().hashCode() override fun toString(): String = "CrdtSingleton.Operation.Clear($versionMap, $actor)" } } companion object { /** Creates a [CrdtSingleton] from pre-existing data. */ fun <T : Referencable> createWithData( data: Data<T> ) = CrdtSingleton<T>().apply { set = CrdtSet(data.asCrdtSetData()) } } }
bsd-3-clause
Maccimo/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/ExampleWorkspaceModelEventsHandler.kt
4
10071
// 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.workspaceModel.ide.impl import com.intellij.openapi.Disposable import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.ModuleRootManager import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.legacyBridge.module.isModuleUnloaded import com.intellij.workspaceModel.storage.EntityChange import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.bridgeEntities.api.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl /** * This class is not handling events about global libraries and SDK changes. Such events should * be processed via [com.intellij.openapi.roots.ModuleRootListener] */ class ExampleWorkspaceModelEventsHandler(private val project: Project): Disposable { init { val messageBusConnection = project.messageBus.connect(this) WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(messageBusConnection, object : WorkspaceModelChangeListener { override fun changed(event: VersionedStorageChange) { // Example of handling VirtualFileUrl change at entities with update cache based on the changed urls handleLibraryChanged(event) handleContentRootChanged(event) handleSourceRootChanged(event) // If cache invalidation depends on specific properties e.g. [org.jetbrains.jps.model.java.JavaResourceRootProperties.getRelativeOutputPath] // changes from [JavaResourceRootEntity] should be handled handleJavaSourceRootChanged(event) handleJavaResourceRootChanged(event) handleCustomSourceRootPropertiesChanged(event) handleModuleChanged(event) handleJavaModuleSettingsChanged(event) handleLibraryPropertiesChanged(event) handleModuleGroupPathChanged(event) handleModuleCustomImlDataChanged(event) } }) } private fun handleLibraryChanged(event: VersionedStorageChange) { event.getChanges(LibraryEntity::class.java).forEach { change -> val (entity, _) = getEntityAndStorage(event, change) if (!libraryIsDependency(entity, project)) return@forEach val (addedUrls, removedUrls) = calculateChangedUrls(change, listOf(), listOf({ roots.map { it.url }}, { excludedRoots })) updateCache(addedUrls.urls, removedUrls.urls) } } /** * If your cache invalidation depends on [com.intellij.openapi.roots.impl.libraries.LibraryEx.getKind] or * [com.intellij.openapi.roots.impl.libraries.LibraryEx.getProperties] you should handle changes from [LibraryPropertiesEntity] */ private fun handleLibraryPropertiesChanged(event: VersionedStorageChange) { event.getChanges(LibraryPropertiesEntity::class.java).forEach { change -> val (entity, _) = getEntityAndStorage(event, change) if (!libraryIsDependency(entity.library, project)) return@forEach updateCache() } } private fun handleContentRootChanged(event: VersionedStorageChange) { event.getChanges(ContentRootEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ module }) return@forEach val (addedUrls, removedUrls) = calculateChangedUrls(change, listOf({url}), listOf({ excludedUrls })) updateCache(addedUrls.urls, removedUrls.urls) } } private fun handleSourceRootChanged(event: VersionedStorageChange) { event.getChanges(SourceRootEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ contentRoot.module }) return@forEach val (addedUrls, removedUrls) = calculateChangedUrls(change, listOf({url})) updateCache(addedUrls.urls, removedUrls.urls) } } private fun handleJavaModuleSettingsChanged(event: VersionedStorageChange) { event.getChanges(JavaModuleSettingsEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ module }) return@forEach val (addedUrls, removedUrls) = calculateChangedUrls(change, listOf({compilerOutput}, {compilerOutputForTests})) updateCache(addedUrls.urls, removedUrls.urls) } } private fun handleModuleChanged(event: VersionedStorageChange) { event.getChanges(ModuleEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ this }) return@forEach updateCache() } } private fun handleModuleGroupPathChanged(event: VersionedStorageChange) { event.getChanges(ModuleGroupPathEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ module }) return@forEach updateCache() } } private fun handleModuleCustomImlDataChanged(event: VersionedStorageChange) { event.getChanges(ModuleCustomImlDataEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ module }) return@forEach updateCache() } } private fun handleJavaSourceRootChanged(event: VersionedStorageChange) { event.getChanges(JavaSourceRootEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ sourceRoot.contentRoot.module }) return@forEach updateCache() } } /** * If cache invalidation depends on specific properties e.g. [org.jetbrains.jps.model.java.JavaResourceRootProperties.getRelativeOutputPath] * changes from [JavaResourceRootEntity] should be handled */ private fun handleJavaResourceRootChanged(event: VersionedStorageChange) { event.getChanges(JavaResourceRootEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change) { sourceRoot.contentRoot.module }) return@forEach updateCache() } } private fun handleCustomSourceRootPropertiesChanged(event: VersionedStorageChange) { event.getChanges(CustomSourceRootPropertiesEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change) { sourceRoot.contentRoot.module }) return@forEach updateCache() } } private fun <T: WorkspaceEntity> getEntityAndStorage(event: VersionedStorageChange, change: EntityChange<T>): Pair<T, EntityStorage> { return when (change) { is EntityChange.Added -> change.entity to event.storageAfter is EntityChange.Removed -> change.entity to event.storageBefore is EntityChange.Replaced -> change.newEntity to event.storageAfter } } private fun <T: WorkspaceEntity> isInUnloadedModule(event: VersionedStorageChange, change: EntityChange<T>, moduleAssessor: T.() -> ModuleEntity): Boolean { val (entity, storage) = getEntityAndStorage(event, change) return entity.moduleAssessor().isModuleUnloaded(storage) } /** * Example of method for calculation changed VirtualFileUrls at entities */ private fun <T: WorkspaceEntity> calculateChangedUrls(change: EntityChange<T>, vfuAssessors: List<T.() -> VirtualFileUrl?>, vfuListAssessors: List<T.() -> List<VirtualFileUrl>> = emptyList()): Pair<Added, Removed> { val addedVirtualFileUrls = mutableSetOf<VirtualFileUrl>() val removedVirtualFileUrls = mutableSetOf<VirtualFileUrl>() vfuAssessors.forEach { fieldAssessor -> when (change) { is EntityChange.Added -> fieldAssessor.invoke(change.entity)?.also { addedVirtualFileUrls.add(it) } is EntityChange.Removed -> fieldAssessor.invoke(change.entity)?.also { removedVirtualFileUrls.add(it) } is EntityChange.Replaced -> { val newVirtualFileUrl = fieldAssessor.invoke(change.newEntity) val oldVirtualFileUrl = fieldAssessor.invoke(change.oldEntity) if (newVirtualFileUrl != oldVirtualFileUrl) { newVirtualFileUrl?.also { addedVirtualFileUrls.add(it) } oldVirtualFileUrl?.also { removedVirtualFileUrls.add(it) } } } } } vfuListAssessors.forEach { fieldAssessor -> when (change) { is EntityChange.Added -> { val virtualFileUrls = fieldAssessor.invoke(change.entity) if (virtualFileUrls.isNotEmpty()) { addedVirtualFileUrls.addAll(virtualFileUrls) } } is EntityChange.Removed -> { val virtualFileUrls = fieldAssessor.invoke(change.entity) if (virtualFileUrls.isNotEmpty()) { removedVirtualFileUrls.addAll(virtualFileUrls) } } is EntityChange.Replaced -> { val newVirtualFileUrls = fieldAssessor.invoke(change.newEntity).toSet() val oldVirtualFileUrls = fieldAssessor.invoke(change.oldEntity).toSet() addedVirtualFileUrls.addAll(newVirtualFileUrls.subtract(oldVirtualFileUrls)) removedVirtualFileUrls.addAll(oldVirtualFileUrls.subtract(newVirtualFileUrls)) } } } return Added(addedVirtualFileUrls) to Removed(removedVirtualFileUrls) } private fun libraryIsDependency(library: LibraryEntity, project: Project): Boolean { if (library.tableId is LibraryTableId.ModuleLibraryTableId) return true val libraryName = library.name ModuleManager.getInstance(project).modules.forEach { module -> val exists = ModuleRootManager.getInstance(module).orderEntries.any { it is LibraryOrderEntry && it.libraryName == libraryName } if (exists) return true } return false } private fun updateCache() { } private fun updateCache(addedVirtualFileUrls: MutableSet<VirtualFileUrl>, removedVirtualFileUrls: MutableSet<VirtualFileUrl>) { } private data class Added(val urls: MutableSet<VirtualFileUrl>) private data class Removed(val urls: MutableSet<VirtualFileUrl>) override fun dispose() { } }
apache-2.0
ThoseGrapefruits/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustItemImplMixin.kt
1
466
package org.rust.lang.core.psi.impl.mixin import com.intellij.lang.ASTNode import org.rust.lang.core.psi.RustItem import org.rust.lang.core.psi.RustNamedElement import org.rust.lang.core.psi.impl.RustNamedElementImpl public abstract class RustItemImplMixin(node: ASTNode) : RustNamedElementImpl(node) , RustItem { override fun getBoundElements(): Collection<RustNamedElement> = listOf(this) }
mit
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/statements/loops/BreakStatement.kt
1
759
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.statements.loops import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.vimscript.model.Executable import com.maddyhome.idea.vim.vimscript.model.ExecutionResult import com.maddyhome.idea.vim.vimscript.model.VimLContext object BreakStatement : Executable { override lateinit var vimContext: VimLContext override fun execute(editor: VimEditor, context: ExecutionContext): ExecutionResult { return ExecutionResult.Break } }
mit
JStege1206/AdventOfCode
aoc-2018/src/test/kotlin/nl/jstege/adventofcode/aoc2018/days/Day20Test.kt
1
139
package nl.jstege.adventofcode.aoc2018.days import nl.jstege.adventofcode.aoccommon.utils.DayTester class Day20Test : DayTester(Day20())
mit
blindpirate/gradle
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/PluginDependenciesSpecScopeTest.kt
3
3290
package org.gradle.kotlin.dsl import org.gradle.groovy.scripts.TextResourceScriptSource import org.gradle.internal.resource.StringTextResource import org.gradle.plugin.management.internal.PluginRequestInternal import org.gradle.plugin.management.internal.autoapply.AutoAppliedGradleEnterprisePlugin import org.gradle.plugin.use.PluginDependenciesSpec import org.gradle.plugin.use.internal.PluginRequestCollector import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class PluginDependenciesSpecScopeTest { @Test fun `given a single id, it should create a single request with no version`() { expecting(plugin(id = "plugin-id")) { id("plugin-id") } } @Test fun `given a single id and apply value, it should create a single request with no version`() { listOf(true, false).forEach { applyValue -> expecting(plugin(id = "plugin-id", isApply = applyValue)) { id("plugin-id") apply applyValue } } } @Test fun `given a single id and version, it should create a single request`() { expecting(plugin(id = "plugin-id", version = "1.0")) { id("plugin-id") version "1.0" } } @Test fun `given two ids and a single version, it should create two requests`() { expecting(plugin(id = "plugin-a", version = "1.0"), plugin(id = "plugin-b")) { id("plugin-a") version "1.0" id("plugin-b") } } @Test fun `given gradle-enterprise plugin accessor, it should create a single request matching the auto-applied plugin version`() { expecting(plugin(id = "com.gradle.enterprise", version = AutoAppliedGradleEnterprisePlugin.VERSION)) { `gradle-enterprise` } } @Test fun `given gradle-enterprise plugin accessor with version, it should create a single request with given version`() { expecting(plugin(id = "com.gradle.enterprise", version = "1.7.1")) { `gradle-enterprise` version "1.7.1" } } @Test fun `given kotlin plugin accessor, it should create a single request with no version`() { expecting(plugin(id = "org.jetbrains.kotlin.jvm", version = null)) { kotlin("jvm") } } @Test fun `given kotlin plugin accessor with version, it should create a single request with given version`() { expecting(plugin(id = "org.jetbrains.kotlin.jvm", version = "1.1.1")) { kotlin("jvm") version "1.1.1" } } } fun expecting(vararg expected: Plugin, block: PluginDependenciesSpec.() -> Unit) { assertThat( plugins(block).map { Plugin(it.id.id, it.version, it.isApply) }, equalTo(expected.asList()) ) } fun plugins(block: PluginDependenciesSpecScope.() -> Unit): List<PluginRequestInternal> = PluginRequestCollector( TextResourceScriptSource(StringTextResource("script", "")) ).run { PluginDependenciesSpecScope(createSpec(1)).block() pluginRequests.toList() } fun plugin(id: String, version: String? = null, isApply: Boolean = true) = Plugin(id, version, isApply) data class Plugin(val id: String, val version: String?, val isApply: Boolean)
apache-2.0
JetBrains/ideavim
.teamcity/_Self/buildTypes/TestsForIntelliJ_201.kt
1
1724
@file:Suppress("ClassName") package _Self.buildTypes import jetbrains.buildServer.configs.kotlin.v2019_2.BuildType import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.gradle import jetbrains.buildServer.configs.kotlin.v2019_2.failureConditions.BuildFailureOnMetric import jetbrains.buildServer.configs.kotlin.v2019_2.failureConditions.failOnMetricChange import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.vcs sealed class TestsForIntelliJ_201_branch(private val version: String) : BuildType({ name = "Tests for IntelliJ $version" params { param("env.ORG_GRADLE_PROJECT_downloadIdeaSources", "false") param("env.ORG_GRADLE_PROJECT_ideaVersion", "IC-$version") param("env.ORG_GRADLE_PROJECT_instrumentPluginCode", "false") param("env.ORG_GRADLE_PROJECT_javaVersion", "1.8") } vcs { root(_Self.vcsRoots.Branch_201) checkoutMode = CheckoutMode.AUTO } steps { gradle { tasks = "clean test" buildFile = "" enableStacktrace = true param("org.jfrog.artifactory.selectedDeployableServer.defaultModuleVersionConfiguration", "GLOBAL") } } triggers { vcs { branchFilter = "" } } requirements { noLessThanVer("teamcity.agent.jvm.version", "1.8") } failureConditions { failOnMetricChange { metric = BuildFailureOnMetric.MetricType.TEST_COUNT threshold = 20 units = BuildFailureOnMetric.MetricUnit.PERCENTS comparison = BuildFailureOnMetric.MetricComparison.LESS compareTo = build { buildRule = lastSuccessful() } } } }) object TestsForIntelliJ20201 : TestsForIntelliJ_201_branch("2020.1")
mit
crashlytics/18thScale
app/src/main/java/com/firebase/hackweek/tank18thscale/Tilter.kt
1
342
package com.firebase.hackweek.tank18thscale class Tilter(private val threshold: Float = 0f, private val ti : TankInterface) { fun tilt(angle: Float) { if (angle > 0 && angle > this.threshold) { ti.tiltUp() } if (angle < 0 && angle < (-1 * this.threshold)) { ti.tiltDown() } } }
apache-2.0
KotlinNLP/SimpleDNN
src/test/kotlin/core/optimizer/ParamsOptimizerUtils.kt
1
1536
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.optimizer import com.kotlinnlp.simplednn.core.layers.models.feedforward.simple.FeedforwardLayerParameters import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory /** * */ object ParamsOptimizerUtils { /** * */ fun buildParams() = FeedforwardLayerParameters(inputSize = 4, outputSize = 2).also { it.unit.weights.values.assignValues(DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.3, 0.4, 0.2, -0.2), doubleArrayOf(0.2, -0.1, 0.1, 0.6) ))) it.unit.biases.values.assignValues(DenseNDArrayFactory.arrayOf( doubleArrayOf(0.3, -0.4) )) } /** * */ fun buildWeightsErrorsValues1() = DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.3, 0.4, 0.2, -0.2), doubleArrayOf(0.2, -0.1, 0.1, 0.6) )) /** * */ fun buildBiasesErrorsValues1() = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3, -0.4)) /** * */ fun buildWeightsErrorsValues2() = DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.7, -0.8, 0.1, -0.6), doubleArrayOf(0.8, 0.6, -0.9, -0.2) )) /** * */ fun buildBiasesErrorsValues2() = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.9, 0.1)) }
mpl-2.0
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/granular/usecases/OverviewUseCase.kt
1
11545
package org.wordpress.android.ui.stats.refresh.lists.sections.granular.usecases import kotlinx.coroutines.CoroutineDispatcher import org.wordpress.android.R import org.wordpress.android.analytics.AnalyticsTracker import org.wordpress.android.analytics.AnalyticsTracker.Stat.STATS_OVERVIEW_ERROR import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.stats.LimitMode import org.wordpress.android.fluxc.model.stats.time.VisitsAndViewsModel import org.wordpress.android.fluxc.network.utils.StatsGranularity import org.wordpress.android.fluxc.store.StatsStore.TimeStatsType.OVERVIEW import org.wordpress.android.fluxc.store.stats.time.VisitsAndViewsStore import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValueItem import org.wordpress.android.ui.stats.refresh.lists.sections.granular.GranularUseCaseFactory import org.wordpress.android.ui.stats.refresh.lists.sections.granular.SelectedDateProvider import org.wordpress.android.ui.stats.refresh.lists.sections.granular.usecases.OverviewUseCase.UiState import org.wordpress.android.ui.stats.refresh.lists.widget.WidgetUpdater.StatsWidgetUpdaters import org.wordpress.android.ui.stats.refresh.utils.StatsDateFormatter import org.wordpress.android.ui.stats.refresh.utils.StatsSiteProvider import org.wordpress.android.ui.stats.refresh.utils.toStatsSection import org.wordpress.android.ui.stats.refresh.utils.trackGranular import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T import org.wordpress.android.util.LocaleManagerWrapper import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import org.wordpress.android.viewmodel.ResourceProvider import java.util.Calendar import javax.inject.Inject import javax.inject.Named import kotlin.math.ceil const val OVERVIEW_ITEMS_TO_LOAD = 15 @Suppress("LongParameterList") class OverviewUseCase constructor( private val statsGranularity: StatsGranularity, private val visitsAndViewsStore: VisitsAndViewsStore, private val selectedDateProvider: SelectedDateProvider, private val statsSiteProvider: StatsSiteProvider, private val statsDateFormatter: StatsDateFormatter, private val overviewMapper: OverviewMapper, @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher, private val analyticsTracker: AnalyticsTrackerWrapper, private val statsWidgetUpdaters: StatsWidgetUpdaters, private val localeManagerWrapper: LocaleManagerWrapper, private val resourceProvider: ResourceProvider ) : BaseStatsUseCase<VisitsAndViewsModel, UiState>( OVERVIEW, mainDispatcher, backgroundDispatcher, UiState(), uiUpdateParams = listOf(UseCaseParam.SelectedDateParam(statsGranularity.toStatsSection())) ) { override fun buildLoadingItem(): List<BlockListItem> = listOf( ValueItem( value = "0", unit = R.string.stats_views, isFirst = true, contentDescription = resourceProvider.getString(R.string.stats_loading_card) ) ) override suspend fun loadCachedData(): VisitsAndViewsModel? { statsWidgetUpdaters.updateViewsWidget(statsSiteProvider.siteModel.siteId) statsWidgetUpdaters.updateWeekViewsWidget(statsSiteProvider.siteModel.siteId) val cachedData = visitsAndViewsStore.getVisits( statsSiteProvider.siteModel, statsGranularity, LimitMode.All ) if (cachedData != null) { logIfIncorrectData(cachedData, statsGranularity, statsSiteProvider.siteModel, false) selectedDateProvider.onDateLoadingSucceeded(statsGranularity) } return cachedData } override suspend fun fetchRemoteData(forced: Boolean): State<VisitsAndViewsModel> { val response = visitsAndViewsStore.fetchVisits( statsSiteProvider.siteModel, statsGranularity, LimitMode.Top(OVERVIEW_ITEMS_TO_LOAD), forced ) val model = response.model val error = response.error return when { error != null -> { selectedDateProvider.onDateLoadingFailed(statsGranularity) State.Error(error.message ?: error.type.name) } model != null && model.dates.isNotEmpty() -> { logIfIncorrectData(model, statsGranularity, statsSiteProvider.siteModel, true) selectedDateProvider.onDateLoadingSucceeded(statsGranularity) State.Data(model) } else -> { selectedDateProvider.onDateLoadingSucceeded(statsGranularity) State.Empty() } } } /** * Track the incorrect data shown for some users * see https://github.com/wordpress-mobile/WordPress-Android/issues/11412 */ private fun logIfIncorrectData( model: VisitsAndViewsModel, granularity: StatsGranularity, site: SiteModel, fetched: Boolean ) { model.dates.lastOrNull()?.let { lastDayData -> val yesterday = localeManagerWrapper.getCurrentCalendar() yesterday.add(Calendar.DAY_OF_YEAR, -1) val lastDayDate = statsDateFormatter.parseStatsDate(granularity, lastDayData.period) if (lastDayDate.before(yesterday.time)) { val currentCalendar = localeManagerWrapper.getCurrentCalendar() val lastItemAge = ceil((currentCalendar.timeInMillis - lastDayDate.time) / 86400000.0) analyticsTracker.track( STATS_OVERVIEW_ERROR, mapOf( "stats_last_date" to statsDateFormatter.printStatsDate(lastDayDate), "stats_current_date" to statsDateFormatter.printStatsDate(currentCalendar.time), "stats_age_in_days" to lastItemAge.toInt(), "is_jetpack_connected" to site.isJetpackConnected, "is_atomic" to site.isWPComAtomic, "action_source" to if (fetched) "remote" else "cached" ) ) } } } override fun buildUiModel( domainModel: VisitsAndViewsModel, uiState: UiState ): List<BlockListItem> { val items = mutableListOf<BlockListItem>() if (domainModel.dates.isNotEmpty()) { val dateFromProvider = selectedDateProvider.getSelectedDate(statsGranularity) val visibleBarCount = uiState.visibleBarCount ?: domainModel.dates.size val availableDates = domainModel.dates.map { statsDateFormatter.parseStatsDate( statsGranularity, it.period ) } val selectedDate = dateFromProvider ?: availableDates.last() val index = availableDates.indexOf(selectedDate) selectedDateProvider.selectDate( selectedDate, availableDates.takeLast(visibleBarCount), statsGranularity ) val selectedItem = domainModel.dates.getOrNull(index) ?: domainModel.dates.last() val previousItem = domainModel.dates.getOrNull(domainModel.dates.indexOf(selectedItem) - 1) items.add( overviewMapper.buildTitle( selectedItem, previousItem, uiState.selectedPosition, isLast = selectedItem == domainModel.dates.last(), statsGranularity = statsGranularity ) ) items.addAll( overviewMapper.buildChart( domainModel.dates, statsGranularity, this::onBarSelected, this::onBarChartDrawn, uiState.selectedPosition, selectedItem.period ) ) items.add( overviewMapper.buildColumns( selectedItem, this::onColumnSelected, uiState.selectedPosition ) ) } else { selectedDateProvider.onDateLoadingFailed(statsGranularity) AppLog.e(T.STATS, "There is no data to be shown in the overview block") } return items } private fun onBarSelected(period: String?) { analyticsTracker.trackGranular( AnalyticsTracker.Stat.STATS_OVERVIEW_BAR_CHART_TAPPED, statsGranularity ) if (period != null && period != "empty") { val selectedDate = statsDateFormatter.parseStatsDate(statsGranularity, period) selectedDateProvider.selectDate( selectedDate, statsGranularity ) } } private fun onColumnSelected(position: Int) { analyticsTracker.trackGranular( AnalyticsTracker.Stat.STATS_OVERVIEW_TYPE_TAPPED, statsGranularity ) updateUiState { it.copy(selectedPosition = position) } } private fun onBarChartDrawn(visibleBarCount: Int) { updateUiState { it.copy(visibleBarCount = visibleBarCount) } } data class UiState(val selectedPosition: Int = 0, val visibleBarCount: Int? = null) class OverviewUseCaseFactory @Inject constructor( @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher, private val statsSiteProvider: StatsSiteProvider, private val selectedDateProvider: SelectedDateProvider, private val statsDateFormatter: StatsDateFormatter, private val overviewMapper: OverviewMapper, private val visitsAndViewsStore: VisitsAndViewsStore, private val analyticsTracker: AnalyticsTrackerWrapper, private val statsWidgetUpdaters: StatsWidgetUpdaters, private val localeManagerWrapper: LocaleManagerWrapper, private val resourceProvider: ResourceProvider ) : GranularUseCaseFactory { override fun build(granularity: StatsGranularity, useCaseMode: UseCaseMode) = OverviewUseCase( granularity, visitsAndViewsStore, selectedDateProvider, statsSiteProvider, statsDateFormatter, overviewMapper, mainDispatcher, backgroundDispatcher, analyticsTracker, statsWidgetUpdaters, localeManagerWrapper, resourceProvider ) } }
gpl-2.0
f-list/exported
mobile/android/app/src/main/kotlin/net/f_list/fchat/Logs.kt
1
8788
package net.f_list.fchat import android.content.Context import android.util.SparseArray import android.webkit.JavascriptInterface import org.json.JSONArray import org.json.JSONStringer import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.RandomAccessFile import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.CharBuffer import java.util.* class Logs(private val ctx: Context) { data class IndexItem(val name: String, val index: MutableMap<Int, Int> = LinkedHashMap(), val offsets: MutableList<Long> = ArrayList()) private var index: MutableMap<String, IndexItem>? = null private var loadedIndex: MutableMap<String, IndexItem>? = null private lateinit var baseDir: File private var character: String? = null private val encoder = Charsets.UTF_8.newEncoder() private val decoder = Charsets.UTF_8.newDecoder() private val buffer = ByteBuffer.allocateDirect(51000).order(ByteOrder.LITTLE_ENDIAN) private fun loadIndex(character: String): MutableMap<String, IndexItem> { val files = File(ctx.filesDir, "$character/logs").listFiles({ _, name -> name.endsWith(".idx") }) val index = HashMap<String, IndexItem>(files.size) for(file in files) { FileInputStream(file).use { stream -> buffer.clear() val read = stream.channel.read(buffer) buffer.rewind() val nameLength = buffer.get().toInt() buffer.limit(nameLength + 1) val cb = CharBuffer.allocate(nameLength) decoder.reset() decoder.decode(buffer, cb, true) decoder.flush(cb) cb.flip() val indexItem = IndexItem(cb.toString()) buffer.limit(read) while(buffer.position() < buffer.limit()) { val key = buffer.short.toInt() indexItem.index[key] = indexItem.offsets.size indexItem.offsets.add(buffer.int.toLong() or (buffer.get().toLong() shl 32)) } index[file.nameWithoutExtension] = indexItem } } return index } @JavascriptInterface fun initN(character: String): String { baseDir = File(ctx.filesDir, "$character/logs") baseDir.mkdirs() this.character = character index = loadIndex(character) loadedIndex = index val json = JSONStringer().`object`() for(item in index!!) json.key(item.key).`object`().key("name").value(item.value.name).key("dates").value(JSONArray(item.value.index.keys)).endObject() return json.endObject().toString() } @JavascriptInterface fun logMessage(key: String, conversation: String, time: Int, type: Int, sender: String, text: String) { val day = time / 86400 val file = File(baseDir, key) buffer.clear() if(!index!!.containsKey(key)) { index!![key] = IndexItem(conversation) buffer.position(1) encoder.encode(CharBuffer.wrap(conversation), buffer, true) buffer.put(0, (buffer.position() - 1).toByte()) } val item = index!![key]!! if(!item.index.containsKey(day)) { buffer.putShort(day.toShort()) val size = file.length() item.index[day] = item.offsets.size item.offsets.add(size) buffer.putInt((size and 0xffffffffL).toInt()).put((size shr 32).toByte()) FileOutputStream(File(baseDir, "$key.idx"), true).use { file -> buffer.flip() file.channel.write(buffer) } } FileOutputStream(file, true).use { file -> buffer.clear() buffer.putInt(time) buffer.put(type.toByte()) buffer.position(6) encoder.encode(CharBuffer.wrap(sender), buffer, true) val senderLength = buffer.position() - 6 buffer.put(5, senderLength.toByte()) buffer.position(8 + senderLength) encoder.encode(CharBuffer.wrap(text), buffer, true) buffer.putShort(senderLength + 6, (buffer.position() - senderLength - 8).toShort()) buffer.putShort(buffer.position().toShort()) buffer.flip() file.channel.write(buffer) } } @JavascriptInterface fun getBacklogN(key: String): String { buffer.clear() val file = File(baseDir, key) if(!file.exists()) return "[]" val list = LinkedList<JSONStringer>() FileInputStream(file).use { stream -> val channel = stream.channel val lengthBuffer = ByteBuffer.allocateDirect(4).order(ByteOrder.LITTLE_ENDIAN) channel.position(channel.size()) while(channel.position() > 0 && list.size < 20) { lengthBuffer.rewind() lengthBuffer.limit(2) channel.position(channel.position() - 2) channel.read(lengthBuffer) lengthBuffer.clear() val length = lengthBuffer.int channel.position(channel.position() - length - 2) buffer.rewind() buffer.limit(length) channel.read(buffer) buffer.rewind() val stringer = JSONStringer() deserializeMessage(buffer, stringer) list.addFirst(stringer) channel.position(channel.position() - length) } } val json = StringBuilder("[") for(item in list) json.append(item).append(",") json.setLength(json.length - 1) return json.append("]").toString() } @JavascriptInterface fun getLogsN(character: String, key: String, date: Int): String { val indexItem = loadedIndex!![key] ?: return "[]" val dateKey = indexItem.index[date] ?: return "[]" val json = JSONStringer() json.array() FileInputStream(File(ctx.filesDir, "$character/logs/$key")).use { stream -> val channel = stream.channel val start = indexItem.offsets[dateKey] val end = if(dateKey >= indexItem.offsets.size - 1) channel.size() else indexItem.offsets[dateKey + 1] channel.position(start) val buffer = ByteBuffer.allocateDirect((end - start).toInt()).order(ByteOrder.LITTLE_ENDIAN) channel.read(buffer) buffer.rewind() while(buffer.position() < buffer.limit()) { deserializeMessage(buffer, json) buffer.limit(buffer.capacity()) buffer.position(buffer.position() + 2) } } return json.endArray().toString() } @JavascriptInterface fun loadIndexN(character: String): String { loadedIndex = if(character == this.character) this.index else this.loadIndex(character) val json = JSONStringer().`object`() for(item in loadedIndex!!) json.key(item.key).`object`().key("name").value(item.value.name).key("dates").value(JSONArray(item.value.index.keys)).endObject() return json.endObject().toString() } @JavascriptInterface fun getCharactersN(): String { return JSONArray(ctx.filesDir.listFiles().filter { it.isDirectory }.map { it.name }).toString() } @JavascriptInterface fun repair() { val files = baseDir.listFiles() val indexBuffer = ByteBuffer.allocateDirect(7).order(ByteOrder.LITTLE_ENDIAN) for(entry in files) { if(entry.name.endsWith(".idx")) continue RandomAccessFile("$entry.idx", "rw").use { idx -> buffer.clear() buffer.limit(1) idx.channel.read(buffer) idx.channel.truncate((buffer.get(0) + 1).toLong()) idx.channel.position(idx.channel.size()) RandomAccessFile(entry, "rw").use { file -> var lastDay = 0 val size = file.channel.size() var pos = 0L try { while(file.channel.position() < size) { buffer.clear() pos = file.channel.position() val read = file.channel.read(buffer) var success = false buffer.flip() while(buffer.remaining() > 10) { val offset = buffer.position() val day = buffer.int / 86400 buffer.get() val senderLength = buffer.get() if(buffer.remaining() < senderLength + 4) break buffer.limit(buffer.position() + senderLength) decoder.decode(buffer) buffer.limit(read) val textLength = buffer.short.toInt() if(buffer.remaining() < textLength + 2) break buffer.limit(buffer.position() + textLength) decoder.decode(buffer) buffer.limit(read) val messageSize = buffer.position() - offset if(messageSize != buffer.short.toInt()) throw Exception() if(day > lastDay) { lastDay = day indexBuffer.position(0) indexBuffer.putShort(day.toShort()) indexBuffer.putInt((pos and 0xffffffffL).toInt()).put((pos shr 32).toByte()) indexBuffer.position(0) idx.channel.write(indexBuffer) } pos += messageSize + 2 success = true } if(!success) throw Exception() file.channel.position(pos) } } catch(e: Exception) { file.channel.truncate(pos) } } } } } private fun deserializeMessage(buffer: ByteBuffer, json: JSONStringer) { val start = buffer.position() json.`object`() json.key("time") json.value(buffer.int) json.key("type") json.value(buffer.get()) json.key("sender") val senderLength = buffer.get() buffer.limit(start + 6 + senderLength) json.value(decoder.decode(buffer)) buffer.limit(buffer.capacity()) val textLength = buffer.short.toInt() and 0xffff json.key("text") buffer.limit(start + 8 + senderLength + textLength) json.value(decoder.decode(buffer)) json.endObject() } }
mit
ingokegel/intellij-community
plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/util/AbstractZeLastPackagePerformanceTest.kt
4
690
// 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.perf.util import junit.framework.TestCase /** * To be executed in the end of all tests, subclasses have to be the last package test, * see `com.intellij.TestCaseLoader#getClasses` * * As there tests are running as performance tests (see `com.intellij.TestCaseLoader#PERFORMANCE_TESTS_ONLY_FLAG`), * subclasses have to be named with `Performance` in their name * */ abstract class AbstractZeLastPackagePerformanceTest: TestCase() { fun test() { uploadAggregateResults() } }
apache-2.0
martinhellwig/DatapassWidget
app/src/main/java/de/schooltec/datapass/ConnectionChangeReceiver.kt
1
2373
package de.schooltec.datapass import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.os.AsyncTask import de.schooltec.datapass.AppWidgetIdUtil.getAllStoredAppWidgetIds /** * Gets events, if the connectivity-status gets changed and updates all widgets, if wifi is off and mobile data on. * * @author Martin Hellwig * @author Markus Hettig */ class ConnectionChangeReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { // Get connection mode val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager @Suppress("DEPRECATION") val connectionType = when { connectivityManager.activeNetworkInfo == null -> ConnectionType.NONE else -> { when (connectivityManager.activeNetworkInfo.type) { ConnectivityManager.TYPE_MOBILE -> ConnectionType.MOBILE ConnectivityManager.TYPE_WIFI -> ConnectionType.WIFI else -> return } } } // wait 3 seconds, so that phone has hopefully inet connection try { Thread.sleep(3000) } catch (ignored: InterruptedException) { } // Get all appIds val storedAppIds = getAllStoredAppWidgetIds(context) /* Only update in silent mode if switched to mobile data. Otherwise you are probably in wifi mode, ergo there is no new information about the used data and therefore grayish the progress bar. */ val updateMode = if (connectionType == ConnectionType.MOBILE) UpdateMode.SILENT else UpdateMode.ULTRA_SILENT storedAppIds.forEach { val appWidgetId = Integer.valueOf(it.substring(0, it.indexOf(","))) val carrier = it.substring(it.indexOf(",") + 1) UpdateWidgetTask( appWidgetId, context, updateMode, carrier ).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } } private enum class ConnectionType { MOBILE, WIFI, NONE } }
apache-2.0
ingokegel/intellij-community
plugins/kotlin/jvm-debugger/test/testData/stepping/stepOver/stopInInlineUnderOtherCall.kt
13
407
package stopInInlineUnderOtherCall fun main(args: Array<String>) { val a = 1 nonInline( { inlineCall { { //Breakpoint! foo(a) }() } } ) } fun foo(a: Any) {} fun nonInline(f: () -> Unit) { f() } inline fun inlineCall(f: () -> Unit) { f() }
apache-2.0
ingokegel/intellij-community
plugins/settings-sync/tests/com/intellij/settingsSync/SettingsSyncFlowTest.kt
1
7228
package com.intellij.settingsSync import com.intellij.util.io.readText import com.intellij.util.io.write import org.eclipse.jgit.api.Git import org.eclipse.jgit.lib.Repository import org.eclipse.jgit.revwalk.RevCommit import org.eclipse.jgit.storage.file.FileRepositoryBuilder import org.eclipse.jgit.treewalk.TreeWalk import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.nio.charset.StandardCharsets import java.nio.file.Path import kotlin.io.path.div import kotlin.io.path.writeText @RunWith(JUnit4::class) internal class SettingsSyncFlowTest : SettingsSyncTestBase() { private lateinit var ideMediator: MockSettingsSyncIdeMediator @Before internal fun initFields() { ideMediator = MockSettingsSyncIdeMediator() } private fun initSettingsSync(initMode: SettingsSyncBridge.InitMode = SettingsSyncBridge.InitMode.JustInit) { val controls = SettingsSyncMain.init(application, disposable, settingsSyncStorage, configDir, remoteCommunicator, ideMediator) updateChecker = controls.updateChecker bridge = controls.bridge bridge.initialize(initMode) } @Test fun `existing settings should be copied on initialization`() { val fileName = "options/laf.xml" val initialContent = "LaF Initial" configDir.resolve(fileName).write(initialContent) initSettingsSync(SettingsSyncBridge.InitMode.PushToServer) val pushedSnapshot = remoteCommunicator.latestPushedSnapshot assertNotNull("Nothing has been pushed", pushedSnapshot) pushedSnapshot!!.assertSettingsSnapshot { fileState(fileName, initialContent) } } @Test fun `settings modified between IDE sessions should be logged`() { // emulate first session with initialization val fileName = "options/laf.xml" val file = configDir.resolve(fileName).write("LaF Initial") val log = GitSettingsLog(settingsSyncStorage, configDir, disposable, MockSettingsSyncIdeMediator.getAllFilesFromSettings(configDir)) log.initialize() log.logExistingSettings() // modify between sessions val contentBetweenSessions = "LaF Between Sessions" file.writeText(contentBetweenSessions) initSettingsSync() val pushedSnapshot = remoteCommunicator.latestPushedSnapshot assertNotNull("Nothing has been pushed", pushedSnapshot) pushedSnapshot!!.assertSettingsSnapshot { fileState(fileName, contentBetweenSessions) } } @Test fun `first push after IDE start should update from server if needed`() { // prepare settings on server val editorXml = "options/editor.xml" val editorContent = "Editor from Server" remoteCommunicator.prepareFileOnServer(settingsSnapshot { fileState(editorXml, editorContent) }) // prepare local settings val lafXml = "options/laf.xml" val lafContent = "LaF Initial" configDir.resolve(lafXml).write(lafContent) initSettingsSync() val pushedSnapshot = remoteCommunicator.latestPushedSnapshot assertNotNull("Nothing has been pushed", pushedSnapshot) pushedSnapshot!!.assertSettingsSnapshot { fileState(lafXml, lafContent) fileState(editorXml, editorContent) } } @Test fun `enable settings sync with Push to Server should overwrite server snapshot instead of merging with it`() { // prepare settings on server val editorXml = "options/editor.xml" val editorContent = "Editor from Server" remoteCommunicator.prepareFileOnServer(settingsSnapshot { fileState(editorXml, editorContent) }) // prepare local settings val lafXml = "options/laf.xml" val lafContent = "LaF Initial" configDir.resolve(lafXml).write(lafContent) initSettingsSync(SettingsSyncBridge.InitMode.PushToServer) val pushedSnapshot = remoteCommunicator.latestPushedSnapshot assertNotNull("Nothing has been pushed", pushedSnapshot) pushedSnapshot!!.assertSettingsSnapshot { fileState(lafXml, lafContent) } } @Test fun `enable settings via Take from Server should log existing settings`() { val fileName = "options/laf.xml" val initialContent = "LaF Initial" configDir.resolve(fileName).write(initialContent) val cloudContent = "LaF from Server" val snapshot = settingsSnapshot { fileState(fileName, cloudContent) } initSettingsSync(SettingsSyncBridge.InitMode.TakeFromServer(SyncSettingsEvent.CloudChange(snapshot))) assertEquals("Incorrect content", cloudContent, (settingsSyncStorage / "options" / "laf.xml").readText()) assertAppliedToIde("options/laf.xml", cloudContent) val dotGit = settingsSyncStorage.resolve(".git") FileRepositoryBuilder.create(dotGit.toFile()).use { repository -> val git = Git(repository) val commits = git.log() .add(repository.findRef("master").objectId) .add(repository.findRef("ide").objectId) .add(repository.findRef("cloud").objectId) .call().toList() assertEquals("Unexpected number of commits. Commits: ${commits.joinToString { "'${it.shortMessage}'" }}", 3, commits.size) val (applyCloud, copyExistingSettings, initial) = commits assertEquals("Unexpected content in the 'copy existing settings' commit", initialContent, getContent(repository, copyExistingSettings, fileName)) assertEquals("Unexpected content in the 'apply from cloud' commit", cloudContent, getContent(repository, applyCloud, fileName)) } } @Test fun `enable settings with migration`() { val migration = migrationFromLafXml() initSettingsSync(SettingsSyncBridge.InitMode.MigrateFromOldStorage(migration)) assertEquals("Incorrect content", "Migration Data", (settingsSyncStorage / "options" / "laf.xml").readText()) } @Test fun `enable settings with migration and data on server should prefer server data`() { val migration = migrationFromLafXml() remoteCommunicator.prepareFileOnServer(settingsSnapshot { fileState("options/laf.xml", "Server Data") }) initSettingsSync(SettingsSyncBridge.InitMode.MigrateFromOldStorage(migration)) assertEquals("Incorrect content", "Server Data", (settingsSyncStorage / "options" / "laf.xml").readText()) } private fun migrationFromLafXml() = object : SettingsSyncMigration { override fun isLocalDataAvailable(appConfigDir: Path): Boolean { TODO("Not yet implemented") } override fun getLocalDataIfAvailable(appConfigDir: Path): SettingsSnapshot { return settingsSnapshot { fileState("options/laf.xml", "Migration Data") } } } private fun assertAppliedToIde(fileSpec: String, expectedContent: String) { val value = ideMediator.files[fileSpec] assertNotNull("$fileSpec was not applied to the IDE", value) assertEquals("Incorrect content of the applied $fileSpec", expectedContent, value) } private fun getContent(repository: Repository, commit: RevCommit, path: String): String { TreeWalk.forPath(repository, path, commit.tree).use { treeWalk -> repository.newObjectReader().use { objectReader -> val blob = treeWalk.getObjectId(0) return String(objectReader.open(blob).bytes, StandardCharsets.UTF_8) } } } }
apache-2.0
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/kr_ocap/KROCAPTransitData.kt
1
2620
/* * KROCAPTransitData.kt * * Copyright 2019 Michael Farrell <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.kr_ocap import au.id.micolous.metrodroid.card.iso7816.ISO7816TLV import au.id.micolous.metrodroid.card.ksx6924.KROCAPConfigDFApplication import au.id.micolous.metrodroid.card.ksx6924.KROCAPData.TAGMAP import au.id.micolous.metrodroid.card.ksx6924.KROCAPData.TAG_SERIAL_NUMBER import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.transit.TransitIdentity import au.id.micolous.metrodroid.transit.serialonly.SerialOnlyTransitData import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.ImmutableByteArray /** * Reader for South Korean One Card All Pass Config DF FCI. * * This is only used as a fall-back if [au.id.micolous.metrodroid.card.ksx6924.KSX6924Application] is not available. See * [KROCAPConfigDFApplication] for selection logic. * * Reference: https://github.com/micolous/metrodroid/wiki/South-Korea#a0000004520001 */ @Parcelize class KROCAPTransitData(val pdata: ImmutableByteArray) : SerialOnlyTransitData() { override val reason: Reason get() = Reason.MORE_RESEARCH_NEEDED override val serialNumber get() = getSerial(pdata) override val cardName get() = NAME override val extraInfo: List<ListItem>? get() = ISO7816TLV.infoBerTLV(pdata, TAGMAP) companion object { const val NAME = "One Card All Pass" private fun getSerial(pdata: ImmutableByteArray) = ISO7816TLV.findBERTLV(pdata, TAG_SERIAL_NUMBER, false)?.getHexString() fun parseTransitIdentity(card: KROCAPConfigDFApplication): TransitIdentity? { return card.appProprietaryBerTlv?.let { TransitIdentity(NAME, getSerial(it)) } } fun parseTransitData(card: KROCAPConfigDFApplication) = card.appProprietaryBerTlv?.let { KROCAPTransitData(it) } } }
gpl-3.0
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/serialonly/NolTransitData.kt
1
3626
/* * NolTransitData.kt * * Copyright 2019 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.serialonly import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.card.desfire.DesfireCard import au.id.micolous.metrodroid.card.desfire.DesfireCardTransitFactory import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.transit.CardInfo import au.id.micolous.metrodroid.transit.TransitIdentity import au.id.micolous.metrodroid.transit.TransitRegion import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.NumberUtils @Parcelize data class NolTransitData (private val mSerial: Int?, private val mType: Int?): SerialOnlyTransitData() { override val reason: Reason get() = Reason.LOCKED override val extraInfo: List<ListItem>? get() = super.extraInfo.orEmpty() + listOf(ListItem(R.string.card_type, when (mType) { 0x4d5 -> Localizer.localizeString(R.string.nol_silver) 0x4d9 -> Localizer.localizeString(R.string.nol_red) else -> Localizer.localizeString(R.string.unknown_format, "${mType?.toString(16)}") })) override val serialNumber get() = formatSerial(mSerial) override val cardName get() = Localizer.localizeString(NAME) companion object { private const val APP_ID_SERIAL = 0xffffff private val NAME = R.string.card_name_nol private val CARD_INFO = CardInfo( name = NAME, locationId = R.string.location_dubai, imageId = R.drawable.nol, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.MifareDesfire, region = TransitRegion.UAE, resourceExtraNote = R.string.card_note_card_number_only) private fun getSerial(card: DesfireCard) = card.getApplication(APP_ID_SERIAL)?.getFile(8)?.data?.getBitsFromBuffer( 61, 32) private fun formatSerial(serial: Int?) = if (serial != null) NumberUtils.formatNumber(serial.toLong(), " ", 3, 3, 4) else null val FACTORY: DesfireCardTransitFactory = object : DesfireCardTransitFactory { override fun earlyCheck(appIds: IntArray) = (0x4078 in appIds) && (APP_ID_SERIAL in appIds) override fun parseTransitData(card: DesfireCard) = NolTransitData(mSerial = getSerial(card), mType = card.getApplication(APP_ID_SERIAL)?.getFile(8) ?.data?.byteArrayToInt(0xc, 2)) override fun parseTransitIdentity(card: DesfireCard) = TransitIdentity(NAME, formatSerial(getSerial(card))) override val allCards get() = listOf(CARD_INFO) } } }
gpl-3.0
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/privacy/advanced/AdvancedPrivacySettingsViewModel.kt
2
3456
package org.thoughtcrime.securesms.components.settings.app.privacy.advanced import android.content.SharedPreferences import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.jobs.RefreshAttributesJob import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.util.SingleLiveEvent import org.thoughtcrime.securesms.util.TextSecurePreferences import org.thoughtcrime.securesms.util.livedata.Store class AdvancedPrivacySettingsViewModel( private val sharedPreferences: SharedPreferences, private val repository: AdvancedPrivacySettingsRepository ) : ViewModel() { private val store = Store(getState()) private val singleEvents = SingleLiveEvent<Event>() val state: LiveData<AdvancedPrivacySettingsState> = store.stateLiveData val events: LiveData<Event> = singleEvents fun disablePushMessages() { store.update { getState().copy(showProgressSpinner = true) } repository.disablePushMessages { when (it) { AdvancedPrivacySettingsRepository.DisablePushMessagesResult.SUCCESS -> { TextSecurePreferences.setPushRegistered(ApplicationDependencies.getApplication(), false) SignalStore.registrationValues().clearRegistrationComplete() } AdvancedPrivacySettingsRepository.DisablePushMessagesResult.NETWORK_ERROR -> { singleEvents.postValue(Event.DISABLE_PUSH_FAILED) } } store.update { getState().copy(showProgressSpinner = false) } } } fun setAlwaysRelayCalls(enabled: Boolean) { sharedPreferences.edit().putBoolean(TextSecurePreferences.ALWAYS_RELAY_CALLS_PREF, enabled).apply() refresh() } fun setShowStatusIconForSealedSender(enabled: Boolean) { sharedPreferences.edit().putBoolean(TextSecurePreferences.SHOW_UNIDENTIFIED_DELIVERY_INDICATORS, enabled).apply() repository.syncShowSealedSenderIconState() refresh() } fun setAllowSealedSenderFromAnyone(enabled: Boolean) { sharedPreferences.edit().putBoolean(TextSecurePreferences.UNIVERSAL_UNIDENTIFIED_ACCESS, enabled).apply() ApplicationDependencies.getJobManager().add(RefreshAttributesJob()) refresh() } fun refresh() { store.update { getState().copy(showProgressSpinner = it.showProgressSpinner) } } private fun getState() = AdvancedPrivacySettingsState( isPushEnabled = TextSecurePreferences.isPushRegistered(ApplicationDependencies.getApplication()), alwaysRelayCalls = TextSecurePreferences.isTurnOnly(ApplicationDependencies.getApplication()), showSealedSenderStatusIcon = TextSecurePreferences.isShowUnidentifiedDeliveryIndicatorsEnabled( ApplicationDependencies.getApplication() ), allowSealedSenderFromAnyone = TextSecurePreferences.isUniversalUnidentifiedAccess( ApplicationDependencies.getApplication() ), false ) enum class Event { DISABLE_PUSH_FAILED } class Factory( private val sharedPreferences: SharedPreferences, private val repository: AdvancedPrivacySettingsRepository ) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return requireNotNull( modelClass.cast( AdvancedPrivacySettingsViewModel( sharedPreferences, repository ) ) ) } } }
gpl-3.0
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/en1545/En1545Parsed.kt
1
7011
/* * En1545Fixed.kt * * Copyright 2018 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.en1545 import au.id.micolous.metrodroid.multi.Parcelable import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.time.MetroTimeZone import au.id.micolous.metrodroid.time.Timestamp import au.id.micolous.metrodroid.util.NumberUtils import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.ImmutableByteArray sealed class En1545Value : Parcelable @Parcelize class En1545ValueInt(val v: Int) : En1545Value() @Parcelize class En1545ValueString(val v: String) : En1545Value() @Parcelize class En1545Parsed(private val map: MutableMap<String, En1545Value> = mutableMapOf()) : Parcelable { operator fun plus(other: En1545Parsed) = En1545Parsed((map + other.map).toMutableMap()) fun insertInt(name: String, path: String, value: Int) { map[makeFullName(name, path)] = En1545ValueInt(value) } fun insertString(name: String, path: String, value: String) { map[makeFullName(name, path)] = En1545ValueString(value) } fun getInfo(skipSet: Set<String>): List<ListItem> = map.entries.sortedBy { it.key } .filter { (key, _) -> !skipSet.contains(getBaseName(key)) }.map { (key, l) -> when (l) { is En1545ValueInt -> ListItem(key, NumberUtils.intToHex(l.v)) is En1545ValueString -> ListItem(key, l.v) } } private fun getBaseName(name: String): String { return name.substring(name.lastIndexOf('/') + 1) } fun makeString(separator: String, skipSet: Set<String>): String { val ret = StringBuilder() for ((key, value) in map) { if (skipSet.contains(getBaseName(key))) continue ret.append(key).append(" = ") if (value is En1545ValueInt) ret.append(NumberUtils.intToHex(value.v)) if (value is En1545ValueString) ret.append("\"").append(value.v).append("\"") ret.append(separator) } return ret.toString() } override fun toString(): String { return "[" + makeString(", ", emptySet()) + "]" } fun getInt(name: String, path: String = ""): Int? { return (map[makeFullName(name, path)] as? En1545ValueInt)?.v } fun getInt(name: String, vararg ipath: Int): Int? { val path = StringBuilder() for (iel in ipath) path.append("/").append(iel.toString()) return (map[makeFullName(name, path.toString())] as? En1545ValueInt)?.v } fun getIntOrZero(name: String, path: String = "") = getInt(name, path) ?: 0 fun getString(name: String, path: String = ""): String? { return (map[makeFullName(name, path)] as? En1545ValueString)?.v } fun getTimeStamp(name: String, tz: MetroTimeZone): Timestamp? { if (contains(En1545FixedInteger.dateTimeName(name))) return En1545FixedInteger.parseTimeSec( getIntOrZero(En1545FixedInteger.dateTimeName(name)), tz) if (contains(En1545FixedInteger.dateTimeLocalName(name))) return En1545FixedInteger.parseTimeSecLocal( getIntOrZero(En1545FixedInteger.dateTimeLocalName(name)), tz) if (contains(En1545FixedInteger.timeName(name)) && contains(En1545FixedInteger.dateName(name))) return En1545FixedInteger.parseTime( getIntOrZero(En1545FixedInteger.dateName(name)), getIntOrZero(En1545FixedInteger.timeName(name)), tz) if (contains(En1545FixedInteger.timeLocalName(name)) && contains(En1545FixedInteger.dateName(name))) return En1545FixedInteger.parseTimeLocal( getIntOrZero(En1545FixedInteger.dateName(name)), getIntOrZero(En1545FixedInteger.timeLocalName(name)), tz) if (contains(En1545FixedInteger.timePacked16Name(name)) && contains(En1545FixedInteger.dateName(name))) return En1545FixedInteger.parseTimePacked16( getIntOrZero(En1545FixedInteger.dateName(name)), getIntOrZero(En1545FixedInteger.timePacked16Name(name)), tz) if (contains(En1545FixedInteger.timePacked11LocalName(name)) && contains(En1545FixedInteger.datePackedName(name))) return En1545FixedInteger.parseTimePacked11Local( getIntOrZero(En1545FixedInteger.datePackedName(name)), getIntOrZero(En1545FixedInteger.timePacked11LocalName(name)), tz) if (contains(En1545FixedInteger.dateName(name))) return En1545FixedInteger.parseDate( getIntOrZero(En1545FixedInteger.dateName(name)), tz) if (contains(En1545FixedInteger.datePackedName(name))) return En1545FixedInteger.parseDatePacked( getIntOrZero(En1545FixedInteger.datePackedName(name))) if (contains(En1545FixedInteger.dateBCDName(name))) return En1545FixedInteger.parseDateBCD( getIntOrZero(En1545FixedInteger.dateBCDName(name))) return null // TODO: any need to support time-only cases? } fun contains(name: String, path: String = ""): Boolean { return map.containsKey(makeFullName(name, path)) } fun append(data: ImmutableByteArray, off: Int, field: En1545Field): En1545Parsed { field.parseField(data, off, "", this) { obj, offset, len -> obj.getBitsFromBuffer(offset, len) } return this } fun appendLeBits(data: ImmutableByteArray, off: Int, field: En1545Field): En1545Parsed { field.parseField(data, off, "", this) { obj, offset, len -> obj.getBitsFromBufferLeBits(offset, len) } return this } fun append(data: ImmutableByteArray, field: En1545Field): En1545Parsed { return append(data, 0, field) } fun appendLeBits(data: ImmutableByteArray, field: En1545Field): En1545Parsed { return appendLeBits(data, 0, field) } companion object { private fun makeFullName(name: String, path: String?): String { return if (path == null || path.isEmpty()) name else "$path/$name" } private fun dig2(v: Int): String = when (v) { in 0..9 -> "0$v" else -> "$v" } } }
gpl-3.0
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-5/app/src/main/java/dev/mfazio/pennydrop/binding/BindingAdapters.kt
4
261
package dev.mfazio.pennydrop.binding import android.view.View import androidx.databinding.BindingAdapter @BindingAdapter("isHidden") fun bindIsHidden(view: View, isInvisible: Boolean) { view.visibility = if (isInvisible) View.INVISIBLE else View.VISIBLE }
apache-2.0
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/TransitData.kt
1
9773
/* * TransitData.kt * * Copyright 2011-2014 Eric Butler <[email protected]> * Copyright 2015-2019 Michael Farrell <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit import au.id.micolous.metrodroid.multi.* import au.id.micolous.metrodroid.time.Daystamp import au.id.micolous.metrodroid.time.Timestamp import au.id.micolous.metrodroid.ui.HeaderListItem import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.Preferences import au.id.micolous.metrodroid.util.TripObfuscator abstract class TransitData : Parcelable { /** * The (currency) balance of the card's _purse_. Most cards have only one purse. * * By default, this returns `null`, so no balance information will be displayed (and it is presumed unknown). * * If a card **only** stores season passes or a number of credited rides (instead of currency), return `null`. * * Cards with more than one purse must implement [balances] instead. * * Cards with a single purse _should_ implement this method, and [TransitData.balance] will automatically handle * the conversion. * * Note: This method is protected -- callers must use [balances], even in the case there is only one purse. * * @see balances * @return The balance of the card, or `null` if it is not known. */ protected open val balance: TransitBalance? get() = null /** * The (currency) balances of all of the card's _purses_. * * Cards with multiple "purse" balances (generally: hybrid transit cards that can act as multiple transit cards) * must implement this method, and must not implement [balance]. * * Cards with a single "purse" balance should implement [balance] instead -- the default implementation in * [TransitData] will automatically up-convert it. * * @return The purse balance(s) of the card, or `null` if it is not known. */ open val balances: List<TransitBalance>? get() { val b = balance ?: return null return listOf(b) } /** * The serial number of the card. Generally printed on the card itself, or shown on receipts from ticket vending * machines. * * If a card has more than one serial number, then show the second serial number in [info]. */ abstract val serialNumber: String? /** * Lists all trips on the card. * * If the transit card does not store trip information, or the [TransitData] implementation does not support * reading trips yet, return `null`. * * If the [TransitData] implementation supports reading trip data, but no trips have been taken on the card, return * an [emptyList]. * * Note: UI elements must use [prepareTrips] instead, which implements obfuscation. * * @return A [List] of [Trip]s, or `null` if not supported. * @see [prepareTrips] */ open val trips: List<Trip>? get() = null open val subscriptions: List<Subscription>? get() = null /** * Allows [TransitData] implementors to show extra information that doesn't fit within the standard bounds of the * interface. By default, this returns `null`, which hides the "Info" tab. * * Implementors **must** implement obfuscation through this method: * * * Check for [Preferences.hideCardNumbers] whenever you show a card number, or other mark (such as name, height, * weight, birthday or gender) that could be used to identify this card or its holder. * * * Pass dates and times ([Timestamp] and [Daystamp]) through [TripObfuscator.maybeObfuscateTS]. * * * Pass all currency amounts through [TransitCurrency.formatCurrencyString] and * [TransitCurrency.maybeObfuscateBalance]. * */ open val info: List<ListItem>? get() = null abstract val cardName: String /** * You can optionally add a link to an FAQ page for the card. This will be shown in the ... * drop down menu for cards that are supported, and on the main page for subclasses of * [au.id.micolous.metrodroid.transit.serialonly.SerialOnlyTransitData]. * * @return Uri pointing to an FAQ page, or null if no page is to be supplied. */ open val moreInfoPage: String? get() = null /** * You may optionally link to a page which allows you to view the online services for the card. * * By default, this returns `null`, which causes the menu item to be removed. * * @return Uri to card's online services page. */ open val onlineServicesPage: String? get() = null open val warning: String? get() = null /** * If a [TransitData] provider doesn't know some of the stops / stations on a user's card, * then it may raise a signal to the user to submit the unknown stations to our web service. * * @return false if all stations are known (default), true if there are unknown stations */ open val hasUnknownStations: Boolean get() = false /** * Finds the [Daystamp] of the latest [Trip] taken on the card. This value is **not** obfuscated. * * This is helpful for cards that define their [balance] validity period as "_n_ years since last use". * * @return Latest timestamp of a trip, or `null` if there are no trips or no trips with timestamps. */ fun getLastUseDaystamp(): Daystamp? { // Find the last trip taken on the card. return trips?.mapNotNull { t -> t.endTimestamp ?: t.startTimestamp }?.map { it.toDaystamp() } ?.maxBy { it.daysSinceEpoch } } /** * Declares levels of raw information to display, useful for development and debugging. */ enum class RawLevel { /** Display no extra information (default). */ NONE, /** Display only unknown fields, or fields that are not displayed in other contexts. */ UNKNOWN_ONLY, /** Display all fields, even ones that are decoded in other contexts. */ ALL; companion object { fun fromString(v: String): RawLevel? = values().find { it.toString() == v } } } /** * Prepares a list of trips for display in the UI. * * This will obfuscate trip details if the user has enabled one of the trip obfuscation [Preferences]. * * @param safe When `false` (default), the exact [trips] will be returned verbatim if no obfuscation [Preferences] * have been enabled. * * When `true`, [trips] is passed through [TripObfuscator] regardless of whether the user has enabled one * of the trip obfuscation [Preferences]. If no obfuscation flags are enabled, [TripObfuscator] will simply copy * all fields verbatim. * * This is required for Swift interop, as properties can't throw exceptions in Swift. * * @return A list of trips for display purposes. If [trips] is null, this also returns null. * * @see [trips], [TripObfuscator.obfuscateTrips] */ @NativeThrows fun prepareTrips(safe: Boolean = false): List<Trip>? = logAndSwiftWrap ("TransitData", "prepareTrips failed") lam@{ val trips = this.trips ?: return@lam null val maybeObfuscatedTrips = if (safe || Preferences.obfuscateTripDates || Preferences.obfuscateTripTimes || Preferences.obfuscateTripFares) { TripObfuscator.obfuscateTrips(trips, Preferences.obfuscateTripDates, Preferences.obfuscateTripTimes, Preferences.obfuscateTripFares) } else { trips } // Explicitly sort these events return@lam maybeObfuscatedTrips.sortedWith(Trip.Comparator()) } /** * Raw field information from the card, which is only useful for development and debugging. By default, this * returns `null`. * * This has the same semantics as [info], except obfuscation is never used on these fields. * * This is only called when [Preferences.rawLevel] is not [RawLevel.NONE]. * * @param level Level of detail requested. * @see [info] */ open fun getRawFields(level: RawLevel): List<ListItem>? = null companion object { fun mergeInfo(transitData: TransitData): List<ListItem>? { val rawLevel = Preferences.rawLevel val inf = transitData.info if (rawLevel == RawLevel.NONE) return inf val rawInf = transitData.getRawFields(rawLevel) ?: return inf return inf.orEmpty() + listOf(HeaderListItem(Localizer.localizeString(R.string.raw_header))) + rawInf } fun hasInfo(transitData: TransitData): Boolean { if (transitData.info != null) return true val rawLevel = Preferences.rawLevel if (rawLevel == RawLevel.NONE) return false return transitData.getRawFields(rawLevel) != null } } }
gpl-3.0
JavaEden/Orchid-Core
OrchidCore/src/main/kotlin/com/eden/orchid/impl/compilers/clog/ClogSetupListener.kt
2
6601
package com.eden.orchid.impl.compilers.clog import com.caseyjbrooks.clog.Clog import com.caseyjbrooks.clog.ClogLogger import com.caseyjbrooks.clog.DefaultLogger import com.caseyjbrooks.clog.parseltongue.Parseltongue import com.eden.orchid.Orchid import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.compilers.TemplateFunction import com.eden.orchid.api.events.On import com.eden.orchid.api.events.OrchidEventListener import com.eden.orchid.utilities.SuppressedWarnings import java.util.Arrays import java.util.HashMap import java.util.HashSet import java.util.logging.Handler import java.util.logging.Level import java.util.logging.LogManager import java.util.logging.LogRecord import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton @Singleton @JvmSuppressWildcards @Suppress(SuppressedWarnings.UNUSED_PARAMETER) class ClogSetupListener @Inject constructor( private val contextProvider: Provider<OrchidContext>, private val templateTagsProvider: Provider<Set<TemplateFunction>> ) : OrchidEventListener { private val warningLogger = AbstractLogCollector(contextProvider, "Warnings:", Clog.Priority.WARNING) private val errorLogger = AbstractLogCollector(contextProvider, "Errors:", Clog.Priority.ERROR) private val fatalLogger = AbstractLogCollector(contextProvider, "Fatal exceptions:", Clog.Priority.FATAL) @On(Orchid.Lifecycle.InitComplete::class) fun onInitComplete(event: Orchid.Lifecycle.InitComplete) { Clog.getInstance().addLogger(Clog.KEY_W, warningLogger) Clog.getInstance().addLogger(Clog.KEY_E, errorLogger) Clog.getInstance().addLogger(Clog.KEY_WTF, fatalLogger) } @On(Orchid.Lifecycle.OnStart::class) fun onStart(event: Orchid.Lifecycle.OnStart) { val formatter = Clog.getInstance().formatter if (formatter is Parseltongue) { val incantations = templateTagsProvider.get() .map { templateTag -> ClogIncantationWrapper( contextProvider, templateTag.name, Arrays.asList(*templateTag.parameters()), templateTag.javaClass ) } formatter.addSpells(*incantations.toTypedArray()) } } @On(Orchid.Lifecycle.BuildFinish::class) fun onBuildFinish(event: Orchid.Lifecycle.BuildFinish) { printPendingMessages() } @On(Orchid.Lifecycle.DeployFinish::class) fun onBuildFinish(deployFinish: Orchid.Lifecycle.DeployFinish) { printPendingMessages() } @On(Orchid.Lifecycle.Shutdown::class) fun onShutdown(event: Orchid.Lifecycle.Shutdown) { printPendingMessages() } private fun printPendingMessages() { warningLogger.printAllMessages() errorLogger.printAllMessages() fatalLogger.printAllMessages() } companion object { @JvmStatic fun registerJavaLoggingHandler() { //reset() will remove all default handlers LogManager.getLogManager().reset() val rootLogger = LogManager.getLogManager().getLogger("") // add our custom Java Logging handler rootLogger.addHandler(ClogJavaLoggingHandler()) // ignore annoying Hibernate Validator and JSass messages Clog.getInstance().addTagToBlacklist("org.hibernate.validator.internal.util.Version") Clog.getInstance().addTagToBlacklist("io.bit3.jsass.adapter.NativeLoader") // Ignore Pebble internal logging Clog.getInstance().addTagToBlacklist("com.mitchellbosecke.pebble.lexer.LexerImpl") Clog.getInstance().addTagToBlacklist("com.mitchellbosecke.pebble.lexer.TemplateSource") Clog.getInstance().addTagToBlacklist("com.mitchellbosecke.pebble.PebbleEngine") } } } data class LogMessage(val message: String, val throwable: Throwable?) private class AbstractLogCollector( val contextProvider: Provider<OrchidContext>, val headerMessage: String, val loggerPriority: Clog.Priority ) : ClogLogger { val messages: MutableMap<String, MutableSet<LogMessage>> = HashMap() override fun priority(): Clog.Priority = loggerPriority override fun isActive(): Boolean = true override fun log(tag: String, message: String): Int { messages.getOrPut(tag) { HashSet() }.add(LogMessage(message, null)) if (!contextProvider.get().state.isWorkingState) { printAllMessages() } return 0 } override fun log(tag: String, message: String, throwable: Throwable): Int { messages.getOrPut(tag) { HashSet() }.add(LogMessage(message, null)) if (!contextProvider.get().state.isWorkingState) { printAllMessages() } return 0 } fun printAllMessages() { if (messages.size > 0) { val logger = DefaultLogger(priority()) logger.log("", headerMessage) messages.forEach { tag, logMessages -> logger.log(tag, "") logMessages.forEach { message -> if (message.throwable != null) { logger.log("", " - " + message.message, message.throwable) } else { logger.log("", " - " + message.message) } } println("") } messages.clear() println("") } } } private class ClogJavaLoggingHandler : Handler() { override fun publish(record: LogRecord) { val level = record.level val levelInt = level.intValue() val clog = Clog.tag(record.sourceClassName) if (level == Level.OFF) { // do nothing } else if (level == Level.ALL) { // always log at verbose level clog.v(record.message) } else { // log at closest Clog level if (levelInt >= Level.SEVERE.intValue()) { clog.e(record.message) } else if (levelInt >= Level.WARNING.intValue()) { clog.w(record.message) } else if (levelInt >= Level.INFO.intValue()) { clog.i(record.message) } else if (levelInt >= Level.CONFIG.intValue()) { clog.d(record.message) } else { clog.v(record.message) } } } override fun flush() {} @Throws(SecurityException::class) override fun close() { } }
mit
spinnaker/orca
orca-remote-stage/src/main/kotlin/com/netflix/spinnaker/orca/remote/model/RemoteStageExtensionPayload.kt
3
627
package com.netflix.spinnaker.orca.remote.model import com.netflix.spinnaker.kork.plugins.remote.extension.transport.RemoteExtensionPayload /** * The payload sent to the remote stage on invocation. */ data class RemoteStageExtensionPayload( /** The remote stage type. */ val type: String, /** The stage execution ID. */ val id: String, /** The pipeline execution ID that the stage execution ID belongs to. */ val pipelineExecutionId: String, /** The stage context which will contain all the stage parameters and configuration details. */ val context: MutableMap<String, Any?> ) : RemoteExtensionPayload
apache-2.0
GunoH/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/mirror/provider.kt
4
2509
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror import com.sun.jdi.* import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.DefaultExecutionContext import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty interface ReferenceTypeProvider { fun getCls(): ClassType } interface MirrorProvider<T, F> { fun mirror(value: T?, context: DefaultExecutionContext): F? fun isCompatible(value: T?): Boolean } class MethodMirrorDelegate<T, F>(val name: String, private val mirrorProvider: MirrorProvider<T, F>, val signature: String? = null) : ReadOnlyProperty<ReferenceTypeProvider, MethodEvaluator.MirrorMethodEvaluator<T, F>> { override fun getValue(thisRef: ReferenceTypeProvider, property: KProperty<*>): MethodEvaluator.MirrorMethodEvaluator<T, F> { val methods = if (signature == null) thisRef.getCls().methodsByName(name) else thisRef.getCls().methodsByName(name, signature) return MethodEvaluator.MirrorMethodEvaluator(methods.singleOrNull(), mirrorProvider) } } class MethodDelegate<T>(val name: String, val signature: String? = null) : ReadOnlyProperty<ReferenceTypeProvider, MethodEvaluator<T>> { override fun getValue(thisRef: ReferenceTypeProvider, property: KProperty<*>): MethodEvaluator<T> { val methods = if (signature == null) thisRef.getCls().methodsByName(name) else thisRef.getCls().methodsByName(name, signature) return MethodEvaluator.DefaultMethodEvaluator(methods.singleOrNull()) } } class FieldMirrorDelegate<T, F>(val name: String, private val mirrorProvider: MirrorProvider<T, F>) : ReadOnlyProperty<ReferenceTypeProvider, FieldEvaluator.MirrorFieldEvaluator<T, F>> { override fun getValue(thisRef: ReferenceTypeProvider, property: KProperty<*>): FieldEvaluator.MirrorFieldEvaluator<T, F> { return FieldEvaluator.MirrorFieldEvaluator(thisRef.getCls().fieldByName(name), thisRef, mirrorProvider) } } class FieldDelegate<T>(val name: String) : ReadOnlyProperty<ReferenceTypeProvider, FieldEvaluator<T>> { override fun getValue(thisRef: ReferenceTypeProvider, property: KProperty<*>): FieldEvaluator<T> { return FieldEvaluator.DefaultFieldEvaluator(thisRef.getCls().fieldByName(name), thisRef) } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/copyright/tests/testData/update/MultiComments.kt
8
119
/* PRESENT 1 */ /* PRESENT 2 */ // PRESENT 3 /** PRESENT */ package/* ABSENT 1 */ normal /* ABSENT 2 */ // COMMENTS: 4
apache-2.0
GunoH/intellij-community
plugins/repository-search/src/main/kotlin/org/jetbrains/idea/packagesearch/api/PackageSearchApiClient.kt
2
6475
/* * 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 org.jetbrains.idea.packagesearch.api import com.intellij.openapi.components.service import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.engine.HttpClientEngine import io.ktor.client.engine.cio.CIO import io.ktor.client.plugins.DefaultRequest import io.ktor.client.plugins.HttpRequestRetry import io.ktor.client.plugins.HttpTimeout import io.ktor.client.plugins.UserAgent import io.ktor.client.plugins.cache.HttpCache import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.plugins.logging.Logging import io.ktor.client.request.accept import io.ktor.http.ContentType import io.ktor.http.appendEncodedPathSegments import io.ktor.http.path import io.ktor.serialization.kotlinx.json.json import kotlinx.serialization.json.Json import org.jetbrains.idea.packagesearch.DefaultPackageServiceConfig import org.jetbrains.idea.packagesearch.HashingAlgorithm import org.jetbrains.idea.packagesearch.PackageSearchServiceConfig import org.jetbrains.idea.reposearch.DependencySearchBundle import org.jetbrains.packagesearch.api.statistics.ApiStatisticsResponse import org.jetbrains.packagesearch.api.v2.ApiPackageResponse import org.jetbrains.packagesearch.api.v2.ApiPackagesResponse import org.jetbrains.packagesearch.api.v2.ApiRepositoriesResponse import org.jetbrains.packagesearch.api.v2.ApiStandardPackage import java.io.Closeable class PackageSearchApiClient( private val config: PackageSearchServiceConfig = service<DefaultPackageServiceConfig>(), engine: HttpClientEngine? = null, ) : Closeable { private val clientConfig: HttpClientConfig<*>.() -> Unit get() = { install(ContentNegotiation) { val json = Json { ignoreUnknownKeys = true encodeDefaults = false } packageSearch(json) json(json) } install(Logging) { logger = config.logger level = config.logLevel } install(UserAgent) { agent = config.userAgent } install(DefaultRequest) { url { protocol = config.protocol host = config.host path("api/") } } install(HttpTimeout) { requestTimeout = config.timeout } install(HttpRequestRetry) { retryOnServerErrors(5) constantDelay() } if (config.useCache) install(HttpCache) } private val httpClient = if (engine != null) HttpClient(engine, clientConfig) else HttpClient(CIO, clientConfig) private val maxRequestResultsCount = 25 private val maxMavenCoordinatesParts = 3 suspend fun packagesByQuery( searchQuery: String, onlyStable: Boolean = false, onlyMpp: Boolean = false, repositoryIds: List<String> = emptyList() ): ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> { if (searchQuery.isEmpty()) { return emptyStandardV2PackagesWithRepos } return httpClient.getBody { url { appendEncodedPathSegments("package") parameters { append("query", searchQuery) append("onlyStable", onlyStable) append("onlyMpp", onlyMpp) if (repositoryIds.isNotEmpty()) { append("repositoryIds", repositoryIds) } } } } } suspend fun suggestPackages( groupId: String?, artifactId: String?, onlyMpp: Boolean = false, repositoryIds: List<String> = emptyList() ): ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> { if (groupId == null && artifactId == null) { return emptyStandardV2PackagesWithRepos } return httpClient.getBody { url { appendEncodedPathSegments("packages") parameters { append("groupid", groupId ?: "") append("artifactid", artifactId ?: "") append("onlyMpp", onlyMpp) if (repositoryIds.isNotEmpty()) { append("repositoryIds", repositoryIds) } } } } } suspend fun packagesByRange(range: List<String>): ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> { if (range.isEmpty()) { return emptyStandardV2PackagesWithRepos } require(range.size <= maxRequestResultsCount) { DependencySearchBundle.message("reposearch.search.client.error.too.many.requests.for.range") } require(range.none { it.split(":").size >= maxMavenCoordinatesParts }) { DependencySearchBundle.message("reposearch.search.client.error.no.versions.for.range") } return httpClient.getBody { url { appendEncodedPathSegments("package") parameters { append("range", range) } } } } suspend fun packageByHash( hash: String, hashingAlgorithm: HashingAlgorithm ): ApiPackageResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> = httpClient.getBody { url { appendEncodedPathSegments("package") parameters { append(hashingAlgorithm.name.lowercase(), hash) } } } suspend fun packageById(id: String): ApiPackageResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> = httpClient.getBody { url { appendEncodedPathSegments("package", id) } } suspend fun readmeByPackageId(id: String): String = httpClient.getBody { url { appendEncodedPathSegments("package", id, "readme") } accept(ContentType.Text.Html) } suspend fun statistics(): ApiStatisticsResponse = httpClient.getBody { url { appendEncodedPathSegments("statistics") } } suspend fun repositories(): ApiRepositoriesResponse = httpClient.getBody { url { appendEncodedPathSegments("repositories") } } override fun close() = httpClient.close() }
apache-2.0
yongce/AndroidLib
baseLib/src/main/java/me/ycdev/android/lib/common/utils/MainHandler.kt
1
200
package me.ycdev.android.lib.common.utils import android.os.Handler import android.os.Looper @Suppress("unused", "MemberVisibilityCanBePrivate") object MainHandler : Handler(Looper.getMainLooper())
apache-2.0
Novatec-Consulting-GmbH/testit-testutils
logrecorder/logrecorder-log4j/src/main/kotlin/info/novatec/testit/logrecorder/log4j/junit5/RecordLoggers.kt
1
1507
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package info.novatec.testit.logrecorder.log4j.junit5 import org.junit.jupiter.api.extension.ExtendWith import kotlin.reflect.KClass /** * Annotating any test method with this annotation will start the recording of * log messages while the test method is executed. * * Only those loggers configured with this annotation - either by it's class or * name - will be recorded! Multiple loggers can be set by either method and * combinations between class and explicit names are possible as well. * * @see value * @see names * @since 1.0 */ @Retention @Target(AnnotationTarget.FUNCTION) @ExtendWith(Log4jRecorderExtension::class) annotation class RecordLoggers( /** * Classes who's name should be used to identify loggers to record. */ vararg val value: KClass<*> = [], /** * Names of loggers to record. */ val names: Array<String> = [] )
apache-2.0
cfieber/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/StartTaskHandler.kt
1
2219
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.Task import com.netflix.spinnaker.orca.events.TaskStarted import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.orca.q.StartTask import com.netflix.spinnaker.q.Queue import org.springframework.beans.factory.annotation.Qualifier import org.springframework.context.ApplicationEventPublisher import org.springframework.stereotype.Component import java.time.Clock @Component class StartTaskHandler( override val queue: Queue, override val repository: ExecutionRepository, override val contextParameterProcessor: ContextParameterProcessor, @Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher, private val clock: Clock ) : OrcaMessageHandler<StartTask>, ExpressionAware { override fun handle(message: StartTask) { message.withTask { stage, task -> task.status = RUNNING task.startTime = clock.millis() val mergedContextStage = stage.withMergedContext() repository.storeStage(mergedContextStage) queue.push(RunTask(message, task.id, task.type)) publisher.publishEvent(TaskStarted(this, mergedContextStage, task)) } } override val messageType = StartTask::class.java @Suppress("UNCHECKED_CAST") private val com.netflix.spinnaker.orca.pipeline.model.Task.type get() = Class.forName(implementingClass) as Class<out Task> }
apache-2.0
Flocksserver/Androidkt-CleanArchitecture-Template
app/src/main/java/de/flocksserver/androidkt_cleanarchitecture_template/model/mapper/ContentVMMapper.kt
1
938
package de.flocksserver.androidkt_cleanarchitecture_template.model.mapper import de.flocksserver.androidkt_cleanarchitecture_template.model.ContentViewModel import de.flocksserver.domain.model.ContentModel import javax.inject.Inject /** * Created by marcel on 10.08.17. */ class ContentVMMapper @Inject constructor( private val itemVMMapper: ItemViewMapper ) : BaseMapperMVM<ContentViewModel, ContentModel>() { override fun transformMtoVM(model: ContentModel?): ContentViewModel? { if (model != null) { return ContentViewModel( itemVMMapper.transformMtoVM(model.items) ) } return null } override fun transformVMtoM(viewModel: ContentViewModel?): ContentModel? { if (viewModel != null) { return ContentModel( itemVMMapper.transformVMtoM(viewModel.items) ) } return null } }
apache-2.0
cmzy/okhttp
buildSrc/src/main/kotlin/artifacts.kt
1
1999
/* * Copyright (C) 2021 Square, 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 * * 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. */ import aQute.bnd.gradle.BundleTaskExtension import java.io.File import org.gradle.api.Project import org.gradle.api.plugins.ExtensionAware import org.gradle.api.tasks.SourceSetContainer import org.gradle.kotlin.dsl.apply import org.gradle.kotlin.dsl.get fun Project.applyOsgi(vararg bndProperties: String) { apply(plugin = "biz.aQute.bnd.builder") val osgi = sourceSets.create("osgi") tasks["jar"].extensions.configure<BundleTaskExtension>(BundleTaskExtension.NAME) { setClasspath(osgi.compileClasspath + sourceSets["main"].compileClasspath) bnd(*bndProperties) } dependencies.add("osgiApi", Dependencies.kotlinStdlibOsgi) } /** * Returns a .jar file for the golden version of this project. * https://github.com/Visistema/Groovy1/blob/ba5eb9b2f19ca0cc8927359ce414c4e1974b7016/gradle/binarycompatibility.gradle#L48 */ fun Project.baselineJar(version: String = "3.14.1"): File? { val originalGroup = group return try { val jarFile = "$name-$version.jar" group = "virtual_group_for_japicmp" val dependency = dependencies.create("$originalGroup:$name:$version@jar") configurations.detachedConfiguration(dependency).files.find { (it.name == jarFile) } } catch (e: Exception) { null } finally { group = originalGroup } } val Project.sourceSets: SourceSetContainer get() = (this as ExtensionAware).extensions["sourceSets"] as SourceSetContainer
apache-2.0
mdanielwork/intellij-community
platform/script-debugger/protocol/protocol-reader/src/TypeWriter.kt
3
8531
// 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.protocolReader import org.jetbrains.jsonProtocol.JsonObjectBased import java.lang.reflect.Method import java.util.* internal const val FIELD_PREFIX = '_' internal const val NAME_VAR_NAME = "_n" private fun assignField(out: TextOutput, fieldName: String) = out.append(FIELD_PREFIX).append(fieldName).append(" = ") internal class TypeRef<T>(val typeClass: Class<T>) { var type: TypeWriter<T>? = null } internal class TypeWriter<T>(val typeClass: Class<T>, jsonSuperClass: TypeRef<*>?, private val volatileFields: List<VolatileFieldBinding>, private val methodHandlerMap: LinkedHashMap<Method, MethodHandler>, /** Loaders that should read values and save them in field array on parse time. */ private val fieldLoaders: List<FieldLoader>, private val hasLazyFields: Boolean) { /** Subtype aspects of the type or null */ val subtypeAspect = if (jsonSuperClass == null) null else ExistingSubtypeAspect(jsonSuperClass) fun writeInstantiateCode(scope: ClassScope, out: TextOutput) { writeInstantiateCode(scope, false, out) } fun writeInstantiateCode(scope: ClassScope, deferredReading: Boolean, out: TextOutput) { val className = scope.getTypeImplReference(this) if (deferredReading || subtypeAspect == null) { out.append(className) } else { subtypeAspect.writeInstantiateCode(className, out) } } fun write(fileScope: FileScope) { val out = fileScope.output val valueImplClassName = fileScope.getTypeImplShortName(this) out.append("private class ").append(valueImplClassName).append('(').append(JSON_READER_PARAMETER_DEF).comma().append("preReadName: String?") subtypeAspect?.writeSuperFieldJava(out) out.append(") : ").append(typeClass.canonicalName).openBlock() if (hasLazyFields || JsonObjectBased::class.java.isAssignableFrom(typeClass)) { out.append("private var ").append(PENDING_INPUT_READER_NAME).append(": ").append(JSON_READER_CLASS_NAME).append("? = reader.subReader()!!").newLine() } val classScope = fileScope.newClassScope() for (field in volatileFields) { field.writeFieldDeclaration(classScope, out) out.newLine() } for (loader in fieldLoaders) { if (loader.asImpl) { out.append("override") } else { out.append("private") } out.append(" var ").appendName(loader) fun addType() { out.append(": ") loader.valueReader.appendFinishedValueTypeName(out) out.append("? = null") } if (loader.valueReader is PrimitiveValueReader) { val defaultValue = loader.defaultValue ?: loader.valueReader.defaultValue if (defaultValue != null) { out.append(" = ").append(defaultValue) } else { addType() } } else { addType() } out.newLine() } if (fieldLoaders.isNotEmpty()) { out.newLine() } writeConstructorMethod(classScope, out) out.newLine() subtypeAspect?.writeParseMethod(classScope, out) for ((key, value) in methodHandlerMap.entries) { out.newLine() value.writeMethodImplementationJava(classScope, key, out) out.newLine() } writeBaseMethods(out) subtypeAspect?.writeGetSuperMethodJava(out) writeEqualsMethod(valueImplClassName, out) out.indentOut().append('}') } /** * Generates Java implementation of standard methods of JSON type class (if needed): * {@link org.jetbrains.jsonProtocol.JsonObjectBased#getDeferredReader()} */ private fun writeBaseMethods(out: TextOutput) { val method: Method try { method = typeClass.getMethod("getDeferredReader") } catch (ignored: NoSuchMethodException) { // Method not found, skip. return } out.newLine() writeMethodDeclarationJava(out, method) out.append(" = ").append(PENDING_INPUT_READER_NAME) } private fun writeEqualsMethod(valueImplClassName: String, out: TextOutput) { if (fieldLoaders.isEmpty()) { return } out.newLine().append("override fun equals(other: Any?): Boolean = ") out.append("other is ").append(valueImplClassName) // at first we should compare primitive values, then enums, then string, then objects fun fieldWeight(reader: ValueReader): Int { var w = 10 if (reader is PrimitiveValueReader) { w-- if (reader.className != "String") { w-- } } else if (reader is EnumReader) { // -1 as primitive, -1 as not a string w -= 2 } return w } for (loader in fieldLoaders.sortedWith(Comparator<FieldLoader> { f1, f2 -> fieldWeight((f1.valueReader)) - fieldWeight((f2.valueReader))})) { out.append(" && ") out.appendName(loader).append(" == ").append("other.").appendName(loader) } out.newLine() } private fun writeConstructorMethod(classScope: ClassScope, out: TextOutput) { out.append("init").block { if (fieldLoaders.isEmpty()) { out.append(READER_NAME).append(".skipValue()") } else { out.append("var ").append(NAME_VAR_NAME).append(" = preReadName") out.newLine().append("if (").append(NAME_VAR_NAME).append(" == null && reader.hasNext() && reader.beginObject().hasNext())").block { out.append(NAME_VAR_NAME).append(" = reader.nextName()") } out.newLine() writeReadFields(out, classScope) // we don't read all data if we have lazy fields, so, we should not check end of stream //if (!hasLazyFields) { out.newLine().newLine().append(READER_NAME).append(".endObject()") //} } } } private fun writeReadFields(out: TextOutput, classScope: ClassScope) { val stopIfAllFieldsWereRead = hasLazyFields val hasOnlyOneFieldLoader = fieldLoaders.size == 1 val isTracedStop = stopIfAllFieldsWereRead && !hasOnlyOneFieldLoader if (isTracedStop) { out.newLine().append("var i = 0") } out.newLine().append("loop@ while (").append(NAME_VAR_NAME).append(" != null)").block { (out + "when (" + NAME_VAR_NAME + ")").block { var isFirst = true for (fieldLoader in fieldLoaders) { if (fieldLoader.skipRead) { continue } if (!isFirst) { out.newLine() } out.append('"') if (fieldLoader.jsonName.first() == '$') { out.append('\\') } out.append(fieldLoader.jsonName).append('"').append(" -> ") if (stopIfAllFieldsWereRead && !isTracedStop) { out.openBlock() } val primitiveValueName = if (fieldLoader.valueReader is ObjectValueReader) fieldLoader.valueReader.primitiveValueName else null if (primitiveValueName != null) { out.append("if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_OBJECT)").openBlock() } out.appendName(fieldLoader).append(" = ") fieldLoader.valueReader.writeReadCode(classScope, false, out) if (primitiveValueName != null) { out.closeBlock().newLine().append("else").block { assignField(out, "${primitiveValueName}Type") out.append("reader.peek()").newLine() assignField(out, primitiveValueName) out + "reader.nextString(true)" } } if (stopIfAllFieldsWereRead && !isTracedStop) { out.newLine().append(READER_NAME).append(".skipValues()").newLine().append("break@loop").closeBlock() } if (isFirst) { isFirst = false } } out.newLine().append("else ->") if (isTracedStop) { out.block { out.append("reader.skipValue()") out.newLine() + NAME_VAR_NAME + " = reader.nextNameOrNull()" out.newLine() + "continue@loop" } } else { out.space().append("reader.skipValue()") } } out.newLine() + NAME_VAR_NAME + " = reader.nextNameOrNull()" if (isTracedStop) { out.newLine().newLine().append("if (i++ == ").append(fieldLoaders.size - 1).append(")").block { (out + READER_NAME + ".skipValues()").newLine() + "break" } } } } }
apache-2.0
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/views/ImagePreviewDialog.kt
1
6525
package org.wikipedia.views import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import androidx.core.os.bundleOf import com.google.android.material.bottomsheet.BottomSheetBehavior import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.schedulers.Schedulers import org.wikipedia.R import org.wikipedia.commons.ImageTagsProvider import org.wikipedia.databinding.DialogImagePreviewBinding import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.mwapi.MwQueryPage import org.wikipedia.descriptions.DescriptionEditActivity.Action import org.wikipedia.json.GsonMarshaller import org.wikipedia.json.GsonUnmarshaller import org.wikipedia.page.ExtendedBottomSheetDialogFragment import org.wikipedia.suggestededits.PageSummaryForEdit import org.wikipedia.util.DimenUtil import org.wikipedia.util.L10nUtil.setConditionalLayoutDirection import org.wikipedia.util.StringUtil import org.wikipedia.util.log.L class ImagePreviewDialog : ExtendedBottomSheetDialogFragment(), DialogInterface.OnDismissListener { private var _binding: DialogImagePreviewBinding? = null private val binding get() = _binding!! private lateinit var pageSummaryForEdit: PageSummaryForEdit private lateinit var action: Action private val disposables = CompositeDisposable() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = DialogImagePreviewBinding.inflate(inflater, container, false) pageSummaryForEdit = GsonUnmarshaller.unmarshal(PageSummaryForEdit::class.java, requireArguments().getString(ARG_SUMMARY)) action = requireArguments().getSerializable(ARG_ACTION) as Action setConditionalLayoutDirection(binding.root, pageSummaryForEdit.lang) return binding.root } override fun onStart() { super.onStart() BottomSheetBehavior.from(requireView().parent as View).peekHeight = DimenUtil.roundedDpToPx(DimenUtil.getDimension(R.dimen.imagePreviewSheetPeekHeight)) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.progressBar.visibility = VISIBLE binding.toolbarView.setOnClickListener { dismiss() } binding.titleText.text = StringUtil.removeHTMLTags(StringUtil.removeNamespace(pageSummaryForEdit.displayTitle!!)) loadImageInfo() } override fun onDestroyView() { binding.toolbarView.setOnClickListener(null) _binding = null disposables.clear() super.onDestroyView() } private fun showError(caught: Throwable?) { binding.dialogDetailContainer.layoutTransition = null binding.dialogDetailContainer.minimumHeight = 0 binding.progressBar.visibility = GONE binding.filePageView.visibility = GONE binding.errorView.visibility = VISIBLE binding.errorView.setError(caught) } private fun loadImageInfo() { lateinit var imageTags: Map<String, List<String>> lateinit var page: MwQueryPage var isFromCommons = false var thumbnailWidth = 0 var thumbnailHeight = 0 disposables.add(ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getImageInfo(pageSummaryForEdit.title, pageSummaryForEdit.lang) .subscribeOn(Schedulers.io()) .flatMap { if (it.query()!!.pages()!![0].imageInfo() == null) { // If file page originally comes from *.wikipedia.org (i.e. movie posters), it will not have imageInfo and pageId. ServiceFactory.get(pageSummaryForEdit.pageTitle.wikiSite).getImageInfo(pageSummaryForEdit.title, pageSummaryForEdit.lang) } else { // Fetch API from commons.wikimedia.org and check whether if it is not a "shared" image. isFromCommons = !it.query()!!.pages()!![0].isImageShared Observable.just(it) } } .flatMap { response -> page = response.query()!!.pages()!![0] if (page.imageInfo() != null) { val imageInfo = page.imageInfo()!! pageSummaryForEdit.timestamp = imageInfo.timestamp pageSummaryForEdit.user = imageInfo.user pageSummaryForEdit.metadata = imageInfo.metadata thumbnailWidth = imageInfo.thumbWidth thumbnailHeight = imageInfo.thumbHeight } ImageTagsProvider.getImageTagsObservable(page.pageId(), pageSummaryForEdit.lang) } .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate { binding.filePageView.visibility = VISIBLE binding.progressBar.visibility = GONE binding.filePageView.setup( this, pageSummaryForEdit, imageTags, page, binding.dialogDetailContainer.width, thumbnailWidth, thumbnailHeight, imageFromCommons = isFromCommons, showFilename = false, showEditButton = false, action = action ) } .subscribe({ imageTags = it }, { caught -> L.e(caught) showError(caught) })) } companion object { private const val ARG_SUMMARY = "summary" private const val ARG_ACTION = "action" fun newInstance(pageSummaryForEdit: PageSummaryForEdit, action: Action): ImagePreviewDialog { val dialog = ImagePreviewDialog() dialog.arguments = bundleOf(ARG_SUMMARY to GsonMarshaller.marshal(pageSummaryForEdit), ARG_ACTION to action) return dialog } } }
apache-2.0
fyookball/electrum
android/app/src/main/java/org/electroncash/electroncash3/Exchange.kt
1
1563
package org.electroncash.electroncash3 import androidx.lifecycle.MediatorLiveData val EXCHANGE_CALLBACKS = setOf("on_quotes", "on_history") val libExchange by lazy { libMod("exchange_rate") } val fiatUpdate = MediatorLiveData<Unit>().apply { value = Unit } val fx by lazy { daemonModel.daemon.get("fx")!! } fun initExchange() { settings.getString("currency").observeForever { fx.callAttr("set_currency", it) } settings.getString("use_exchange").observeForever { fx.callAttr("set_exchange", it) } with (fiatUpdate) { addSource(settings.getBoolean("use_exchange_rate"), { value = Unit }) addSource(settings.getString("currency"), { value = Unit }) addSource(settings.getString("use_exchange"), { value = Unit }) } } fun formatFiatAmountAndUnit(amount: Long): String? { val amountStr = formatFiatAmount(amount) if (amountStr == null) { return null } else { return amountStr + " " + formatFiatUnit() } } fun formatSatoshisAndFiat(amount: Long): String { var result = formatSatoshisAndUnit(amount) val fiat = formatFiatAmountAndUnit(amount) if (fiat != null) { result += " ($fiat)" } return result } fun formatFiatAmount(amount: Long): String? { if (!fx.callAttr("is_enabled").toBoolean()) { return null } val amountStr = fx.callAttr("format_amount", amount).toString() return if (amountStr.isEmpty()) null else amountStr } fun formatFiatUnit(): String { return fx.callAttr("get_currency").toString() }
mit
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/configuration/internal/MultiUserDatabaseManagerForD2ManagerUnitShould.kt
1
3888
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.configuration.internal import com.nhaarman.mockitokotlin2.* import org.hisp.dhis.android.core.arch.db.access.internal.DatabaseAdapterFactory import org.hisp.dhis.android.core.arch.storage.internal.Credentials import org.hisp.dhis.android.core.arch.storage.internal.ObjectKeyValueStore import org.hisp.dhis.android.core.common.BaseCallShould import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class MultiUserDatabaseManagerForD2ManagerUnitShould : BaseCallShould() { private val databaseAdapterFactory: DatabaseAdapterFactory = mock() private val migration: DatabaseConfigurationMigration = mock() private val databaseConfigurationStore: ObjectKeyValueStore<DatabasesConfiguration> = mock() private val username = "username" private val serverUrl = "https://dhis2.org" private val credentials = Credentials(username, serverUrl, "password", null) private val unencryptedDbName = "un.db" private val accountUnencrypted = DatabaseAccount.builder() .databaseName(unencryptedDbName) .username(username) .serverUrl(serverUrl) .encrypted(false) .databaseCreationDate(DATE) .build() private val databasesConfiguration = DatabasesConfiguration.builder() .accounts(listOf(accountUnencrypted)) .build() private lateinit var manager: MultiUserDatabaseManagerForD2Manager @Before @Throws(Exception::class) override fun setUp() { super.setUp() manager = MultiUserDatabaseManagerForD2Manager( databaseAdapter, migration, databaseAdapterFactory, databaseConfigurationStore ) whenever(databaseConfigurationStore.get()).doReturn(databasesConfiguration) } @Test fun not_try_to_load_db_if_not_logged_when_calling_loadIfLogged() { manager.loadIfLogged(null) verifyNoMoreInteractions(databaseAdapterFactory) } @Test fun load_db_if_logged_when_calling_loadIfLogged() { manager.loadIfLogged(credentials) verify(databaseAdapterFactory).createOrOpenDatabase(databaseAdapter, accountUnencrypted) } companion object { private const val DATE = "2014-06-06T20:44:21.375" } }
bsd-3-clause
Heapy/kpress
kpress-engine/src/main/kotlin/io/heapy/kpress/application/AsciiDocEngine.kt
1
1734
package io.heapy.kpress.application import io.heapy.kpress.engine.extensions.logger import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import kotlinx.coroutines.withContext import org.asciidoctor.Asciidoctor import org.asciidoctor.OptionsBuilder /** * Converts input data to html markup. * @author Ruslan Ibragimov */ class AsciiDocEngine( shutdownManager: ShutdownManager ) { init { shutdownManager.onShutdown("Asciidoctor") { if (asciidoctor.isActive || asciidoctor.isCompleted) { if (asciidoctor.isActive) LOGGER.info("Await Asciidoctor creation to stop Asciidoctor...") if (asciidoctor.isCompleted) LOGGER.info("Stopping asciidoctor...") asciidoctor.await().shutdown() LOGGER.info("Thanks Matsumoto, Asciidoctor stopped") } if (!asciidoctor.isActive && !asciidoctor.isCompleted) { LOGGER.info("Lucky, looks like you doesn't used Asciidoctor this time") } } } private val asciidoctor = GlobalScope.async(Dispatchers.IO, start = CoroutineStart.LAZY) { LOGGER.info("Creating asciidoctor... May take a while") Asciidoctor.Factory.create().also { LOGGER.info("Allons-y! Asciidoctor ${it.asciidoctorVersion()} created!") } } suspend fun convert(content: String): String = withContext(Dispatchers.IO) { val optionsBuilder = OptionsBuilder.options().inPlace(false) asciidoctor.await().convert(content, optionsBuilder) } companion object { private val LOGGER = logger<AsciiDocEngine>() } }
gpl-3.0
mcdimus/mate-wp
src/main/kotlin/ee/mcdimus/matewp/service/BingPhotoOfTheDayService.kt
1
1769
package ee.mcdimus.matewp.service import ee.mcdimus.matewp.model.ImageData import org.json.simple.JSONArray import org.json.simple.JSONObject import org.json.simple.JSONValue import org.json.simple.parser.ParseException import java.net.URL /** * @author Dmitri Maksimov */ class BingPhotoOfTheDayService { companion object { private const val BING_PHOTO_OF_THE_DAY_URL = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US" private const val START_DATE = "startdate" private const val COPYRIGHT = "copyright" private const val URL_BASE = "urlbase" private const val IMAGES = "images" } fun getData(): ImageData { val url = URL(BING_PHOTO_OF_THE_DAY_URL) val conn = url.openConnection() conn.inputStream.bufferedReader().use { try { val jsonObject = JSONValue.parseWithException(it) as JSONObject validateProperties(jsonObject, listOf(IMAGES)) val images = jsonObject[IMAGES] as JSONArray if (images.isEmpty()) { throw IllegalStateException("'$IMAGES' is empty") } val image = images[0] as JSONObject validateProperties(image, listOf(START_DATE, COPYRIGHT, URL_BASE)) return ImageData( startDate = image[START_DATE] as String, copyright = image[COPYRIGHT] as String, urlBase = image[URL_BASE] as String ) } catch(e: ParseException) { throw IllegalStateException(e.message) } } } private fun validateProperties(jsonObject: JSONObject, properties: List<String>) { for (property in properties) { if (!jsonObject.contains(property)) { throw IllegalStateException("$jsonObject has no required property '$property'") } } } }
mit
nadraliev/DsrWeatherApp
app/src/main/java/soutvoid/com/DsrWeatherApp/interactor/triggers/jobs/BaseTriggerJob.kt
1
516
package soutvoid.com.DsrWeatherApp.interactor.triggers.jobs import com.birbit.android.jobqueue.Job import com.birbit.android.jobqueue.Params import soutvoid.com.DsrWeatherApp.app.dagger.AppComponent import soutvoid.com.DsrWeatherApp.interactor.triggers.TriggersRepository import javax.inject.Inject abstract class BaseTriggerJob(params: Params): Job(params) { @Inject lateinit var triggerRep: TriggersRepository open fun inject(appComponent: AppComponent) { appComponent.inject(this) } }
apache-2.0
spotify/heroic
heroic-elasticsearch-utils/src/main/java/com/spotify/heroic/elasticsearch/RestClientWrapper.kt
1
2898
/* * Copyright (c) 2020 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.spotify.heroic.elasticsearch import com.spotify.heroic.common.Duration import com.spotify.heroic.elasticsearch.index.IndexMapping import eu.toolchain.async.AsyncFramework import org.apache.http.HttpHost import org.elasticsearch.client.RestClient import org.elasticsearch.client.RestHighLevelClient import org.elasticsearch.client.sniff.Sniffer import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms import java.net.InetAddress import java.net.UnknownHostException import java.util.concurrent.TimeUnit private const val DEFAULT_PORT = 9200 data class RestClientWrapper @JvmOverloads constructor( val seeds: List<String> = listOf("localhost"), val sniff: Boolean = false, val sniffInterval: Duration = Duration.of(30, TimeUnit.SECONDS) ): ClientWrapper<ParsedStringTerms> { private val client = RestHighLevelClient(RestClient.builder(*parseSeeds())) private val sniffer: Sniffer? = if (sniff) { Sniffer.builder(client.lowLevelClient) .setSniffIntervalMillis(sniffInterval.toMilliseconds().toInt()) .build() } else { null } override fun start( async: AsyncFramework, index: IndexMapping, templateName: String, type: BackendType ): Connection<ParsedStringTerms> { return RestConnection(client, sniffer, async, index, templateName, type) } private fun parseSeeds(): Array<HttpHost> { return seeds .map(::parseInetSocketTransportAddress) .map {(host, port) -> HttpHost(host, port) } .toTypedArray() } private fun parseInetSocketTransportAddress(seed: String): Pair<InetAddress, Int> { try { if (seed.contains(":")) { val parts = seed.split(":") return InetAddress.getByName(parts.first()) to parts.last().toInt() } return InetAddress.getByName(seed) to DEFAULT_PORT } catch (e: UnknownHostException) { throw RuntimeException(e) } } }
apache-2.0
Reacto-Rx/reactorx-core
library/src/main/kotlin/org/reactorx/state/model/Action.kt
1
99
package org.reactorx.state.model /** * @author Filip Prochazka (@filipproch) */ interface Action
mit
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/extractFunction/stringTemplates/fullContent.kt
13
317
// PARAM_DESCRIPTOR: value-parameter a: kotlin.Int defined in foo // PARAM_TYPES: kotlin.Int, kotlin.Number, kotlin.Comparable<kotlin.Int>, java.io.Serializable, kotlin.Any fun foo(a: Int): String { val x = "abc$a" val y = "abc${a}" val z = "abc{$a}def" return "<selection>abc$a</selection>" + "def" }
apache-2.0
subhalaxmin/Programming-Kotlin
Chapter07/src/main/kotlin/com/packt/chapter7/7.14.functions.kt
1
1087
package com.packt.chapter7 import kotlin.reflect.KClass import kotlin.reflect.declaredMemberExtensionFunctions import kotlin.reflect.functions import kotlin.reflect.memberFunctions import kotlin.reflect.memberProperties class Rocket() { var lat: Double = 0.0 var long: Double = 0.0 fun explode() { println("Boom") } fun setCourse(lat: Double, long: Double) { require(lat.isValid()) require(long.isValid()) this.lat = lat this.long = long } fun Double.isValid() = Math.abs(this) <= 180 } fun <T : Any> printFunctions(kclass: KClass<T>) { kclass.declaredMemberExtensionFunctions kclass.memberFunctions.forEach { println(it.name) } } fun <T : Any> printProperties(kclass: KClass<T>) { kclass.memberProperties.forEach { println(it.name) } } fun <T : Any> invokeExplodeFunction(kclass: KClass<T>) { val function = kclass.functions.find { it.name == "explode" } function?.call(Rocket()) } fun main(args: Array<String>) { printFunctions(Rocket::class) printProperties(Rocket::class) invokeExplodeFunction(Rocket::class) }
mit
securityfirst/Umbrella_android
app/src/main/java/org/secfirst/umbrella/feature/difficulty/view/DifficultyView.kt
1
347
package org.secfirst.umbrella.feature.difficulty.view import org.secfirst.umbrella.data.database.difficulty.Difficulty import org.secfirst.umbrella.feature.base.view.BaseView interface DifficultyView : BaseView { fun showDifficulties(difficulties: List<Difficulty>, toolbarTitle: String) fun startSegment(difficultyIds: List<String>) }
gpl-3.0
pflammertsma/cryptogram
app/src/main/java/com/pixplicity/cryptogram/models/PuzzleProgressState.kt
1
685
package com.pixplicity.cryptogram.models import com.google.gson.annotations.SerializedName import java.util.* class PuzzleProgressState { @SerializedName("current") var currentId: Int? = null private set @SerializedName("progress") private var mProgress: ArrayList<PuzzleProgress>? = null val progress: ArrayList<PuzzleProgress> get() { if (mProgress == null) { mProgress = ArrayList() } return mProgress!! } fun setCurrentId(puzzleId: Int) { currentId = puzzleId } fun addProgress(puzzleProgress: PuzzleProgress) { progress.add(puzzleProgress) } }
mit