repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
afollestad/material-cab | library/src/main/java/com/afollestad/materialcab/Callbacks.kt | 1 | 1539 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.materialcab
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewPropertyAnimator
import com.afollestad.materialcab.attached.AttachedCab
typealias CreateCallback = (cab: AttachedCab, menu: Menu) -> Unit
typealias SelectCallback = (item: MenuItem) -> Boolean
typealias DestroyCallback = (cab: AttachedCab) -> Boolean
typealias CabAnimator = (view: View, animator: ViewPropertyAnimator) -> Unit
typealias CabApply = AttachedCab.() -> Unit
internal fun List<CreateCallback>.invokeAll(
cab: AttachedCab,
menu: Menu
) = forEach { it(cab, menu) }
internal fun List<SelectCallback>.invokeAll(menuItem: MenuItem): Boolean {
if (isEmpty()) {
return false
}
return all { it(menuItem) }
}
internal fun List<DestroyCallback>.invokeAll(cab: AttachedCab): Boolean {
if (isEmpty()) {
return true
}
return all { it(cab) }
}
| apache-2.0 | ee8b82656dc4706195155779656a59bc | 29.176471 | 76 | 0.74269 | 4.018277 | false | false | false | false |
devunt/ika | app/src/main/kotlin/org/ozinger/ika/messaging/MessagingProvider.kt | 1 | 2841 | package org.ozinger.ika.messaging
import io.lettuce.core.RedisClient
import io.lettuce.core.pubsub.RedisPubSubListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.serializer
import org.ozinger.ika.channel.IncomingPacketChannel
import org.ozinger.ika.channel.OutgoingPacketChannel
import org.ozinger.ika.command.PRIVMSG
import org.ozinger.ika.configuration.Configuration
import org.ozinger.ika.definition.ChannelName
import org.ozinger.ika.definition.UniversalUserId
import org.ozinger.ika.state.IRCUsers
object MessagingProvider {
private val client = RedisClient.create(Configuration.INSTANCE.infra.redis)
private val publishingConnection = client.connectPubSub().sync()
private val subscribingConnection = client.connectPubSub().sync()
private val format = Json {
ignoreUnknownKeys = true
classDiscriminator = "event"
}
suspend fun intercommunicate() = coroutineScope {
launch(Dispatchers.IO) { ingressHandler() }
launch(Dispatchers.IO) { egressHandler() }
}
private suspend fun ingressHandler() {
IncomingPacketChannel.collect { packet ->
@Suppress("NON_EXHAUSTIVE_WHEN_STATEMENT")
when (val command = packet.command) {
is PRIVMSG -> {
if (packet.sender is UniversalUserId && command.recipient is ChannelName) {
publish(ChatMessage(IRCUsers[packet.sender].mask, command.recipient.value, command.message))
}
}
}
}
}
private suspend fun egressHandler() {
subscribingConnection.statefulConnection.addListener(object : RedisPubSubListener<String, String> {
override fun message(channel: String, message: String) {
val event = format.decodeFromString<Event>(message)
runBlocking { OutgoingPacketChannel.send(event.asPacket()) }
when (event) {
is ChatMessage -> publish(event)
else -> {}
}
}
override fun message(pattern: String, channel: String, message: String) {}
override fun subscribed(channel: String, count: Long) {}
override fun psubscribed(pattern: String, count: Long) {}
override fun unsubscribed(channel: String, count: Long) {}
override fun punsubscribed(pattern: String, count: Long) {}
})
subscribingConnection.subscribe("to-ika")
}
fun publish(event: Event) {
publishingConnection.publish("from-ika", format.encodeToString(serializer(), event))
}
}
| agpl-3.0 | 36e5933ac080743e9fe615e3874e9894 | 39.585714 | 116 | 0.67617 | 4.82343 | false | false | false | false |
SoulBeaver/kindinium | src/main/kotlin/com/sbg/vindinium/kindinium/ProgramArguments.kt | 1 | 2750 | /*
Copyright 2014 Christian Broomfield
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.sbg.vindinium.kindinium
import com.beust.jcommander.Parameter
import com.beust.jcommander.IParameterValidator
import com.beust.jcommander.ParameterException
/**
* Describes the possible command-line arguments allowed for kindinium.
*
* Currently, only two arguments are supported:
*
* <ul>
* <li>-mode (default 'training') the game mode with which to play the game</li>
* <li>-turns (default 300) how many turns a game should last</li>
* </ul>
*/
class ProgramArguments {
Parameter(names = array("-mode", "-m"),
description = "Vinidium's supported game modes are [training, arena]. Default is training.",
validateWith = javaClass<GameModeValidator>())
val gameMode: String = "training"
Parameter(names = array("-turns", "-t"),
description = "How long a game shoudl run. Default is 300 turns.",
validateWith = javaClass<GameTurnsValidator>())
val gameTurns: Int = 300
Parameter(names = array("-map"),
description = "Play on a predefined map from m1..m6. Default is none (randomly generated map).",
validateWith = javaClass<GameMapValidator>())
val gameMap: String? = null
}
private class GameModeValidator: IParameterValidator {
private val validGameModes = array("arena", "training")
override fun validate(name: String?, value: String?) {
if (validGameModes.firstOrNull { it.equalsIgnoreCase(value!!) } == null)
throw ParameterException("The only accepted game modes are 'training' and 'master'")
}
}
private class GameTurnsValidator: IParameterValidator {
override fun validate(name: String?, value: String?) {
if (value!!.toInt() <= 0)
throw ParameterException("Only positive non-null integer values are allowed.")
}
}
private class GameMapValidator: IParameterValidator {
private val validMaps = array("m1", "m2", "m3", "m4", "m5", "m6")
override fun validate(name: String?, value: String?) {
if (validMaps.firstOrNull { it.equalsIgnoreCase(value!!) } == null)
throw ParameterException("The only accepted map values are m1..m6.")
}
} | apache-2.0 | 8c977c58ed3a125e218d318f33059325 | 37.208333 | 112 | 0.692364 | 4.263566 | false | false | false | false |
ntemplon/legends-of-omterra | core/src/com/jupiter/europa/entity/component/RaceComponent.kt | 1 | 2172 | /*
* The MIT License
*
* Copyright 2015 Nathan Templon.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.jupiter.europa.entity.component
import com.badlogic.ashley.core.Component
import com.badlogic.gdx.utils.Json
import com.badlogic.gdx.utils.Json.Serializable
import com.badlogic.gdx.utils.JsonValue
import com.jupiter.europa.entity.stats.race.PlayerRaces
import com.jupiter.europa.entity.stats.race.Race
/**
* @author Nathan Templon
*/
public class RaceComponent(race: Race? = null) : Component(), Serializable {
// Fields
public var race: Race? = race
private set
// Serializable (Json) Implementation
override fun write(json: Json) {
json.writeValue(RACE_KEY, this.race.toString())
}
override fun read(json: Json, jsonData: JsonValue) {
if (jsonData.has(RACE_KEY)) {
val race = try {
PlayerRaces.valueOf(jsonData.getString(RACE_KEY))
} catch (ex: Exception) {
PlayerRaces.Human
}
this.race = race
}
}
companion object {
private val RACE_KEY = "race"
}
}
| mit | 8ba47a6e05e257dd26d4ea96f32c367e | 32.415385 | 80 | 0.703499 | 4.233918 | false | false | false | false |
dirkraft/cartograph | cartograph/src/main/kotlin/com/github/dirkraft/cartograph/mapping.kt | 1 | 3902 | package com.github.dirkraft.cartograph
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.Timestamp
import java.sql.Types
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.starProjectedType
import kotlin.reflect.jvm.javaType
internal data class WriteMapping(
val columnName: String,
val value: Any,
val sqlPlaceholder: String
)
/**
* Reflectively transforms `obj` properties to an array of column_name and corresponding values
*/
internal fun calcWriteMappings(obj: Any): LinkedHashMap<String, WriteMapping> {
val mapping = LinkedHashMap<String, WriteMapping>()
val props = obj.javaClass.kotlin.memberProperties
.filter { it.findAnnotation<CartIgnore>() == null }
for (prop in props) {
val colName = camelCaseTo_snake_case(prop.name)
val value = prop.get(obj) ?: TypedNull.of((prop.returnType.javaType as Class<*>).kotlin)
val placeholder = Annotations.resolvePlaceholder(prop)
mapping.put(colName, WriteMapping(colName, value, placeholder))
}
return mapping
}
data class TypedNull(val sqlType: Int) {
companion object {
fun of(type: KClass<*>): TypedNull {
val sqlType = when (type) {
Date::class -> Types.TIMESTAMP
Int::class -> Types.INTEGER
Long::class -> Types.INTEGER
Float::class -> Types.FLOAT
Double::class -> Types.DOUBLE
String::class -> Types.VARCHAR
else -> throw UnsupportedOperationException("Unhandled NULL type for property: " + type)
}
return TypedNull(sqlType)
}
}
}
/**
* Reflectively set positional parameters of a [PreparedStatement]
*/
internal fun PreparedStatement.mapIn(args: Collection<Any>) {
for ((i, arg) in args.withIndex()) when (arg) {
is Boolean -> setBoolean(i + 1, arg)
is Date -> setTimestamp(i + 1, Timestamp(arg.time))
is Int -> setInt(i + 1, arg)
is Long -> setLong(i + 1, arg)
is Float -> setFloat(i + 1, arg)
is Double -> setDouble(i + 1, arg)
is String -> setString(i + 1, arg)
is TypedNull -> setNull(i + 1, arg.sqlType)
else -> throw CartographException("Unhandled param type: " + arg.javaClass)
}
}
internal fun ResultSet.getValue(colIdx: Int, type: KType, nullable: Boolean): Any? {
val columnType = metaData.getColumnType(colIdx)
return when (columnType) {
Types.BOOLEAN, Types.BIT -> getBoolean(colIdx)
Types.INTEGER -> mapNumber(colIdx, type)
Types.FLOAT -> getFloat(colIdx)
Types.DOUBLE -> {
val v = getDouble(colIdx)
if (type == Float::class.starProjectedType) {
return v.toFloat()
} else {
v
}
}
Types.NULL -> null
Types.TIMESTAMP -> getTimestamp(colIdx)?.let { Date(it.time) }
Types.VARCHAR -> if (nullable) getString(colIdx) else getString(colIdx).orEmpty()
Types.OTHER -> getString(colIdx) // try string because JSON
else -> throw CartographException("Unhandled sql type: " + columnType)
}
}
internal fun ResultSet.mapNumber(colIdx: Int, type: KType): Any? {
val longVal = getLong(colIdx)
return if (type.javaType.toString() == "class java.util.Date") {
// sqlite returns a date simply as a INTEGER. Map it back to Date if that is the prop type.
Date(longVal)
} else if (longVal == 0L && wasNull()) {
// ResultSet.getLong -> 0 apparently means NULL.
null
} else if (type.javaType.toString().let { it == "class java.lang.Integer" || it == "int" }) {
longVal.toInt()
} else {
longVal
}
}
| mit | f0a6f0128e223afc07db2632b28cec3e | 35.46729 | 104 | 0.628139 | 4.173262 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstallReceiver.kt | 2 | 4227 | package eu.kanade.tachiyomi.extension.util
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import eu.kanade.tachiyomi.extension.model.Extension
import eu.kanade.tachiyomi.extension.model.LoadResult
import eu.kanade.tachiyomi.util.launchNow
import kotlinx.coroutines.experimental.async
/**
* Broadcast receiver that listens for the system's packages installed, updated or removed, and only
* notifies the given [listener] when the package is an extension.
*
* @param listener The listener that should be notified of extension installation events.
*/
internal class ExtensionInstallReceiver(private val listener: Listener) :
BroadcastReceiver() {
/**
* Registers this broadcast receiver
*/
fun register(context: Context) {
context.registerReceiver(this, filter)
}
/**
* Returns the intent filter this receiver should subscribe to.
*/
private val filter get() = IntentFilter().apply {
addAction(Intent.ACTION_PACKAGE_ADDED)
addAction(Intent.ACTION_PACKAGE_REPLACED)
addAction(Intent.ACTION_PACKAGE_REMOVED)
addDataScheme("package")
}
/**
* Called when one of the events of the [filter] is received. When the package is an extension,
* it's loaded in background and it notifies the [listener] when finished.
*/
override fun onReceive(context: Context, intent: Intent?) {
if (intent == null) return
when (intent.action) {
Intent.ACTION_PACKAGE_ADDED -> {
if (!isReplacing(intent)) launchNow {
val result = getExtensionFromIntent(context, intent)
when (result) {
is LoadResult.Success -> listener.onExtensionInstalled(result.extension)
is LoadResult.Untrusted -> listener.onExtensionUntrusted(result.extension)
}
}
}
Intent.ACTION_PACKAGE_REPLACED -> {
launchNow {
val result = getExtensionFromIntent(context, intent)
when (result) {
is LoadResult.Success -> listener.onExtensionUpdated(result.extension)
// Not needed as a package can't be upgraded if the signature is different
is LoadResult.Untrusted -> {}
}
}
}
Intent.ACTION_PACKAGE_REMOVED -> {
if (!isReplacing(intent)) {
val pkgName = getPackageNameFromIntent(intent)
if (pkgName != null) {
listener.onPackageUninstalled(pkgName)
}
}
}
}
}
/**
* Returns true if this package is performing an update.
*
* @param intent The intent that triggered the event.
*/
private fun isReplacing(intent: Intent): Boolean {
return intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)
}
/**
* Returns the extension triggered by the given intent.
*
* @param context The application context.
* @param intent The intent containing the package name of the extension.
*/
private suspend fun getExtensionFromIntent(context: Context, intent: Intent?): LoadResult {
val pkgName = getPackageNameFromIntent(intent) ?:
return LoadResult.Error("Package name not found")
return async { ExtensionLoader.loadExtensionFromPkgName(context, pkgName) }.await()
}
/**
* Returns the package name of the installed, updated or removed application.
*/
private fun getPackageNameFromIntent(intent: Intent?): String? {
return intent?.data?.encodedSchemeSpecificPart ?: return null
}
/**
* Listener that receives extension installation events.
*/
interface Listener {
fun onExtensionInstalled(extension: Extension.Installed)
fun onExtensionUpdated(extension: Extension.Installed)
fun onExtensionUntrusted(extension: Extension.Untrusted)
fun onPackageUninstalled(pkgName: String)
}
}
| apache-2.0 | be9fbf93b1fd8402008687cb1dba9a87 | 36.078947 | 100 | 0.630234 | 5.186503 | false | false | false | false |
http4k/http4k | http4k-security/oauth/src/test/kotlin/org/http4k/security/oauth/server/GenerateAccessTokenTest.kt | 1 | 14624 | package org.http4k.security.oauth.server
import com.natpryce.hamkrest.and
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.containsSubstring
import com.natpryce.hamkrest.equalTo
import dev.forkhandles.result4k.get
import org.http4k.core.Body
import org.http4k.core.ContentType
import org.http4k.core.Method.GET
import org.http4k.core.Method.POST
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.BAD_REQUEST
import org.http4k.core.Status.Companion.OK
import org.http4k.core.Status.Companion.UNAUTHORIZED
import org.http4k.core.Uri
import org.http4k.core.body.form
import org.http4k.format.AutoMarshallingJson
import org.http4k.format.Jackson
import org.http4k.hamkrest.hasBody
import org.http4k.hamkrest.hasStatus
import org.http4k.security.AccessTokenResponse
import org.http4k.security.ResponseType.CodeIdToken
import org.http4k.security.State
import org.http4k.security.oauth.server.OAuthServerMoshi.auto
import org.http4k.security.oauth.server.accesstoken.ClientSecretAccessTokenRequestAuthentication
import org.http4k.security.oauth.server.accesstoken.GrantType
import org.http4k.security.oauth.server.accesstoken.GrantTypesConfiguration
import org.http4k.util.FixedClock
import org.junit.jupiter.api.Test
import java.time.Clock
import java.time.Instant
import java.time.ZoneId
import java.time.temporal.ChronoUnit.SECONDS
import java.time.temporal.TemporalUnit
class GenerateAccessTokenTest {
private val json: AutoMarshallingJson<*> = Jackson
private val handlerClock = SettableClock()
private val codes = InMemoryAuthorizationCodes(FixedClock)
private val authRequest = AuthRequest(ClientId("a-clientId"), listOf(), Uri.of("redirect"), State("state"))
private val request = Request(GET, "http://some-thing")
private val code = codes.create(request, authRequest, Response(OK)).get()
private val clientValidator = HardcodedClientValidator(authRequest.client, authRequest.redirectUri!!, "a-secret")
private val handler = GenerateAccessToken(codes, DummyAccessTokens(), handlerClock, DummyIdTokens(), DummyRefreshTokens(), JsonResponseErrorRenderer(json), GrantTypesConfiguration.default(ClientSecretAccessTokenRequestAuthentication(clientValidator)))
@Test
fun `generates a dummy token`() {
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", code.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(OK) and hasBody(
Body.auto<AccessTokenResponse>().toLens(),
equalTo(AccessTokenResponse("dummy-access-token", "Bearer"))
))
}
@Test
fun `generates dummy access_token and id_token if an oidc request`() {
val codeForIdTokenRequest = codes.create(request, authRequest.copy(scopes = listOf("openid")), Response(OK)).get()
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", codeForIdTokenRequest.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(OK))
assertThat(
Body.auto<AccessTokenResponse>().toLens()(response),
equalTo(AccessTokenResponse("dummy-access-token", "Bearer", id_token = "dummy-id-token-for-access-token"))
)
}
@Test
fun `allowing refreshing a token`() {
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "refresh_token")
.form("refresh_token", "valid-refresh-token")
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret"))
assertThat(response, hasStatus(OK) and hasBody(
Body.auto<AccessTokenResponse>().toLens(), equalTo(
AccessTokenResponse(
access_token = DummyRefreshTokens.newAccessToken.value,
token_type = DummyRefreshTokens.newAccessToken.type,
scope = DummyRefreshTokens.newAccessToken.scope,
expires_in = DummyRefreshTokens.newAccessToken.expiresIn,
refresh_token = DummyRefreshTokens.newAccessToken.refreshToken?.value
)
)
))
}
@Test
fun `bad request for missing refresh_token parameter`() {
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "refresh_token")
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret"))
assertThat(response, hasStatus(BAD_REQUEST) and hasBody(withErrorType("invalid_request")))
}
@Test
fun `validates credentials for refresh tokens`() {
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "refresh_token")
.form("refresh_token", "invalid-refresh-token")
.form("client_id", authRequest.client.value)
.form("client_secret", "not a valid secret"))
assertThat(response, hasStatus(UNAUTHORIZED) and hasBody(withErrorType("invalid_client")))
}
@Test
fun `copes with error from actual refresh tokens`() {
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "refresh_token")
.form("refresh_token", "invalid-refresh-token")
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret"))
assertThat(response, hasStatus(BAD_REQUEST) and hasBody(withErrorType("invalid_request")))
}
@Test
fun `generates dummy access_token and id_token`() {
val codeForIdTokenRequest = codes.create(request, authRequest.copy(responseType = CodeIdToken, scopes = listOf("openid")), Response(OK)).get()
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", codeForIdTokenRequest.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(OK))
assertThat(
Body.auto<AccessTokenResponse>().toLens()(response),
equalTo(AccessTokenResponse("dummy-access-token", "Bearer", id_token = "dummy-id-token-for-access-token"))
)
}
@Test
fun `generates dummy token for client credentials grant type`() {
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "client_credentials")
.form("client_secret", "a-secret")
.form("client_id", authRequest.client.value)
)
assertThat(response, hasStatus(OK) and hasBody(
Body.auto<AccessTokenResponse>().toLens(),
equalTo(AccessTokenResponse("dummy-access-token", "Bearer"))
))
}
@Test
fun `handles invalid grant_type`() {
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "something_else")
.form("code", code.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(BAD_REQUEST) and hasBody(withErrorType("unsupported_grant_type")))
}
@Test
fun `handles invalid client credentials`() {
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", code.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "wrong-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(UNAUTHORIZED) and hasBody(withErrorType("invalid_client")))
}
@Test
fun `handles expired code`() {
handlerClock.advance(1, SECONDS)
val expiredCode = codes.create(request, authRequest, Response(OK)).get()
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", expiredCode.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(BAD_REQUEST) and hasBody(withErrorType("invalid_grant")))
}
@Test
fun `handles client id different from one in authorization code`() {
val storedCode = codes.create(request, authRequest.copy(client = ClientId("different client")), Response(OK)).get()
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", storedCode.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(BAD_REQUEST) and hasBody(withErrorType("invalid_grant")))
}
@Test
fun `handles redirectUri different from one in authorization code`() {
val storedCode = codes.create(request, authRequest.copy(redirectUri = Uri.of("somethingelse")), Response(OK)).get()
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", storedCode.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(BAD_REQUEST) and hasBody(withErrorType("invalid_grant")))
}
@Test
fun `handles already used authentication code`() {
val handler = GenerateAccessToken(codes, ErroringAccessTokens(AuthorizationCodeAlreadyUsed), handlerClock, DummyIdTokens(), DummyRefreshTokens(), JsonResponseErrorRenderer(json), GrantTypesConfiguration.default(ClientSecretAccessTokenRequestAuthentication(clientValidator)))
val request = Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", code.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
val response = handler(request)
assertThat(response, hasStatus(BAD_REQUEST) and hasBody(withErrorType("invalid_grant")))
}
@Test
fun `correctly returns documentation uri if provided`() {
val documentationUri = "SomeUri"
val handler = GenerateAccessToken(codes, ErroringAccessTokens(AuthorizationCodeAlreadyUsed), handlerClock, DummyIdTokens(), DummyRefreshTokens(), JsonResponseErrorRenderer(json, documentationUri), GrantTypesConfiguration.default(ClientSecretAccessTokenRequestAuthentication(clientValidator)))
val request = Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", code.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
val response = handler(request)
assertThat(response, hasStatus(BAD_REQUEST) and hasBody(withErrorTypeAndUri("invalid_grant", documentationUri)))
}
@Test
fun `handles grant type not in configuration`() {
val handler = GenerateAccessToken(codes, ErroringAccessTokens(AuthorizationCodeAlreadyUsed), handlerClock, DummyIdTokens(), DummyRefreshTokens(), JsonResponseErrorRenderer(json), GrantTypesConfiguration(emptyMap()))
val response = handler(Request(POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", GrantType.ClientCredentials.rfcValue)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
)
assertThat(response, hasStatus(BAD_REQUEST) and hasBody(withErrorType("unsupported_grant_type")))
}
private fun withErrorType(errorType: String) =
containsSubstring("\"error\":\"$errorType\"")
.and(containsSubstring("\"error_description\":"))
.and(containsSubstring("\"error_uri\":null"))
private fun withErrorTypeAndUri(errorType: String, errorUri: String) = containsSubstring("\"error\":\"$errorType\"")
.and(containsSubstring("\"error_description\":"))
.and(containsSubstring("\"error_uri\":\"${errorUri}\""))
}
class SettableClock : Clock() {
private var currentTime = Instant.EPOCH
fun advance(amount: Long, unit: TemporalUnit) {
currentTime = currentTime.plus(amount, unit)
}
override fun withZone(zone: ZoneId?): Clock = this
override fun getZone(): ZoneId = ZoneId.systemDefault()
override fun instant(): Instant = currentTime
}
| apache-2.0 | 243868a061ab6093f76ca9030b163e8c | 43.996923 | 300 | 0.664798 | 4.388956 | false | true | false | false |
alter-ego/unisannio-reboot | app/src/test/java/solutions/alterego/android/unisannio/scienze/ScienzeParserTest.kt | 1 | 837 | package solutions.alterego.android.unisannio.scienze
import org.jsoup.nodes.Document
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.mockito.runners.MockitoJUnitRunner
import solutions.alterego.android.assertThat
import solutions.alterego.android.unisannio.URLS
@RunWith(MockitoJUnitRunner::class)
class ScienzeParserTest {
val url = URLS.SCIENZE_NEWS;
val parser = ScienzeParser();
val retriver = ScienzeRetriever(url);
lateinit var document: Document
@Before
fun setUp(){
document = retriver.getDocument(url);
assertThat(document).isNotNull;
}
@After
fun tearDown(){
}
@Test
fun testParser() {
val list = parser.parse(document);
assertThat(list).isNotNull;
}
} | apache-2.0 | 7727592a2449293e113182475faf9827 | 21.052632 | 52 | 0.728793 | 4.024038 | false | true | false | false |
googlecreativelab/digital-wellbeing-experiments-toolkit | notifications/notification-snoozer/app/src/main/java/com/digitalwellbeingexperiments/toolkit/notificationsnoozer/Extensions.kt | 1 | 1550 | // 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.digitalwellbeingexperiments.toolkit.notificationsnoozer
import android.app.Notification
import android.service.notification.StatusBarNotification
import java.text.SimpleDateFormat
import java.util.*
fun Any.TAG() = this.javaClass.simpleName
fun StatusBarNotification.getText(): String = (this.notification.extras.get(Notification.EXTRA_TEXT) ?: "").toString()
fun StatusBarNotification.getTitle(): String = (this.notification.extras.get(Notification.EXTRA_TITLE) ?: "").toString()
fun StatusBarNotification.getTitleBig(): String = (this.notification.extras.get(Notification.EXTRA_TITLE_BIG) ?: "").toString()
fun StatusBarNotification.getSubText(): String = (this.notification.extras.get(Notification.EXTRA_SUB_TEXT) ?: "").toString()
fun formatTimestamp(timestamp: Long, pattern: String = "EEE, dd MMM yyyy, HH:mm:ss"): String {
val sdf = SimpleDateFormat(pattern)
val resultdate = Date(timestamp)
return sdf.format(resultdate)
} | apache-2.0 | 31d5801d368302c8a88eb1e1c9d1b8a2 | 42.083333 | 127 | 0.765161 | 4.211957 | false | false | false | false |
jonnyhsia/storybook | app/src/main/java/com/jonnyhsia/storybook/biz/profile/ProfileRepository.kt | 1 | 1957 | package com.jonnyhsia.storybook.biz.profile
import com.jonnyhsia.storybook.biz.base.BaseRepository
import com.jonnyhsia.storybook.biz.base.CacheWrapper
import com.jonnyhsia.storybook.biz.base.OnFailed
import com.jonnyhsia.storybook.biz.base.OnSubscribe
import com.jonnyhsia.storybook.biz.profile.entity.User
class ProfileRepository(private val remoteDataSource: ProfileRemoteDataSource,
private val localDataSource: ProfileLocalDataSource)
: BaseRepository, ProfileDataSource {
private var cachedProfileData = CacheWrapper<User>()
override fun preload() {
// 仅预加载
this.getMyProfile(
onSubscribe = {},
onSuccess = {},
onNoLoginUserFound = {},
onFailed = { _, _ -> })
}
override fun getMyProfile(onSubscribe: OnSubscribe,
onSuccess: GetProfileSuccess,
onNoLoginUserFound: OnNoLoginUserFound,
onFailed: OnFailed) {
if (cachedProfileData.isValid) {
onSuccess(cachedProfileData.unpack())
}
remoteDataSource.getMyProfile(
onSubscribe = onSubscribe,
onSuccess = { user ->
// 回调前保存缓存与本地
cachedProfileData.cache(user)
localDataSource.saveProfile(user)
onSuccess(user)
},
onNoLoginUserFound = onNoLoginUserFound,
onFailed = onFailed)
}
override fun getUserProfile(userId: String, onSuccess: GetProfileSuccess, onFailed: OnFailed) {
}
companion object {
@JvmStatic
fun instance() = Holder.instance
}
private object Holder {
@JvmStatic
val instance: ProfileRepository = ProfileRepository(
ProfileRemoteDataSource(), ProfileLocalDataSource())
}
} | apache-2.0 | d9f1521f7370fa49f4a3ab918a8fb30b | 32.275862 | 99 | 0.602903 | 5.227642 | false | false | false | false |
lbbento/pitchup | wear2/src/main/kotlin/com/lbbento/pitchupwear/main/MainActivity.kt | 1 | 1455 | package com.lbbento.pitchupwear.main
import android.os.Bundle
import android.widget.Toast.LENGTH_SHORT
import android.widget.Toast.makeText
import com.lbbento.pitchupwear.R
import com.lbbento.pitchupwear.ui.BaseActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : BaseActivity<MainPresenter>(), MainView {
override fun setupInjection() {
activityComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun updateNote(note: String) {
main_activity_notetext.text = note
}
override fun updateToDefaultStatus() {
main_activity_notetext.text = getString(R.string.main_activity_play)
}
override fun updateIndicator(diffInCents: Float) {
main_activity_gauge.speedTo(diffInCents, 600)
}
override fun updateCurrentFrequency(currentFreq: Float) {
main_activity_freqtext.text = getString(R.string.freq_in_hertz, currentFreq)
}
override fun getCurrentNote(): String {
return main_activity_notetext.text.toString()
}
override fun informError() {
makeText(this, R.string.error_occurred, LENGTH_SHORT).show()
}
override fun setupGauge() {
main_activity_gauge.maxSpeed = 100
main_activity_gauge.minSpeed = -100
main_activity_gauge.speedTo(0f, 1000)
}
}
| apache-2.0 | 30532ffde0fdfaabf290060d0ba7b53c | 27.529412 | 84 | 0.705155 | 4.087079 | false | false | false | false |
facebook/react-native | packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GenerateCodegenArtifactsTask.kt | 1 | 3172 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.tasks
import com.facebook.react.utils.JsonUtils
import com.facebook.react.utils.windowsAwareCommandLine
import org.gradle.api.file.Directory
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFile
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.Exec
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.OutputDirectory
abstract class GenerateCodegenArtifactsTask : Exec() {
@get:Internal abstract val reactNativeDir: DirectoryProperty
@get:Internal abstract val codegenDir: DirectoryProperty
@get:Internal abstract val generatedSrcDir: DirectoryProperty
@get:InputFile abstract val packageJsonFile: RegularFileProperty
@get:Input abstract val nodeExecutableAndArgs: ListProperty<String>
@get:Input abstract val codegenJavaPackageName: Property<String>
@get:Input abstract val libraryName: Property<String>
@get:InputFile
val combineJsToSchemaCli: Provider<RegularFile> =
codegenDir.file("lib/cli/combine/combine-js-to-schema-cli.js")
@get:InputFile
val generatedSchemaFile: Provider<RegularFile> = generatedSrcDir.file("schema.json")
@get:OutputDirectory val generatedJavaFiles: Provider<Directory> = generatedSrcDir.dir("java")
@get:OutputDirectory val generatedJniFiles: Provider<Directory> = generatedSrcDir.dir("jni")
override fun exec() {
val (resolvedLibraryName, resolvedCodegenJavaPackageName) = resolveTaskParameters()
setupCommandLine(resolvedLibraryName, resolvedCodegenJavaPackageName)
super.exec()
}
internal fun resolveTaskParameters(): Pair<String, String> {
val parsedPackageJson =
if (packageJsonFile.isPresent && packageJsonFile.get().asFile.exists()) {
JsonUtils.fromCodegenJson(packageJsonFile.get().asFile)
} else {
null
}
val resolvedLibraryName = parsedPackageJson?.codegenConfig?.name ?: libraryName.get()
val resolvedCodegenJavaPackageName =
parsedPackageJson?.codegenConfig?.android?.javaPackageName ?: codegenJavaPackageName.get()
return resolvedLibraryName to resolvedCodegenJavaPackageName
}
internal fun setupCommandLine(libraryName: String, codegenJavaPackageName: String) {
commandLine(
windowsAwareCommandLine(
*nodeExecutableAndArgs.get().toTypedArray(),
reactNativeDir.file("scripts/generate-specs-cli.js").get().asFile.absolutePath,
"--platform",
"android",
"--schemaPath",
generatedSchemaFile.get().asFile.absolutePath,
"--outputDir",
generatedSrcDir.get().asFile.absolutePath,
"--libraryName",
libraryName,
"--javaPackageName",
codegenJavaPackageName))
}
}
| mit | 2c0080b7f5621461ccdd72c90fc758f9 | 35.45977 | 98 | 0.745271 | 4.583815 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/snackbar/SensibleSwipeDismissBehavior.kt | 1 | 8227 | /*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.snackbar
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.annotation.VisibleForTesting
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.marginLeft
import androidx.core.view.marginRight
import androidx.customview.widget.ViewDragHelper
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import com.ichi2.anki.AnkiDroidApp
import com.ichi2.anki.UIUtils
import kotlin.math.absoluteValue
import kotlin.math.sign
/**
* This is more a fix for the inconsistent behavior of `SwipeDismissBehavior`,
* rather than a custom implementation. This addresses the following issues:
*
* * When the snackbar is swiped to the right, its opacity changes,
* but not when swiped to the left;
*
* * When moving the snackbar to dismiss it, the target distance calculation does not take
* the margins into account, which makes the snackbar briefly appear stuck near the edge;
*
* * Any amount of horizontal velocity will dismiss the snackbar,
* which can result in user dismissing the snackbar even though they didn't want to;
*
* * If you drag the snackbar to the right, and then flinging it to the left,
* it will suddenly change course and start moving to the right.
*/
open class SensibleSwipeDismissBehavior : BaseTransientBottomBar.Behavior() {
private var viewDragHelper: ViewDragHelper? = null
override fun onInterceptTouchEvent(parent: CoordinatorLayout, child: View, event: MotionEvent): Boolean {
ensureViewDragHelper(parent)
return viewDragHelper!!.shouldInterceptTouchEvent(event)
}
override fun onTouchEvent(parent: CoordinatorLayout, child: View, event: MotionEvent): Boolean {
viewDragHelper?.processTouchEvent(event)
return viewDragHelper != null
}
private fun ensureViewDragHelper(parent: ViewGroup) {
if (viewDragHelper == null) {
viewDragHelper = ViewDragHelper.create(parent, ViewDragHelperCallback())
}
}
/** See [com.google.android.material.behavior.SwipeDismissBehavior.dragCallback] */
inner class ViewDragHelperCallback : ViewDragHelper.Callback() {
@VisibleForTesting var initialChildLeft = Int.MIN_VALUE
override fun getViewHorizontalDragRange(child: View) = child.width
override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int) = left
override fun clampViewPositionVertical(child: View, top: Int, dy: Int) = child.top
override fun onViewDragStateChanged(state: Int) {
listener?.onDragStateChanged(state)
}
override fun tryCaptureView(child: View, pointerId: Int) = child is Snackbar.SnackbarLayout
override fun onViewCaptured(child: View, pointerId: Int) {
if (initialChildLeft == Int.MIN_VALUE) {
initialChildLeft = child.left
}
child.parent?.requestDisallowInterceptTouchEvent(true)
child.startIgnoringExternalChangesOfHorizontalPosition()
}
override fun onViewReleased(child: View, xvel: Float, yvel: Float) {
val dismiss = shouldDismiss(child, xvel)
val targetChildLeft = when (dismiss) {
Dismiss.DoNotDismiss -> initialChildLeft
Dismiss.ToTheRight -> initialChildLeft + child.width + child.marginRight
Dismiss.ToTheLeft -> initialChildLeft - child.width - child.marginLeft
}
fun onViewSettled() {
if (dismiss != Dismiss.DoNotDismiss) {
listener?.onDismiss(child)
}
child.stopIgnoringExternalChangesOfHorizontalPosition()
}
if (viewDragHelper?.settleCapturedViewAt(targetChildLeft, child.top) == true) {
child.postOnAnimation(object : Runnable {
override fun run() {
if (viewDragHelper?.continueSettling(true) == true) {
child.postOnAnimation(this)
} else {
onViewSettled()
}
}
})
} else {
onViewSettled()
}
}
/**
* The finger was lifted off the snackbar, which may still have horizontal velocity.
* This decides whether the snackbar should be dismissed.
*
* * If current snackbar speed is high, dismiss to the direction of fling;
*
* * If snackbar traveled a lot, and currently is either stationary,
* or is moving away from the original position,
* dismiss to the direction of the closest edge;
*
* * Else do not dismiss, and return to original position.
*/
@VisibleForTesting fun shouldDismiss(child: View, xvel: Float): Dismiss {
return if (xvel.absoluteValue > FLING_TO_DISMISS_SPEED_THRESHOLD) {
if (xvel > 0f) Dismiss.ToTheRight else Dismiss.ToTheLeft
} else {
val distanceTraveled = child.left - initialChildLeft
val distanceTraveledRatio = distanceTraveled.absoluteValue.toFloat() / child.width
val shouldDismiss = distanceTraveledRatio > DRAG_TO_DISMISS_DISTANCE_RATIO &&
(xvel == 0f || xvel.sign.toInt() == distanceTraveled.sign)
when {
!shouldDismiss -> Dismiss.DoNotDismiss
distanceTraveled > 0 -> Dismiss.ToTheRight
else -> Dismiss.ToTheLeft
}
}
}
/**
* `CoordinatorLayout` may try to layout its children while the snackbar is settling,
* for instance, if you touch other views after dragging and releasing the snackbar,
* or if you try dragging a snackbar right after flicking the card list in Card browser.
* This makes it briefly flicker in the original position--
* especially if the alpha of the snackbar isn't changed.
*
* While this glitch is quite rare in practice, there's a straightforward workaround.
* When such a layout event occurs, we are undoing any horizontal changes. There's probably
* a more decent way of resolving this, but--again--this is an extremely rare glitch.
*/
@Suppress("UNUSED_ANONYMOUS_PARAMETER") // just to make parameter list readable
private val horizontalLayoutChangeUndoingLayoutChangeListener = View.OnLayoutChangeListener {
view, newLeft, newTop, newRight, newBottom, oldLeft, oldTop, oldRight, oldBottom ->
if (newLeft != oldLeft && newLeft == initialChildLeft) {
view.layout(oldLeft, newTop, oldRight, newBottom)
}
}
private fun View.startIgnoringExternalChangesOfHorizontalPosition() {
addOnLayoutChangeListener(horizontalLayoutChangeUndoingLayoutChangeListener)
}
private fun View.stopIgnoringExternalChangesOfHorizontalPosition() {
removeOnLayoutChangeListener(horizontalLayoutChangeUndoingLayoutChangeListener)
}
}
}
@VisibleForTesting enum class Dismiss { DoNotDismiss, ToTheLeft, ToTheRight }
private val FLING_TO_DISMISS_SPEED_THRESHOLD =
UIUtils.convertDpToPixel(1000f, AnkiDroidApp.instance.applicationContext)
private const val DRAG_TO_DISMISS_DISTANCE_RATIO = .5f
| gpl-3.0 | 1135121b70bf32fa4dabfd3c7c7036e3 | 43.711957 | 109 | 0.665127 | 4.882493 | false | false | false | false |
rock3r/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UseIfInsteadOfWhenSpec.kt | 2 | 2084 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object UseIfInsteadOfWhenSpec : Spek({
val subject by memoized { UseIfInsteadOfWhen() }
describe("UseIfInsteadOfWhen rule") {
it("reports when using two branches") {
val code = """
fun function(): Boolean? {
val x = null
when (x) {
null -> return true
else -> return false
}
}
"""
assertThat(subject.compileAndLint(code)).hasSize(1)
}
it("does not report when using one branch") {
val code = """
fun function(): Boolean? {
val x = null
when (x) {
else -> return false
}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("does not report when using more than two branches") {
val code = """
fun function(): Boolean? {
val x = null
when (x) {
null -> return true
3 -> return null
else -> return false
}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("does not report when second branch is not 'else'") {
val code = """
fun function(): Boolean? {
val x = null
when (x) {
null -> return true
3 -> return null
}
return false
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
}
})
| apache-2.0 | cda7e0a804b609069dfcc4c7a6677932 | 30.104478 | 65 | 0.432821 | 5.709589 | false | false | false | false |
rock3r/detekt | detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/JCommander.kt | 1 | 1561 | package io.gitlab.arturbosch.detekt.cli
import com.beust.jcommander.JCommander
import com.beust.jcommander.ParameterException
import java.io.PrintStream
@Suppress("detekt.SpreadOperator", "detekt.ThrowsCount")
inline fun <reified T : Args> parseArguments(
args: Array<out String>,
outPrinter: PrintStream,
errorPrinter: PrintStream,
validateCli: T.(MessageCollector) -> Unit = {}
): T {
val cli = T::class.java.declaredConstructors
.firstOrNull()
?.newInstance() as? T
?: error("Could not create Args object for class ${T::class.java}")
val jCommander = JCommander()
jCommander.addObject(cli)
jCommander.programName = "detekt"
try {
jCommander.parse(*args)
} catch (ex: ParameterException) {
errorPrinter.println("${ex.message}\n")
jCommander.usage(outPrinter)
throw HandledArgumentViolation()
}
if (cli.help) {
jCommander.usage(outPrinter)
throw HelpRequest()
}
val violations = mutableListOf<String>()
validateCli(cli, object : MessageCollector {
override fun plusAssign(msg: String) {
violations += msg
}
})
if (violations.isNotEmpty()) {
violations.forEach(errorPrinter::println)
errorPrinter.println()
jCommander.usage(outPrinter)
throw HandledArgumentViolation()
}
return cli
}
fun JCommander.usage(outPrinter: PrintStream) {
val usage = StringBuilder()
this.usageFormatter.usage(usage)
outPrinter.println(usage.toString())
}
| apache-2.0 | 2dc20363d2488fc9ebc7d19fb8f8c3d7 | 26.385965 | 75 | 0.664318 | 4.276712 | false | false | false | false |
JetBrains/anko | anko/library/generated/sdk27-coroutines/src/main/java/ListenersWithCoroutines.kt | 2 | 38145 | @file:JvmName("Sdk27CoroutinesListenersWithCoroutinesKt")
package org.jetbrains.anko.sdk27.coroutines
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.CoroutineStart
import android.view.WindowInsets
fun android.view.View.onLayoutChange(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(v: android.view.View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) -> Unit
) {
addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom)
}
}
}
fun android.view.View.onAttachStateChangeListener(
context: CoroutineContext = Dispatchers.Main,
init: __View_OnAttachStateChangeListener.() -> Unit
) {
val listener = __View_OnAttachStateChangeListener(context)
listener.init()
addOnAttachStateChangeListener(listener)
}
class __View_OnAttachStateChangeListener(private val context: CoroutineContext) : android.view.View.OnAttachStateChangeListener {
private var _onViewAttachedToWindow: (suspend CoroutineScope.(android.view.View) -> Unit)? = null
override fun onViewAttachedToWindow(v: android.view.View) {
val handler = _onViewAttachedToWindow ?: return
GlobalScope.launch(context) {
handler(v)
}
}
fun onViewAttachedToWindow(
listener: suspend CoroutineScope.(android.view.View) -> Unit
) {
_onViewAttachedToWindow = listener
}
private var _onViewDetachedFromWindow: (suspend CoroutineScope.(android.view.View) -> Unit)? = null
override fun onViewDetachedFromWindow(v: android.view.View) {
val handler = _onViewDetachedFromWindow ?: return
GlobalScope.launch(context) {
handler(v)
}
}
fun onViewDetachedFromWindow(
listener: suspend CoroutineScope.(android.view.View) -> Unit
) {
_onViewDetachedFromWindow = listener
}
}fun android.widget.TextView.textChangedListener(
context: CoroutineContext = Dispatchers.Main,
init: __TextWatcher.() -> Unit
) {
val listener = __TextWatcher(context)
listener.init()
addTextChangedListener(listener)
}
class __TextWatcher(private val context: CoroutineContext) : android.text.TextWatcher {
private var _beforeTextChanged: (suspend CoroutineScope.(CharSequence?, Int, Int, Int) -> Unit)? = null
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
val handler = _beforeTextChanged ?: return
GlobalScope.launch(context) {
handler(s, start, count, after)
}
}
fun beforeTextChanged(
listener: suspend CoroutineScope.(CharSequence?, Int, Int, Int) -> Unit
) {
_beforeTextChanged = listener
}
private var _onTextChanged: (suspend CoroutineScope.(CharSequence?, Int, Int, Int) -> Unit)? = null
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val handler = _onTextChanged ?: return
GlobalScope.launch(context) {
handler(s, start, before, count)
}
}
fun onTextChanged(
listener: suspend CoroutineScope.(CharSequence?, Int, Int, Int) -> Unit
) {
_onTextChanged = listener
}
private var _afterTextChanged: (suspend CoroutineScope.(android.text.Editable?) -> Unit)? = null
override fun afterTextChanged(s: android.text.Editable?) {
val handler = _afterTextChanged ?: return
GlobalScope.launch(context) {
handler(s)
}
}
fun afterTextChanged(
listener: suspend CoroutineScope.(android.text.Editable?) -> Unit
) {
_afterTextChanged = listener
}
}fun android.gesture.GestureOverlayView.onGestureListener(
context: CoroutineContext = Dispatchers.Main,
init: __GestureOverlayView_OnGestureListener.() -> Unit
) {
val listener = __GestureOverlayView_OnGestureListener(context)
listener.init()
addOnGestureListener(listener)
}
class __GestureOverlayView_OnGestureListener(private val context: CoroutineContext) : android.gesture.GestureOverlayView.OnGestureListener {
private var _onGestureStarted: (suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureStarted(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
val handler = _onGestureStarted ?: return
GlobalScope.launch(context) {
handler(overlay, event)
}
}
fun onGestureStarted(
listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit
) {
_onGestureStarted = listener
}
private var _onGesture: (suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGesture(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
val handler = _onGesture ?: return
GlobalScope.launch(context) {
handler(overlay, event)
}
}
fun onGesture(
listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit
) {
_onGesture = listener
}
private var _onGestureEnded: (suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureEnded(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
val handler = _onGestureEnded ?: return
GlobalScope.launch(context) {
handler(overlay, event)
}
}
fun onGestureEnded(
listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit
) {
_onGestureEnded = listener
}
private var _onGestureCancelled: (suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureCancelled(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
val handler = _onGestureCancelled ?: return
GlobalScope.launch(context) {
handler(overlay, event)
}
}
fun onGestureCancelled(
listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit
) {
_onGestureCancelled = listener
}
}fun android.gesture.GestureOverlayView.onGesturePerformed(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(overlay: android.gesture.GestureOverlayView?, gesture: android.gesture.Gesture?) -> Unit
) {
addOnGesturePerformedListener { overlay, gesture ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(overlay, gesture)
}
}
}
fun android.gesture.GestureOverlayView.onGesturingListener(
context: CoroutineContext = Dispatchers.Main,
init: __GestureOverlayView_OnGesturingListener.() -> Unit
) {
val listener = __GestureOverlayView_OnGesturingListener(context)
listener.init()
addOnGesturingListener(listener)
}
class __GestureOverlayView_OnGesturingListener(private val context: CoroutineContext) : android.gesture.GestureOverlayView.OnGesturingListener {
private var _onGesturingStarted: (suspend CoroutineScope.(android.gesture.GestureOverlayView?) -> Unit)? = null
override fun onGesturingStarted(overlay: android.gesture.GestureOverlayView?) {
val handler = _onGesturingStarted ?: return
GlobalScope.launch(context) {
handler(overlay)
}
}
fun onGesturingStarted(
listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?) -> Unit
) {
_onGesturingStarted = listener
}
private var _onGesturingEnded: (suspend CoroutineScope.(android.gesture.GestureOverlayView?) -> Unit)? = null
override fun onGesturingEnded(overlay: android.gesture.GestureOverlayView?) {
val handler = _onGesturingEnded ?: return
GlobalScope.launch(context) {
handler(overlay)
}
}
fun onGesturingEnded(
listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?) -> Unit
) {
_onGesturingEnded = listener
}
}fun android.media.tv.TvView.onUnhandledInputEvent(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(event: android.view.InputEvent?) -> Unit
) {
setOnUnhandledInputEventListener { event ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(event)
}
returnValue
}
}
fun android.view.View.onApplyWindowInsets(
context: CoroutineContext = Dispatchers.Main,
returnValue: WindowInsets,
handler: suspend CoroutineScope.(v: android.view.View?, insets: android.view.WindowInsets?) -> Unit
) {
setOnApplyWindowInsetsListener { v, insets ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v, insets)
}
returnValue
}
}
fun android.view.View.onCapturedPointer(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(view: android.view.View?, event: android.view.MotionEvent?) -> Unit
) {
setOnCapturedPointerListener { view, event ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(view, event)
}
returnValue
}
}
fun android.view.View.onClick(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnClickListener { v ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v)
}
}
}
fun android.view.View.onContextClick(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnContextClickListener { v ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v)
}
returnValue
}
}
fun android.view.View.onCreateContextMenu(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(menu: android.view.ContextMenu?, v: android.view.View?, menuInfo: android.view.ContextMenu.ContextMenuInfo?) -> Unit
) {
setOnCreateContextMenuListener { menu, v, menuInfo ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(menu, v, menuInfo)
}
}
}
fun android.view.View.onDrag(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View, event: android.view.DragEvent) -> Unit
) {
setOnDragListener { v, event ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v, event)
}
returnValue
}
}
fun android.view.View.onFocusChange(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(v: android.view.View, hasFocus: Boolean) -> Unit
) {
setOnFocusChangeListener { v, hasFocus ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v, hasFocus)
}
}
}
fun android.view.View.onGenericMotion(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View, event: android.view.MotionEvent) -> Unit
) {
setOnGenericMotionListener { v, event ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v, event)
}
returnValue
}
}
fun android.view.View.onHover(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View, event: android.view.MotionEvent) -> Unit
) {
setOnHoverListener { v, event ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v, event)
}
returnValue
}
}
fun android.view.View.onKey(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View, keyCode: Int, event: android.view.KeyEvent?) -> Unit
) {
setOnKeyListener { v, keyCode, event ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v, keyCode, event)
}
returnValue
}
}
fun android.view.View.onLongClick(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnLongClickListener { v ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v)
}
returnValue
}
}
fun android.view.View.onScrollChange(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(v: android.view.View?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) -> Unit
) {
setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v, scrollX, scrollY, oldScrollX, oldScrollY)
}
}
}
fun android.view.View.onSystemUiVisibilityChange(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(visibility: Int) -> Unit
) {
setOnSystemUiVisibilityChangeListener { visibility ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(visibility)
}
}
}
fun android.view.View.onTouch(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View, event: android.view.MotionEvent) -> Unit
) {
setOnTouchListener { v, event ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v, event)
}
returnValue
}
}
fun android.view.ViewGroup.onHierarchyChangeListener(
context: CoroutineContext = Dispatchers.Main,
init: __ViewGroup_OnHierarchyChangeListener.() -> Unit
) {
val listener = __ViewGroup_OnHierarchyChangeListener(context)
listener.init()
setOnHierarchyChangeListener(listener)
}
class __ViewGroup_OnHierarchyChangeListener(private val context: CoroutineContext) : android.view.ViewGroup.OnHierarchyChangeListener {
private var _onChildViewAdded: (suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) {
val handler = _onChildViewAdded ?: return
GlobalScope.launch(context) {
handler(parent, child)
}
}
fun onChildViewAdded(
listener: suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit
) {
_onChildViewAdded = listener
}
private var _onChildViewRemoved: (suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) {
val handler = _onChildViewRemoved ?: return
GlobalScope.launch(context) {
handler(parent, child)
}
}
fun onChildViewRemoved(
listener: suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit
) {
_onChildViewRemoved = listener
}
}fun android.view.ViewStub.onInflate(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(stub: android.view.ViewStub?, inflated: android.view.View?) -> Unit
) {
setOnInflateListener { stub, inflated ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(stub, inflated)
}
}
}
fun android.widget.AbsListView.onScrollListener(
context: CoroutineContext = Dispatchers.Main,
init: __AbsListView_OnScrollListener.() -> Unit
) {
val listener = __AbsListView_OnScrollListener(context)
listener.init()
setOnScrollListener(listener)
}
class __AbsListView_OnScrollListener(private val context: CoroutineContext) : android.widget.AbsListView.OnScrollListener {
private var _onScrollStateChanged: (suspend CoroutineScope.(android.widget.AbsListView?, Int) -> Unit)? = null
override fun onScrollStateChanged(view: android.widget.AbsListView?, scrollState: Int) {
val handler = _onScrollStateChanged ?: return
GlobalScope.launch(context) {
handler(view, scrollState)
}
}
fun onScrollStateChanged(
listener: suspend CoroutineScope.(android.widget.AbsListView?, Int) -> Unit
) {
_onScrollStateChanged = listener
}
private var _onScroll: (suspend CoroutineScope.(android.widget.AbsListView?, Int, Int, Int) -> Unit)? = null
override fun onScroll(view: android.widget.AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
val handler = _onScroll ?: return
GlobalScope.launch(context) {
handler(view, firstVisibleItem, visibleItemCount, totalItemCount)
}
}
fun onScroll(
listener: suspend CoroutineScope.(android.widget.AbsListView?, Int, Int, Int) -> Unit
) {
_onScroll = listener
}
}fun android.widget.ActionMenuView.onMenuItemClick(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(item: android.view.MenuItem?) -> Unit
) {
setOnMenuItemClickListener { item ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(item)
}
returnValue
}
}
fun android.widget.AdapterView<out android.widget.Adapter>.onItemClick(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit
) {
setOnItemClickListener { p0, p1, p2, p3 ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(p0, p1, p2, p3)
}
}
}
fun android.widget.AdapterView<out android.widget.Adapter>.onItemLongClick(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit
) {
setOnItemLongClickListener { p0, p1, p2, p3 ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(p0, p1, p2, p3)
}
returnValue
}
}
fun android.widget.AdapterView<out android.widget.Adapter>.onItemSelectedListener(
context: CoroutineContext = Dispatchers.Main,
init: __AdapterView_OnItemSelectedListener.() -> Unit
) {
val listener = __AdapterView_OnItemSelectedListener(context)
listener.init()
setOnItemSelectedListener(listener)
}
class __AdapterView_OnItemSelectedListener(private val context: CoroutineContext) : android.widget.AdapterView.OnItemSelectedListener {
private var _onItemSelected: (suspend CoroutineScope.(android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit)? = null
override fun onItemSelected(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) {
val handler = _onItemSelected ?: return
GlobalScope.launch(context) {
handler(p0, p1, p2, p3)
}
}
fun onItemSelected(
listener: suspend CoroutineScope.(android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit
) {
_onItemSelected = listener
}
private var _onNothingSelected: (suspend CoroutineScope.(android.widget.AdapterView<*>?) -> Unit)? = null
override fun onNothingSelected(p0: android.widget.AdapterView<*>?) {
val handler = _onNothingSelected ?: return
GlobalScope.launch(context) {
handler(p0)
}
}
fun onNothingSelected(
listener: suspend CoroutineScope.(android.widget.AdapterView<*>?) -> Unit
) {
_onNothingSelected = listener
}
}fun android.widget.AutoCompleteTextView.onDismiss(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.() -> Unit
) {
setOnDismissListener { ->
GlobalScope.launch(context, CoroutineStart.DEFAULT, block = handler)
}
}
fun android.widget.CalendarView.onDateChange(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(view: android.widget.CalendarView?, year: Int, month: Int, dayOfMonth: Int) -> Unit
) {
setOnDateChangeListener { view, year, month, dayOfMonth ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(view, year, month, dayOfMonth)
}
}
}
fun android.widget.Chronometer.onChronometerTick(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(chronometer: android.widget.Chronometer?) -> Unit
) {
setOnChronometerTickListener { chronometer ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(chronometer)
}
}
}
fun android.widget.CompoundButton.onCheckedChange(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(buttonView: android.widget.CompoundButton?, isChecked: Boolean) -> Unit
) {
setOnCheckedChangeListener { buttonView, isChecked ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(buttonView, isChecked)
}
}
}
fun android.widget.DatePicker.onDateChanged(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(view: android.widget.DatePicker?, year: Int, monthOfYear: Int, dayOfMonth: Int) -> Unit
) {
setOnDateChangedListener { view, year, monthOfYear, dayOfMonth ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(view, year, monthOfYear, dayOfMonth)
}
}
}
fun android.widget.ExpandableListView.onChildClick(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, childPosition: Int, id: Long) -> Unit
) {
setOnChildClickListener { parent, v, groupPosition, childPosition, id ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(parent, v, groupPosition, childPosition, id)
}
returnValue
}
}
fun android.widget.ExpandableListView.onGroupClick(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, id: Long) -> Unit
) {
setOnGroupClickListener { parent, v, groupPosition, id ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(parent, v, groupPosition, id)
}
returnValue
}
}
fun android.widget.ExpandableListView.onGroupCollapse(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(groupPosition: Int) -> Unit
) {
setOnGroupCollapseListener { groupPosition ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(groupPosition)
}
}
}
fun android.widget.ExpandableListView.onGroupExpand(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(groupPosition: Int) -> Unit
) {
setOnGroupExpandListener { groupPosition ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(groupPosition)
}
}
}
fun android.widget.NumberPicker.onScroll(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(view: android.widget.NumberPicker?, scrollState: Int) -> Unit
) {
setOnScrollListener { view, scrollState ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(view, scrollState)
}
}
}
fun android.widget.NumberPicker.onValueChanged(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(picker: android.widget.NumberPicker?, oldVal: Int, newVal: Int) -> Unit
) {
setOnValueChangedListener { picker, oldVal, newVal ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(picker, oldVal, newVal)
}
}
}
fun android.widget.RadioGroup.onCheckedChange(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(group: android.widget.RadioGroup?, checkedId: Int) -> Unit
) {
setOnCheckedChangeListener { group, checkedId ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(group, checkedId)
}
}
}
fun android.widget.RatingBar.onRatingBarChange(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(ratingBar: android.widget.RatingBar?, rating: Float, fromUser: Boolean) -> Unit
) {
setOnRatingBarChangeListener { ratingBar, rating, fromUser ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(ratingBar, rating, fromUser)
}
}
}
fun android.widget.SearchView.onClose(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.() -> Unit
) {
setOnCloseListener { ->
GlobalScope.launch(context, CoroutineStart.DEFAULT, block = handler)
returnValue
}
}
fun android.widget.SearchView.onQueryTextFocusChange(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(v: android.view.View, hasFocus: Boolean) -> Unit
) {
setOnQueryTextFocusChangeListener { v, hasFocus ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v, hasFocus)
}
}
}
fun android.widget.SearchView.onQueryTextListener(
context: CoroutineContext = Dispatchers.Main,
init: __SearchView_OnQueryTextListener.() -> Unit
) {
val listener = __SearchView_OnQueryTextListener(context)
listener.init()
setOnQueryTextListener(listener)
}
class __SearchView_OnQueryTextListener(private val context: CoroutineContext) : android.widget.SearchView.OnQueryTextListener {
private var _onQueryTextSubmit: (suspend CoroutineScope.(String?) -> Boolean)? = null
private var _onQueryTextSubmit_returnValue: Boolean = false
override fun onQueryTextSubmit(query: String?) : Boolean {
val returnValue = _onQueryTextSubmit_returnValue
val handler = _onQueryTextSubmit ?: return returnValue
GlobalScope.launch(context) {
handler(query)
}
return returnValue
}
fun onQueryTextSubmit(
returnValue: Boolean = false,
listener: suspend CoroutineScope.(String?) -> Boolean
) {
_onQueryTextSubmit = listener
_onQueryTextSubmit_returnValue = returnValue
}
private var _onQueryTextChange: (suspend CoroutineScope.(String?) -> Boolean)? = null
private var _onQueryTextChange_returnValue: Boolean = false
override fun onQueryTextChange(newText: String?) : Boolean {
val returnValue = _onQueryTextChange_returnValue
val handler = _onQueryTextChange ?: return returnValue
GlobalScope.launch(context) {
handler(newText)
}
return returnValue
}
fun onQueryTextChange(
returnValue: Boolean = false,
listener: suspend CoroutineScope.(String?) -> Boolean
) {
_onQueryTextChange = listener
_onQueryTextChange_returnValue = returnValue
}
}fun android.widget.SearchView.onSearchClick(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnSearchClickListener { v ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v)
}
}
}
fun android.widget.SearchView.onSuggestionListener(
context: CoroutineContext = Dispatchers.Main,
init: __SearchView_OnSuggestionListener.() -> Unit
) {
val listener = __SearchView_OnSuggestionListener(context)
listener.init()
setOnSuggestionListener(listener)
}
class __SearchView_OnSuggestionListener(private val context: CoroutineContext) : android.widget.SearchView.OnSuggestionListener {
private var _onSuggestionSelect: (suspend CoroutineScope.(Int) -> Boolean)? = null
private var _onSuggestionSelect_returnValue: Boolean = false
override fun onSuggestionSelect(position: Int) : Boolean {
val returnValue = _onSuggestionSelect_returnValue
val handler = _onSuggestionSelect ?: return returnValue
GlobalScope.launch(context) {
handler(position)
}
return returnValue
}
fun onSuggestionSelect(
returnValue: Boolean = false,
listener: suspend CoroutineScope.(Int) -> Boolean
) {
_onSuggestionSelect = listener
_onSuggestionSelect_returnValue = returnValue
}
private var _onSuggestionClick: (suspend CoroutineScope.(Int) -> Boolean)? = null
private var _onSuggestionClick_returnValue: Boolean = false
override fun onSuggestionClick(position: Int) : Boolean {
val returnValue = _onSuggestionClick_returnValue
val handler = _onSuggestionClick ?: return returnValue
GlobalScope.launch(context) {
handler(position)
}
return returnValue
}
fun onSuggestionClick(
returnValue: Boolean = false,
listener: suspend CoroutineScope.(Int) -> Boolean
) {
_onSuggestionClick = listener
_onSuggestionClick_returnValue = returnValue
}
}fun android.widget.SeekBar.onSeekBarChangeListener(
context: CoroutineContext = Dispatchers.Main,
init: __SeekBar_OnSeekBarChangeListener.() -> Unit
) {
val listener = __SeekBar_OnSeekBarChangeListener(context)
listener.init()
setOnSeekBarChangeListener(listener)
}
class __SeekBar_OnSeekBarChangeListener(private val context: CoroutineContext) : android.widget.SeekBar.OnSeekBarChangeListener {
private var _onProgressChanged: (suspend CoroutineScope.(android.widget.SeekBar?, Int, Boolean) -> Unit)? = null
override fun onProgressChanged(seekBar: android.widget.SeekBar?, progress: Int, fromUser: Boolean) {
val handler = _onProgressChanged ?: return
GlobalScope.launch(context) {
handler(seekBar, progress, fromUser)
}
}
fun onProgressChanged(
listener: suspend CoroutineScope.(android.widget.SeekBar?, Int, Boolean) -> Unit
) {
_onProgressChanged = listener
}
private var _onStartTrackingTouch: (suspend CoroutineScope.(android.widget.SeekBar?) -> Unit)? = null
override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) {
val handler = _onStartTrackingTouch ?: return
GlobalScope.launch(context) {
handler(seekBar)
}
}
fun onStartTrackingTouch(
listener: suspend CoroutineScope.(android.widget.SeekBar?) -> Unit
) {
_onStartTrackingTouch = listener
}
private var _onStopTrackingTouch: (suspend CoroutineScope.(android.widget.SeekBar?) -> Unit)? = null
override fun onStopTrackingTouch(seekBar: android.widget.SeekBar?) {
val handler = _onStopTrackingTouch ?: return
GlobalScope.launch(context) {
handler(seekBar)
}
}
fun onStopTrackingTouch(
listener: suspend CoroutineScope.(android.widget.SeekBar?) -> Unit
) {
_onStopTrackingTouch = listener
}
}fun android.widget.SlidingDrawer.onDrawerClose(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.() -> Unit
) {
setOnDrawerCloseListener { ->
GlobalScope.launch(context, CoroutineStart.DEFAULT, block = handler)
}
}
fun android.widget.SlidingDrawer.onDrawerOpen(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.() -> Unit
) {
setOnDrawerOpenListener { ->
GlobalScope.launch(context, CoroutineStart.DEFAULT, block = handler)
}
}
fun android.widget.SlidingDrawer.onDrawerScrollListener(
context: CoroutineContext = Dispatchers.Main,
init: __SlidingDrawer_OnDrawerScrollListener.() -> Unit
) {
val listener = __SlidingDrawer_OnDrawerScrollListener(context)
listener.init()
setOnDrawerScrollListener(listener)
}
class __SlidingDrawer_OnDrawerScrollListener(private val context: CoroutineContext) : android.widget.SlidingDrawer.OnDrawerScrollListener {
private var _onScrollStarted: (suspend CoroutineScope.() -> Unit)? = null
override fun onScrollStarted() {
val handler = _onScrollStarted ?: return
GlobalScope.launch(context, block = handler)
}
fun onScrollStarted(
listener: suspend CoroutineScope.() -> Unit
) {
_onScrollStarted = listener
}
private var _onScrollEnded: (suspend CoroutineScope.() -> Unit)? = null
override fun onScrollEnded() {
val handler = _onScrollEnded ?: return
GlobalScope.launch(context, block = handler)
}
fun onScrollEnded(
listener: suspend CoroutineScope.() -> Unit
) {
_onScrollEnded = listener
}
}fun android.widget.TabHost.onTabChanged(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(tabId: String?) -> Unit
) {
setOnTabChangedListener { tabId ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(tabId)
}
}
}
fun android.widget.TextView.onEditorAction(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.widget.TextView?, actionId: Int, event: android.view.KeyEvent?) -> Unit
) {
setOnEditorActionListener { v, actionId, event ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v, actionId, event)
}
returnValue
}
}
fun android.widget.TimePicker.onTimeChanged(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(view: android.widget.TimePicker?, hourOfDay: Int, minute: Int) -> Unit
) {
setOnTimeChangedListener { view, hourOfDay, minute ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(view, hourOfDay, minute)
}
}
}
fun android.widget.Toolbar.onMenuItemClick(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(item: android.view.MenuItem?) -> Unit
) {
setOnMenuItemClickListener { item ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(item)
}
returnValue
}
}
fun android.widget.VideoView.onCompletion(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(mp: android.media.MediaPlayer?) -> Unit
) {
setOnCompletionListener { mp ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(mp)
}
}
}
fun android.widget.VideoView.onError(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Unit
) {
setOnErrorListener { mp, what, extra ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(mp, what, extra)
}
returnValue
}
}
fun android.widget.VideoView.onInfo(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Unit
) {
setOnInfoListener { mp, what, extra ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(mp, what, extra)
}
returnValue
}
}
fun android.widget.VideoView.onPrepared(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(mp: android.media.MediaPlayer?) -> Unit
) {
setOnPreparedListener { mp ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(mp)
}
}
}
fun android.widget.ZoomControls.onZoomInClick(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnZoomInClickListener { v ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v)
}
}
}
fun android.widget.ZoomControls.onZoomOutClick(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnZoomOutClickListener { v ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v)
}
}
}
| apache-2.0 | 5486c9dc764003f1d9af266bdf043872 | 32.756637 | 175 | 0.672644 | 4.971976 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/src/commonMain/kotlin/nl/adaptivity/diagram/svg/SVGPen.kt | 1 | 3393 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.diagram.svg
import nl.adaptivity.diagram.Pen
import nl.adaptivity.diagram.Rectangle
import nl.adaptivity.diagram.svg.TextMeasurer.MeasureInfo
class SVGPen<M : MeasureInfo>(private val textMeasurer: TextMeasurer<M>) : Pen<SVGPen<M>> {
var color = -0x1000000
private set
override var strokeWidth: Double = 0.toDouble()
override var fontSize: Double = 0.toDouble()
private set(value) {
textMeasureInfo.setFontSize(value)
}
override var isTextItalics: Boolean = false
override var isTextBold: Boolean = false
private var _textMeasureInfo: M? = null
private val textMeasureInfo: M
get() = _textMeasureInfo ?: textMeasurer.getTextMeasureInfo(this).also { _textMeasureInfo = it }
override fun setColor(red: Int, green: Int, blue: Int): SVGPen<M> {
return setColor(red, green, blue, 0xff)
}
override fun setColor(red: Int, green: Int, blue: Int, alpha: Int): SVGPen<M> {
color = alpha and 0xff shl 24 or (red and 0xff shl 16) or (green and 0xff shl 8) or (blue and 0xff)
return this
}
@Deprecated("Use property access without return value")
override fun setStrokeWidth(strokeWidth: Double): SVGPen<M> {
this.strokeWidth = strokeWidth
return this
}
@Deprecated("Use property access without return value")
override fun setFontSize(fontSize: Double): SVGPen<M> {
this.fontSize = fontSize
return this
}
override fun measureTextWidth(text: String, foldWidth: Double): Double =
textMeasurer.measureTextWidth(textMeasureInfo, text, foldWidth)
override fun measureTextSize(dest: Rectangle, x: Double, y: Double, text: String, foldWidth: Double): Rectangle {
textMeasurer.measureTextSize(dest, textMeasureInfo, text, foldWidth)
dest.top += y
dest.left += x
return dest
}
override val textMaxAscent: Double
get() = textMeasurer.getTextMaxAscent(textMeasureInfo)
override val textAscent: Double
get() = textMeasurer.getTextAscent(textMeasureInfo)
override val textDescent: Double
get() = textMeasurer.getTextDescent(textMeasureInfo)
override val textMaxDescent: Double
get() = textMeasurer.getTextMaxDescent(textMeasureInfo)
override val textLeading: Double
get() = textMeasurer.getTextLeading(textMeasureInfo)
fun copy(): SVGPen<M> {
val o = this
return SVGPen(textMeasurer).apply {
color = o.color
strokeWidth = o.strokeWidth
fontSize = o.fontSize
isTextItalics = o.isTextItalics
isTextBold = o.isTextBold
}
}
}
| lgpl-3.0 | 8302bcedba482a1cbeb93c65a1a2fb2d | 32.594059 | 117 | 0.686413 | 4.199257 | false | false | false | false |
WijayaPrinting/wp-javafx | openpss/src/com/hendraanggrian/openpss/schema/Payment.kt | 1 | 1464 | package com.hendraanggrian.openpss.schema
import com.hendraanggrian.openpss.nosql.Document
import com.hendraanggrian.openpss.nosql.Schema
import com.hendraanggrian.openpss.nosql.StringId
import kotlinx.nosql.dateTime
import kotlinx.nosql.double
import kotlinx.nosql.id
import kotlinx.nosql.nullableString
import org.joda.time.DateTime
object Payments : Schema<Payment>("payments", Payment::class) {
val invoiceId = id("invoice_id", Invoices)
val employeeId = id("employee_id", Employees)
val dateTime = dateTime("date_time")
val value = double("value")
val reference = nullableString("reference")
}
data class Payment(
var invoiceId: StringId<Invoices>,
var employeeId: StringId<Employees>,
val dateTime: DateTime,
val value: Double,
val reference: String?
) : Document<Payments> {
companion object {
fun new(
invoiceId: StringId<Invoices>,
employeeId: StringId<Employees>,
dateTime: DateTime,
value: Double,
reference: String? = null
): Payment = Payment(
invoiceId,
employeeId,
dateTime,
value,
reference
)
fun gather(payments: List<Payment>, isCash: Boolean) = payments
.filter { it.isCash() == isCash }
.sumByDouble { it.value }
}
override lateinit var id: StringId<Payments>
fun isCash(): Boolean = reference == null
}
| apache-2.0 | cfd1d093edc19108d9c9726a56126f1f | 27.153846 | 71 | 0.650273 | 4.370149 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/loadtest/dataprovider/EdpSimulator.kt | 1 | 24758 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.loadtest.dataprovider
import com.google.protobuf.ByteString
import com.google.protobuf.duration
import io.grpc.StatusException
import java.nio.file.Paths
import java.util.logging.Level
import java.util.logging.Logger
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import org.apache.commons.math3.distribution.LaplaceDistribution
import org.wfanet.anysketch.AnySketch
import org.wfanet.anysketch.Sketch
import org.wfanet.anysketch.SketchConfig
import org.wfanet.anysketch.SketchConfigKt.indexSpec
import org.wfanet.anysketch.SketchConfigKt.valueSpec
import org.wfanet.anysketch.SketchProtos
import org.wfanet.anysketch.crypto.CombineElGamalPublicKeysRequest
import org.wfanet.anysketch.crypto.CombineElGamalPublicKeysResponse
import org.wfanet.anysketch.crypto.ElGamalPublicKey as AnySketchElGamalPublicKey
import org.wfanet.anysketch.crypto.EncryptSketchRequest
import org.wfanet.anysketch.crypto.EncryptSketchResponse
import org.wfanet.anysketch.crypto.SketchEncrypterAdapter
import org.wfanet.anysketch.distribution
import org.wfanet.anysketch.exponentialDistribution
import org.wfanet.anysketch.oracleDistribution
import org.wfanet.anysketch.sketchConfig
import org.wfanet.anysketch.uniformDistribution
import org.wfanet.estimation.VidSampler
import org.wfanet.measurement.api.v2alpha.CertificatesGrpcKt.CertificatesCoroutineStub
import org.wfanet.measurement.api.v2alpha.DataProviderKey
import org.wfanet.measurement.api.v2alpha.ElGamalPublicKey
import org.wfanet.measurement.api.v2alpha.EncryptionPublicKey
import org.wfanet.measurement.api.v2alpha.EventGroup
import org.wfanet.measurement.api.v2alpha.EventGroupKt.eventTemplate
import org.wfanet.measurement.api.v2alpha.EventGroupsGrpcKt.EventGroupsCoroutineStub
import org.wfanet.measurement.api.v2alpha.FulfillRequisitionRequest
import org.wfanet.measurement.api.v2alpha.FulfillRequisitionRequestKt.bodyChunk
import org.wfanet.measurement.api.v2alpha.FulfillRequisitionRequestKt.header
import org.wfanet.measurement.api.v2alpha.LiquidLegionsSketchParams
import org.wfanet.measurement.api.v2alpha.ListRequisitionsRequestKt.filter
import org.wfanet.measurement.api.v2alpha.Measurement
import org.wfanet.measurement.api.v2alpha.MeasurementKt
import org.wfanet.measurement.api.v2alpha.MeasurementKt.ResultKt.frequency
import org.wfanet.measurement.api.v2alpha.MeasurementKt.ResultKt.impression
import org.wfanet.measurement.api.v2alpha.MeasurementKt.ResultKt.reach
import org.wfanet.measurement.api.v2alpha.MeasurementKt.ResultKt.watchDuration
import org.wfanet.measurement.api.v2alpha.MeasurementSpec
import org.wfanet.measurement.api.v2alpha.ProtocolConfig
import org.wfanet.measurement.api.v2alpha.Requisition
import org.wfanet.measurement.api.v2alpha.RequisitionFulfillmentGrpcKt.RequisitionFulfillmentCoroutineStub
import org.wfanet.measurement.api.v2alpha.RequisitionKt.refusal
import org.wfanet.measurement.api.v2alpha.RequisitionSpec
import org.wfanet.measurement.api.v2alpha.RequisitionSpec.EventFilter
import org.wfanet.measurement.api.v2alpha.RequisitionsGrpcKt.RequisitionsCoroutineStub
import org.wfanet.measurement.api.v2alpha.SignedData
import org.wfanet.measurement.api.v2alpha.createEventGroupRequest
import org.wfanet.measurement.api.v2alpha.eventGroup
import org.wfanet.measurement.api.v2alpha.fulfillDirectRequisitionRequest
import org.wfanet.measurement.api.v2alpha.fulfillRequisitionRequest
import org.wfanet.measurement.api.v2alpha.getCertificateRequest
import org.wfanet.measurement.api.v2alpha.listRequisitionsRequest
import org.wfanet.measurement.api.v2alpha.refuseRequisitionRequest
import org.wfanet.measurement.common.asBufferedFlow
import org.wfanet.measurement.common.crypto.PrivateKeyHandle
import org.wfanet.measurement.common.crypto.SigningKeyHandle
import org.wfanet.measurement.common.crypto.readCertificate
import org.wfanet.measurement.common.identity.apiIdToExternalId
import org.wfanet.measurement.common.loadLibrary
import org.wfanet.measurement.common.throttler.MinimumIntervalThrottler
import org.wfanet.measurement.consent.client.common.toPublicKeyHandle
import org.wfanet.measurement.consent.client.dataprovider.computeRequisitionFingerprint
import org.wfanet.measurement.consent.client.dataprovider.decryptRequisitionSpec
import org.wfanet.measurement.consent.client.dataprovider.verifyMeasurementSpec
import org.wfanet.measurement.consent.client.dataprovider.verifyRequisitionSpec
import org.wfanet.measurement.consent.client.duchy.signResult
import org.wfanet.measurement.eventdataprovider.eventfiltration.validation.EventFilterValidationException
import org.wfanet.measurement.eventdataprovider.privacybudgetmanagement.PrivacyBudgetManager
import org.wfanet.measurement.eventdataprovider.privacybudgetmanagement.PrivacyBudgetManagerException
import org.wfanet.measurement.eventdataprovider.privacybudgetmanagement.Reference
import org.wfanet.measurement.eventdataprovider.privacybudgetmanagement.api.v2alpha.PrivacyQueryMapper
import org.wfanet.measurement.loadtest.config.EventFilters.VID_SAMPLER_HASH_FUNCTION
import org.wfanet.measurement.loadtest.storage.SketchStore
data class EdpData(
/** The EDP's public API resource name. */
val name: String,
/** The EDP's display name. */
val displayName: String,
/** The EDP's consent signaling encryption key. */
val encryptionKey: PrivateKeyHandle,
/** The EDP's consent signaling signing key. */
val signingKey: SigningKeyHandle
)
/** A simulator handling EDP businesses. */
class EdpSimulator(
private val edpData: EdpData,
private val measurementConsumerName: String,
private val certificatesStub: CertificatesCoroutineStub,
private val eventGroupsStub: EventGroupsCoroutineStub,
private val requisitionsStub: RequisitionsCoroutineStub,
private val requisitionFulfillmentStub: RequisitionFulfillmentCoroutineStub,
private val sketchStore: SketchStore,
private val eventQuery: EventQuery,
private val throttler: MinimumIntervalThrottler,
private val eventTemplateNames: List<String>,
private val privacyBudgetManager: PrivacyBudgetManager
) {
/** A sequence of operations done in the simulator. */
suspend fun run() {
throttler.loopOnReady { executeRequisitionFulfillingWorkflow() }
}
/** Creates an eventGroup for the MC. */
suspend fun createEventGroup(): EventGroup {
val request = createEventGroupRequest {
parent = edpData.name
eventGroup = eventGroup {
measurementConsumer = measurementConsumerName
eventGroupReferenceId = "001"
eventTemplates += eventTemplateNames.map { eventTemplate { type = it } }
}
}
val eventGroup =
try {
eventGroupsStub.createEventGroup(request)
} catch (e: StatusException) {
throw Exception("Error creating event group", e)
}
logger.info("Successfully created eventGroup ${eventGroup.name}...")
return eventGroup
}
/** Executes the requisition fulfillment workflow. */
suspend fun executeRequisitionFulfillingWorkflow() {
logger.info("Executing requisitionFulfillingWorkflow...")
val requisitions = getRequisitions()
if (requisitions.isEmpty()) {
logger.fine("No unfulfilled requisition. Polling again later...")
return
}
for (requisition in requisitions) {
logger.info("Processing requisition ${requisition.name}...")
val measurementConsumerCertificate =
try {
certificatesStub.getCertificate(
getCertificateRequest { name = requisition.measurementConsumerCertificate }
)
} catch (e: StatusException) {
throw Exception("Error fetching cert ${requisition.measurementConsumerCertificate}", e)
}
val measurementConsumerCertificateX509 =
readCertificate(measurementConsumerCertificate.x509Der)
if (
!verifyMeasurementSpec(
signedMeasurementSpec = requisition.measurementSpec,
measurementConsumerCertificate = measurementConsumerCertificateX509,
)
) {
logger.info("RequisitionFulfillmentWorkflow failed due to: invalid measurementSpec.")
refuseRequisition(
requisition.name,
Requisition.Refusal.Justification.SPECIFICATION_INVALID,
"Invalid measurementSpec"
)
}
val measurementSpec = MeasurementSpec.parseFrom(requisition.measurementSpec.data)
val requisitionFingerprint = computeRequisitionFingerprint(requisition)
val signedRequisitionSpec: SignedData =
decryptRequisitionSpec(requisition.encryptedRequisitionSpec, edpData.encryptionKey)
val requisitionSpec = RequisitionSpec.parseFrom(signedRequisitionSpec.data)
if (
!verifyRequisitionSpec(
signedRequisitionSpec = signedRequisitionSpec,
requisitionSpec = requisitionSpec,
measurementConsumerCertificate = measurementConsumerCertificateX509,
measurementSpec = measurementSpec,
)
) {
logger.info("RequisitionFulfillmentWorkflow failed due to: invalid requisitionSpec.")
refuseRequisition(
requisition.name,
Requisition.Refusal.Justification.SPECIFICATION_INVALID,
"Invalid requisitionSpec"
)
}
if (requisition.protocolConfig.protocolsList.any { protocol -> protocol.hasDirect() }) {
when (measurementSpec.measurementTypeCase) {
MeasurementSpec.MeasurementTypeCase.REACH_AND_FREQUENCY -> {
fulfillDirectReachAndFrequencyMeasurement(requisition, requisitionSpec, measurementSpec)
}
MeasurementSpec.MeasurementTypeCase.IMPRESSION ->
fulfillImpressionMeasurement(requisition, requisitionSpec, measurementSpec)
MeasurementSpec.MeasurementTypeCase.DURATION ->
fulfillDurationMeasurement(requisition, requisitionSpec, measurementSpec)
else ->
logger.info("Skipping requisition ${requisition.name}, unsupported measurement type")
}
} else {
fulfillRequisitionForReachAndFrequencyMeasurement(
requisition,
measurementSpec,
requisitionFingerprint,
requisitionSpec
)
}
}
}
private suspend fun refuseRequisition(
requisitionName: String,
justification: Requisition.Refusal.Justification,
message: String
): Requisition {
try {
return requisitionsStub.refuseRequisition(
refuseRequisitionRequest {
name = requisitionName
refusal = refusal {
this.justification = justification
this.message = message
}
}
)
} catch (e: StatusException) {
throw Exception("Error refusing requisition $requisitionName", e)
}
}
private fun populateAnySketch(
eventFilter: EventFilter,
vidSampler: VidSampler,
vidSamplingIntervalStart: Float,
vidSamplingIntervalWidth: Float,
anySketch: AnySketch
) {
eventQuery
.getUserVirtualIds(eventFilter)
.filter {
vidSampler.vidIsInSamplingBucket(it, vidSamplingIntervalStart, vidSamplingIntervalWidth)
}
.forEach { anySketch.insert(it, mapOf("frequency" to 1L)) }
}
private suspend fun chargePrivacyBudget(
requisitionName: String,
measurementSpec: MeasurementSpec,
requisitionSpec: RequisitionSpec
) =
try {
privacyBudgetManager.chargePrivacyBudget(
PrivacyQueryMapper.getPrivacyQuery(
Reference(measurementConsumerName, requisitionName, false),
requisitionSpec,
measurementSpec
)
)
} catch (e: PrivacyBudgetManagerException) {
logger.log(
Level.WARNING,
"RequisitionFulfillmentWorkflow failed due to: Not Enough Privacy Budget",
e
)
refuseRequisition(
requisitionName,
Requisition.Refusal.Justification.INSUFFICIENT_PRIVACY_BUDGET,
"Privacy Budget Exceeded."
)
}
private suspend fun generateSketch(
requisitionName: String,
sketchConfig: SketchConfig,
measurementSpec: MeasurementSpec,
requisitionSpec: RequisitionSpec
): Sketch {
chargePrivacyBudget(requisitionName, measurementSpec, requisitionSpec)
val vidSamplingIntervalStart = measurementSpec.vidSamplingInterval.start
val vidSamplingIntervalWidth = measurementSpec.vidSamplingInterval.width
val anySketch: AnySketch = SketchProtos.toAnySketch(sketchConfig)
logger.info("Generating Sketch...")
requisitionSpec.eventGroupsList.forEach {
populateAnySketch(
it.value.filter,
VidSampler(VID_SAMPLER_HASH_FUNCTION),
vidSamplingIntervalStart,
vidSamplingIntervalWidth,
anySketch
)
}
return SketchProtos.fromAnySketch(anySketch, sketchConfig)
}
private fun encryptSketch(
sketch: Sketch,
combinedPublicKey: AnySketchElGamalPublicKey,
protocolConfig: ProtocolConfig.LiquidLegionsV2
): ByteString {
logger.info("Encrypting Sketch...")
val request =
EncryptSketchRequest.newBuilder()
.apply {
this.sketch = sketch
elGamalKeys = combinedPublicKey
curveId = protocolConfig.ellipticCurveId.toLong()
maximumValue = protocolConfig.maximumFrequency
destroyedRegisterStrategy =
EncryptSketchRequest.DestroyedRegisterStrategy.FLAGGED_KEY // for LL_V2 protocol
// TODO(wangyaopw): add publisher noise
}
.build()
val response =
EncryptSketchResponse.parseFrom(SketchEncrypterAdapter.EncryptSketch(request.toByteArray()))
return response.encryptedSketch
}
/**
* Calculate reach and frequency for measurement with multiple EDPs by creating encrypted sketch
* and send to Duchy to perform MPC and fulfillRequisition
*/
private suspend fun fulfillRequisitionForReachAndFrequencyMeasurement(
requisition: Requisition,
measurementSpec: MeasurementSpec,
requisitionFingerprint: ByteString,
requisitionSpec: RequisitionSpec
) {
val llv2Protocol: ProtocolConfig.Protocol =
requireNotNull(
requisition.protocolConfig.protocolsList.find { protocol -> protocol.hasLiquidLegionsV2() }
) {
"Protocol with LiquidLegionsV2 is missing"
}
val liquidLegionsV2: ProtocolConfig.LiquidLegionsV2 = llv2Protocol.liquidLegionsV2
val combinedPublicKey = requisition.getCombinedPublicKey(liquidLegionsV2.ellipticCurveId)
val sketchConfig = liquidLegionsV2.sketchParams.toSketchConfig()
val sketch =
try {
generateSketch(requisition.name, sketchConfig, measurementSpec, requisitionSpec)
} catch (e: EventFilterValidationException) {
logger.log(
Level.WARNING,
"RequisitionFulfillmentWorkflow failed due to: invalid EventFilter",
e
)
return
}
logger.info("Writing sketch to storage")
sketchStore.write(requisition, sketch.toByteString())
val encryptedSketch = encryptSketch(sketch, combinedPublicKey, liquidLegionsV2)
fulfillRequisition(
requisition.name,
requisitionFingerprint,
requisitionSpec.nonce,
encryptedSketch
)
}
private suspend fun fulfillRequisition(
requisitionName: String,
requisitionFingerprint: ByteString,
nonce: Long,
data: ByteString,
) {
logger.info("Fulfilling requisition $requisitionName...")
val requests: Flow<FulfillRequisitionRequest> = flow {
emit(
fulfillRequisitionRequest {
header = header {
name = requisitionName
this.requisitionFingerprint = requisitionFingerprint
this.nonce = nonce
}
}
)
emitAll(
data.asBufferedFlow(RPC_CHUNK_SIZE_BYTES).map {
fulfillRequisitionRequest { bodyChunk = bodyChunk { this.data = it } }
}
)
}
try {
requisitionFulfillmentStub.fulfillRequisition(requests)
} catch (e: StatusException) {
throw Exception("Error fulfilling requisition $requisitionName", e)
}
}
private fun Requisition.getCombinedPublicKey(curveId: Int): AnySketchElGamalPublicKey {
logger.info("Getting combined public key...")
val listOfKeys = this.duchiesList.map { it.getElGamalKey() }
val request =
CombineElGamalPublicKeysRequest.newBuilder()
.also {
it.curveId = curveId.toLong()
it.addAllElGamalKeys(listOfKeys)
}
.build()
return CombineElGamalPublicKeysResponse.parseFrom(
SketchEncrypterAdapter.CombineElGamalPublicKeys(request.toByteArray())
)
.elGamalKeys
}
private suspend fun getRequisitions(): List<Requisition> {
val request = listRequisitionsRequest {
parent = edpData.name
filter = filter {
states += Requisition.State.UNFULFILLED
measurementStates += Measurement.State.AWAITING_REQUISITION_FULFILLMENT
}
}
try {
return requisitionsStub.listRequisitions(request).requisitionsList
} catch (e: StatusException) {
throw Exception("Error listing requisitions", e)
}
}
/**
* Calculate direct reach and frequency for measurement with single EDP by summing up VIDs
* directly and fulfillDirectMeasurement
*/
private suspend fun fulfillDirectReachAndFrequencyMeasurement(
requisition: Requisition,
requisitionSpec: RequisitionSpec,
measurementSpec: MeasurementSpec
) {
logger.info("Calculating direct reach and frequency...")
val vidSampler = VidSampler(VID_SAMPLER_HASH_FUNCTION)
val vidSamplingIntervalStart = measurementSpec.vidSamplingInterval.start
val vidSamplingIntervalWidth = measurementSpec.vidSamplingInterval.width
val vidList: List<Long> =
requisitionSpec.eventGroupsList
.distinctBy { eventGroup -> eventGroup.key }
.flatMap { eventGroup -> eventQuery.getUserVirtualIds(eventGroup.value.filter) }
.filter { vid ->
vidSampler.vidIsInSamplingBucket(vid, vidSamplingIntervalStart, vidSamplingIntervalWidth)
}
val (reachValue, frequencyMap) =
calculateDirectReachAndFrequency(vidList, vidSamplingIntervalWidth)
logger.info("Adding publisher noise to direct reach and frequency...")
val laplaceForReach =
LaplaceDistribution(0.0, 1 / measurementSpec.reachAndFrequency.reachPrivacyParams.epsilon)
laplaceForReach.reseedRandomGenerator(1)
val reachNoisedValue = reachValue + laplaceForReach.sample().toInt()
val laplaceForFrequency =
LaplaceDistribution(0.0, 1 / measurementSpec.reachAndFrequency.frequencyPrivacyParams.epsilon)
laplaceForFrequency.reseedRandomGenerator(1)
val frequencyNoisedMap = mutableMapOf<Long, Double>()
frequencyMap.forEach { (frequency, percentage) ->
frequencyNoisedMap[frequency] =
(percentage * reachValue.toDouble() + laplaceForFrequency.sample()) / reachValue.toDouble()
}
val requisitionData =
MeasurementKt.result {
reach = reach { value = reachNoisedValue }
frequency = frequency { relativeFrequencyDistribution.putAll(frequencyNoisedMap) }
}
fulfillDirectMeasurement(requisition, requisitionSpec, measurementSpec, requisitionData)
}
private suspend fun fulfillImpressionMeasurement(
requisition: Requisition,
requisitionSpec: RequisitionSpec,
measurementSpec: MeasurementSpec
) {
val requisitionData =
MeasurementKt.result {
impression = impression {
// Use externalDataProviderId since it's a known value the FrontendSimulator can verify.
// TODO: Calculate impression from data.
value = apiIdToExternalId(DataProviderKey.fromName(edpData.name)!!.dataProviderId)
}
}
fulfillDirectMeasurement(requisition, requisitionSpec, measurementSpec, requisitionData)
}
private suspend fun fulfillDurationMeasurement(
requisition: Requisition,
requisitionSpec: RequisitionSpec,
measurementSpec: MeasurementSpec
) {
val requisitionData =
MeasurementKt.result {
watchDuration = watchDuration {
value = duration {
// Use externalDataProviderId since it's a known value the FrontendSimulator can verify.
seconds = apiIdToExternalId(DataProviderKey.fromName(edpData.name)!!.dataProviderId)
}
}
}
fulfillDirectMeasurement(requisition, requisitionSpec, measurementSpec, requisitionData)
}
private suspend fun fulfillDirectMeasurement(
requisition: Requisition,
requisitionSpec: RequisitionSpec,
measurementSpec: MeasurementSpec,
requisitionData: Measurement.Result
) {
val measurementEncryptionPublicKey =
EncryptionPublicKey.parseFrom(measurementSpec.measurementPublicKey)
val signedData = signResult(requisitionData, edpData.signingKey)
val encryptedData =
measurementEncryptionPublicKey.toPublicKeyHandle().hybridEncrypt(signedData.toByteString())
try {
requisitionsStub.fulfillDirectRequisition(
fulfillDirectRequisitionRequest {
name = requisition.name
this.encryptedData = encryptedData
nonce = requisitionSpec.nonce
}
)
} catch (e: StatusException) {
throw Exception("Error fulfilling direct requisition ${requisition.name}", e)
}
}
companion object {
private const val RPC_CHUNK_SIZE_BYTES = 32 * 1024 // 32 KiB
private val logger: Logger = Logger.getLogger(this::class.java.name)
init {
loadLibrary(
name = "sketch_encrypter_adapter",
directoryPath =
Paths.get(
"any_sketch_java",
"src",
"main",
"java",
"org",
"wfanet",
"anysketch",
"crypto"
)
)
}
/**
* Function to calculate direct reach and frequency from VIDs in
* fulfillDirectReachAndFrequencyMeasurement(). Reach needs to scale by sampling rate
* @param vidList List of VIDs
* @param samplingRate Probability of sampling which is vidSamplingIntervalWidth
* @return Pair of reach value and frequency map
*/
fun calculateDirectReachAndFrequency(
vidList: List<Long>,
samplingRate: Float
): Pair<Long, Map<Long, Double>> {
require(samplingRate > 0 && samplingRate <= 1.0) { "Invalid samplingRate $samplingRate" }
var reachValue = vidList.toSet().size.toLong()
val frequencyMap = mutableMapOf<Long, Double>().withDefault { 0.0 }
vidList
.groupingBy { it }
.eachCount()
.forEach { (_, frequency) ->
frequencyMap[frequency.toLong()] = frequencyMap.getValue(frequency.toLong()) + 1.0
}
frequencyMap.forEach { (frequency, _) ->
frequencyMap[frequency] = frequencyMap.getValue(frequency) / reachValue.toDouble()
}
reachValue = (reachValue / samplingRate).toLong()
return Pair(reachValue, frequencyMap)
}
}
}
private fun Requisition.DuchyEntry.getElGamalKey(): AnySketchElGamalPublicKey {
val key = ElGamalPublicKey.parseFrom(this.value.liquidLegionsV2.elGamalPublicKey.data)
return AnySketchElGamalPublicKey.newBuilder()
.also {
it.generator = key.generator
it.element = key.element
}
.build()
}
private fun LiquidLegionsSketchParams.toSketchConfig(): SketchConfig {
return sketchConfig {
indexes += indexSpec {
name = "Index"
distribution = distribution {
exponential = exponentialDistribution {
rate = decayRate
numValues = maxSize
}
}
}
values += valueSpec {
name = "SamplingIndicator"
aggregator = SketchConfig.ValueSpec.Aggregator.UNIQUE
distribution = distribution {
uniform = uniformDistribution { numValues = samplingIndicatorSize }
}
}
values += valueSpec {
name = "Frequency"
aggregator = SketchConfig.ValueSpec.Aggregator.SUM
distribution = distribution { oracle = oracleDistribution { key = "frequency" } }
}
}
}
| apache-2.0 | 4104b9a2e74a29bb5318bde753c3aaa6 | 36.972393 | 106 | 0.735964 | 4.722106 | false | false | false | false |
RoverPlatform/rover-android | core/src/main/kotlin/io/rover/sdk/core/events/contextproviders/DeviceContextProvider.kt | 1 | 800 | package io.rover.sdk.core.events.contextproviders
import android.os.Build
import io.rover.sdk.core.data.domain.DeviceContext
import io.rover.sdk.core.events.ContextProvider
import io.rover.sdk.core.platform.getDeviceName
/**
* Captures and adds details about the product details of the user's device and its running Android
* version to [DeviceContext].
*/
class DeviceContextProvider : ContextProvider {
private val deviceMarketingName = getDeviceName()
override fun captureContext(deviceContext: DeviceContext): DeviceContext {
return deviceContext.copy(
operatingSystemVersion = Build.VERSION.RELEASE,
operatingSystemName = "Android",
deviceManufacturer = Build.MANUFACTURER,
deviceModel = deviceMarketingName
)
}
}
| apache-2.0 | c118241562e80880682798bf22ac141c | 35.363636 | 99 | 0.74 | 4.571429 | false | false | false | false |
jamieadkins95/Roach | decktracker-data/src/main/java/com/jamieadkins/decktracker/data/CardPredictorRepositoryImpl.kt | 1 | 3191 | package com.jamieadkins.decktracker.data
import com.jamieadkins.gwent.domain.GwentFaction
import com.jamieadkins.gwent.domain.card.repository.CardRepository
import com.jamieadkins.gwent.domain.tracker.predictions.CardPrediction
import com.jamieadkins.gwent.domain.tracker.predictions.CardPredictions
import com.jamieadkins.gwent.domain.tracker.predictions.CardPredictorRepository
import com.jamieadkins.gwent.domain.tracker.predictions.SimilarDeck
import io.reactivex.Maybe
import io.reactivex.Single
import timber.log.Timber
import javax.inject.Inject
class CardPredictorRepositoryImpl @Inject constructor(
private val api: CardPredictorApi,
private val cardRepository: CardRepository
) : CardPredictorRepository {
override fun getPredictions(leaderId: String, cardIds: List<String>): Maybe<CardPredictions> {
if (cardIds.isEmpty()) return Maybe.empty()
return api.analyseDeck(leaderId, cardIds.joinToString(","))
.flatMapMaybe { response ->
cardRepository.getCards(response.probabilities?.keys?.map { it.toString() } ?: emptyList())
.firstElement()
.map { cards ->
val notEnoughDecks = (response.deckCountForLeader ?: 0) < MIN_DECK_COUNT_FOR_LEADER
val predictions = response.probabilities?.entries?.mapNotNull { entry ->
cards.find { it.id == entry.key.toString() }?.let { card ->
CardPrediction(card, (entry.value * 100).toInt())
}
} ?: emptyList()
val similarDecks = response.similarDecks?.map {
SimilarDeck(it.name ?: "", it.id ?: "", it.url ?: "", it.votes ?: 0)
} ?: emptyList()
CardPredictions(notEnoughDecks, similarDecks, predictions)
}
}
.onErrorReturn {
Timber.e(it)
CardPredictions(false, emptyList(), emptyList())
}
}
private fun mapFactionToString(faction: GwentFaction): String {
return when (faction) {
GwentFaction.MONSTER -> "monsters"
GwentFaction.NORTHERN_REALMS -> "northernrealms"
GwentFaction.SCOIATAEL -> "scoiatael"
GwentFaction.SKELLIGE -> "skellige"
GwentFaction.NILFGAARD -> "nilfgaard"
GwentFaction.SYNDICATE -> "syndicate"
else -> throw IllegalArgumentException("Unrecognised faction $faction")
}
}
private fun mapStringToFaction(faction: String): GwentFaction {
return when (faction) {
"monsters" -> GwentFaction.MONSTER
"northernrealms" -> GwentFaction.NORTHERN_REALMS
"scoiatael" -> GwentFaction.SCOIATAEL
"skellige" -> GwentFaction.SKELLIGE
"nilfgaard" -> GwentFaction.NILFGAARD
"syndicate" -> GwentFaction.SYNDICATE
else -> throw IllegalArgumentException("Unrecognised faction $faction")
}
}
private companion object {
private const val MIN_DECK_COUNT_FOR_LEADER = 15
}
} | apache-2.0 | c8da9a59c734173c47b65b6acc09a912 | 43.957746 | 107 | 0.618301 | 4.685756 | false | false | false | false |
NextFaze/dev-fun | test/src/testData/kotlin/tested/kapt_and_compile/top_level_functions/TopLevelFunctions.kt | 1 | 926 | @file:Suppress("UNUSED_PARAMETER", "unused", "PackageName")
package tested.kapt_and_compile.top_level_functions
import com.nextfaze.devfun.function.DeveloperFunction
import com.nextfaze.devfun.inject.Constructable
annotation class TopLevelFunctions
@DeveloperFunction
fun someTopLevelFunction() = Unit
@DeveloperFunction
internal fun internalTopLevelFunction() = Unit
@DeveloperFunction
private fun privateTopLevelFunction() = Unit
@DeveloperFunction
fun topLevelFunctionWithArgs(arg0: String, arg1: Float) = Unit
@DeveloperFunction
internal fun internalTopLevelFunctionWithArgs(arg0: String, arg1: Int) = Unit
@DeveloperFunction
private fun privateTopLevelFunctionWithArgs(arg0: String, arg1: Float) = Unit
@Constructable
private class SomeClass(val someValue: String)
@DeveloperFunction
fun String.someTopLevelFunctionToasted() = Unit
@DeveloperFunction
private fun SomeClass.privateTopLevelFunction() = Unit
| apache-2.0 | 5b0de6e402aed8d31ffdb6e6e5ec522a | 23.368421 | 77 | 0.826134 | 4.430622 | false | false | false | false |
mastrgamr/rettiwt | app/src/main/java/net/mastrgamr/rettiwt/adapters/TimelineAdapter.kt | 1 | 1950 | package net.mastrgamr.rettiwt.adapters
import android.content.Context
import android.databinding.DataBindingUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.twitter.sdk.android.core.models.Tweet
import net.mastrgamr.rettiwt.R
import net.mastrgamr.rettiwt.databinding.TimelineItemBinding
import net.mastrgamr.rettiwt.viewmodels.TimelineItemViewModel
/**
* Project: rettiwt
* Written by: mastrgamr
* Date: 6/3/17
*/
class TimelineAdapter(var items: List<Tweet>) : RecyclerView.Adapter<TimelineAdapter.TimelineViewHolder>() {
val TAG = javaClass.simpleName
constructor() : this(emptyList())
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
class TimelineViewHolder(var view: TimelineItemBinding) : RecyclerView.ViewHolder(view.root)
override fun onBindViewHolder(holder: TimelineViewHolder?, position: Int) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder!!.view.vm.tweet.set(items[position].text)
holder.view.vm.user.set(items[position].user.screenName)
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): TimelineAdapter.TimelineViewHolder {
val inflater = parent!!.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val binding: TimelineItemBinding = DataBindingUtil.inflate(inflater, R.layout.timeline_item, parent, false)
binding.vm = TimelineItemViewModel()
return TimelineViewHolder(binding)
}
override fun getItemCount(): Int {
return items.size
}
fun updateItems(tweets: List<Tweet>){
items = emptyList()
items = tweets
notifyDataSetChanged()
}
} | apache-2.0 | 5d9be37d44e5fb4a218d79d707dceddb | 35.12963 | 115 | 0.737949 | 4.333333 | false | false | false | false |
JDA-Applications/Kotlin-JDA | src/main/kotlin/club/minnced/kjda/KJDAUtils.kt | 1 | 1133 | /*
* Copyright 2016 - 2017 Florian Spieß
*
* 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 club.minnced.kjda
operator fun CharSequence.times(amount: Int): String {
val out = StringBuilder(this)
repeat(amount) {
out += this
}
return out.toString()
}
val SPACES = Regex("\\s+")
operator fun CharSequence.div(amount: Int): List<String> {
if (amount < 1)
return this.split(SPACES)
return this.split(SPACES, amount)
}
operator fun String.rem(col: Collection<Any?>) = rem(col.toTypedArray<Any?>())
operator fun String.rem(arr: Array<Any?>) = String.format(this, *arr)
| apache-2.0 | 56d68345cf0b8d8565b09149c7f4570c | 30.444444 | 78 | 0.70053 | 3.837288 | false | false | false | false |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/StructureService.kt | 1 | 18147 | package net.nemerosa.ontrack.model.structure
import net.nemerosa.ontrack.common.Document
import net.nemerosa.ontrack.model.Ack
import net.nemerosa.ontrack.model.pagination.PaginatedList
import org.springframework.security.access.AccessDeniedException
import java.time.LocalDateTime
import java.util.*
import java.util.function.BiFunction
interface StructureService {
val projectStatusViews: List<ProjectStatusView>
val projectList: List<Project>
// Projects
fun newProject(project: Project): Project
/**
* Looks for a project using its ID.
* @param projectId ID of the project
* @return Project or `null` if not found
*/
fun findProjectByID(projectId: ID): Project?
/**
* Finds a list of projects using part of their name
*
* @param pattern Part to look for, case-insensitive
* @return List of projects
*/
fun findProjectsByNamePattern(pattern: String): List<Project>
fun getProject(projectId: ID): Project
fun saveProject(project: Project)
fun disableProject(project: Project): Project
fun enableProject(project: Project): Project
fun deleteProject(projectId: ID): Ack
// Branches
/**
* Looks for a branch using its ID.
* @param branchId ID of the branch
* @return Branch or `null` if not found
*/
fun findBranchByID(branchId: ID): Branch?
fun getBranch(branchId: ID): Branch
fun getBranchesForProject(projectId: ID): List<Branch>
fun newBranch(branch: Branch): Branch
fun getBranchStatusViews(projectId: ID): List<BranchStatusView>
fun getBranchStatusView(branch: Branch): BranchStatusView
fun saveBranch(branch: Branch)
fun disableBranch(branch: Branch): Branch
fun enableBranch(branch: Branch): Branch
fun deleteBranch(branchId: ID): Ack
// Builds
fun newBuild(build: Build): Build
fun saveBuild(build: Build): Build
/**
* Looks for a build using its ID.
* @param buildId ID of the build
* @return Build or `null` if not found
*/
fun findBuildByID(buildId: ID): Build?
fun getBuild(buildId: ID): Build
// TODO Replace by Build?
fun findBuildByName(project: String, branch: String, build: String): Optional<Build>
fun getEarliestPromotionsAfterBuild(build: Build): BranchStatusView
/**
* Finds a build on a branch whose name is the closest. It assumes that build names
* are in a numeric format.
*/
// TODO Replace by Build?
fun findBuildAfterUsingNumericForm(id: ID, buildName: String): Optional<Build>
/**
* Gets an aggregated view of a build, with its promotion runs, validation stamps and decorations.
*/
fun getBuildView(build: Build, withDecorations: Boolean): BuildView
fun getLastBuildForBranch(branch: Branch): Build?
/**
* Gets the number of builds for a branch.
*/
fun getBuildCount(branch: Branch): Int
/**
* Gets the number of builds for a project.
*
* @param project Project to get the build count for
* @return Number of builds in this project
*/
fun getBuildCountForProject(project: Project): Int
fun deleteBuild(buildId: ID): Ack
// TODO Replace by Build?
fun getPreviousBuild(buildId: ID): Optional<Build>
// TODO Replace by Build?
fun getNextBuild(buildId: ID): Optional<Build>
/**
* Build links
*/
fun addBuildLink(fromBuild: Build, toBuild: Build)
fun deleteBuildLink(fromBuild: Build, toBuild: Build)
/**
* Gets the builds used by the given one.
*
* @param build Source build
* @param offset Offset for pagination
* @param size Page size for pagination
* @param filter Optional filter on the builds
* @return List of builds which are used by the given one
*/
fun getBuildsUsedBy(build: Build, offset: Int = 0, size: Int = 10, filter: (Build) -> Boolean = { true }): PaginatedList<Build>
/**
* Gets the builds which use the given one.
*
* @param build Source build
* @param offset Offset for pagination
* @param size Page size for pagination
* @param filter Optional filter on the builds
* @return List of builds which use the given one
*/
fun getBuildsUsing(build: Build, offset: Int = 0, size: Int = 10, filter: (Build) -> Boolean = { true }): PaginatedList<Build>
fun searchBuildsLinkedTo(projectName: String, buildPattern: String): List<Build>
fun editBuildLinks(build: Build, form: BuildLinkForm)
fun isLinkedFrom(build: Build, project: String, buildPattern: String): Boolean
fun isLinkedTo(build: Build, project: String, buildPattern: String): Boolean
/**
* Loops over ALL the build links. Use this method with care, mostly for external indexation.
*/
fun forEachBuildLink(code: (from: Build, to: Build) -> Unit)
/**
* Looks for the first build which matches a given predicate.
*
* @param branchId Branch to look builds into
* @param sortDirection Build search direction
* @param buildPredicate Predicate for a match
* @return Build if found, `null` otherwise
*/
fun findBuild(branchId: ID, sortDirection: BuildSortDirection, buildPredicate: (Build) -> Boolean): Build?
/**
* Loops over all the builds of a branch, stopping when [processor] returns `false`.
*
* @param branch Branch to look builds into
* @param processor Must return `false` when the looping must stop
* @param sortDirection Build search direction
*/
fun forEachBuild(branch: Branch, sortDirection: BuildSortDirection, processor: (Build) -> Boolean)
// TODO Replace by Build?
fun getLastBuild(branchId: ID): Optional<Build>
fun buildSearch(projectId: ID, form: BuildSearchForm): List<Build>
fun getValidationStampRunViewsForBuild(build: Build, offset: Int = 0, size: Int = 10): List<ValidationStampRunView>
// Promotion levels
fun getPromotionLevelListForBranch(branchId: ID): List<PromotionLevel>
fun newPromotionLevel(promotionLevel: PromotionLevel): PromotionLevel
fun getPromotionLevel(promotionLevelId: ID): PromotionLevel
/**
* Looks for a promotion level using its ID.
* @param promotionLevelId ID of the promotion level
* @return Promotion level or `null` if not found
*/
fun findPromotionLevelByID(promotionLevelId: ID): PromotionLevel?
fun getPromotionLevelImage(promotionLevelId: ID): Document
fun setPromotionLevelImage(promotionLevelId: ID, document: Document?)
fun savePromotionLevel(promotionLevel: PromotionLevel)
fun deletePromotionLevel(promotionLevelId: ID): Ack
fun reorderPromotionLevels(branchId: ID, reordering: Reordering)
fun newPromotionLevelFromPredefined(branch: Branch, predefinedPromotionLevel: PredefinedPromotionLevel): PromotionLevel
fun getOrCreatePromotionLevel(branch: Branch, promotionLevelId: Int?, promotionLevelName: String?): PromotionLevel
// Promotion runs
fun newPromotionRun(promotionRun: PromotionRun): PromotionRun
fun getPromotionRun(promotionRunId: ID): PromotionRun
/**
* Looks for a promotion run using its ID.
* @param promotionRunId ID of the promotion run
* @return Promotion run or `null` if not found
*/
fun findPromotionRunByID(promotionRunId: ID): PromotionRun?
// TODO Replace by PromotionLevel?
fun findPromotionLevelByName(project: String, branch: String, promotionLevel: String): Optional<PromotionLevel>
fun getPromotionRunsForBuild(buildId: ID): List<PromotionRun>
fun getLastPromotionRunsForBuild(buildId: ID): List<PromotionRun>
// TODO Replace by PromotionRun?
fun getLastPromotionRunForBuildAndPromotionLevel(build: Build, promotionLevel: PromotionLevel): Optional<PromotionRun>
fun getPromotionRunsForBuildAndPromotionLevel(build: Build, promotionLevel: PromotionLevel): List<PromotionRun>
fun getLastPromotionRunForPromotionLevel(promotionLevel: PromotionLevel): PromotionRun?
fun getPromotionRunView(promotionLevel: PromotionLevel): PromotionRunView
fun deletePromotionRun(promotionRunId: ID): Ack
// TODO Replace by PromotionRun?
fun getEarliestPromotionRunAfterBuild(promotionLevel: PromotionLevel, build: Build): Optional<PromotionRun>
fun getPromotionRunsForPromotionLevel(promotionLevelId: ID): List<PromotionRun>
/**
* Bulk update of all promotion levels in other projects/branches and in predefined promotion levels,
* following the model designed by the promotion level ID.
*
* @param promotionLevelId ID of the promotion level model
* @return Result of the update
*/
fun bulkUpdatePromotionLevels(promotionLevelId: ID): Ack
// Validation stamps
fun getValidationStampListForBranch(branchId: ID): List<ValidationStamp>
fun newValidationStamp(validationStamp: ValidationStamp): ValidationStamp
fun getValidationStamp(validationStampId: ID): ValidationStamp
/**
* Looks for a validation stamp using its ID.
* @param validationStampId ID of the validation stamp
* @return Validation stamp or `null` if not found
*/
fun findValidationStampByID(validationStampId: ID): ValidationStamp?
// TODO Replace by ValidationStamp?
fun findValidationStampByName(project: String, branch: String, validationStamp: String): Optional<ValidationStamp>
fun getValidationStampImage(validationStampId: ID): Document
fun setValidationStampImage(validationStampId: ID, document: Document?)
fun saveValidationStamp(validationStamp: ValidationStamp)
fun deleteValidationStamp(validationStampId: ID): Ack
fun reorderValidationStamps(branchId: ID, reordering: Reordering)
fun newValidationStampFromPredefined(branch: Branch, stamp: PredefinedValidationStamp): ValidationStamp
fun getOrCreateValidationStamp(branch: Branch, validationStampName: String): ValidationStamp
/**
* Bulk update of all validation stamps in other projects/branches and in predefined validation stamps,
* following the model designed by the validation stamp ID.
*
* @param validationStampId ID of the validation stamp model
* @return Result of the update
*/
fun bulkUpdateValidationStamps(validationStampId: ID): Ack
// Validation runs
fun newValidationRun(build: Build, validationRunRequest: ValidationRunRequest): ValidationRun
/**
* Deletes an existing validation run
*/
fun deleteValidationRun(validationRun: ValidationRun): Ack
fun getValidationRun(validationRunId: ID): ValidationRun
/**
* Looks for a validation run using its ID.
* @param validationRunId ID of the validation run
* @return Validation run or `null` if not found
*/
fun findValidationRunByID(validationRunId: ID): ValidationRun?
/**
* Gets the list of validation runs for a build.
*
* @param buildId ID of the build
* @param offset Offset in the list
* @param count Maximum number of elements to return
* @param sortingMode How to sort the runs ([ValidationRunSortingMode.ID] by default)
* @return List of validation runs
*/
fun getValidationRunsForBuild(buildId: ID, offset: Int, count: Int, sortingMode: ValidationRunSortingMode = ValidationRunSortingMode.ID): List<ValidationRun>
/**
* Gets the number of validation runs for a build.
*
* @param buildId ID of the build
* @return Number of validation runs
*/
fun getValidationRunsCountForBuild(buildId: ID): Int
/**
* Gets the list of validation runs for a build and a validation stamp.
*
* @param buildId ID of the build
* @param validationStampId ID of the validation stamp
* @param offset Offset in the list
* @param count Maximum number of elemnts to return
* @return List of validation runs
*/
fun getValidationRunsForBuildAndValidationStamp(buildId: ID, validationStampId: ID, offset: Int, count: Int): List<ValidationRun>
/**
* Gets the list of validation runs for a build and a validation stamp, and a list of accepted statuses
*
* @param buildId ID of the build
* @param validationStampId ID of the validation stamp
* @param statuses List of statuses for the last status of the run
* @param offset Offset in the list
* @param count Maximum number of elemnts to return
* @return List of validation runs
*/
fun getValidationRunsForBuildAndValidationStampAndStatus(
buildId: ID,
validationStampId: ID,
statuses: List<ValidationRunStatusID>,
offset: Int,
count: Int
): List<ValidationRun>
fun getValidationRunsForValidationStamp(validationStamp: ValidationStamp, offset: Int, count: Int): List<ValidationRun>
/**
* Gets the validation runs for a given validation stamp between two timestamps.
*/
fun getValidationRunsForValidationStampBetweenDates(validationStampId: ID, start: LocalDateTime, end: LocalDateTime): List<ValidationRun>
fun getValidationRunsForValidationStamp(validationStampId: ID, offset: Int, count: Int): List<ValidationRun>
/**
* Gets the list of validation runs for a given validation stamp and a list of statuses.
* @param validationStamp Validation stamp
* @param statuses List of statuses for the last status of the run
* @param offset Offset in the list
* @param count Maximum number of elemnts to return
* @return List of validation runs
*/
fun getValidationRunsForValidationStampAndStatus(
validationStamp: ValidationStamp,
statuses: List<ValidationRunStatusID>,
offset: Int,
count: Int
): List<ValidationRun>
/**
* Gets the list of validation runs for a given validation stamp and a list of statuses.
* @param validationStampId ID of the validation stamp
* @param statuses List of statuses for the last status of the run
* @param offset Offset in the list
* @param count Maximum number of elemnts to return
* @return List of validation runs
*/
fun getValidationRunsForValidationStampAndStatus(
validationStampId: ID,
statuses: List<ValidationRunStatusID>,
offset: Int,
count: Int
): List<ValidationRun>
/**
* Gets the list of validation runs for a branch and a list of statuses.
* @param branchId ID of the branch
* @param statuses List of statuses for the last status of the run
* @param offset Offset in the list
* @param count Maximum number of elemnts to return
* @return List of validation runs
*/
fun getValidationRunsForStatus(
branchId: ID,
statuses: List<ValidationRunStatusID>,
offset: Int,
count: Int
): List<ValidationRun>
fun newValidationRunStatus(validationRun: ValidationRun, runStatus: ValidationRunStatus): ValidationRun
/**
* Re-exporting all validation run data metrics.
*/
fun restoreValidationRunDataMetrics(logger: (String) -> Unit = {})
/**
* Gets the parent validation run for a given validation run status ID
*
* @param validationRunStatusId ID of the validation run status ID
* @param checkForAccess `false` if the access for view must be checked
* @return Validation run which contains the status ID or `null` if the current user
* has no access to it. Never `null` if the [checkForAccess] if `true`.
*/
fun getParentValidationRun(validationRunStatusId: ID, checkForAccess: Boolean = true): ValidationRun?
/**
* Gets a validation run status using its ID.
*
* @param id ID of the validation run status
* @return Validation run status
*/
fun getValidationRunStatus(id: ID): ValidationRunStatus
/**
* Edits a validation run status comment.
*
* @param run Parent validation run
* @param runStatusId ID of the specific run status to edit
* @param comment New comment
* @return Updated validation run
*/
fun saveValidationRunStatusComment(run: ValidationRun, runStatusId: ID, comment: String): ValidationRun
/**
* Checks if the validation run status comment is editable by the current user
*/
fun isValidationRunStatusCommentEditable(validationRunStatus: ID): Boolean
/**
* Gets the total number of validation runs for a build and a validation stamp
*
* @param buildId ID of the build
* @param validationStampId ID of the validation stamp
* @return Number of validation runs for the validation stamp
*/
fun getValidationRunsCountForBuildAndValidationStamp(buildId: ID, validationStampId: ID): Int
/**
* Gets the total number of validation runs for a validation stamp
*
* @param validationStampId ID of the validation stamp
* @return Number of validation runs for the validation stamp
*/
fun getValidationRunsCountForValidationStamp(validationStampId: ID): Int
// Entity searches by name
// TODO Replace by Project?
fun findProjectByName(project: String): Optional<Project>
/**
* Gets the project by its name if authorized to access it. If it does exist, but the user is
* not authorized to see it, throws an [AccessDeniedException]
*
* @param project Name of the project to look for
* @return Project if it exists and is authorized, or null if if does not exist
* @throws AccessDeniedException If the project does exist but the user has no access to it
*/
fun findProjectByNameIfAuthorized(project: String): Project?
// TODO Replace by Branch?
fun findBranchByName(project: String, branch: String): Optional<Branch>
fun entityLoader(): BiFunction<ProjectEntityType, ID, ProjectEntity>
}
| mit | ae535a540c156d556c8b238c80f160a3 | 34.652259 | 161 | 0.696975 | 4.840491 | false | false | false | false |
SeunAdelekan/Kanary | examples/Kanary-Mini-Twitter-Clone/src/curious/cwitter/db.kt | 1 | 5734 | package curious.cwitter
import kotliquery.Row
import kotliquery.queryOf
import kotliquery.sessionOf
import java.time.ZonedDateTime
import java.util.*
data class User(
val id: Int,
val firstName: String?,
val lastName: String?,
val email: String?,
val pword: String?,
val createdAt: String?,
val sessionId: String?)
data class Cweet(
val id: Int,
val text: String?,
val creatorId: Int,
val createdAt: String?)
data class TimelineCweet(
val cweetId: Int,
val text: String?,
val creatorId: Int,
val createdAt: String?,
val firstName: String?,
val lastName: String?)
class DataHandler {
val session = sessionOf("jdbc:sqlite:cweet.db", "", "")
val toUser: (Row) -> User = { row ->
User(
row.int("id"),
row.stringOrNull("first_name"),
row.stringOrNull("last_name"),
row.stringOrNull("email"),
row.stringOrNull("pword"),
row.stringOrNull("created_at"),
row.stringOrNull("session_id")
)
}
val toCweet: (Row) -> Cweet = { row ->
Cweet(
row.int("id"),
row.stringOrNull("text"),
row.int("creator_id"),
row.stringOrNull("created_at")
)
}
val toTimelineCweet: (Row) -> TimelineCweet = { row ->
TimelineCweet(
row.int("cweet_id"),
row.stringOrNull("text"),
row.int("creator_id"),
row.stringOrNull("created_at"),
row.stringOrNull("first_name"),
row.stringOrNull("last_name")
)
}
fun init(): Unit {
session.run(queryOf("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name CHAR NOT NULL,
last_name CHAR NOT NULL,
email CHAR NOT NULL,
pword CHAR NOT NULL,
created_at CHAR NOT NULL,
session_id CHAR NULL
)
""").asExecute)
session.run(queryOf("""
CREATE TABLE IF NOT EXISTS cweets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text CHAR NOT NULL,
creator_id INTEGER NOT NULL,
created_at CHAR NOT NULL
)
""").asExecute)
}
fun getCweets(): List<TimelineCweet> {
return session.run(queryOf("select cweets.id as cweet_id, text, creator_id, cweets.created_at, users.first_name, last_name from cweets LEFT JOIN users ON users.id = creator_id").map(toTimelineCweet).asList)
}
fun getUserCweets(user_id: Int): List<TimelineCweet> {
return session.run(queryOf("select cweets.id as cweet_id, text, creator_id, cweets.created_at, users.first_name, last_name from cweets LEFT JOIN users ON users.id = creator_id where users.id = ?", user_id).map(toTimelineCweet).asList)
}
fun postCweet(text: String, creator_id: Int): TimelineCweet? {
var cweet: TimelineCweet? = null
try {
val insertQuery: String = "insert into cweets (text, creator_id, created_at) values (?, ?, ?)"
session.run(queryOf(insertQuery, text, creator_id, java.time.ZonedDateTime.now()).asUpdate)
val fetchQuery = queryOf("select cweets.id as cweet_id, text, creator_id, cweets.created_at, users.first_name, last_name from cweets LEFT JOIN users ON users.id = creator_id where creator_id = ? ORDER BY cweets.id DESC LIMIT 1", creator_id).map(toTimelineCweet).asSingle
cweet = session.run(fetchQuery)
} catch (e: Exception){
e.printStackTrace()
}
return cweet
}
fun registerUser(first_name: String, last_name: String, email: String, hpword: String): User? {
var user: User? = null
try {
val insertQuery: String = "insert into users (first_name, last_name, email, pword, created_at) values (?, ?, ?, ?, ?)"
session.run(queryOf(insertQuery, first_name, last_name, email, hpword, java.time.ZonedDateTime.now()).asUpdate)
user = fetchUser(email, hpword)
} catch (e: Exception){
e.printStackTrace()
}
return user
}
fun fetchUser(email: String, pword: String): User? {
var user: User? = null
try {
val fetchQuery = queryOf("select id, first_name, last_name, email, pword, created_at, session_id from users where email = ? and pword = ?", email, pword).map(toUser).asSingle
user = session.run(fetchQuery)
} catch (e: Exception){
e.printStackTrace()
}
return user
}
fun validateEmail(email: String): Boolean {
val fetchQuery = queryOf("select id, first_name, last_name, email, pword, created_at, session_id from users where email = ?", email).map(toUser).asSingle
val user: User? = session.run(fetchQuery)
if (user != null && user.email == email){
return false
}
return true
}
fun updateSessionId(user_id: Int, sessionId: String): Int{
return session.run(queryOf("update users set session_id = ? where id = ?", sessionId, user_id).asUpdate)
}
fun fetchUserWithSessionId(sessionId: String): User? {
val fetchQuery = queryOf("select id, first_name, last_name, email, pword, created_at, session_id from users where session_id = ?", sessionId).map(toUser).asSingle
val user: User? = session.run(fetchQuery)
return user
}
}
| apache-2.0 | 2f3f6ddea5cb629b86d3ad5e0eb568cb | 35.75641 | 282 | 0.571329 | 4.122214 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/settings/subsettings/general/GeneralSettingsPresenter.kt | 1 | 2545 | package treehou.se.habit.ui.settings.subsettings.general
import io.reactivex.android.schedulers.AndroidSchedulers
import treehou.se.habit.dagger.RxPresenter
import treehou.se.habit.util.Settings
import treehou.se.habit.util.logging.Logger
import javax.inject.Inject
class GeneralSettingsPresenter @Inject
constructor(private val view: GeneralSettingsContract.View) : RxPresenter(), GeneralSettingsContract.Presenter {
@Inject lateinit var settings: Settings
@Inject lateinit var logger: Logger
override fun subscribe() {
super.subscribe()
val settingsAutoloadSitemapRx = settings.autoloadSitemapRx
settingsAutoloadSitemapRx
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ show -> view.showAutoLoadSitemap(show!!) }
, { logger.e(TAG, "settingsAutoloadSitemapRx update failed", it) })
val settingsShowSitemapInMenuRx = settings.showSitemapsInMenuRx
settingsShowSitemapInMenuRx.asObservable()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe ({ show -> view.showSitemapsInMenu(show) }
, { logger.e(TAG, "settingsShowSitemapInMenuRx update failed", it) })
val settingsFullscreenRx = settings.fullscreenPref
settingsFullscreenRx.asObservable()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe ({ show -> view.setFullscreen(show!!) }
, { logger.e(TAG, "settingsFullscreenRx update failed", it) })
}
override fun themeSelected(theme: Int) {
val themePref = settings.themePref
if (themePref.get() != theme) {
themePref.set(theme)
view.updateTheme()
}
}
override fun setShowSitemapsInMenu(show: Boolean) {
settings.showSitemapsInMenuRx.set(show)
}
override fun setAutoLoadSitemap(show: Boolean) {
val autoloadSitemapRx = settings.autoloadSitemapRx
if (show != autoloadSitemapRx.blockingFirst()) {
settings.setAutoloadSitemapRx(show)
}
}
override fun setFullscreen(fullscreen: Boolean) {
val fullscreenPrefRx = settings.fullscreenPref
if (fullscreen != fullscreenPrefRx.get()) {
fullscreenPrefRx.set(fullscreen)
}
}
companion object {
val TAG = "GeneralSettingsPresenter"
}
}
| epl-1.0 | 8249a7ac79c7a21f8aee48db119fca08 | 35.357143 | 112 | 0.655403 | 4.704251 | false | false | false | false |
ReactiveSocket/reactivesocket-tck | rsocket-tck-core/src/main/kotlin/io/rsocket/tck/frame/LeaseFrame.kt | 1 | 1134 | package io.rsocket.tck.frame
import io.netty.buffer.*
import io.rsocket.tck.frame.shared.*
data class LeaseFrame(
override val header: FrameHeader<LeaseFlags>,
val ttl: Int,
val numberOfRequests: Int,
val metadata: ByteBuf?
) : Frame<LeaseFlags>(FrameType.LEASE) {
override fun buffer(allocator: ByteBufAllocator): ByteBuf {
val header = headerBuffer(allocator) {
writeInt(ttl)
writeInt(numberOfRequests)
}
return when (metadata) {
null -> header
else -> allocator.compose(header, metadata)
}
}
}
fun RawFrame.asLease(): LeaseFrame = typed(FrameType.LEASE) {
val flags = LeaseFlags(metadata = header.flags.value check CommonFlag.Metadata)
val ttl = readInt()
val numberOfRequests = readInt()
val metadata = if (flags.metadata) slice() else null
LeaseFrame(
header = header.withFlags(flags),
ttl = ttl,
numberOfRequests = numberOfRequests,
metadata = metadata
)
}
data class LeaseFlags(
val metadata: Boolean
) : TypedFlags({
CommonFlag.Metadata setIf metadata
}) | apache-2.0 | 0e378673ae1b98452f69a4a0cbd37edd | 26.682927 | 83 | 0.653439 | 4.215613 | false | false | false | false |
cbeust/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/MavenId.kt | 2 | 3099 | package com.beust.kobalt.maven
import com.beust.kobalt.api.Kobalt
import org.eclipse.aether.artifact.DefaultArtifact
/**
* Encapsulate a Maven id captured in one string, as used by Gradle or Ivy, e.g. "org.testng:testng:6.9.9".
* These id's are somewhat painful to manipulate because on top of containing groupId, artifactId
* and version, they also accept an optional packaging (e.g. "aar") and qualifier (e.g. "no_aop").
* Determining which is which in an untyped string separated by colons is not clearly defined so
* this class does a best attempt at deconstructing an id but there's surely room for improvement.
*
* This class accepts a versionless id, which needs to end with a :, e.g. "com.beust:jcommander:" (which
* usually means "latest version") but it doesn't handle version ranges yet.
*/
class MavenId private constructor(val groupId: String, val artifactId: String, val packaging: String?,
val classifier: String?, val version: String?) {
companion object {
fun isMavenId(id: String) = if (id.startsWith("file://")) {
false
} else {
with(id.split(':')) {
size >= 3 && size <= 5
}
}
fun isRangedVersion(s: String): Boolean {
return s.first() in listOf('[', '(') && s.last() in listOf(']', ')')
}
/**
* Similar to create(MavenId) but don't run IMavenIdInterceptors.
*/
fun createNoInterceptors(id: String) : MavenId = DefaultArtifact(id).run {
MavenId(groupId, artifactId, extension, classifier, version)
}
fun toMavenId(id: String) = if (id.endsWith(":")) id + "(0,]" else id
/**
* The main entry point to create Maven Id's. Id's created by this function
* will run through IMavenIdInterceptors.
*/
fun create(originalId: String) : MavenId {
val id = toMavenId(originalId)
var originalMavenId = createNoInterceptors(id)
var interceptedMavenId = originalMavenId
val interceptors = Kobalt.context?.pluginInfo?.mavenIdInterceptors
if (interceptors != null) {
interceptedMavenId = interceptors.fold(originalMavenId, {
id, interceptor -> interceptor.intercept(id) })
}
return interceptedMavenId
}
fun create(groupId: String, artifactId: String, packaging: String?, classifier: String?, version: String?) =
create(toId(groupId, artifactId, packaging, classifier, version))
fun toId(groupId: String, artifactId: String, packaging: String? = null, classifier: String? = null,
version: String?) =
"$groupId:$artifactId" +
(if (packaging != null && packaging != "") ":$packaging" else "") +
(if (classifier != null && classifier != "") ":$classifier" else "") +
":$version"
}
val hasVersion = version != null
val toId = MavenId.toId(groupId, artifactId, packaging, classifier, version)
}
| apache-2.0 | d6b90f50c76caeab68bbfed41b260365 | 40.878378 | 116 | 0.611165 | 4.537335 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise | imitate/src/main/java/com/engineer/imitate/ui/widget/LabelLayout.kt | 1 | 1976 | package com.engineer.imitate.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import com.engineer.imitate.R
import com.engineer.imitate.util.dp
import kotlinx.android.synthetic.main.label_layout_container.view.*
class LabelLayoutProvider {
companion object {
fun provideLabelLayout(context: Context, labels: Array<String>): View {
val toggle = LabelLayoutContainer(context)
toggle.setData(labels)
return toggle
}
}
}
class LabelLayoutContainer : FrameLayout {
// <editor-fold defaultstate="collapsed" desc="构造函数">
constructor(context: Context) : super(context) {
initView(context)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
initView(context)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
initView(context)
}
// </editor-fold>
private fun initView(context: Context?) {
LayoutInflater.from(context).inflate(R.layout.label_layout_container, this, true)
}
fun setData(labels: Array<String>) {
toggle.setMin(150)
val box = LabelFlowLayout(context)
val p = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
val value = 6.dp
p.setMargins(value, value, value, value)
for (text in labels) {
val item = LayoutInflater.from(context).inflate(R.layout.label_tv, null)
val tv = item.findViewById<TextView>(R.id.text)
tv.text = text
box.addView(item, p)
}
toggle.addContentView(box, ToggleLayout.Status.CLOSE)
}
} | apache-2.0 | e38b50f953055bd87b7d42e21aad713d | 28.833333 | 89 | 0.662093 | 4.334802 | false | false | false | false |
samtstern/quickstart-android | storage/app/src/main/java/com/google/firebase/quickstart/firebasestorage/kotlin/MyUploadService.kt | 1 | 5745 | package com.google.firebase.quickstart.firebasestorage.kotlin
import android.app.Service
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.firebasestorage.R
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.ktx.storage
/**
* Service to handle uploading files to Firebase Storage.
*/
class MyUploadService : MyBaseTaskService() {
// [START declare_ref]
private lateinit var storageRef: StorageReference
// [END declare_ref]
override fun onCreate() {
super.onCreate()
// [START get_storage_ref]
storageRef = Firebase.storage.reference
// [END get_storage_ref]
}
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Log.d(TAG, "onStartCommand:$intent:$startId")
if (ACTION_UPLOAD == intent.action) {
val fileUri = intent.getParcelableExtra<Uri>(EXTRA_FILE_URI)!!
// Make sure we have permission to read the data
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
contentResolver.takePersistableUriPermission(
fileUri,
Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
uploadFromUri(fileUri)
}
return Service.START_REDELIVER_INTENT
}
// [START upload_from_uri]
private fun uploadFromUri(fileUri: Uri) {
Log.d(TAG, "uploadFromUri:src:" + fileUri.toString())
// [START_EXCLUDE]
taskStarted()
showProgressNotification(getString(R.string.progress_uploading), 0, 0)
// [END_EXCLUDE]
// [START get_child_ref]
// Get a reference to store file at photos/<FILENAME>.jpg
fileUri.lastPathSegment?.let {
val photoRef = storageRef.child("photos")
.child(it)
// [END get_child_ref]
// Upload file to Firebase Storage
Log.d(TAG, "uploadFromUri:dst:" + photoRef.path)
photoRef.putFile(fileUri).addOnProgressListener { taskSnapshot ->
showProgressNotification(getString(R.string.progress_uploading),
taskSnapshot.bytesTransferred,
taskSnapshot.totalByteCount)
}.continueWithTask { task ->
// Forward any exceptions
if (!task.isSuccessful) {
throw task.exception!!
}
Log.d(TAG, "uploadFromUri: upload success")
// Request the public download URL
photoRef.downloadUrl
}.addOnSuccessListener { downloadUri ->
// Upload succeeded
Log.d(TAG, "uploadFromUri: getDownloadUri success")
// [START_EXCLUDE]
broadcastUploadFinished(downloadUri, fileUri)
showUploadFinishedNotification(downloadUri, fileUri)
taskCompleted()
// [END_EXCLUDE]
}.addOnFailureListener { exception ->
// Upload failed
Log.w(TAG, "uploadFromUri:onFailure", exception)
// [START_EXCLUDE]
broadcastUploadFinished(null, fileUri)
showUploadFinishedNotification(null, fileUri)
taskCompleted()
// [END_EXCLUDE]
}
}
}
// [END upload_from_uri]
/**
* Broadcast finished upload (success or failure).
* @return true if a running receiver received the broadcast.
*/
private fun broadcastUploadFinished(downloadUrl: Uri?, fileUri: Uri?): Boolean {
val success = downloadUrl != null
val action = if (success) UPLOAD_COMPLETED else UPLOAD_ERROR
val broadcast = Intent(action)
.putExtra(EXTRA_DOWNLOAD_URL, downloadUrl)
.putExtra(EXTRA_FILE_URI, fileUri)
return LocalBroadcastManager.getInstance(applicationContext)
.sendBroadcast(broadcast)
}
/**
* Show a notification for a finished upload.
*/
private fun showUploadFinishedNotification(downloadUrl: Uri?, fileUri: Uri?) {
// Hide the progress notification
dismissProgressNotification()
// Make Intent to MainActivity
val intent = Intent(this, MainActivity::class.java)
.putExtra(EXTRA_DOWNLOAD_URL, downloadUrl)
.putExtra(EXTRA_FILE_URI, fileUri)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
val success = downloadUrl != null
val caption = if (success) getString(R.string.upload_success) else getString(R.string.upload_failure)
showFinishedNotification(caption, intent, success)
}
companion object {
private const val TAG = "MyUploadService"
/** Intent Actions */
const val ACTION_UPLOAD = "action_upload"
const val UPLOAD_COMPLETED = "upload_completed"
const val UPLOAD_ERROR = "upload_error"
/** Intent Extras */
const val EXTRA_FILE_URI = "extra_file_uri"
const val EXTRA_DOWNLOAD_URL = "extra_download_url"
val intentFilter: IntentFilter
get() {
val filter = IntentFilter()
filter.addAction(UPLOAD_COMPLETED)
filter.addAction(UPLOAD_ERROR)
return filter
}
}
}
| apache-2.0 | a235f3ee2a1e10437c6748220abc264f | 33.608434 | 109 | 0.608007 | 4.910256 | false | false | false | false |
apixandru/intellij-community | tools/index-tools/src/org/jetbrains/index/stubs/StubsGenerator.kt | 1 | 10216 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author traff
*/
package org.jetbrains.index.stubs
import com.google.common.hash.HashCode
import com.intellij.idea.IdeaTestApplication
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileFilter
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.psi.impl.DebugUtil
import com.intellij.psi.stubs.*
import com.intellij.util.indexing.FileContentImpl
import com.intellij.util.io.PersistentHashMap
import com.intellij.util.ui.UIUtil
import junit.framework.TestCase
import java.io.ByteArrayInputStream
import java.io.File
import java.util.*
/**
* Generates stubs and stores them in one persistent hash map
*/
open class StubsGenerator(private val stubsVersion: String) {
open val fileFilter
get() = VirtualFileFilter { true }
fun buildStubsForRoots(stubsStorageFilePath: String,
roots: List<VirtualFile>) {
val hashing = FileContentHashing()
val stubExternalizer = StubTreeExternalizer()
val storage = PersistentHashMap<HashCode, SerializedStubTree>(File(stubsStorageFilePath + ".input"),
HashCodeDescriptor.instance, stubExternalizer)
println("Writing stubs to ${storage.baseFile.absolutePath}")
val serializationManager = SerializationManagerImpl(File(stubsStorageFilePath + ".names"))
try {
val map = HashMap<HashCode, Pair<String, SerializedStubTree>>()
for (file in roots) {
VfsUtilCore.visitChildrenRecursively(file, object : VirtualFileVisitor<Boolean>() {
override fun visitFile(file: VirtualFile): Boolean {
try {
if (fileFilter.accept(file)) {
val fileContent = FileContentImpl(file, file.contentsToByteArray())
val stub = buildStubForFile(fileContent, serializationManager)
val hashCode = hashing.hashString(fileContent)
val bytes = BufferExposingByteArrayOutputStream()
serializationManager.serialize(stub, bytes)
val contentLength =
if (file.fileType.isBinary) {
-1
}
else {
fileContent.psiFileForPsiDependentIndex.textLength
}
val stubTree = SerializedStubTree(bytes.internalBuffer, bytes.size(), stub, file.length, contentLength)
val item = map.get(hashCode)
if (item == null) {
storage.put(hashCode, stubTree)
map.put(hashCode, Pair(fileContent.contentAsText.toString(), stubTree))
}
else {
TestCase.assertEquals(item.first, fileContent.contentAsText.toString())
TestCase.assertTrue(stubTree == item.second)
}
}
}
catch (e: NoSuchElementException) {
return false
}
return true
}
})
}
}
finally {
storage.close()
Disposer.dispose(serializationManager)
writeStubsVersionFile(stubsStorageFilePath, stubsVersion)
}
}
open fun buildStubForFile(fileContent: FileContentImpl,
serializationManager: SerializationManagerImpl): Stub {
return ReadAction.compute<Stub, Throwable> { StubTreeBuilder.buildStubTree(fileContent) }
}
}
fun writeStubsVersionFile(stubsStorageFilePath: String, stubsVersion: String) {
FileUtil.writeToFile(File(stubsStorageFilePath + ".version"), stubsVersion)
}
fun mergeStubs(paths: List<String>, stubsFilePath: String, stubsFileName: String, projectPath: String, stubsVersion: String) {
val app = IdeaTestApplication.getInstance()
val project = ProjectManager.getInstance().loadAndOpenProject(projectPath)!!
// we don't need a project here, but I didn't find a better way to wait until indices and components are initialized
try {
val stubExternalizer = StubTreeExternalizer()
val storageFile = File(stubsFilePath, stubsFileName + ".input")
if (storageFile.exists()) {
storageFile.delete()
}
val storage = PersistentHashMap<HashCode, SerializedStubTree>(storageFile,
HashCodeDescriptor.instance, stubExternalizer)
val stringEnumeratorFile = File(stubsFilePath, stubsFileName + ".names")
if (stringEnumeratorFile.exists()) {
stringEnumeratorFile.delete()
}
val newSerializationManager = SerializationManagerImpl(stringEnumeratorFile)
val map = HashMap<HashCode, Int>()
println("Writing results to ${storageFile.absolutePath}")
for (path in paths) {
println("Reading stubs from $path")
var count = 0
val fromStorageFile = File(path, stubsFileName + ".input")
val fromStorage = PersistentHashMap<HashCode, SerializedStubTree>(fromStorageFile,
HashCodeDescriptor.instance, stubExternalizer)
val serializationManager = SerializationManagerImpl(File(path, stubsFileName + ".names"))
try {
fromStorage.processKeysWithExistingMapping(
{ key ->
count++
val value = fromStorage.get(key)
val stub = value.getStub(false, serializationManager)
// re-serialize stub tree to correctly enumerate strings in the new string enumerator
val bytes = BufferExposingByteArrayOutputStream()
newSerializationManager.serialize(stub, bytes)
val newStubTree = SerializedStubTree(bytes.internalBuffer, bytes.size(), null, value.byteContentLength,
value.charContentLength)
if (storage.containsMapping(key)) {
if (newStubTree != storage.get(key)) { // TODO: why are they slightly different???
val s = storage.get(key).getStub(false, newSerializationManager)
val bytes2 = BufferExposingByteArrayOutputStream()
newSerializationManager.serialize(stub, bytes2)
val newStubTree2 = SerializedStubTree(bytes2.internalBuffer, bytes2.size(), null, value.byteContentLength,
value.charContentLength)
TestCase.assertTrue(newStubTree == newStubTree2) // wtf!!! why are they equal now???
}
map.put(key, map.get(key)!! + 1)
}
else {
storage.put(key, newStubTree)
map.put(key, 1)
}
true
})
}
finally {
fromStorage.close()
Disposer.dispose(serializationManager)
}
println("Items in ${fromStorageFile.absolutePath}: $count")
}
storage.close()
Disposer.dispose(newSerializationManager)
val total = map.size
println("Total items in storage: $total")
writeStubsVersionFile(stringEnumeratorFile.nameWithoutExtension, stubsVersion)
for (i in 2..paths.size) {
val count = map.entries.stream().filter({ e -> e.value == i }).count()
println("Intersection between $i: ${"%.2f".format(if (total > 0) 100.0 * count / total else 0.0)}%")
}
}
finally {
UIUtil.invokeAndWaitIfNeeded(Runnable {
ProjectManager.getInstance().closeProject(project)
WriteAction.run<Throwable> {
Disposer.dispose(project)
Disposer.dispose(app)
}
})
}
System.exit(0)
}
/**
* Generates stubs for file content for different language levels returned by languageLevelIterator
* and checks that they are all equal.
*/
abstract class LanguageLevelAwareStubsGenerator<T>(stubsVersion: String) : StubsGenerator(stubsVersion) {
abstract fun languageLevelIterator(): Iterator<T>
abstract fun applyLanguageLevel(level: T)
abstract fun defaultLanguageLevel(): T
override fun buildStubForFile(fileContent: FileContentImpl, serializationManager: SerializationManagerImpl): Stub {
var prevLanguageLevelBytes: ByteArray? = null
var prevLanguageLevel: T? = null
var prevStub: Stub? = null
val iter = languageLevelIterator()
for (languageLevel in iter) {
applyLanguageLevel(languageLevel)
val stub = super.buildStubForFile(fileContent, serializationManager)
val bytes = BufferExposingByteArrayOutputStream()
serializationManager.serialize(stub, bytes)
if (prevLanguageLevelBytes != null) {
if (!Arrays.equals(bytes.toByteArray(), prevLanguageLevelBytes)) {
val stub2 = serializationManager.deserialize(ByteArrayInputStream(prevLanguageLevelBytes))
val msg = "Stubs are different for ${fileContent.file.path} between Python versions $prevLanguageLevel and $languageLevel.\n"
TestCase.assertEquals(msg, DebugUtil.stubTreeToString(stub), DebugUtil.stubTreeToString(stub2))
TestCase.fail(msg + "But DebugUtil.stubTreeToString values of stubs are unfortunately equal.")
}
}
prevLanguageLevelBytes = bytes.toByteArray()
prevLanguageLevel = languageLevel
prevStub = stub
}
applyLanguageLevel(defaultLanguageLevel())
return prevStub!!
}
}
| apache-2.0 | 8cd7be21ae2b8a9a5789a9e8172f755a | 35.22695 | 135 | 0.663861 | 5.309771 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/page/edithistory/EditHistoryListActivity.kt | 1 | 24354 | package org.wikipedia.page.edithistory
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.view.ActionMode
import androidx.core.graphics.ColorUtils
import androidx.core.view.MenuItemCompat
import androidx.core.view.isVisible
import androidx.core.widget.ImageViewCompat
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.paging.PagingData
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.activity.BaseActivity
import org.wikipedia.analytics.eventplatform.EditHistoryInteractionEvent
import org.wikipedia.databinding.ActivityEditHistoryBinding
import org.wikipedia.databinding.ViewEditHistoryEmptyMessagesBinding
import org.wikipedia.databinding.ViewEditHistorySearchBarBinding
import org.wikipedia.dataclient.mwapi.MwQueryPage
import org.wikipedia.dataclient.restbase.EditCount
import org.wikipedia.diff.ArticleEditDetailsActivity
import org.wikipedia.history.HistoryEntry
import org.wikipedia.history.SearchActionModeCallback
import org.wikipedia.page.ExclusiveBottomSheetPresenter
import org.wikipedia.page.LinkMovementMethodExt
import org.wikipedia.page.PageTitle
import org.wikipedia.richtext.RichTextUtil
import org.wikipedia.settings.Prefs
import org.wikipedia.staticdata.UserAliasData
import org.wikipedia.talk.UserTalkPopupHelper
import org.wikipedia.util.*
import org.wikipedia.views.EditHistoryFilterOverflowView
import org.wikipedia.views.EditHistoryStatsView
import org.wikipedia.views.SearchAndFilterActionProvider
import org.wikipedia.views.WikiErrorView
class EditHistoryListActivity : BaseActivity() {
private lateinit var binding: ActivityEditHistoryBinding
private val editHistoryListAdapter = EditHistoryListAdapter()
private val editHistoryStatsAdapter = StatsItemAdapter()
private val editHistorySearchBarAdapter = SearchBarAdapter()
private val editHistoryEmptyMessagesAdapter = EmptyMessagesAdapter()
private val loadHeader = LoadingItemAdapter { editHistoryListAdapter.retry() }
private val loadFooter = LoadingItemAdapter { editHistoryListAdapter.retry() }
private val viewModel: EditHistoryListViewModel by viewModels { EditHistoryListViewModel.Factory(intent.extras!!) }
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
private var actionMode: ActionMode? = null
private val searchActionModeCallback = SearchCallback()
private var editHistoryInteractionEvent: EditHistoryInteractionEvent? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEditHistoryBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
binding.articleTitleView.isVisible = false
binding.articleTitleView.text = getString(R.string.page_edit_history_activity_title, StringUtil.fromHtml(viewModel.pageTitle.displayText))
val colorCompareBackground = ResourceUtil.getThemedColor(this, android.R.attr.colorBackground)
binding.compareFromCard.setCardBackgroundColor(ColorUtils.blendARGB(colorCompareBackground,
ResourceUtil.getThemedColor(this, R.attr.colorAccent), 0.05f))
binding.compareToCard.setCardBackgroundColor(ColorUtils.blendARGB(colorCompareBackground,
ResourceUtil.getThemedColor(this, R.attr.color_group_68), 0.05f))
updateCompareState()
binding.compareButton.setOnClickListener {
viewModel.toggleCompareState()
updateCompareState()
editHistoryInteractionEvent?.logCompare1()
}
binding.compareConfirmButton.setOnClickListener {
if (viewModel.selectedRevisionFrom != null && viewModel.selectedRevisionTo != null) {
startActivity(ArticleEditDetailsActivity.newIntent(this@EditHistoryListActivity,
viewModel.pageTitle, viewModel.selectedRevisionFrom!!.revId,
viewModel.selectedRevisionTo!!.revId))
}
editHistoryInteractionEvent?.logCompare2()
}
binding.editHistoryRefreshContainer.setOnRefreshListener {
viewModel.clearCache()
editHistoryListAdapter.reload()
}
binding.editHistoryRecycler.layoutManager = LinearLayoutManager(this)
setupAdapters()
binding.editHistoryRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
binding.articleTitleView.isVisible = binding.editHistoryRecycler.computeVerticalScrollOffset() > recyclerView.getChildAt(0).height
}
})
lifecycleScope.launchWhenCreated {
editHistoryListAdapter.loadStateFlow.distinctUntilChangedBy { it.refresh }
.filter { it.refresh is LoadState.NotLoading }
.collectLatest {
if (binding.editHistoryRefreshContainer.isRefreshing) {
binding.editHistoryRefreshContainer.isRefreshing = false
}
}
}
lifecycleScope.launchWhenCreated {
editHistoryListAdapter.loadStateFlow.collectLatest {
loadHeader.loadState = it.refresh
loadFooter.loadState = it.append
enableCompareButton(binding.compareButton, editHistoryListAdapter.itemCount > 2)
val showEmpty = (it.append is LoadState.NotLoading && it.source.refresh is LoadState.NotLoading && editHistoryListAdapter.itemCount == 0)
if (showEmpty) {
(binding.editHistoryRecycler.adapter as ConcatAdapter).addAdapter(editHistoryEmptyMessagesAdapter)
} else {
(binding.editHistoryRecycler.adapter as ConcatAdapter).removeAdapter(editHistoryEmptyMessagesAdapter)
}
}
}
viewModel.editHistoryStatsData.observe(this) {
if (it is Resource.Success) {
if (editHistoryInteractionEvent == null) {
editHistoryInteractionEvent = EditHistoryInteractionEvent(viewModel.pageTitle.wikiSite.dbName(), viewModel.pageId)
editHistoryInteractionEvent?.logShowHistory()
}
}
editHistoryStatsAdapter.notifyItemChanged(0)
editHistorySearchBarAdapter.notifyItemChanged(0)
}
lifecycleScope.launch {
viewModel.editHistoryFlow.collectLatest {
editHistoryListAdapter.submitData(it)
}
}
if (viewModel.actionModeActive) {
startSearchActionMode()
}
}
private fun updateCompareState() {
binding.compareContainer.isVisible = viewModel.comparing
binding.compareButton.text = getString(if (!viewModel.comparing) R.string.revision_compare_button else android.R.string.cancel)
editHistoryListAdapter.notifyItemRangeChanged(0, editHistoryListAdapter.itemCount)
setNavigationBarColor(ResourceUtil.getThemedColor(this, if (viewModel.comparing) android.R.attr.colorBackground else R.attr.paper_color))
updateCompareStateItems()
}
private fun updateCompareStateItems() {
binding.compareFromCard.isVisible = viewModel.selectedRevisionFrom != null
if (viewModel.selectedRevisionFrom != null) {
binding.compareFromText.text = DateUtil.getShortDayWithTimeString(viewModel.selectedRevisionFrom!!.timeStamp)
}
binding.compareToCard.isVisible = viewModel.selectedRevisionTo != null
if (viewModel.selectedRevisionTo != null) {
binding.compareToText.text = DateUtil.getShortDayWithTimeString(viewModel.selectedRevisionTo!!.timeStamp)
}
enableCompareButton(binding.compareConfirmButton, viewModel.selectedRevisionFrom != null && viewModel.selectedRevisionTo != null)
}
private fun enableCompareButton(button: TextView, enable: Boolean) {
if (enable) {
button.isEnabled = true
button.setTextColor(ResourceUtil.getThemedColor(this, R.attr.colorAccent))
} else {
button.isEnabled = false
button.setTextColor(ResourceUtil.getThemedColor(this, R.attr.material_theme_secondary_color))
}
}
private fun setupAdapters() {
if (actionMode != null) {
binding.editHistoryRecycler.adapter = editHistoryListAdapter.withLoadStateFooter(loadFooter)
} else {
binding.editHistoryRecycler.adapter =
editHistoryListAdapter.withLoadStateHeaderAndFooter(loadHeader, loadFooter).also {
it.addAdapter(0, editHistoryStatsAdapter)
it.addAdapter(1, editHistorySearchBarAdapter)
}
}
}
override fun onBackPressed() {
if (viewModel.comparing) {
viewModel.toggleCompareState()
updateCompareState()
return
}
super.onBackPressed()
}
private fun startSearchActionMode() {
actionMode = startSupportActionMode(searchActionModeCallback)
editHistoryInteractionEvent?.logSearchClick()
}
fun showFilterOverflowMenu() {
editHistoryInteractionEvent?.logFilterClick()
val editCountsValue = viewModel.editHistoryStatsData.value
if (editCountsValue is Resource.Success) {
val anchorView = if (actionMode != null && searchActionModeCallback.searchAndFilterActionProvider != null)
searchActionModeCallback.searchBarFilterIcon!! else if (editHistorySearchBarAdapter.viewHolder != null)
editHistorySearchBarAdapter.viewHolder!!.binding.filterByButton else binding.root
EditHistoryFilterOverflowView(this@EditHistoryListActivity).show(anchorView, editCountsValue.data) {
editHistoryInteractionEvent?.logFilterSelection(Prefs.editHistoryFilterType.ifEmpty { EditCount.EDIT_TYPE_ALL })
setupAdapters()
editHistoryListAdapter.reload()
editHistorySearchBarAdapter.notifyItemChanged(0)
actionMode?.let {
searchActionModeCallback.updateFilterIconAndText()
}
}
}
}
private inner class SearchBarAdapter : RecyclerView.Adapter<SearchBarViewHolder>() {
var viewHolder: SearchBarViewHolder? = null
override fun onBindViewHolder(holder: SearchBarViewHolder, position: Int) {
holder.bindItem()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchBarViewHolder {
viewHolder = SearchBarViewHolder(ViewEditHistorySearchBarBinding.inflate(layoutInflater, parent, false))
return viewHolder!!
}
override fun getItemCount(): Int { return 1 }
}
private inner class EmptyMessagesAdapter : RecyclerView.Adapter<EmptyMessagesViewHolder>() {
override fun onBindViewHolder(holder: EmptyMessagesViewHolder, position: Int) {
holder.bindItem()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EmptyMessagesViewHolder {
return EmptyMessagesViewHolder(ViewEditHistoryEmptyMessagesBinding.inflate(layoutInflater, parent, false))
}
override fun getItemCount(): Int { return 1 }
}
private inner class StatsItemAdapter : RecyclerView.Adapter<StatsViewHolder>() {
override fun onBindViewHolder(holder: StatsViewHolder, position: Int) {
holder.bindItem()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StatsViewHolder {
return StatsViewHolder(EditHistoryStatsView(this@EditHistoryListActivity))
}
override fun getItemCount(): Int { return 1 }
}
private inner class LoadingItemAdapter(private val retry: () -> Unit) : LoadStateAdapter<LoadingViewHolder>() {
override fun onBindViewHolder(holder: LoadingViewHolder, loadState: LoadState) {
holder.bindItem(loadState, retry)
}
override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): LoadingViewHolder {
return LoadingViewHolder(layoutInflater.inflate(R.layout.item_list_progress, parent, false))
}
}
private inner class EditHistoryDiffCallback : DiffUtil.ItemCallback<EditHistoryListViewModel.EditHistoryItemModel>() {
override fun areContentsTheSame(oldItem: EditHistoryListViewModel.EditHistoryItemModel, newItem: EditHistoryListViewModel.EditHistoryItemModel): Boolean {
if (oldItem is EditHistoryListViewModel.EditHistorySeparator && newItem is EditHistoryListViewModel.EditHistorySeparator) {
return oldItem.date == newItem.date
} else if (oldItem is EditHistoryListViewModel.EditHistoryItem && newItem is EditHistoryListViewModel.EditHistoryItem) {
return oldItem.item.revId == newItem.item.revId
}
return false
}
override fun areItemsTheSame(oldItem: EditHistoryListViewModel.EditHistoryItemModel, newItem: EditHistoryListViewModel.EditHistoryItemModel): Boolean {
return oldItem == newItem
}
}
private inner class EditHistoryListAdapter :
PagingDataAdapter<EditHistoryListViewModel.EditHistoryItemModel, RecyclerView.ViewHolder>(EditHistoryDiffCallback()) {
fun reload() {
submitData(lifecycle, PagingData.empty())
viewModel.editHistorySource?.invalidate()
}
override fun getItemViewType(position: Int): Int {
return if (getItem(position) is EditHistoryListViewModel.EditHistorySeparator) {
VIEW_TYPE_SEPARATOR
} else {
VIEW_TYPE_ITEM
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == VIEW_TYPE_SEPARATOR) {
SeparatorViewHolder(layoutInflater.inflate(R.layout.item_edit_history_separator, parent, false))
} else {
EditHistoryListItemHolder(EditHistoryItemView(this@EditHistoryListActivity))
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val item = getItem(position)
if (holder is SeparatorViewHolder) {
holder.bindItem((item as EditHistoryListViewModel.EditHistorySeparator).date)
} else if (holder is EditHistoryListItemHolder) {
holder.bindItem((item as EditHistoryListViewModel.EditHistoryItem).item)
}
}
}
private inner class LoadingViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItem(loadState: LoadState, retry: () -> Unit) {
val errorView = itemView.findViewById<WikiErrorView>(R.id.errorView)
val progressBar = itemView.findViewById<View>(R.id.progressBar)
progressBar.isVisible = loadState is LoadState.Loading
errorView.isVisible = loadState is LoadState.Error
errorView.retryClickListener = OnClickListener { retry() }
if (loadState is LoadState.Error) {
errorView.setError(loadState.error, viewModel.pageTitle)
}
}
}
private inner class StatsViewHolder constructor(private val view: EditHistoryStatsView) : RecyclerView.ViewHolder(view) {
fun bindItem() {
val statsFlowValue = viewModel.editHistoryStatsData.value
if (statsFlowValue is Resource.Success) {
view.setup(viewModel.pageTitle, statsFlowValue.data)
} else {
view.setup(viewModel.pageTitle, null)
}
}
}
private inner class SeparatorViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItem(listItem: String) {
val dateText = itemView.findViewById<TextView>(R.id.date_text)
dateText.text = listItem
}
}
private inner class SearchBarViewHolder constructor(val binding: ViewEditHistorySearchBarBinding) : RecyclerView.ViewHolder(binding.root) {
init {
binding.root.isVisible = false
updateFilterCount()
}
fun bindItem() {
binding.filterByButton.isVisible = viewModel.editHistoryStatsData.value is Resource.Success
binding.root.setCardBackgroundColor(
ResourceUtil.getThemedColor(this@EditHistoryListActivity, R.attr.color_group_22)
)
itemView.setOnClickListener {
startSearchActionMode()
}
binding.filterByButton.setOnClickListener {
showFilterOverflowMenu()
}
FeedbackUtil.setButtonLongPressToast(binding.filterByButton)
binding.root.isVisible = true
}
private fun updateFilterCount() {
if (Prefs.editHistoryFilterType.isEmpty()) {
binding.filterCount.visibility = View.GONE
ImageViewCompat.setImageTintList(binding.filterByButton,
ResourceUtil.getThemedColorStateList(this@EditHistoryListActivity, R.attr.color_group_9))
} else {
binding.filterCount.visibility = View.VISIBLE
binding.filterCount.text = (if (Prefs.editHistoryFilterType.isNotEmpty()) 1 else 0).toString()
ImageViewCompat.setImageTintList(binding.filterByButton,
ResourceUtil.getThemedColorStateList(this@EditHistoryListActivity, R.attr.colorAccent))
}
}
}
private inner class EmptyMessagesViewHolder constructor(val binding: ViewEditHistoryEmptyMessagesBinding) : RecyclerView.ViewHolder(binding.root) {
init {
binding.emptySearchMessage.movementMethod = LinkMovementMethodExt { _ ->
showFilterOverflowMenu()
}
}
fun bindItem() {
binding.emptySearchMessage.text = StringUtil.fromHtml(getString(R.string.page_edit_history_empty_search_message))
RichTextUtil.removeUnderlinesFromLinks(binding.emptySearchMessage)
binding.searchEmptyText.isVisible = actionMode != null
binding.searchEmptyContainer.isVisible = Prefs.editHistoryFilterType.isNotEmpty()
}
}
private inner class EditHistoryListItemHolder constructor(private val view: EditHistoryItemView) : RecyclerView.ViewHolder(view), EditHistoryItemView.Listener {
private lateinit var revision: MwQueryPage.Revision
fun bindItem(revision: MwQueryPage.Revision) {
this.revision = revision
view.setContents(revision, viewModel.currentQuery)
updateSelectState()
view.listener = this
}
override fun onClick() {
if (viewModel.comparing) {
toggleSelectState()
} else {
startActivity(ArticleEditDetailsActivity.newIntent(this@EditHistoryListActivity,
viewModel.pageTitle, revision.revId))
}
}
override fun onLongClick() {
if (!viewModel.comparing) {
viewModel.toggleCompareState()
updateCompareState()
editHistoryInteractionEvent?.logCompare1()
}
toggleSelectState()
}
override fun onUserNameClick(v: View) {
if (viewModel.comparing) {
toggleSelectState()
} else {
UserTalkPopupHelper.show(this@EditHistoryListActivity, bottomSheetPresenter,
PageTitle(UserAliasData.valueFor(viewModel.pageTitle.wikiSite.languageCode),
revision.user, viewModel.pageTitle.wikiSite), revision.isAnon, v,
Constants.InvokeSource.DIFF_ACTIVITY, HistoryEntry.SOURCE_EDIT_DIFF_DETAILS,
revisionId = revision.revId, pageId = viewModel.pageId)
}
}
override fun onToggleSelect() {
toggleSelectState()
}
private fun toggleSelectState() {
if (!viewModel.toggleSelectRevision(revision)) {
FeedbackUtil.showMessage(this@EditHistoryListActivity, R.string.revision_compare_two_only)
return
}
updateSelectState()
updateCompareStateItems()
}
private fun updateSelectState() {
view.setSelectedState(viewModel.getSelectedState(revision))
}
}
private inner class SearchCallback : SearchActionModeCallback() {
var searchAndFilterActionProvider: SearchAndFilterActionProvider? = null
val searchBarFilterIcon get() = searchAndFilterActionProvider?.filterIcon
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
searchAndFilterActionProvider = SearchAndFilterActionProvider(this@EditHistoryListActivity, searchHintString,
object : SearchAndFilterActionProvider.Callback {
override fun onQueryTextChange(s: String) {
onQueryChange(s)
}
override fun onQueryTextFocusChange() {
}
override fun onFilterIconClick() {
showFilterOverflowMenu()
}
override fun getExcludedFilterCount(): Int {
return if (Prefs.editHistoryFilterType.isNotEmpty()) 1 else 0
}
override fun getFilterIconContentDescription(): Int {
return R.string.page_edit_history_filter_by
}
})
val menuItem = menu.add(searchHintString)
MenuItemCompat.setActionProvider(menuItem, searchAndFilterActionProvider)
actionMode = mode
searchAndFilterActionProvider?.setQueryText(viewModel.currentQuery)
setupAdapters()
viewModel.actionModeActive = true
return super.onCreateActionMode(mode, menu)
}
override fun onQueryChange(s: String) {
viewModel.currentQuery = s
setupAdapters()
editHistoryListAdapter.reload()
}
override fun onDestroyActionMode(mode: ActionMode) {
super.onDestroyActionMode(mode)
actionMode = null
viewModel.currentQuery = ""
editHistoryListAdapter.reload()
viewModel.actionModeActive = false
setupAdapters()
}
override fun getSearchHintString(): String {
return getString(R.string.page_edit_history_search_or_filter_edits_hint)
}
override fun getParentContext(): Context {
return this@EditHistoryListActivity
}
fun updateFilterIconAndText() {
searchAndFilterActionProvider?.updateFilterIconAndText()
}
}
companion object {
private const val VIEW_TYPE_SEPARATOR = 0
private const val VIEW_TYPE_ITEM = 1
const val INTENT_EXTRA_PAGE_TITLE = "pageTitle"
fun newIntent(context: Context, pageTitle: PageTitle): Intent {
return Intent(context, EditHistoryListActivity::class.java)
.putExtra(INTENT_EXTRA_PAGE_TITLE, pageTitle)
}
}
}
| apache-2.0 | 2a918b217e4d4d931c23d4366cbf71f5 | 42.802158 | 164 | 0.676398 | 5.482665 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/PlainPasteEditText.kt | 1 | 2099 | package org.wikipedia.views
import android.content.ClipData
import android.content.Context
import android.text.InputType
import android.util.AttributeSet
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import androidx.core.view.ContentInfoCompat
import androidx.core.view.ViewCompat
import com.google.android.material.textfield.TextInputEditText
open class PlainPasteEditText : TextInputEditText {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle)
init {
// The MIME type(s) need to be set for onReceiveContent() to be called.
ViewCompat.setOnReceiveContentListener(this, arrayOf("text/*"), null)
}
override fun onReceiveContent(payload: ContentInfoCompat): ContentInfoCompat? {
// Do not allow pasting of formatted text! We do this by replacing the contents of the clip
// with plain text.
val clip = payload.clip
val lastClipText = clip.getItemAt(clip.itemCount - 1).coerceToText(context).toString()
val updatedPayload = ContentInfoCompat.Builder(payload)
.setClip(ClipData.newPlainText(null, lastClipText))
.build()
return super.onReceiveContent(updatedPayload)
}
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
// For multiline EditTexts that specify a done keyboard action, unset the no carriage return
// flag which otherwise limits the EditText to a single line
val multilineInput = inputType and InputType.TYPE_TEXT_FLAG_MULTI_LINE == InputType.TYPE_TEXT_FLAG_MULTI_LINE
val actionDone = outAttrs.imeOptions and EditorInfo.IME_ACTION_DONE == EditorInfo.IME_ACTION_DONE
if (actionDone && multilineInput) {
outAttrs.imeOptions = outAttrs.imeOptions and EditorInfo.IME_FLAG_NO_ENTER_ACTION.inv()
}
return super.onCreateInputConnection(outAttrs)
}
}
| apache-2.0 | 608f489afbd364b34ad3db6bcf8559e3 | 46.704545 | 117 | 0.737018 | 4.664444 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/sitrep/SitReportScreen.kt | 1 | 1975 | package au.com.codeka.warworlds.client.game.sitrep
import android.view.ViewGroup
import au.com.codeka.warworlds.client.App
import au.com.codeka.warworlds.client.concurrency.Threads
import au.com.codeka.warworlds.client.game.solarsystem.SolarSystemScreen
import au.com.codeka.warworlds.client.ui.Screen
import au.com.codeka.warworlds.client.ui.ScreenContext
import au.com.codeka.warworlds.client.ui.ShowInfo
import au.com.codeka.warworlds.client.util.eventbus.EventHandler
import au.com.codeka.warworlds.common.Log
import au.com.codeka.warworlds.common.proto.RpcPacket
import au.com.codeka.warworlds.common.proto.SituationReport
import au.com.codeka.warworlds.common.proto.Star
class SitReportScreen : Screen() {
companion object {
private val log = Log("SitReportScreen")
}
private lateinit var layout: SitReportLayout
override fun onCreate(context: ScreenContext, container: ViewGroup) {
super.onCreate(context, container)
layout = SitReportLayout(
context.activity,
object : SitReportLayout.Callback {
override fun onStarClick(star: Star?) {
context.pushScreen(SolarSystemScreen(star!!, -1))
}
})
App.eventBus.register(eventHandler)
}
override fun onDestroy() {
super.onDestroy()
App.eventBus.unregister(eventHandler)
}
fun refresh(sitReports: List<SituationReport>) {
log.info("populating response: ${sitReports.size} reports")
layout.refresh(sitReports)
}
override fun onShow(): ShowInfo {
App.taskRunner.runTask({
val resp = App.server.sendRpc(RpcPacket(sit_report_request = RpcPacket.SitReportRequest()))
App.taskRunner.runTask({
refresh(resp.sit_report_response!!.sit_reports)
}, Threads.UI)
}, Threads.BACKGROUND)
return ShowInfo.builder().view(layout).build()
}
private val eventHandler: Any = object : Any() {
@EventHandler
fun onStarUpdated(s: Star) {
layout.onStarUpdated(s)
}
}
}
| mit | 70acb45570773c6f3067a56bb2dca948 | 29.384615 | 97 | 0.728608 | 3.827519 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/analytics/amplitude/AmplitudeModule.kt | 2 | 4518 | package abi44_0_0.expo.modules.analytics.amplitude
import android.content.Context
import com.amplitude.api.Amplitude
import com.amplitude.api.AmplitudeClient
import com.amplitude.api.TrackingOptions
import org.json.JSONArray
import org.json.JSONObject
import abi44_0_0.expo.modules.core.ExportedModule
import abi44_0_0.expo.modules.core.Promise
import abi44_0_0.expo.modules.core.arguments.ReadableArguments
import abi44_0_0.expo.modules.core.interfaces.ExpoMethod
open class AmplitudeModule(context: Context?) : ExportedModule(context) {
private var mClient: AmplitudeClient? = null
private var mPendingTrackingOptions: TrackingOptions? = null
override fun getName(): String {
return "ExpoAmplitude"
}
protected open fun getClient(apiKey: String?): AmplitudeClient {
return Amplitude.getInstance(apiKey)
}
@ExpoMethod
fun initializeAsync(apiKey: String, promise: Promise) {
mClient = getClient(apiKey)
val client = mClient
if (mPendingTrackingOptions != null) {
client?.setTrackingOptions(mPendingTrackingOptions)
}
client?.initialize(context, apiKey)
promise.resolve(null)
}
private inline fun rejectUnlessClientInitialized(promise: Promise, block: (AmplitudeClient) -> Unit) {
val client = mClient
if (client == null) {
promise.reject("E_NO_INIT", "Amplitude client has not been initialized, are you sure you have configured it with #init(apiKey)?")
return
}
block(client)
}
@ExpoMethod
fun setUserIdAsync(userId: String?, promise: Promise) =
rejectUnlessClientInitialized(promise) { client ->
client.userId = userId
promise.resolve(null)
}
@ExpoMethod
fun setUserPropertiesAsync(properties: Map<String, Any?>, promise: Promise) =
rejectUnlessClientInitialized(promise) { client ->
client.setUserProperties(JSONObject(properties))
promise.resolve(null)
}
@ExpoMethod
fun clearUserPropertiesAsync(promise: Promise) =
rejectUnlessClientInitialized(promise) { client ->
client.clearUserProperties()
promise.resolve(null)
}
@ExpoMethod
fun logEventAsync(eventName: String, promise: Promise) =
rejectUnlessClientInitialized(promise) { client ->
client.logEvent(eventName)
promise.resolve(null)
}
@ExpoMethod
fun logEventWithPropertiesAsync(eventName: String, properties: Map<String, Any?>, promise: Promise) =
rejectUnlessClientInitialized(promise) { client ->
client.logEvent(eventName, JSONObject(properties))
promise.resolve(null)
}
@ExpoMethod
fun setGroupAsync(groupType: String, groupNames: List<Any?>, promise: Promise) =
rejectUnlessClientInitialized(promise) { client ->
client.setGroup(groupType, JSONArray(groupNames))
promise.resolve(null)
}
@ExpoMethod
fun setTrackingOptionsAsync(options: ReadableArguments, promise: Promise) {
val trackingOptions = TrackingOptions()
if (options.getBoolean("disableAdid")) {
trackingOptions.disableAdid()
}
if (options.getBoolean("disableCarrier")) {
trackingOptions.disableCarrier()
}
if (options.getBoolean("disableCity")) {
trackingOptions.disableCity()
}
if (options.getBoolean("disableCountry")) {
trackingOptions.disableCountry()
}
if (options.getBoolean("disableDeviceBrand")) {
trackingOptions.disableDeviceBrand()
}
if (options.getBoolean("disableDeviceModel")) {
trackingOptions.disableDeviceModel()
}
if (options.getBoolean("disableDMA")) {
trackingOptions.disableDma()
}
if (options.getBoolean("disableIPAddress")) {
trackingOptions.disableIpAddress()
}
if (options.getBoolean("disableLanguage")) {
trackingOptions.disableLanguage()
}
if (options.getBoolean("disableLatLng")) {
trackingOptions.disableLatLng()
}
if (options.getBoolean("disableOSName")) {
trackingOptions.disableOsName()
}
if (options.getBoolean("disableOSVersion")) {
trackingOptions.disableOsVersion()
}
if (options.getBoolean("disablePlatform")) {
trackingOptions.disablePlatform()
}
if (options.getBoolean("disableRegion")) {
trackingOptions.disableRegion()
}
if (options.getBoolean("disableVersionName")) {
trackingOptions.disableVersionName()
}
if (mClient != null) {
mClient!!.setTrackingOptions(trackingOptions)
} else {
mPendingTrackingOptions = trackingOptions
}
promise.resolve(null)
}
}
| bsd-3-clause | f940f214a044edba7a314246b29f0086 | 30.158621 | 135 | 0.712483 | 4.331735 | false | false | false | false |
MaximumSquotting/chopin | app/src/main/java/com/chopin/chopin/fragments/MyChippedList.kt | 1 | 2172 | package com.chopin.chopin.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import bindView
import butterknife.ButterKnife
import com.chopin.chopin.ConnectionHandler
import com.chopin.chopin.R
import com.chopin.chopin.adapters.RVAdapter
import com.chopin.chopin.models.Offer
import java.util.*
class MyChippedList : Fragment() {
private var offers: ArrayList<Offer>? = null
private var mRecyclerView: RecyclerView? = null
private var connectionHandler: ConnectionHandler = ConnectionHandler()
val swipe : SwipeRefreshLayout by bindView(R.id.swipe)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
connectionHandler = ConnectionHandler()
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val v = inflater!!.inflate(R.layout.fragment_list, container, false)
ButterKnife.bind(this, v)
return v
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
offers = ArrayList<Offer>()
mRecyclerView = activity.findViewById(R.id.list) as RecyclerView
mRecyclerView!!.setHasFixedSize(true)
// use a linear layout manager
val mLayoutManager = LinearLayoutManager(this.context)
mRecyclerView!!.layoutManager = mLayoutManager
offers = connectionHandler!!.chippedOffersFromServer
val adapter = RVAdapter(offers, activity)
mRecyclerView!!.adapter = adapter
swipe?.setOnRefreshListener {
Log.d("onRefresh", "calling get()")
offers = connectionHandler.myOfferFromServer
adapter!!.notifyDataSetChanged()
swipe!!.isRefreshing = false
}
}
}// Required empty public constructor
| mit | 03a30b375f24b4629fbb557dbc956f14 | 33.47619 | 79 | 0.718232 | 4.891892 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/highlight/RsRainbowVisitor.kt | 3 | 1707 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.highlight
import com.intellij.codeInsight.daemon.RainbowVisitor
import com.intellij.codeInsight.daemon.impl.HighlightVisitor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsPatBinding
import org.rust.lang.core.psi.RsPath
import org.rust.lang.core.psi.ext.descendantsOfType
class RsRainbowVisitor : RainbowVisitor() {
override fun suitableForFile(file: PsiFile): Boolean = file is RsFile
override fun clone(): HighlightVisitor = RsRainbowVisitor()
override fun visit(function: PsiElement) {
if (function !is RsFunction) return
fun addInfo(ident: PsiElement, colorTag: String) {
addInfo(getInfo(function, ident, colorTag, null))
}
val bindingToUniqueName: Map<RsPatBinding, String> = run {
val allBindings = function.descendantsOfType<RsPatBinding>().filter { it.name != null }
val byName = allBindings.groupBy { it.name }
allBindings.associateWith { "${it.name}#${byName[it.name]!!.indexOf(it)}" }
}
for ((binding, name) in bindingToUniqueName) {
addInfo(binding.referenceNameElement, name)
}
for (path in function.descendantsOfType<RsPath>()) {
val target = path.reference?.resolve() as? RsPatBinding ?: continue
val colorTag = bindingToUniqueName[target] ?: return
val ident = path.referenceNameElement ?: return
addInfo(ident, colorTag)
}
}
}
| mit | 036740a53563d3a1621e56fe7bdf552a | 35.319149 | 99 | 0.68717 | 4.310606 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/config/ImageSource.kt | 1 | 1258 | /*
Copyright 2017-2020 Charles Korn.
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 batect.config
import java.nio.file.Path
sealed class ImageSource
data class BuildImage(val buildDirectory: Path, val buildArgs: Map<String, VariableExpression> = emptyMap(), val dockerfilePath: String = "Dockerfile") : ImageSource() {
override fun toString(): String = "${this.javaClass.simpleName}(" +
"build directory: '$buildDirectory', " +
"build args: [${buildArgs.map { "${it.key}=${it.value}" }.joinToString(", ")}], " +
"Dockerfile path: '$dockerfilePath')"
}
data class PullImage(val imageName: String) : ImageSource() {
override fun toString(): String = "${this.javaClass.simpleName}(image: '$imageName')"
}
| apache-2.0 | f3de4185fe52f01f3c0442851c13cbe4 | 38.3125 | 169 | 0.711447 | 4.398601 | false | false | false | false |
erva/CellAdapter | sample-x-kotlin/src/main/kotlin/io/erva/sample/single/SingleChoiceActivity.kt | 1 | 1712 | package io.erva.sample.single
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import io.erva.celladapter.x.Cell
import io.erva.celladapter.x.CellAdapter
import io.erva.celladapter.x.select.SelectableCellAdapter
import io.erva.celladapter.x.select.mode.SingleSelectionManager
import io.erva.sample.DividerItemDecoration
import io.erva.sample.R
import kotlinx.android.synthetic.main.activity_with_recycler_view.*
class SingleChoiceActivity : AppCompatActivity() {
val singleSelectionManager = SingleSelectionManager()
private var adapter: CellAdapter = SelectableCellAdapter(selectionManager = singleSelectionManager).let {
it.cell(SingleChoiceCell::class) {
item(SingleChoiceModel::class)
listener(object : Cell.Listener<SingleChoiceModel> {
override fun onCellClicked(item: SingleChoiceModel) {
supportActionBar!!.subtitle = String.format("Selected %d", singleSelectionManager.getSelectedPosition())
}
})
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_with_recycler_view)
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.addItemDecoration(DividerItemDecoration(this))
recycler_view.adapter = adapter
for (it in 0..33) {
adapter.addItem(SingleChoiceModel("Single select $it"))
}
adapter.notifyDataSetChanged()
supportActionBar!!.subtitle = String.format("Selected %d", singleSelectionManager.getSelectedPosition())
}
} | mit | 7efa4f686820ea79b279a0553de61bfe | 38.837209 | 124 | 0.727804 | 4.795518 | false | false | false | false |
androidx/androidx | compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/DeclarativeGraphicsDemo.kt | 3 | 5553 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.demos
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.inset
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.unit.dp
@Composable
fun DeclarativeGraphicsDemo() {
/**
* Demo that shows how to leverage DrawScope to draw 4 rectangular quadrants
* inset by a given dimension with a diamond drawn within each of the quadrants
*/
Canvas(
modifier =
Modifier.fillMaxSize()
.wrapContentSize(Alignment.Center)
.size(120.dp, 120.dp)
) {
drawRect(color = Color.Gray)
// Inset content by 10 pixels on the left/right sides and 12 by the
// top/bottom
inset(10.0f, 12.0f) {
val quadrantSize = size / 2.0f
drawRect(
size = quadrantSize,
color = Color.Red
)
// Scale the drawing environment down by 50% about the center of the square drawn
// in the top left quadrant
scale(0.5f, Offset(size.width / 4, size.height / 4)) {
// Rotate the drawing environment 45 degrees about the center of the square
// drawn in the top left
rotate(45.0f, Offset(size.width / 4, size.height / 4)) {
drawRect(
size = quadrantSize,
color = Color.Yellow,
alpha = 0.75f
)
}
}
// Translate the drawing environment to the right by half the size of the current
// width
translate(size.width / 2, 0.0f) {
drawRect(
size = quadrantSize,
color = Color.Yellow
)
// Scale the drawing environment down by 50% about the center of the square drawn
// in the top right quadrant
scale(0.5f, Offset(size.width / 4, size.height / 4)) {
// rotate the drawing environment 45 degrees about the center of the drawn
// square in the top right
rotate(45.0f, Offset(size.width / 4, size.height / 4)) {
drawRect(
size = quadrantSize,
color = Color.Red,
alpha = 0.75f
)
}
}
}
// Translate the drawing environment down by half the size of the current height
translate(0.0f, size.height / 2) {
drawRect(
size = quadrantSize,
color = Color.Green
)
// Scale the drawing environment down by 50% about the center of the square drawn
// in the bottom left quadrant
scale(0.5f, Offset(size.width / 4, size.height / 4)) {
// Rotate the drawing environment by 45 degrees about the center of the
// square drawn in the bottom left quadrant
rotate(45.0f, Offset(size.width / 4, size.height / 4)) {
drawRect(
size = quadrantSize,
color = Color.Blue,
alpha = 0.75f
)
}
}
}
// Translate the drawing environment to the bottom right quadrant of the inset bounds
translate(size.width / 2, size.height / 2) {
drawRect(
size = quadrantSize,
color = Color.Blue
)
// Scale the drawing environment down by 50% about the center of the square drawn
// in the bottom right quadrant
scale(0.5f, Offset(size.width / 4, size.height / 4)) {
// Rotate the drawing environment 45 degrees about the center of the drawn
// square in the bottom right
rotate(45.0f, Offset(size.width / 4, size.height / 4)) {
drawRect(
size = quadrantSize,
color = Color.Green,
alpha = 0.75f
)
}
}
}
}
}
} | apache-2.0 | 5c5608d3c115af4c550814a8dc7df717 | 41.723077 | 97 | 0.538808 | 5.029891 | false | false | false | false |
androidx/androidx | fragment/fragment/src/androidTest/java/androidx/fragment/app/ViewModelTest.kt | 3 | 11071 | /*
* 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.fragment.app
import androidx.fragment.app.test.EmptyFragmentTestActivity
import androidx.fragment.app.test.TestViewModel
import androidx.fragment.app.test.ViewModelActivity
import androidx.fragment.app.test.ViewModelActivity.ViewModelFragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.test.annotation.UiThreadTest
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.testutils.withActivity
import androidx.testutils.withUse
import com.google.common.truth.Truth.assertThat
import leakcanary.DetectLeaksAfterTestSuccess
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class ViewModelTest {
@get:Rule
val rule = DetectLeaksAfterTestSuccess()
@Test(expected = IllegalStateException::class)
@UiThreadTest
fun testNotAttachedFragment() {
// This is similar to calling getViewModelStore in Fragment's constructor
Fragment().viewModelStore
}
@Test
fun testMaxLifecycleInitializedFragment() {
withUse(ActivityScenario.launch(EmptyFragmentTestActivity::class.java)) {
withActivity {
val fragment = StrictFragment()
supportFragmentManager.beginTransaction()
.setReorderingAllowed(true)
.add(android.R.id.content, fragment)
.setMaxLifecycle(fragment, Lifecycle.State.INITIALIZED)
.commitNow()
try {
fragment.viewModelStore
} catch (e: IllegalStateException) {
assertThat(e).hasMessageThat().contains(
"Calling getViewModelStore() before a Fragment " +
"reaches onCreate() when using setMaxLifecycle(INITIALIZED) is " +
"not supported"
)
}
}
}
}
@Test
fun testMaxLifecycleInitializedNestedFragment() {
withUse(ActivityScenario.launch(EmptyFragmentTestActivity::class.java)) {
withActivity {
val fragment = StrictFragment()
val childFragment = StrictFragment()
supportFragmentManager.beginTransaction()
.setReorderingAllowed(true)
.add(android.R.id.content, fragment)
.setMaxLifecycle(fragment, Lifecycle.State.INITIALIZED)
.commitNow()
fragment.childFragmentManager.beginTransaction()
.add(android.R.id.content, childFragment)
.commitNow()
try {
childFragment.viewModelStore
} catch (e: IllegalStateException) {
assertThat(e).hasMessageThat().contains(
"Calling getViewModelStore() before a Fragment " +
"reaches onCreate() when using setMaxLifecycle(INITIALIZED) is " +
"not supported"
)
}
}
}
}
@Test
fun testSameActivityViewModels() {
withUse(ActivityScenario.launch(ViewModelActivity::class.java)) {
val activityModel = withActivity { activityModel }
val defaultActivityModel = withActivity { defaultActivityModel }
assertThat(defaultActivityModel).isNotSameInstanceAs(activityModel)
var fragment1 = withActivity { getFragment(ViewModelActivity.FRAGMENT_TAG_1) }
var fragment2 = withActivity { getFragment(ViewModelActivity.FRAGMENT_TAG_2) }
assertThat(fragment1).isNotNull()
assertThat(fragment2).isNotNull()
assertThat(fragment1.activityModel).isSameInstanceAs(activityModel)
assertThat(fragment2.activityModel).isSameInstanceAs(activityModel)
assertThat(fragment1.defaultActivityModel).isSameInstanceAs(defaultActivityModel)
assertThat(fragment2.defaultActivityModel).isSameInstanceAs(defaultActivityModel)
recreate()
assertThat(withActivity { activityModel }).isSameInstanceAs(activityModel)
assertThat(withActivity { defaultActivityModel }).isSameInstanceAs(defaultActivityModel)
fragment1 = withActivity { getFragment(ViewModelActivity.FRAGMENT_TAG_1) }
fragment2 = withActivity { getFragment(ViewModelActivity.FRAGMENT_TAG_2) }
assertThat(fragment1).isNotNull()
assertThat(fragment2).isNotNull()
assertThat(fragment1.activityModel).isSameInstanceAs(activityModel)
assertThat(fragment2.activityModel).isSameInstanceAs(activityModel)
assertThat(fragment1.defaultActivityModel).isSameInstanceAs(defaultActivityModel)
assertThat(fragment2.defaultActivityModel).isSameInstanceAs(defaultActivityModel)
}
}
@Test
fun testSameFragmentViewModels() {
withUse(ActivityScenario.launch(ViewModelActivity::class.java)) {
var fragment1 = withActivity { getFragment(ViewModelActivity.FRAGMENT_TAG_1) }
var fragment2 = withActivity { getFragment(ViewModelActivity.FRAGMENT_TAG_2) }
assertThat(fragment1).isNotNull()
assertThat(fragment2).isNotNull()
assertThat(fragment1.fragmentModel).isNotSameInstanceAs(fragment2.fragmentModel)
val fragment1Model = fragment1.fragmentModel
val fragment2Model = fragment2.fragmentModel
recreate()
fragment1 = withActivity { getFragment(ViewModelActivity.FRAGMENT_TAG_1) }
fragment2 = withActivity { getFragment(ViewModelActivity.FRAGMENT_TAG_2) }
assertThat(fragment1).isNotNull()
assertThat(fragment2).isNotNull()
assertThat(fragment1.fragmentModel).isSameInstanceAs(fragment1Model)
assertThat(fragment2.fragmentModel).isSameInstanceAs(fragment2Model)
}
}
@Test
fun testCreateFragmentViewModelViaExtras() {
withUse(ActivityScenario.launch(ViewModelActivity::class.java)) {
val fragment = withActivity { getFragment(ViewModelActivity.FRAGMENT_TAG_1) }
val creationViewModel = ViewModelProvider(
fragment.viewModelStore,
fragment.defaultViewModelProviderFactory,
fragment.defaultViewModelCreationExtras
)["test", TestViewModel::class.java]
recreate()
val recreatedFragment = withActivity { getFragment(ViewModelActivity.FRAGMENT_TAG_1) }
assertThat(ViewModelProvider(recreatedFragment)["test", TestViewModel::class.java])
.isSameInstanceAs(creationViewModel)
}
}
@Test
fun testFragmentOnClearedWhenFinished() {
withUse(ActivityScenario.launch(ViewModelActivity::class.java)) {
val fragmentModel = withActivity {
getFragment(ViewModelActivity.FRAGMENT_TAG_1).fragmentModel
}
val fragmentAndroidModel = withActivity {
getFragment(ViewModelActivity.FRAGMENT_TAG_1).androidModel
}
val fragmentSavedStateAndroidModel = withActivity {
getFragment(ViewModelActivity.FRAGMENT_TAG_1).savedStateModel
}
val backStackFragmentModel = withActivity {
getFragment(ViewModelActivity.FRAGMENT_TAG_BACK_STACK).fragmentModel
}
assertThat(fragmentModel.cleared).isFalse()
assertThat(fragmentAndroidModel.cleared).isFalse()
assertThat(fragmentSavedStateAndroidModel.cleared).isFalse()
assertThat(backStackFragmentModel.cleared).isFalse()
recreate()
// recreate shouldn't clear the ViewModels
assertThat(fragmentModel.cleared).isFalse()
assertThat(fragmentAndroidModel.cleared).isFalse()
assertThat(fragmentSavedStateAndroidModel.cleared).isFalse()
assertThat(backStackFragmentModel.cleared).isFalse()
moveToState(Lifecycle.State.DESTROYED)
// But destroying the Activity should
assertThat(fragmentModel.cleared).isTrue()
assertThat(fragmentAndroidModel.cleared).isTrue()
assertThat(fragmentSavedStateAndroidModel.cleared).isTrue()
assertThat(backStackFragmentModel.cleared).isTrue()
}
}
@Test
fun testFragmentOnCleared() {
withUse(ActivityScenario.launch(ViewModelActivity::class.java)) {
val fragment = withActivity {
Fragment().also {
supportFragmentManager.beginTransaction().add(it, "temp").commitNow()
}
}
val viewModelProvider = ViewModelProvider(fragment)
val vm = viewModelProvider.get(TestViewModel::class.java)
assertThat(vm.cleared).isFalse()
onActivity { activity ->
activity.supportFragmentManager.beginTransaction().remove(fragment).commitNow()
}
assertThat(vm.cleared).isTrue()
}
}
@Test
fun testDefaultFactoryAfterReuse() {
withUse(ActivityScenario.launch(ViewModelActivity::class.java)) {
val fragment = withActivity {
Fragment().also {
supportFragmentManager.beginTransaction().add(it, "temp").commitNow()
}
}
val defaultFactory = fragment.defaultViewModelProviderFactory
onActivity { activity ->
activity.supportFragmentManager.beginTransaction().remove(fragment).commitNow()
}
// Now re-add the removed fragment
onActivity { activity ->
activity.supportFragmentManager.beginTransaction()
.add(fragment, "temp")
.commitNow()
}
val newDefaultFactory = fragment.defaultViewModelProviderFactory
// New Fragment should have a new default factory
assertThat(newDefaultFactory).isNotSameInstanceAs(defaultFactory)
}
}
}
private fun FragmentActivity.getFragment(tag: String) =
supportFragmentManager.findFragmentByTag(tag) as ViewModelFragment
| apache-2.0 | d6411039b0b089b9f3128f24db6c2c2c | 39.852399 | 100 | 0.652064 | 5.71259 | false | true | false | false |
androidx/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/fancy/AnimatedClockDemo.kt | 3 | 6844 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.demos.fancy
import androidx.compose.animation.core.animate
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.withInfiniteAnimationFrameMillis
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.isActive
import java.util.Calendar
private class Time(hours: State<Int>, minutes: State<Int>, seconds: State<Int>) {
val hours by hours
val minutes by minutes
val seconds by seconds
}
@Preview
@Composable
fun AnimatedClockDemo() {
val calendar = remember { Calendar.getInstance() }
val seconds = remember { mutableStateOf(calendar[Calendar.SECOND]) }
val minutes = remember { mutableStateOf(calendar[Calendar.MINUTE]) }
val hours = remember { mutableStateOf(calendar[Calendar.HOUR_OF_DAY]) }
LaunchedEffect(key1 = Unit) {
// Start from 23:59:50 to give an impressive animation for all numbers
calendar.set(2020, 10, 10, 23, 59, 50)
val initialTime = calendar.timeInMillis
val firstFrameTime = withInfiniteAnimationFrameMillis { it }
while (isActive) {
withInfiniteAnimationFrameMillis {
calendar.timeInMillis = it - firstFrameTime + initialTime
seconds.value = calendar[Calendar.SECOND]
minutes.value = calendar[Calendar.MINUTE]
hours.value = calendar[Calendar.HOUR_OF_DAY]
}
}
}
val time = remember { Time(hours, minutes, seconds) }
FancyClock(time)
}
@Composable
private fun FancyClock(time: Time) {
Row(
modifier = Modifier.fillMaxHeight().fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
NumberColumn(2, time.hours / 10)
NumberColumn(9, time.hours % 10)
Spacer(modifier = Modifier.size(16.dp))
NumberColumn(5, time.minutes / 10)
NumberColumn(9, time.minutes % 10)
Spacer(modifier = Modifier.size(16.dp))
NumberColumn(5, time.seconds / 10)
NumberColumn(9, time.seconds % 10)
}
}
private const val digitHeight = 24
private const val moveDuration = 700
@Composable
private fun NumberColumn(maxDigit: Int, digit: Int) {
val offsetY: Dp = animateDpAsState(
targetValue = ((9 - digit) * digitHeight).dp,
animationSpec = tween(moveDuration),
).value
var circleOffset by remember { mutableStateOf(0f) }
LaunchedEffect(digit) {
if (digit == 0) return@LaunchedEffect // Don't animate for 0 as direction is reversed
animate(
initialValue = 0f,
targetValue = -1f,
animationSpec = tween(moveDuration)
) { animationValue, _ -> circleOffset = animationValue }
animate(
initialValue = -1f,
targetValue = 0f,
animationSpec = spring(dampingRatio = 0.6f)
) { animationValue, _ -> circleOffset = animationValue }
}
var circleStretch by remember { mutableStateOf(1f) }
LaunchedEffect(digit) {
if (digit == 0) return@LaunchedEffect // Don't animate for 0 as direction is reversed
animate(
initialValue = 1f,
targetValue = 2f,
animationSpec = tween(moveDuration)
) { animationValue, _ -> circleStretch = animationValue }
animate(
initialValue = 2f,
targetValue = 1f,
animationSpec = spring(dampingRatio = 0.6f)
) { animationValue, _ -> circleStretch = animationValue }
}
Box(modifier = Modifier.padding(4.dp)) {
// Draw an elevation shadow for the rounded column
Surface(
shape = RoundedCornerShape((digitHeight / 2).dp),
modifier = Modifier
.offset(y = offsetY)
.size(digitHeight.dp, ((maxDigit + 1) * digitHeight).dp),
elevation = 12.dp
) {}
// Draw circle that follows focused digit
Canvas(modifier = Modifier.size(digitHeight.dp, (10 * digitHeight).dp)) {
drawRoundRect(
color = Color(0xffd2e7d6),
size = Size(24.dp.toPx(), (digitHeight * circleStretch).dp.toPx()),
topLeft = Offset(0f, ((9f + circleOffset) * digitHeight).dp.toPx()),
cornerRadius = CornerRadius(
(digitHeight / 2).dp.toPx(),
(digitHeight / 2).dp.toPx()
)
)
}
// Draw all the digits up to count
Column(modifier = Modifier.offset(y = offsetY)) {
for (i in (0..maxDigit)) {
androidx.compose.material.Text(
color = Color.DarkGray,
modifier = Modifier.size(digitHeight.dp),
text = "$i",
textAlign = TextAlign.Center
)
}
}
}
}
| apache-2.0 | d3e2ad99646f6cef81a1b793c0446fe0 | 38.333333 | 93 | 0.66993 | 4.432642 | false | false | false | false |
androidx/androidx | navigation/navigation-safe-args-generator/src/test/test-data/expected/kotlin_nav_writer_test/MainFragmentArgs.kt | 3 | 12333 | package a.b
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.Parcelable
import androidx.lifecycle.SavedStateHandle
import androidx.navigation.NavArgs
import java.io.Serializable
import java.lang.IllegalArgumentException
import java.lang.UnsupportedOperationException
import java.nio.`file`.AccessMode
import kotlin.Array
import kotlin.Boolean
import kotlin.Float
import kotlin.FloatArray
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.jvm.JvmStatic
public data class MainFragmentArgs(
public val main: String,
public val floatArrayArg: FloatArray,
public val objectArrayArg: Array<ActivityInfo>,
public val optional: Int = -1,
public val reference: Int = R.drawable.background,
public val referenceZeroDefaultValue: Int = 0,
public val floatArg: Float = 1F,
public val boolArg: Boolean = true,
public val optionalParcelable: ActivityInfo? = null,
public val enumArg: AccessMode = AccessMode.READ,
) : NavArgs {
@Suppress("CAST_NEVER_SUCCEEDS")
public fun toBundle(): Bundle {
val result = Bundle()
result.putString("main", this.main)
result.putInt("optional", this.optional)
result.putInt("reference", this.reference)
result.putInt("referenceZeroDefaultValue", this.referenceZeroDefaultValue)
result.putFloat("floatArg", this.floatArg)
result.putFloatArray("floatArrayArg", this.floatArrayArg)
result.putParcelableArray("objectArrayArg", this.objectArrayArg)
result.putBoolean("boolArg", this.boolArg)
if (Parcelable::class.java.isAssignableFrom(ActivityInfo::class.java)) {
result.putParcelable("optionalParcelable", this.optionalParcelable as Parcelable?)
} else if (Serializable::class.java.isAssignableFrom(ActivityInfo::class.java)) {
result.putSerializable("optionalParcelable", this.optionalParcelable as Serializable?)
}
if (Parcelable::class.java.isAssignableFrom(AccessMode::class.java)) {
result.putParcelable("enumArg", this.enumArg as Parcelable)
} else if (Serializable::class.java.isAssignableFrom(AccessMode::class.java)) {
result.putSerializable("enumArg", this.enumArg as Serializable)
}
return result
}
@Suppress("CAST_NEVER_SUCCEEDS")
public fun toSavedStateHandle(): SavedStateHandle {
val result = SavedStateHandle()
result.set("main", this.main)
result.set("optional", this.optional)
result.set("reference", this.reference)
result.set("referenceZeroDefaultValue", this.referenceZeroDefaultValue)
result.set("floatArg", this.floatArg)
result.set("floatArrayArg", this.floatArrayArg)
result.set("objectArrayArg", this.objectArrayArg)
result.set("boolArg", this.boolArg)
if (Parcelable::class.java.isAssignableFrom(ActivityInfo::class.java)) {
result.set("optionalParcelable", this.optionalParcelable as Parcelable?)
} else if (Serializable::class.java.isAssignableFrom(ActivityInfo::class.java)) {
result.set("optionalParcelable", this.optionalParcelable as Serializable?)
}
if (Parcelable::class.java.isAssignableFrom(AccessMode::class.java)) {
result.set("enumArg", this.enumArg as Parcelable)
} else if (Serializable::class.java.isAssignableFrom(AccessMode::class.java)) {
result.set("enumArg", this.enumArg as Serializable)
}
return result
}
public companion object {
@JvmStatic
@Suppress("UNCHECKED_CAST","DEPRECATION")
public fun fromBundle(bundle: Bundle): MainFragmentArgs {
bundle.setClassLoader(MainFragmentArgs::class.java.classLoader)
val __main : String?
if (bundle.containsKey("main")) {
__main = bundle.getString("main")
if (__main == null) {
throw IllegalArgumentException("Argument \"main\" is marked as non-null but was passed a null value.")
}
} else {
throw IllegalArgumentException("Required argument \"main\" is missing and does not have an android:defaultValue")
}
val __optional : Int
if (bundle.containsKey("optional")) {
__optional = bundle.getInt("optional")
} else {
__optional = -1
}
val __reference : Int
if (bundle.containsKey("reference")) {
__reference = bundle.getInt("reference")
} else {
__reference = R.drawable.background
}
val __referenceZeroDefaultValue : Int
if (bundle.containsKey("referenceZeroDefaultValue")) {
__referenceZeroDefaultValue = bundle.getInt("referenceZeroDefaultValue")
} else {
__referenceZeroDefaultValue = 0
}
val __floatArg : Float
if (bundle.containsKey("floatArg")) {
__floatArg = bundle.getFloat("floatArg")
} else {
__floatArg = 1F
}
val __floatArrayArg : FloatArray?
if (bundle.containsKey("floatArrayArg")) {
__floatArrayArg = bundle.getFloatArray("floatArrayArg")
if (__floatArrayArg == null) {
throw IllegalArgumentException("Argument \"floatArrayArg\" is marked as non-null but was passed a null value.")
}
} else {
throw IllegalArgumentException("Required argument \"floatArrayArg\" is missing and does not have an android:defaultValue")
}
val __objectArrayArg : Array<ActivityInfo>?
if (bundle.containsKey("objectArrayArg")) {
__objectArrayArg = bundle.getParcelableArray("objectArrayArg")?.map { it as ActivityInfo
}?.toTypedArray()
if (__objectArrayArg == null) {
throw IllegalArgumentException("Argument \"objectArrayArg\" is marked as non-null but was passed a null value.")
}
} else {
throw IllegalArgumentException("Required argument \"objectArrayArg\" is missing and does not have an android:defaultValue")
}
val __boolArg : Boolean
if (bundle.containsKey("boolArg")) {
__boolArg = bundle.getBoolean("boolArg")
} else {
__boolArg = true
}
val __optionalParcelable : ActivityInfo?
if (bundle.containsKey("optionalParcelable")) {
if (Parcelable::class.java.isAssignableFrom(ActivityInfo::class.java) ||
Serializable::class.java.isAssignableFrom(ActivityInfo::class.java)) {
__optionalParcelable = bundle.get("optionalParcelable") as ActivityInfo?
} else {
throw UnsupportedOperationException(ActivityInfo::class.java.name +
" must implement Parcelable or Serializable or must be an Enum.")
}
} else {
__optionalParcelable = null
}
val __enumArg : AccessMode?
if (bundle.containsKey("enumArg")) {
if (Parcelable::class.java.isAssignableFrom(AccessMode::class.java) ||
Serializable::class.java.isAssignableFrom(AccessMode::class.java)) {
__enumArg = bundle.get("enumArg") as AccessMode?
} else {
throw UnsupportedOperationException(AccessMode::class.java.name +
" must implement Parcelable or Serializable or must be an Enum.")
}
if (__enumArg == null) {
throw IllegalArgumentException("Argument \"enumArg\" is marked as non-null but was passed a null value.")
}
} else {
__enumArg = AccessMode.READ
}
return MainFragmentArgs(__main, __floatArrayArg, __objectArrayArg, __optional, __reference,
__referenceZeroDefaultValue, __floatArg, __boolArg, __optionalParcelable, __enumArg)
}
@JvmStatic
public fun fromSavedStateHandle(savedStateHandle: SavedStateHandle): MainFragmentArgs {
val __main : String?
if (savedStateHandle.contains("main")) {
__main = savedStateHandle["main"]
if (__main == null) {
throw IllegalArgumentException("Argument \"main\" is marked as non-null but was passed a null value")
}
} else {
throw IllegalArgumentException("Required argument \"main\" is missing and does not have an android:defaultValue")
}
val __optional : Int?
if (savedStateHandle.contains("optional")) {
__optional = savedStateHandle["optional"]
if (__optional == null) {
throw IllegalArgumentException("Argument \"optional\" of type integer does not support null values")
}
} else {
__optional = -1
}
val __reference : Int?
if (savedStateHandle.contains("reference")) {
__reference = savedStateHandle["reference"]
if (__reference == null) {
throw IllegalArgumentException("Argument \"reference\" of type reference does not support null values")
}
} else {
__reference = R.drawable.background
}
val __referenceZeroDefaultValue : Int?
if (savedStateHandle.contains("referenceZeroDefaultValue")) {
__referenceZeroDefaultValue = savedStateHandle["referenceZeroDefaultValue"]
if (__referenceZeroDefaultValue == null) {
throw IllegalArgumentException("Argument \"referenceZeroDefaultValue\" of type reference does not support null values")
}
} else {
__referenceZeroDefaultValue = 0
}
val __floatArg : Float?
if (savedStateHandle.contains("floatArg")) {
__floatArg = savedStateHandle["floatArg"]
if (__floatArg == null) {
throw IllegalArgumentException("Argument \"floatArg\" of type float does not support null values")
}
} else {
__floatArg = 1F
}
val __floatArrayArg : FloatArray?
if (savedStateHandle.contains("floatArrayArg")) {
__floatArrayArg = savedStateHandle["floatArrayArg"]
if (__floatArrayArg == null) {
throw IllegalArgumentException("Argument \"floatArrayArg\" is marked as non-null but was passed a null value")
}
} else {
throw IllegalArgumentException("Required argument \"floatArrayArg\" is missing and does not have an android:defaultValue")
}
val __objectArrayArg : Array<ActivityInfo>?
if (savedStateHandle.contains("objectArrayArg")) {
__objectArrayArg = savedStateHandle.get<Array<Parcelable>>("objectArrayArg")?.map { it as
ActivityInfo }?.toTypedArray()
if (__objectArrayArg == null) {
throw IllegalArgumentException("Argument \"objectArrayArg\" is marked as non-null but was passed a null value")
}
} else {
throw IllegalArgumentException("Required argument \"objectArrayArg\" is missing and does not have an android:defaultValue")
}
val __boolArg : Boolean?
if (savedStateHandle.contains("boolArg")) {
__boolArg = savedStateHandle["boolArg"]
if (__boolArg == null) {
throw IllegalArgumentException("Argument \"boolArg\" of type boolean does not support null values")
}
} else {
__boolArg = true
}
val __optionalParcelable : ActivityInfo?
if (savedStateHandle.contains("optionalParcelable")) {
if (Parcelable::class.java.isAssignableFrom(ActivityInfo::class.java) ||
Serializable::class.java.isAssignableFrom(ActivityInfo::class.java)) {
__optionalParcelable = savedStateHandle.get<ActivityInfo?>("optionalParcelable")
} else {
throw UnsupportedOperationException(ActivityInfo::class.java.name +
" must implement Parcelable or Serializable or must be an Enum.")
}
} else {
__optionalParcelable = null
}
val __enumArg : AccessMode?
if (savedStateHandle.contains("enumArg")) {
if (Parcelable::class.java.isAssignableFrom(AccessMode::class.java) ||
Serializable::class.java.isAssignableFrom(AccessMode::class.java)) {
__enumArg = savedStateHandle.get<AccessMode?>("enumArg")
} else {
throw UnsupportedOperationException(AccessMode::class.java.name +
" must implement Parcelable or Serializable or must be an Enum.")
}
if (__enumArg == null) {
throw IllegalArgumentException("Argument \"enumArg\" is marked as non-null but was passed a null value")
}
} else {
__enumArg = AccessMode.READ
}
return MainFragmentArgs(__main, __floatArrayArg, __objectArrayArg, __optional, __reference,
__referenceZeroDefaultValue, __floatArg, __boolArg, __optionalParcelable, __enumArg)
}
}
}
| apache-2.0 | 2992594def6aa5910298ce1b2f7512dc | 42.88968 | 131 | 0.666018 | 4.789515 | false | false | false | false |
bibaev/stream-debugger-plugin | src/main/java/com/intellij/debugger/streams/trace/dsl/impl/java/JavaMapVariable.kt | 1 | 1721 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.streams.trace.dsl.impl.java
import com.intellij.debugger.streams.trace.dsl.Expression
import com.intellij.debugger.streams.trace.dsl.Lambda
import com.intellij.debugger.streams.trace.dsl.VariableDeclaration
import com.intellij.debugger.streams.trace.dsl.impl.common.MapVariableBase
import com.intellij.debugger.streams.trace.impl.handler.type.MapType
/**
* @author Vitaliy.Bibaev
*/
class JavaMapVariable(type: MapType, name: String)
: MapVariableBase(type, name) {
override fun get(key: Expression): Expression = call("get", key)
override operator fun set(key: Expression, newValue: Expression): Expression = call("put", key, newValue)
override fun contains(key: Expression): Expression = call("containsKey", key)
override fun keys(): Expression = call("keySet")
override fun size(): Expression = call("size")
override fun computeIfAbsent(key: Expression, supplier: Lambda): Expression = call("computeIfAbsent", key, supplier)
override fun defaultDeclaration(isMutable: Boolean): VariableDeclaration =
JavaVariableDeclaration(this, false, type.defaultValue)
} | apache-2.0 | afbf99475181445802443c5661ba29ff | 39.046512 | 118 | 0.765253 | 4.127098 | false | false | false | false |
philo-dragon/CoolWeather-kotlin | app/src/main/java/com/pfl/coolweather/db/County.kt | 1 | 293 | package com.pfl.coolweather.db
import org.litepal.crud.DataSupport
/**
* Created by Administrator on 2017/10/6 0006.
*/
class County : DataSupport() {
var id: Int = 0
var contyCode: Int = 0
var name: String? = null
var weatherId: String? = null
var cityId: Int = 0
}
| apache-2.0 | d4297ac0cad55b71d60a24685b46db23 | 17.3125 | 46 | 0.651877 | 3.21978 | false | false | false | false |
qikh/kong-lang | src/main/kotlin/lexer/Lexer.kt | 1 | 3580 | package lexer
import token.Token
import token.TokenType
val EOF_CHAR = 0.toChar()
class Lexer(val input: String, var position: Int = 0, var readPosition: Int = 0, var ch: Char = EOF_CHAR) {
init {
readChar()
}
fun readChar() {
if (readPosition >= input.length) {
ch = EOF_CHAR
} else {
ch = input[readPosition]
}
position = readPosition
readPosition += 1
}
fun skipWhitespace() {
while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') {
readChar()
}
}
fun peekChar(): Char {
if (readPosition >= input.length) {
return EOF_CHAR
} else {
return input[readPosition]
}
}
fun readIdentifier(): String {
val positionSave = position
while (isLetter(ch)) {
readChar()
}
return input.substring(positionSave, position)
}
fun readNumber(): String {
val positionSave = position
while (isDigit(ch)) {
readChar()
}
return input.substring(positionSave, position)
}
fun isLetter(c: Char): Boolean {
return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || ch == '_'
}
fun isDigit(c: Char): Boolean {
return '0' <= c && c <= '9'
}
fun readString(): String {
val positionSave = position + 1
while (true) {
readChar()
if (ch == '"') {
break
}
}
return input.substring(positionSave, position)
}
fun nextToken(): Token {
var tok: Token
skipWhitespace()
when (ch) {
'=' -> if (peekChar() == '=') {
val chSave = ch
readChar()
tok = Token(token.EQ, String(charArrayOf(chSave, ch)))
} else {
tok = newToken(token.ASSIGN, ch)
}
'+' -> tok = newToken(token.PLUS, ch)
'-' -> tok = newToken(token.MINUS, ch)
'!' ->
if (peekChar() == '=') {
val chSave = ch
readChar()
tok = Token(token.NOT_EQ, String(charArrayOf(chSave, ch)))
} else {
tok = newToken(token.BANG, ch)
}
'/' -> tok = newToken(token.SLASH, ch)
'*' -> tok = newToken(token.ASTERISK, ch)
'<' -> tok = newToken(token.LT, ch)
'>' -> tok = newToken(token.GT, ch)
';' -> tok = newToken(token.SEMICOLON, ch)
',' -> tok = newToken(token.COMMA, ch)
'{' -> tok = newToken(token.LBRACE, ch)
'}' -> tok = newToken(token.RBRACE, ch)
'(' -> tok = newToken(token.LPAREN, ch)
')' -> tok = newToken(token.RPAREN, ch)
'"' -> tok = Token(token.STRING, readString())
EOF_CHAR -> tok = Token(token.EOF, "")
else ->
if (isLetter(ch)) {
val ident = readIdentifier()
tok = Token(token.lookupIdent(ident), ident)
return tok
} else if (isDigit(ch)) {
tok = Token(token.INT, readNumber())
return tok
} else {
tok = newToken(token.ILLEGAL, ch)
}
}
readChar()
return tok
}
fun newToken(tokenType: TokenType, ch: Char): Token {
return Token(tokenType, ch.toString())
}
}
| apache-2.0 | 09fedb1b236d7bb1362d994640995047 | 26.751938 | 107 | 0.443575 | 4.339394 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/cabal/export/SimpleCabalStep.kt | 1 | 2183 | package org.jetbrains.cabal.export
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.externalSystem.service.project.wizard.AbstractImportFromExternalSystemWizardStep
import com.intellij.openapi.options.ConfigurationException
import org.jetbrains.cabal.export.ImportFromCabalControl
import org.jetbrains.cabal.settings.CabalProjectSettings
import javax.swing.*
import java.awt.*
import com.intellij.openapi.externalSystem.service.settings.AbstractImportFromExternalSystemControl
import com.intellij.openapi.externalSystem.service.project.wizard.AbstractExternalProjectImportBuilder
public class SimpleCabalStep(context: WizardContext) : AbstractImportFromExternalSystemWizardStep(context) {
private val myComponent = JPanel(BorderLayout())
private var mySettingsInitialised = false
private var myControl: ImportFromCabalControl? = null
override fun getBuilder(): CabalProjectImportBuilder? {
return getWizardContext().getProjectBuilder() as CabalProjectImportBuilder
}
override fun getComponent(): JComponent {
return myComponent
}
override fun getWizardContext(): WizardContext {
return super.getWizardContext()!!
}
override fun updateStep() {
if (!mySettingsInitialised) {
initSimpleCabalControl()
}
}
override fun updateDataModel() {
}
throws(ConfigurationException::class)
override fun validate(): Boolean {
myControl?.apply()
if (myControl?.getProjectFormatPanel() != null) {
myControl!!.getProjectFormatPanel()!!.updateData(getWizardContext())
}
val builder = getBuilder()
if (builder == null) {
return false
}
builder.ensureProjectIsDefined(getWizardContext())
return true
}
private fun initSimpleCabalControl() {
val builder = getBuilder()
if (builder == null) {
return
}
builder.prepare(getWizardContext())
myControl = builder.getControl(getWizardContext().getProject())
myComponent.add(myControl!!.getComponent())
mySettingsInitialised = true
}
} | apache-2.0 | cd825edf5245393e964ee97f45267b43 | 31.597015 | 108 | 0.715987 | 5.197619 | false | false | false | false |
anlun/haskell-idea-plugin | generator/src/org/jetbrains/generator/Main.kt | 1 | 1938 | package org.jetbrains.generator
import java.io.FileReader
import java.util.ArrayList
import org.jetbrains.generator.grammar.Grammar
import org.jetbrains.generator.grammar.Rule
import org.jetbrains.generator.grammar.Variant
import java.util.HashMap
import org.jetbrains.generator.grammar.NonFinalVariant
import org.jetbrains.generator.grammar.RuleRef
/**
* Created by atsky on 11/7/14.
*/
fun getTokens(lexer : GrammarLexer) : List<Token> {
val list = ArrayList<Token>();
while (true) {
val tokenType = lexer.yylex()
if (tokenType == null) {
break
}
if (tokenType == TokenType.BLOCK_COMMENT) {
continue
}
if (tokenType == TokenType.EOL_COMMENT) {
continue
}
list.add(Token(tokenType, lexer.yytext()))
}
return list;
}
fun main(args : Array<String>) {
val lexer = GrammarLexer(FileReader("./plugin/haskell.grm"))
val grammarParser = GrammarParser(getTokens(lexer))
val grammar = grammarParser.parseGrammar()!!
val generator = ParserGenerator(mergeGrammar(grammar))
generator.generate()
}
fun mergeGrammar(grammar: Grammar): Grammar {
val newRules = ArrayList<Rule>()
for (rule in grammar.rules) {
newRules.add(Rule(rule.name, merge(rule.variants)))
}
return Grammar(grammar.tokens, newRules)
}
fun merge(variants: List<Variant>): List<Variant> {
val result = ArrayList<Variant>()
val map = HashMap<RuleRef, ArrayList<Variant>>()
for (variant in variants) {
if (variant is NonFinalVariant) {
val name = variant.atom
if (!map.contains(name)) {
map[name] = ArrayList<Variant>()
}
map[name].addAll(variant.next)
} else {
result.add(variant)
}
}
for ((name, vars) in map) {
result.add(NonFinalVariant(name, merge(vars)))
}
return result
} | apache-2.0 | 21b4dcf8b4be30eb99fbe1bcbd7555dc | 26.309859 | 64 | 0.635191 | 4.012422 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/subject/nine/module/text/SingleTextFragment.kt | 1 | 3430 | package com.intfocus.template.subject.nine.module.text
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.intfocus.template.R
import com.intfocus.template.constant.Params
import com.intfocus.template.constant.Params.ARG_PARAM
import com.intfocus.template.ui.BaseModuleFragment
import kotlinx.android.synthetic.main.module_single_text.*
/**
* @author liuruilin
* @data 2017/11/2
* @describe
*/
class SingleTextFragment : BaseModuleFragment(), TextModuleContract.View {
private var rootView: View? = null
private lateinit var datas: TextEntity
private var param: String? = null
private var key: String? = null
private var listItemType: Int = 0
override lateinit var presenter: TextModuleContract.Presenter
companion object {
private val LIST_ITEM_TYPE = "list_item_type"
fun newInstance(param: String?, key: String?, listItemType: Int): SingleTextFragment {
val fragment = SingleTextFragment()
val args = Bundle()
args.putString(ARG_PARAM, param)
args.putString(Params.KEY, key)
args.putString(Params.KEY, key)
args.putInt(LIST_ITEM_TYPE, listItemType)
fragment.arguments = args
return fragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
param = arguments!!.getString(ARG_PARAM)
key = arguments!!.getString(Params.KEY)
listItemType = arguments!!.getInt(LIST_ITEM_TYPE)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (null == rootView) {
rootView = inflater.inflate(R.layout.module_single_text, container, false)
}
return rootView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
param?.let { presenter.loadData(it) }
initView()
}
override fun onDestroy() {
super.onDestroy()
TextModelImpl.destroyInstance()
}
private fun initView() {
et_single_text.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun afterTextChanged(p0: Editable?) {
datas.value = p0.toString()
key?.let { presenter.update(datas, it,listItemType) }
}
})
}
override fun initModule(entity: TextEntity) {
datas = entity
if (entity.element_type.trim().isEmpty()) iv_single_text_element.visibility = View.GONE else iv_single_text_element.setImageResource(getElementResourceId(entity.element_type))
if (entity.title.trim().isEmpty()) tv_single_text_title.visibility = View.GONE else tv_single_text_title.text = entity.title
if (entity.hint.trim().isEmpty()) et_single_text.hint = "" else et_single_text.hint = entity.hint
}
private fun getElementResourceId(element: String): Int {
when (element) {
"" -> return 0
}
return 0
}
}
| gpl-3.0 | e8ec847626eb3d8c8a9f2bf34e18337d | 34 | 183 | 0.657726 | 4.352792 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/domain/latex/model/block/LatexScriptBlock.kt | 2 | 1083 | package org.stepik.android.domain.latex.model.block
class LatexScriptBlock : ContentBlock {
override val header: String = """
<link rel="stylesheet" href="file:///android_asset/katex/katex.min.css" />
<script src="file:///android_asset/katex/katex.min.js" ></script>
<script src="file:///android_asset/katex/auto-render.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
renderMathInElement(document.body, {
delimiters: [
{left: "$$", right: "$$", display: true},
{left: "\\[", right: "\\]", display: true},
{left: "$", right: "$", display: false},
{left: "\\(", right: "\\)", display: false}
]
});
});
</script>
""".trimIndent()
override fun isEnabled(content: String): Boolean =
"$" in content ||
"\\[" in content ||
"math-tex" in content ||
"\\(" in content
} | apache-2.0 | 896b8ede8ee7c83b4f1f73c8c851196a | 39.148148 | 82 | 0.485688 | 4.45679 | false | false | false | false |
Axlchen/SuperFootball | app/src/main/java/com/axlchen/superfootball/ui/MainActivity.kt | 1 | 2533 | package com.axlchen.superfootball.ui
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import com.axlchen.superfootball.R
import com.axlchen.superfootball.repository.hupu.NewsRepository
import com.axlchen.superfootball.repository.hupu.data.News
import com.axlchen.superfootball.repository.hupu.data.NewsData
import com.axlchen.superfootball.repository.hupu.data.NewsList
import com.axlchen.superfootball.ui.adapters.NewsAdapter
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import com.axlchen.superfootball.domain.hupu.model.News as ModelNews
import com.axlchen.superfootball.domain.hupu.model.NewsList as ModelNewsList
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initView()
initData()
}
private fun initData() {
NewsRepository().getNews(object : Callback<NewsData> {
override fun onFailure(call: Call<NewsData>, t: Throwable) {
Log.d("Axlchen:onFailure", t.message)
}
override fun onResponse(call: Call<NewsData>, response: Response<NewsData>) {
Log.d("Axlchen:onResponse", response.body().toString())
if (response.isSuccessful) {
val newsListData = response.body()?.list!!
newsList.adapter = NewsAdapter(convertDataToDomain(newsListData))
}
}
})
}
private fun convertDataToDomain(data: NewsList): ModelNewsList {
return ModelNewsList(data.nextDataExists == 1, convertNewsListToDomain(data.newsList))
}
private fun convertNewsListToDomain(list: List<News>): List<ModelNews> {
val res = list.map { news ->
convertNewsItemToDomain(news)
}
return res.filter { it.type == 1 }
}
private fun convertNewsItemToDomain(news: News) = with(news) {
ModelNews(news.nid, news.title, news.summary, news.uptime, news.img, news.type,
news.lights, news.replies, news.read)
}
private fun initView() {
newsList.layoutManager = LinearLayoutManager(this)
newsList.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
}
}
| apache-2.0 | 3307b09c074c139de66d591b8003f2df | 35.710145 | 95 | 0.702724 | 4.078905 | false | false | false | false |
da1z/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/uast/GroovyDummyUastPlugin.kt | 2 | 4588 | // 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 org.jetbrains.plugins.groovy.lang.psi.uast
import com.intellij.lang.Language
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parents
import org.jetbrains.plugins.groovy.GroovyLanguage
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.uast.*
/**
* This is a very limited implementation of UastPlugin for Groovy,
* provided only to make Groovy play with UAST-based [com.intellij.jam.JamReferenceContributor]
*/
class GroovyDummyUastPlugin : UastLanguagePlugin {
override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? =
convertElementWithParent(element, { parent }, requiredType)
override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? =
convertElementWithParent(element, { makeUParent(element) }, requiredType)
private fun convertElementWithParent(element: PsiElement,
parentProvider: () -> UElement?,
requiredType: Class<out UElement>?): UElement? =
when (element) {
is GrLiteral -> GrULiteral(element, parentProvider)
is GrAnnotationNameValuePair -> GrUNamedExpression(element, parentProvider)
is GrAnnotation -> GrUAnnotation(element, parentProvider)
else -> null
}?.takeIf { requiredType?.isAssignableFrom(it.javaClass) ?: true }
private fun makeUParent(element: PsiElement) =
element.parent.parents().mapNotNull { convertElementWithParent(it, null) }.firstOrNull()
override fun getMethodCallExpression(element: PsiElement,
containingClassFqName: String?,
methodName: String): UastLanguagePlugin.ResolvedMethod? = null //not implemented
override fun getConstructorCallExpression(element: PsiElement,
fqName: String): UastLanguagePlugin.ResolvedConstructor? = null //not implemented
override fun isExpressionValueUsed(element: UExpression): Boolean = TODO("not implemented")
override val priority = 0
override fun isFileSupported(fileName: String) = fileName.endsWith(".groovy", ignoreCase = true)
override val language: Language = GroovyLanguage
}
class GrULiteral(val grElement: GrLiteral, val parentProvider: () -> UElement?) : ULiteralExpression, JvmDeclarationUElement {
override val value: Any?
get() = grElement.value
override val uastParent by lazy(parentProvider)
override val psi: PsiElement? = grElement
override val annotations: List<UAnnotation> = emptyList() //not implemented
}
class GrUNamedExpression(val grElement: GrAnnotationNameValuePair, val parentProvider: () -> UElement?) : UNamedExpression, JvmDeclarationUElement {
override val name: String?
get() = grElement.name
override val expression: UExpression
get() = grElement.value.toUElementOfType() ?: GrUnknownUExpression(grElement.value, this)
override val uastParent by lazy(parentProvider)
override val psi = grElement
override val annotations: List<UAnnotation> = emptyList() //not implemented
}
class GrUAnnotation(val grElement: GrAnnotation, val parentProvider: () -> UElement?) : UAnnotation, JvmDeclarationUElement {
override val qualifiedName: String?
get() = grElement.qualifiedName
override fun resolve(): PsiClass? = grElement.nameReferenceElement?.resolve() as PsiClass?
override val attributeValues: List<UNamedExpression> by lazy {
grElement.parameterList.attributes.map {
GrUNamedExpression(it, { this })
}
}
override fun findAttributeValue(name: String?): UExpression? = null //not implemented
override fun findDeclaredAttributeValue(name: String?): UExpression? = null //not implemented
override val uastParent by lazy(parentProvider)
override val psi: PsiElement? = grElement
}
class GrUnknownUExpression(override val psi: PsiElement?, override val uastParent: UElement?) : UExpression, JvmDeclarationUElement {
override fun asLogString(): String = "GrUnknownUExpression(grElement)"
override val annotations: List<UAnnotation> = emptyList() //not implemented
} | apache-2.0 | 4a177a16c855307acdaa8ce24085833e | 43.125 | 148 | 0.744987 | 5.114827 | false | false | false | false |
maiconhellmann/pomodoro | app/src/test/java/br/com/maiconhellmann/pomodoro/DatabaseHelperTest.kt | 1 | 1204 | package br.com.maiconhellmann.pomodoro
import br.com.maiconhellmann.pomodoro.data.local.DatabaseHelper
import br.com.maiconhellmann.pomodoro.data.local.DbOpenHelper
import br.com.maiconhellmann.pomodoro.util.DefaultConfig
import br.com.maiconhellmann.pomodoro.util.RxSchedulersOverrideRule
import com.squareup.sqlbrite.SqlBrite
import org.junit.Rule
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import rx.android.schedulers.AndroidSchedulers
/**
* Unit tests integration with a SQLite Database using Robolectric
*/
@RunWith(RobolectricTestRunner::class)
@Config(constants = BuildConfig::class, sdk = intArrayOf(DefaultConfig.EMULATE_SDK))
class DatabaseHelperTest {
@Rule @JvmField
val overrideSchedulersRule = RxSchedulersOverrideRule()
val databaseHelper: DatabaseHelper by lazy {
val dbHelper = DbOpenHelper(RuntimeEnvironment.application)
val sqlBrite = SqlBrite.Builder()
.build()
.wrapDatabaseHelper(dbHelper, AndroidSchedulers.mainThread())
DatabaseHelper(sqlBrite)
}
}
| apache-2.0 | 14bc264675182c439719b73071c23250 | 34.484848 | 84 | 0.767442 | 4.666667 | false | true | false | false |
hurricup/intellij-community | platform/configuration-store-impl/src/DirectoryBasedStorage.kt | 1 | 8857 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.StateSplitter
import com.intellij.openapi.components.StateSplitterEx
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.DirectoryStorageUtil
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.components.impl.stores.StateStorageBase
import com.intellij.openapi.util.Pair
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.*
import com.intellij.util.containers.SmartHashSet
import gnu.trove.THashMap
import org.jdom.Element
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.file.Path
abstract class DirectoryBasedStorageBase(@Suppress("DEPRECATION") protected val splitter: StateSplitter,
protected val pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null) : StateStorageBase<StateMap>() {
protected var componentName: String? = null
protected abstract val virtualFile: VirtualFile?
override fun loadData() = StateMap.fromMap(DirectoryStorageUtil.loadFrom(virtualFile, pathMacroSubstitutor))
override fun startExternalization(): StateStorage.ExternalizationSession? = null
override fun analyzeExternalChangesAndUpdateIfNeed(componentNames: MutableSet<String>) {
// todo reload only changed file, compute diff
val newData = loadData()
storageDataRef.set(newData)
if (componentName != null) {
componentNames.add(componentName!!)
}
}
override fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean): Element? {
this.componentName = componentName
if (storageData.isEmpty()) {
return null
}
val state = Element(FileStorageCoreUtil.COMPONENT)
if (splitter is StateSplitterEx) {
for (fileName in storageData.keys()) {
val subState = storageData.getState(fileName, archive) ?: return null
splitter.mergeStateInto(state, subState)
}
}
else {
val subElements = SmartList<Element>()
for (fileName in storageData.keys()) {
val subState = storageData.getState(fileName, archive) ?: return null
subElements.add(subState)
}
if (!subElements.isEmpty()) {
splitter.mergeStatesInto(state, subElements.toTypedArray())
}
}
return state
}
override fun hasState(storageData: StateMap, componentName: String) = storageData.hasStates()
}
open class DirectoryBasedStorage(private val dir: Path,
@Suppress("DEPRECATION") splitter: StateSplitter,
pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null) : DirectoryBasedStorageBase(splitter, pathMacroSubstitutor) {
private @Volatile var cachedVirtualFile: VirtualFile? = null
override val virtualFile: VirtualFile?
get() {
var result = cachedVirtualFile
if (result == null) {
result = LocalFileSystem.getInstance().findFileByPath(dir.systemIndependentPath)
cachedVirtualFile = result
}
return result
}
internal fun setVirtualDir(dir: VirtualFile?) {
cachedVirtualFile = dir
}
override fun startExternalization(): StateStorage.ExternalizationSession? = if (checkIsSavingDisabled()) null else MySaveSession(this, getStorageData())
private class MySaveSession(private val storage: DirectoryBasedStorage, private val originalStates: StateMap) : SaveSessionBase() {
private var copiedStorageData: MutableMap<String, Any>? = null
private val dirtyFileNames = SmartHashSet<String>()
private var someFileRemoved = false
override fun setSerializedState(componentName: String, element: Element?) {
storage.componentName = componentName
if (element.isEmpty()) {
if (copiedStorageData != null) {
copiedStorageData!!.clear()
}
else if (!originalStates.isEmpty()) {
copiedStorageData = THashMap<String, Any>()
}
}
else {
val stateAndFileNameList = storage.splitter.splitState(element!!)
for (pair in stateAndFileNameList) {
doSetState(pair.second, pair.first)
}
outerLoop@
for (key in originalStates.keys()) {
for (pair in stateAndFileNameList) {
if (pair.second == key) {
continue@outerLoop
}
}
if (copiedStorageData == null) {
copiedStorageData = originalStates.toMutableMap()
}
someFileRemoved = true
copiedStorageData!!.remove(key)
}
}
}
private fun doSetState(fileName: String, subState: Element) {
if (copiedStorageData == null) {
copiedStorageData = setStateAndCloneIfNeed(fileName, subState, originalStates)
if (copiedStorageData != null) {
dirtyFileNames.add(fileName)
}
}
else if (updateState(copiedStorageData!!, fileName, subState)) {
dirtyFileNames.add(fileName)
}
}
override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStorageData == null) null else this
override fun save() {
val stateMap = StateMap.fromMap(copiedStorageData!!)
var dir = storage.virtualFile
if (copiedStorageData!!.isEmpty()) {
if (dir != null && dir.exists()) {
deleteFile(this, dir)
}
storage.setStorageData(stateMap)
return
}
if (dir == null || !dir.isValid) {
dir = createDir(storage.dir, this)
storage.cachedVirtualFile = dir
}
if (!dirtyFileNames.isEmpty) {
saveStates(dir, stateMap)
}
if (someFileRemoved && dir.exists()) {
deleteFiles(dir)
}
storage.setStorageData(stateMap)
}
private fun saveStates(dir: VirtualFile, states: StateMap) {
val storeElement = Element(FileStorageCoreUtil.COMPONENT)
for (fileName in states.keys()) {
if (!dirtyFileNames.contains(fileName)) {
continue
}
var element: Element? = null
try {
element = states.getElement(fileName) ?: continue
storage.pathMacroSubstitutor?.collapsePaths(element)
storeElement.setAttribute(FileStorageCoreUtil.NAME, storage.componentName!!)
storeElement.addContent(element)
val file = getFile(fileName, dir, this)
// we don't write xml prolog due to historical reasons (and should not in any case)
writeFile(null, this, file, storeElement, LineSeparator.fromString(if (file.exists()) loadFile(file).second else SystemProperties.getLineSeparator()), false)
}
catch (e: IOException) {
LOG.error(e)
}
finally {
if (element != null) {
element.detach()
}
}
}
}
private fun deleteFiles(dir: VirtualFile) {
runWriteAction {
for (file in dir.children) {
val fileName = file.name
if (fileName.endsWith(FileStorageCoreUtil.DEFAULT_EXT) && !copiedStorageData!!.containsKey(fileName)) {
if (file.isWritable) {
file.delete(this)
}
else {
throw ReadOnlyModificationException(file, null)
}
}
}
}
}
}
private fun setStorageData(newStates: StateMap) {
storageDataRef.set(newStates)
}
}
private val NON_EXISTENT_FILE_DATA = Pair.create<ByteArray, String>(null, SystemProperties.getLineSeparator())
/**
* @return pair.first - file contents (null if file does not exist), pair.second - file line separators
*/
private fun loadFile(file: VirtualFile?): Pair<ByteArray, String> {
if (file == null || !file.exists()) {
return NON_EXISTENT_FILE_DATA
}
val bytes = file.contentsToByteArray()
val lineSeparator = file.detectedLineSeparator ?: detectLineSeparators(Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)), null).separatorString
return Pair.create<ByteArray, String>(bytes, lineSeparator)
} | apache-2.0 | 23373b5f432af4d6925ab4eae474d57a | 33.874016 | 167 | 0.676414 | 5.003955 | false | false | false | false |
java-opengl-labs/ogl-samples | src/main/kotlin/ogl_samples/framework/Test.kt | 1 | 12332 | package ogl_samples.framework
import gli.Texture2d
import glm_.glm
import glm_.mat4x4.Mat4
import glm_.vec2.Vec2
import glm_.vec2.Vec2i
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.glfw.GLFWKeyCallbackI
import org.lwjgl.glfw.GLFWMouseButtonCallbackI
import org.lwjgl.opengl.ARBES2Compatibility.GL_IMPLEMENTATION_COLOR_READ_FORMAT
import org.lwjgl.opengl.ARBES2Compatibility.GL_IMPLEMENTATION_COLOR_READ_TYPE
import org.lwjgl.opengl.GL
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL30.*
import org.lwjgl.opengl.GL32.GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS
import org.lwjgl.system.Platform
import uno.buffer.intBufferBig
import uno.caps.Caps.Profile
import uno.glfw.GlfwWindow
import uno.glfw.glfw
import uno.gln.checkError
import uno.gln.glBindFramebuffer
/**
* Created by GBarbieri on 27.03.2017.
*/
val DEBUG = true
val APPLE = Platform.get() == Platform.MACOSX
val EXIT_SUCCESS = false
val EXIT_FAILURE = true
var AUTOMATED_TESTS = false
abstract class Test(
val title: String,
val profile: Profile, val major: Int, val minor: Int,
val windowSize: Vec2i = Vec2i(640, 480),
orientation: Vec2 = Vec2(0),
position: Vec2 = Vec2(0, 4),
val frameCount: Int = 2,
val success: Success = Success.MATCH_TEMPLATE,
val heuristic: Heuristic = Heuristic.ALL) {
val dataDirectory = "data/"
init {
assert(windowSize.x > 0 && windowSize.y > 0)
glfw.init()
glfw.windowHint {
resizable = false
visible = true
srgb = false
decorated = true
val t = this@Test
api = if (t.profile == Profile.ES) "es" else "gl"
if (version(t.major, t.minor) >= version(3, 2) || t.profile == Profile.ES) {
context.version = "${t.major}.${t.minor}"
if (APPLE) {
profile = "core"
forwardComp = true
}
if (t.profile != Profile.ES) {
profile = if (t.profile == Profile.CORE) "core" else "compat"
forwardComp = t.profile == Profile.CORE
}
debug = DEBUG
}
}
}
val window = run {
val dpi = if (APPLE) 2 else 1
GlfwWindow(windowSize / dpi, title)
}
init {
if (window.handle != 0L) with(window) {
pos = Vec2i(64)
glfwSetMouseButtonCallback(handle, MouseButtonCallback())
glfwSetKeyCallback(handle, KeyCallback())
makeContextCurrent()
GL.createCapabilities()
show()
}
}
constructor(title: String, profile: Profile, major: Int, minor: Int,
frameCount: Int,
success: Success,
windowSize: Vec2i)
: this(title, profile, major, minor, windowSize, Vec2(0), Vec2(0), frameCount, success)
constructor(title: String, profile: Profile, major: Int, minor: Int,
frameCount: Int,
windowSize: Vec2i = Vec2i(640, 480),
orientation: Vec2 = Vec2(0),
position: Vec2 = Vec2(0, 4))
: this(title, profile, major, minor, windowSize, orientation, position, frameCount, Success.RUN_ONLY)
constructor(title: String, profile: Profile, major: Int, minor: Int,
orientation: Vec2,
success: Success = Success.MATCH_TEMPLATE)
: this(title, profile, major, minor, Vec2i(640, 480), orientation, Vec2(0, 4), 2, success)
constructor(title: String, profile: Profile, major: Int, minor: Int,
heuristic: Heuristic)
: this(title, profile, major, minor, Vec2i(640, 480), Vec2(0), Vec2(0, 4), 2, Success.MATCH_TEMPLATE, heuristic)
val timeQueryName = intBufferBig(1)
var timeSum = 0.0
var timeMin = Double.MAX_VALUE
var timeMax = 0.0
var mouseOrigin = Vec2(windowSize shr 1)
var mouseCurrent = Vec2(windowSize shr 1)
var translationOrigin = Vec2(position)
var translationCurrent = Vec2(position)
var rotationOrigin = Vec2(orientation)
var rotationCurrent = Vec2(orientation)
var mouseButtonFlags = 0
val keyPressed = BooleanArray(512, { false })
var error = false
val caps = Caps(profile)
init {
glGetError() // consume caps vec2 error, FIXME
}
abstract fun begin(): Boolean
abstract fun render(): Boolean
abstract fun end(): Boolean
private fun endInternal(): Boolean {
val result = end()
window.destroy()
return result
}
fun loop(): Boolean {
if (window.handle == 0L)
return EXIT_FAILURE
var result = EXIT_SUCCESS
if (version(major, minor) >= version(3, 0))
result = if (checkGLVersion(major, minor)) EXIT_SUCCESS else EXIT_FAILURE
if (result == EXIT_SUCCESS)
result = if (begin()) EXIT_SUCCESS else EXIT_FAILURE
var frameNum = frameCount
while (result == EXIT_SUCCESS && !error) {
result = if (render()) EXIT_SUCCESS else EXIT_FAILURE
result = result && checkError("render")
glfwPollEvents()
if (window.close || (AUTOMATED_TESTS && frameCount == 0)) {
if (success == Success.MATCH_TEMPLATE) {
if (!checkTemplate(window.handle, title))
result = EXIT_FAILURE
checkError("checkTemplate")
}
break
}
swap()
if (AUTOMATED_TESTS) --frameNum
}
if (result == EXIT_SUCCESS)
result = endInternal() && if (result == EXIT_SUCCESS) EXIT_SUCCESS else EXIT_FAILURE
return if (success == Success.GENERATE_ERROR)
if (result != EXIT_SUCCESS || error) EXIT_SUCCESS else EXIT_FAILURE
else
if (result == EXIT_SUCCESS || !error) EXIT_SUCCESS else EXIT_FAILURE
}
fun swap() = glfwSwapBuffers(window.handle)
fun checkTemplate(pWindow: Long, title: String): Boolean {
val colorType = if (profile == Profile.ES) glGetInteger(GL_IMPLEMENTATION_COLOR_READ_TYPE) else GL_UNSIGNED_BYTE
val colorFormat = if (profile == Profile.ES) glGetInteger(GL_IMPLEMENTATION_COLOR_READ_FORMAT) else GL_RGBA
val windowSize = window.framebufferSize
val textureRead = Texture2d(if (colorFormat == GL_RGBA) gli.Format.RGBA8_UNORM_PACK8 else gli.Format.RGB8_UNORM_PACK8, windowSize, 1)
val textureRGB = Texture2d(gli.Format.RGB8_UNORM_PACK8, windowSize, 1)
glBindFramebuffer()
glReadPixels(0, 0, windowSize.x, windowSize.y, colorFormat, colorType,
if (textureRead.format == gli.Format.RGBA8_UNORM_PACK8) textureRead.data() else textureRGB.data())
if (textureRead.format == gli.Format.RGBA8_UNORM_PACK8) {
for (y in 0 until textureRGB.extent().y)
for (x in 0 until textureRGB.extent().x) {
val texelCoord = Vec2i(x, y)
// val color = textureRead.load < glm::u8vec4 > (texelCoord, 0)
// textureRGB.store(texelCoord, 0, color)
}
}
return true // TODO
}
fun checkFramebuffer(): Boolean {
val status = glCheckFramebufferStatus(GL_FRAMEBUFFER)
return if (status != GL_FRAMEBUFFER_COMPLETE) {
println("OpenGL Error(${when (status) {
GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT -> "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"
GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT -> "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"
GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER -> "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"
GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER -> "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"
GL_FRAMEBUFFER_UNSUPPORTED -> "GL_FRAMEBUFFER_UNSUPPORTED"
GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE -> "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"
GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS -> "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"
else -> "GL_FRAMEBUFFER_UNDEFINED" // TODO there is enum
}})")
false
} else true
}
val view: Mat4
get() {
val viewTranslate = Mat4().translate(0f, 0f, -translationCurrent.y)
val viewRotateX = viewTranslate.rotate(rotationCurrent.y, 1f, 0f, 0f)
return viewRotateX.rotate(rotationCurrent.x, 0f, 1f, 0f)
}
enum class Heuristic(val i: Int) {
EQUAL_BIT(1 shl 0),
ABSOLUTE_DIFFERENCE_MAX_ONE_BIT(1 shl 1),
ABSOLUTE_DIFFERENCE_MAX_ONE_KERNEL_BIT(1 shl 2),
ABSOLUTE_DIFFERENCE_MAX_ONE_LARGE_KERNEL_BIT(1 shl 3),
MIPMAPS_ABSOLUTE_DIFFERENCE_MAX_ONE_BIT(1 shl 4),
MIPMAPS_ABSOLUTE_DIFFERENCE_MAX_FOUR_BIT(1 shl 5),
MIPMAPS_ABSOLUTE_DIFFERENCE_MAX_CHANNEL_BIT(1 shl 6),
ALL(EQUAL_BIT or ABSOLUTE_DIFFERENCE_MAX_ONE_BIT or ABSOLUTE_DIFFERENCE_MAX_ONE_KERNEL_BIT.i or
ABSOLUTE_DIFFERENCE_MAX_ONE_LARGE_KERNEL_BIT.i or MIPMAPS_ABSOLUTE_DIFFERENCE_MAX_ONE_BIT.i or
MIPMAPS_ABSOLUTE_DIFFERENCE_MAX_FOUR_BIT.i);
infix fun or(b: Heuristic) = i or b.i
}
enum class Vendor { DEFAULT, AMD, INTEL, NVIDIA, MAX }
enum class SyncMode { VSYNC, ASYNC, TEARING }
enum class Success { RUN_ONLY, GENERATE_ERROR, MATCH_TEMPLATE }
fun version(major: Int, minor: Int) = major * 100 + minor * 10
fun checkGLVersion(majorVersionRequire: Int, minorVersionRequire: Int): Boolean {
val majorVersionContext = glGetInteger(GL_MAJOR_VERSION)
val minorVersionContext = glGetInteger(GL_MINOR_VERSION)
val api = if(profile != Profile.ES) "OpenGL" else "OpenGL ES"
println("$api Version Needed $majorVersionRequire.$minorVersionRequire ( $majorVersionContext.$minorVersionContext Found )")
return version(majorVersionContext, minorVersionContext) >= version(majorVersionContext, minorVersionContext)
}
inner class MouseButtonCallback : GLFWMouseButtonCallbackI {
override fun invoke(window: Long, button: Int, action: Int, mods: Int) {
when (action) {
GLFW_PRESS -> {
mouseOrigin put mouseCurrent
when (button) {
GLFW_MOUSE_BUTTON_LEFT -> {
mouseButtonFlags = mouseButtonFlags or MouseButton.LEFT
translationOrigin put translationCurrent
}
GLFW_MOUSE_BUTTON_MIDDLE -> mouseButtonFlags = mouseButtonFlags or MouseButton.MIDDLE
GLFW_MOUSE_BUTTON_RIGHT -> {
mouseButtonFlags = mouseButtonFlags or MouseButton.RIGHT
rotationOrigin put rotationCurrent
}
}
}
GLFW_RELEASE -> when (button) {
GLFW_MOUSE_BUTTON_LEFT -> {
translationOrigin += (mouseCurrent - mouseOrigin) / 10f
mouseButtonFlags and MouseButton.LEFT.inv()
}
GLFW_MOUSE_BUTTON_MIDDLE -> mouseButtonFlags = mouseButtonFlags and MouseButton.MIDDLE.inv()
GLFW_MOUSE_BUTTON_RIGHT -> {
rotationOrigin += glm.radians(mouseCurrent - mouseOrigin)
mouseButtonFlags = mouseButtonFlags and MouseButton.RIGHT.inv()
}
}
}
}
}
inner class KeyCallback : GLFWKeyCallbackI {
override fun invoke(window: Long, key: Int, scancode: Int, action: Int, mods: Int) {
if (key < 0) return
keyPressed[key] = action == Key.PRESS
if (isKeyPressed(GLFW_KEY_ESCAPE))
[email protected] = true
}
}
fun isKeyPressed(key: Int) = keyPressed[key]
object MouseButton {
val NONE = 0
val LEFT = 1 shl 0
val RIGHT = 1 shl 1
val MIDDLE = 1 shl 2
}
object Key {
val PRESS = GLFW_PRESS
val RELEASE = GLFW_RELEASE
val REPEAT = GLFW_REPEAT
}
} | mit | bb4a3137d5ec805d6740a4107940e1b5 | 35.92515 | 141 | 0.594145 | 4.23489 | false | false | false | false |
abigpotostew/easypolitics | web/src/main/kotlin/bz/stewart/bracken/web/view/browse/IntroDateFilter.kt | 1 | 984 | package bz.stewart.bracken.web.view.browse
import bz.stewart.bracken.web.extension.setId
import bz.stewart.bracken.web.html.ViewRender
import bz.stewart.bracken.web.service.WebPageContext
import kotlinx.html.*
class IntroDateFilter :ViewRender {
override fun renderIn(parent: FlowContent, context: WebPageContext) {
parent.form(classes = "form-inline mr-sm-2") {
label(classes = "mr-sm-2") {
attributes.put("for", "billFilter-dateintrostart")
+"Introduced Start:"
}
input(classes = "form-inline form-control") {
setId("billFilter-dateintrostart")
attributes.put("type", "date")
}
label(classes = "mr-sm-2") {
attributes.put("for", "billFilter-dateintroend")
+"Introduced End:"
}
input(classes = "form-inline form-control") {
setId("billFilter-dateintroend")
attributes.put("type", "date")
}
}
}
} | apache-2.0 | b7460671ffcf8cbe823c656cbbd45ddb | 32.965517 | 72 | 0.609756 | 3.874016 | false | false | false | false |
duncte123/SkyBot | src/main/kotlin/ml/duncte123/skybot/commands/music/SkipCommand.kt | 1 | 3482 | /*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32"
*
* 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 <https://www.gnu.org/licenses/>.
*/
package ml.duncte123.skybot.commands.music
import me.duncte123.botcommons.messaging.MessageUtils.sendMsg
import ml.duncte123.skybot.Settings.NO_STATIC
import ml.duncte123.skybot.Settings.YES_STATIC
import ml.duncte123.skybot.audio.GuildMusicManager
import ml.duncte123.skybot.objects.TrackUserData
import ml.duncte123.skybot.objects.command.CommandContext
import ml.duncte123.skybot.objects.command.MusicCommand
import kotlin.math.ceil
class SkipCommand : MusicCommand() {
init {
this.name = "skip"
this.aliases = arrayOf("next", "nexttrack", "skiptrack")
this.help = "Skips the current track"
}
override fun run(ctx: CommandContext) {
val mng = ctx.audioUtils.getMusicManager(ctx.guild)
val player = mng.player
if (player.playingTrack == null) {
sendMsg(ctx, "The player is not playing.")
return
}
if (!player.playingTrack.isSeekable) {
sendMsg(ctx, "This track is not seekable")
return
}
val author = ctx.author
val trackData = player.playingTrack.getUserData(TrackUserData::class.java)
if (trackData.requester == author.idLong) {
doSkip(ctx, mng)
return
}
// https://github.com/jagrosh/MusicBot/blob/master/src/main/java/com/jagrosh/jmusicbot/commands/music/SkipCmd.java
val listeners = getLavalinkManager()
.getConnectedChannel(ctx.guild)
.members.filter {
!it.user.isBot && !(it.voiceState?.isDeafened ?: false)
}.count()
val votes = trackData.votes
var msg = if (votes.contains(author.idLong)) {
"$NO_STATIC You already voted to skip this song `["
} else {
votes.add(author.idLong)
"$YES_STATIC Successfully voted to skip the song `["
}
val skippers = getLavalinkManager().getConnectedChannel(ctx.guild)
.members.filter { votes.contains(it.idLong) }.count()
val required = ceil(listeners * .55).toInt()
msg += "$skippers votes, $required/$listeners needed]`"
sendMsg(ctx, msg)
if (skippers >= required) {
doSkip(ctx, mng)
}
}
private fun doSkip(ctx: CommandContext, mng: GuildMusicManager) {
val player = mng.player
// player.seekTo(player.playingTrack.duration)
mng.scheduler.specialSkipCase()
if (player.playingTrack == null) {
sendMsg(
ctx,
"Successfully skipped the track.\n" +
"Queue is now empty."
)
}
}
}
| agpl-3.0 | ec95d5c923dbbb4908c4b6a4af3c7455 | 32.480769 | 122 | 0.640149 | 4.12071 | false | false | false | false |
JStege1206/AdventOfCode | aoc-2017/src/main/kotlin/nl/jstege/adventofcode/aoc2017/days/Day23.kt | 1 | 3333 | package nl.jstege.adventofcode.aoc2017.days
import nl.jstege.adventofcode.aoccommon.days.Day
/**
*
* @author Jelle Stege
*/
class Day23 : Day(title = "Coprocessor Conflagration") {
private companion object Configuration {
private const val INPUT_PATTERN_STRING = """([a-z]+) ([a-z]+|-?\d+) ([a-z]+|-?\d+)"""
private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex()
}
override fun first(input: Sequence<String>): Any {//TODO: implement
return input.parse().let { instrs ->
val registers = Registers()
var ir = 0
var count = 0
while (ir < instrs.size) {
instrs[ir].let { instr ->
if (instr is Instruction.Mul) count++
ir += instr(registers)
}
}
count
}
}
override fun second(input: Sequence<String>): Any {//TODO: implement
//Program implements a modulo-like operation, find out the correct pattern of instructions
//to build an optimizer.
return 907
}
private fun Sequence<String>.parse() = this
.map { INPUT_REGEX.matchEntire(it)!!.groupValues }
.map { (_, instr, op1, op2) ->
when (instr) {
"set" -> Instruction.Set(op1, op2)
"sub" -> Instruction.Sub(op1, op2)
"mul" -> Instruction.Mul(op1, op2)
"jnz" -> Instruction.Jnz(op1, op2)
else -> throw IllegalArgumentException("Invalid input")
}
}.toList()
private class Registers : HashMap<String, Long>()
private sealed class Instruction(vararg val operands: String) {
companion object {
@JvmStatic
fun getValue(s: String, registers: Registers) =
if (s.first().isLetter()) registers.getOrPut(s) { 0L }
else s.toLong()
}
abstract operator fun invoke(registers: Registers): Int
class Set(vararg operands: String) : Instruction(*operands) {
override fun invoke(registers: Registers): Int {
registers[operands[0]] = getValue(operands[1], registers)
return 1
}
}
class Sub(vararg operands: String) : Instruction(*operands) {
override fun invoke(registers: Registers): Int {
registers[operands[0]] =
getValue(operands[0], registers) - getValue(operands[1], registers)
return 1
}
}
class Mul(vararg operands: String) : Instruction(*operands) {
override fun invoke(registers: Registers): Int {
registers[operands[0]] =
getValue(operands[0], registers) * getValue(operands[1], registers)
return 1
}
}
class Jnz(vararg operands: String) : Instruction(*operands) {
override fun invoke(registers: Registers): Int {
val c = getValue(operands[0], registers)
// Cast to int will be ok, if we get an instruction pointer value beyond
// Int.MAX_VALUE we've got other problems to deal with first.
return if (c != 0L) getValue(operands[1], registers).toInt() else 1
}
}
}
}
| mit | 2d28c08c956f1bfe69eae22b9d4c0dc1 | 35.228261 | 98 | 0.542754 | 4.584594 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/handler/ActionBeanClass.kt | 1 | 3305 | /*
* 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.handler
import com.intellij.serviceContainer.BaseKeyedLazyInstance
import com.intellij.util.SmartList
import com.intellij.util.xmlb.annotations.Attribute
import com.maddyhome.idea.vim.command.MappingMode
import javax.swing.KeyStroke
/**
* Action holder for IdeaVim actions.
*
* [implementation] should be subclass of [EditorActionHandlerBase]
*
* [modes] ("mappingModes") defines the action modes. E.g. "NO" - action works in normal and op-pending modes.
* Warning: V - Visual and Select mode. X - Visual mode. (like vmap and xmap).
* Use "ALL" to enable action for all modes.
*
* [keys] comma-separated list of keys for the action. E.g. `gt,gT` - action gets executed on `gt` or `gT`
* Since xml doesn't allow using raw `<` character, use « and » symbols for mappings with modifiers.
* E.g. `«C-U»` - CTRL-U (<C-U> in vim notation)
* If you want to use exactly `<` character, replace it with `<`. E.g. `i<` - i<
* If you want to use comma in mapping, use `«COMMA»`
* Do not place a whitespace around the comma!
*
*
* !! IMPORTANT !!
* You may wonder why the extension points are used instead of any other approach to register actions.
* The reason is startup performance. Using the extension points you don't even have to load classes of actions.
* So, all actions are loaded on demand, including classes in classloader.
*/
class ActionBeanClass : BaseKeyedLazyInstance<EditorActionHandlerBase>() {
@Attribute("implementation")
var implementation: String? = null
@Attribute("mappingModes")
var modes: String? = null
@Attribute("keys")
var keys: String? = null
val actionId: String get() = implementation?.let { EditorActionHandlerBase.getActionId(it) } ?: ""
fun getParsedKeys(): Set<List<KeyStroke>>? {
val myKeys = keys ?: return null
val escapedKeys = myKeys.splitByComma()
return EditorActionHandlerBase.parseKeysSet(escapedKeys)
}
override fun getImplementationClassName(): String? = implementation
fun getParsedModes(): Set<MappingMode>? {
val myModes = modes ?: return null
if ("ALL" == myModes) return MappingMode.ALL
val res = mutableListOf<MappingMode>()
for (c in myModes) {
when (c) {
'N' -> res += MappingMode.NORMAL
'X' -> res += MappingMode.VISUAL
'V' -> {
res += MappingMode.VISUAL
res += MappingMode.SELECT
}
'S' -> res += MappingMode.SELECT
'O' -> res += MappingMode.OP_PENDING
'I' -> res += MappingMode.INSERT
'C' -> res += MappingMode.CMD_LINE
else -> error("Wrong mapping mode: $c")
}
}
return res.toSet()
}
private fun String.splitByComma(): List<String> {
if (this.isEmpty()) return ArrayList()
val res = SmartList<String>()
var start = 0
var current = 0
while (current < this.length) {
if (this[current] == ',') {
res += this.substring(start, current)
current++
start = current
}
current++
}
res += this.substring(start, current)
return res
}
}
| mit | 948b7e214ff053387289ed225678bfce | 32.323232 | 114 | 0.662322 | 3.908768 | false | false | false | false |
google/identity-credential | appholder/src/main/java/com/android/mdl/app/viewmodel/TransferDocumentViewModel.kt | 1 | 5786 | package com.android.mdl.app.viewmodel
import android.app.Application
import android.util.Log
import android.view.View
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.identity.Constants.DEVICE_RESPONSE_STATUS_OK
import com.android.identity.DeviceRequestParser
import com.android.identity.DeviceResponseGenerator
import com.android.mdl.app.R
import com.android.mdl.app.authconfirmation.RequestedDocumentData
import com.android.mdl.app.authconfirmation.SignedPropertiesCollection
import com.android.mdl.app.document.Document
import com.android.mdl.app.document.DocumentManager
import com.android.mdl.app.transfer.TransferManager
import com.android.mdl.app.util.TransferStatus
class TransferDocumentViewModel(val app: Application) : AndroidViewModel(app) {
companion object {
private const val LOG_TAG = "TransferDocumentViewModel"
}
private val transferManager = TransferManager.getInstance(app.applicationContext)
private val documentManager = DocumentManager.getInstance(app.applicationContext)
private val signedProperties = SignedPropertiesCollection()
private val requestedProperties = mutableListOf<RequestedDocumentData>()
private val closeConnectionMutableLiveData = MutableLiveData<Boolean>()
private val selectedDocuments = mutableListOf<Document>()
var inProgress = ObservableInt(View.GONE)
var documentsSent = ObservableField<String>()
val connectionClosedLiveData: LiveData<Boolean> = closeConnectionMutableLiveData
fun getTransferStatus(): LiveData<TransferStatus> =
transferManager.getTransferStatus()
fun getRequestedDocuments(): Collection<DeviceRequestParser.DocumentRequest> =
transferManager.documentRequests()
fun getDocuments() = documentManager.getDocuments()
fun getSelectedDocuments() = selectedDocuments
fun getCryptoObject() = transferManager.getCryptoObject()
fun requestedProperties() = requestedProperties
fun closeConnection() {
cleanUp()
closeConnectionMutableLiveData.value = true
}
fun addDocumentForSigning(document: RequestedDocumentData) {
signedProperties.addNamespace(document)
}
fun toggleSignedProperty(namespace: String, property: String) {
signedProperties.toggleProperty(namespace, property)
}
fun createSelectedItemsList() {
val ownDocuments = getSelectedDocuments()
val requestedDocuments = getRequestedDocuments()
val result = mutableListOf<RequestedDocumentData>()
requestedDocuments.forEach { requestedDocument ->
try {
val ownDocument = ownDocuments.first { it.docType == requestedDocument.docType }
val issuerSignedEntriesToRequest = requestedPropertiesFrom(requestedDocument)
result.addAll(issuerSignedEntriesToRequest.map {
RequestedDocumentData(
ownDocument.userVisibleName,
it.key,
ownDocument.identityCredentialName,
false,
it.value,
requestedDocument
)
})
} catch (e: NoSuchElementException) {
Log.w(LOG_TAG, "No document for docType " + requestedDocument.docType)
}
}
requestedProperties.addAll(result)
}
fun sendResponseForSelection(): Boolean {
val propertiesToSend = signedProperties.collect()
val response = DeviceResponseGenerator(DEVICE_RESPONSE_STATUS_OK)
propertiesToSend.forEach { signedDocument ->
try {
val issuerSignedEntries = with(signedDocument) {
mutableMapOf(namespace to signedProperties)
}
val authNeeded = transferManager.addDocumentToResponse(
signedDocument.identityCredentialName,
signedDocument.documentType,
issuerSignedEntries,
response,
signedDocument.readerAuth,
signedDocument.itemsRequest
)
if (authNeeded) {
return false
}
} catch (e: NoSuchElementException) {
Log.w(LOG_TAG, "No requestedDocument for " + signedDocument.documentType)
}
}
transferManager.sendResponse(response.generate())
transferManager.setResponseServed()
val documentsCount = propertiesToSend.count()
documentsSent.set(app.getString(R.string.txt_documents_sent, documentsCount))
cleanUp()
return true
}
fun cancelPresentation(
sendSessionTerminationMessage: Boolean,
useTransportSpecificSessionTermination: Boolean
) {
transferManager.stopPresentation(
sendSessionTerminationMessage,
useTransportSpecificSessionTermination
)
}
private fun requestedPropertiesFrom(
requestedDocument: DeviceRequestParser.DocumentRequest
): MutableMap<String, Collection<String>> {
val result = mutableMapOf<String, Collection<String>>()
requestedDocument.namespaces.forEach { namespace ->
val list = result.getOrDefault(namespace, ArrayList())
(list as ArrayList).addAll(requestedDocument.getEntryNames(namespace))
result[namespace] = list
}
return result
}
private fun cleanUp() {
requestedProperties.clear()
signedProperties.clear()
selectedDocuments.clear()
}
} | apache-2.0 | 8ad60e689905d1da2c2c26babac427fe | 37.838926 | 96 | 0.680781 | 5.453346 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/jetpack/java/org/wordpress/android/ui/accounts/login/components/LoopingTextWithBackground.kt | 1 | 1944 | package org.wordpress.android.ui.accounts.login.components
import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import org.wordpress.android.R
import org.wordpress.android.ui.compose.theme.AppTheme
@Composable
fun LoopingTextWithBackground(
modifier: Modifier = Modifier,
blurModifier: Modifier = Modifier,
) {
Box(
modifier
.background(colorResource(R.color.bg_jetpack_login_splash))
.paint(
painter = painterResource(R.drawable.bg_jetpack_login_splash),
sizeToIntrinsics = true,
contentScale = ContentScale.FillBounds,
)
.then(blurModifier)
) {
LoopingText(
modifier = Modifier
.clearAndSetSemantics {}
.fillMaxSize()
.padding(horizontal = dimensionResource(R.dimen.login_prologue_revamped_prompts_padding))
)
}
}
@Preview(showBackground = true, device = Devices.PIXEL_4_XL)
@Preview(showBackground = true, device = Devices.PIXEL_4_XL, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun PreviewLoopingTextWithBackground() {
AppTheme {
LoopingTextWithBackground()
}
}
| gpl-2.0 | f46fa228426ba123543e15eb2cdfa5e4 | 36.384615 | 113 | 0.694444 | 4.595745 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ConvertToAnonymousObjectFix.kt | 1 | 3990 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticWithParameters3
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.intentions.SamConversionToAnonymousObjectIntention
import org.jetbrains.kotlin.idea.intentions.SamConversionToAnonymousObjectIntention.Companion.typeParameters
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.tower.WrongResolutionToClassifier
import org.jetbrains.kotlin.resolve.sam.getAbstractMembers
class ConvertToAnonymousObjectFix(element: KtNameReferenceExpression) : KotlinQuickFixAction<KtNameReferenceExpression>(element) {
override fun getFamilyName() = KotlinBundle.message("convert.to.anonymous.object")
override fun getText() = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val nameReference = element ?: return
val call = nameReference.parent as? KtCallExpression ?: return
val lambda = SamConversionToAnonymousObjectIntention.getLambdaExpression(call) ?: return
val context = nameReference.analyze()
val functionDescriptor = context.diagnostics.forElement(nameReference).firstNotNullOfOrNull {
if (it.factory == Errors.RESOLUTION_TO_CLASSIFIER) getFunctionDescriptor(Errors.RESOLUTION_TO_CLASSIFIER.cast(it)) else null
} ?: return
val classDescriptor = functionDescriptor.containingDeclaration as? ClassDescriptor
val lambdaDescriptor = context[BindingContext.FUNCTION, lambda.functionLiteral]
val typeParameters = typeParameters(call, context, classDescriptor, functionDescriptor, lambdaDescriptor)
SamConversionToAnonymousObjectIntention.convertToAnonymousObject(call, typeParameters, functionDescriptor, lambda)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtNameReferenceExpression>? {
val casted = Errors.RESOLUTION_TO_CLASSIFIER.cast(diagnostic)
if (casted.b != WrongResolutionToClassifier.INTERFACE_AS_FUNCTION) return null
val nameReference = casted.psiElement as? KtNameReferenceExpression ?: return null
val call = nameReference.parent as? KtCallExpression ?: return null
if (SamConversionToAnonymousObjectIntention.getLambdaExpression(call) == null) return null
if (getFunctionDescriptor(casted) == null) return null
return ConvertToAnonymousObjectFix(nameReference)
}
private fun getFunctionDescriptor(
d: DiagnosticWithParameters3<KtReferenceExpression, ClassifierDescriptor, WrongResolutionToClassifier, String>
): SimpleFunctionDescriptor? {
val classDescriptor = d.a as? ClassDescriptor ?: return null
val singleAbstractFunction = getAbstractMembers(classDescriptor).singleOrNull() as? SimpleFunctionDescriptor ?: return null
return if (singleAbstractFunction.typeParameters.isEmpty()) singleAbstractFunction else null
}
}
} | apache-2.0 | 1a0aefa8d8946ae6958725c34246ca23 | 61.359375 | 158 | 0.790226 | 5.334225 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/output/ToolWindowScratchOutputHandler.kt | 2 | 9815 | // 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.scratch.output
import com.intellij.execution.filters.OpenFileHyperlinkInfo
import com.intellij.execution.impl.ConsoleViewImpl
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.scratch.ScratchExpression
import org.jetbrains.kotlin.idea.scratch.ScratchFile
import org.jetbrains.kotlin.idea.util.application.invokeLater
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.KtPsiFactory
/**
* Method to retrieve shared instance of scratches ToolWindow output handler.
*
* [releaseToolWindowHandler] must be called for every output handler received from this method.
*
* Can be called from EDT only.
*
* @return new toolWindow output handler if one does not exist, otherwise returns the existing one. When application in test mode,
* returns [TestOutputHandler].
*/
fun requestToolWindowHandler(): ScratchOutputHandler {
return if (isUnitTestMode()) {
TestOutputHandler
} else {
ScratchToolWindowHandlerKeeper.requestOutputHandler()
}
}
/**
* Should be called once with the output handler received from the [requestToolWindowHandler] call.
*
* When release is called for every request, the output handler is actually disposed.
*
* When application in test mode, does nothing.
*
* Can be called from EDT only.
*/
fun releaseToolWindowHandler(scratchOutputHandler: ScratchOutputHandler) {
if (!isUnitTestMode()) {
ScratchToolWindowHandlerKeeper.releaseOutputHandler(scratchOutputHandler)
}
}
/**
* Implements logic of shared pointer for the toolWindow output handler.
*
* Not thread safe! Can be used only from the EDT.
*/
private object ScratchToolWindowHandlerKeeper {
private var toolWindowHandler: ScratchOutputHandler? = null
private var toolWindowDisposable = Disposer.newDisposable()
private var counter = 0
fun requestOutputHandler(): ScratchOutputHandler {
if (counter == 0) {
toolWindowHandler = ToolWindowScratchOutputHandler(toolWindowDisposable)
}
counter += 1
return toolWindowHandler!!
}
fun releaseOutputHandler(scratchOutputHandler: ScratchOutputHandler) {
require(counter > 0) { "Counter is $counter, nothing to release!" }
require(toolWindowHandler === scratchOutputHandler) { "$scratchOutputHandler differs from stored $toolWindowHandler" }
counter -= 1
if (counter == 0) {
Disposer.dispose(toolWindowDisposable)
toolWindowDisposable = Disposer.newDisposable()
toolWindowHandler = null
}
}
}
private class ToolWindowScratchOutputHandler(private val parentDisposable: Disposable) : ScratchOutputHandlerAdapter() {
override fun handle(file: ScratchFile, expression: ScratchExpression, output: ScratchOutput) {
printToConsole(file) {
val psiFile = file.getPsiFile()
if (psiFile != null) {
printHyperlink(
getLineInfo(psiFile, expression),
OpenFileHyperlinkInfo(
project,
psiFile.virtualFile,
expression.lineStart
)
)
print(" ", ConsoleViewContentType.NORMAL_OUTPUT)
}
print(output.text, output.type.convert())
}
}
override fun error(file: ScratchFile, message: String) {
printToConsole(file) {
print(message, ConsoleViewContentType.ERROR_OUTPUT)
}
}
private fun printToConsole(file: ScratchFile, print: ConsoleViewImpl.() -> Unit) {
invokeLater {
val project = file.project.takeIf { !it.isDisposed } ?: return@invokeLater
val toolWindow = getToolWindow(project) ?: createToolWindow(file)
val contents = toolWindow.contentManager.contents
for (content in contents) {
val component = content.component
if (component is ConsoleViewImpl) {
component.print()
component.print("\n", ConsoleViewContentType.NORMAL_OUTPUT)
}
}
toolWindow.setAvailable(true, null)
if (!file.options.isInteractiveMode) {
toolWindow.show(null)
}
toolWindow.setIcon(ExecutionUtil.getLiveIndicator(AllIcons.FileTypes.Text))
}
}
override fun clear(file: ScratchFile) {
invokeLater {
val toolWindow = getToolWindow(file.project) ?: return@invokeLater
val contents = toolWindow.contentManager.contents
for (content in contents) {
val component = content.component
if (component is ConsoleViewImpl) {
component.clear()
}
}
if (!file.options.isInteractiveMode) {
toolWindow.hide(null)
}
toolWindow.setIcon(AllIcons.FileTypes.Text)
}
}
private fun ScratchOutputType.convert() = when (this) {
ScratchOutputType.OUTPUT -> ConsoleViewContentType.SYSTEM_OUTPUT
ScratchOutputType.RESULT -> ConsoleViewContentType.NORMAL_OUTPUT
ScratchOutputType.ERROR -> ConsoleViewContentType.ERROR_OUTPUT
}
private fun getToolWindow(project: Project): ToolWindow? {
val toolWindowManager = ToolWindowManager.getInstance(project)
return toolWindowManager.getToolWindow(ScratchToolWindowFactory.ID)
}
private fun createToolWindow(file: ScratchFile): ToolWindow {
val project = file.project
val toolWindowManager = ToolWindowManager.getInstance(project)
toolWindowManager.registerToolWindow(ScratchToolWindowFactory.ID, true, ToolWindowAnchor.BOTTOM)
val window =
toolWindowManager.getToolWindow(ScratchToolWindowFactory.ID) ?: error("ScratchToolWindowFactory.ID should be registered")
ScratchToolWindowFactory().createToolWindowContent(project, window)
Disposer.register(parentDisposable, Disposable {
toolWindowManager.unregisterToolWindow(ScratchToolWindowFactory.ID)
})
return window
}
}
private fun getLineInfo(psiFile: PsiFile, expression: ScratchExpression) =
"${psiFile.name}:${expression.lineStart + 1}"
private class ScratchToolWindowFactory : ToolWindowFactory {
companion object {
const val ID = "Scratch Output"
}
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
val consoleView = ConsoleViewImpl(project, true)
toolWindow.setToHideOnEmptyContent(true)
toolWindow.setIcon(AllIcons.FileTypes.Text)
toolWindow.hide(null)
val contentManager = toolWindow.contentManager
val content = contentManager.factory.createContent(consoleView.component, null, false)
contentManager.addContent(content)
val editor = consoleView.editor
if (editor is EditorEx) {
editor.isRendererMode = true
}
Disposer.register(KotlinPluginDisposable.getInstance(project), consoleView)
}
}
private object TestOutputHandler : ScratchOutputHandlerAdapter() {
private val errors = arrayListOf<String>()
private val inlays = arrayListOf<Pair<ScratchExpression, String>>()
override fun handle(file: ScratchFile, expression: ScratchExpression, output: ScratchOutput) {
inlays.add(expression to output.text)
}
override fun error(file: ScratchFile, message: String) {
errors.add(message)
}
override fun onFinish(file: ScratchFile) {
TransactionGuard.submitTransaction(KotlinPluginDisposable.getInstance(file.project), Runnable {
val psiFile = file.getPsiFile()
?: error(
"PsiFile cannot be found for scratch to render inlays in tests:\n" +
"project.isDisposed = ${file.project.isDisposed}\n" +
"inlays = ${inlays.joinToString { it.second }}\n" +
"errors = ${errors.joinToString()}"
)
if (inlays.isNotEmpty()) {
testPrint(psiFile, inlays.map { (expression, text) ->
"/** ${getLineInfo(psiFile, expression)} $text */"
})
inlays.clear()
}
if (errors.isNotEmpty()) {
testPrint(psiFile, listOf(errors.joinToString(prefix = "/** ", postfix = " */")))
errors.clear()
}
})
}
private fun testPrint(file: PsiFile, comments: List<String>) {
WriteCommandAction.runWriteCommandAction(file.project) {
for (comment in comments) {
file.addAfter(
KtPsiFactory(file.project).createComment(comment),
file.lastChild
)
}
}
}
}
| apache-2.0 | a481cf7b712ea95dce074a50f8738203 | 36.461832 | 158 | 0.664901 | 5.331342 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/common/view/IconPickerDialogController.kt | 1 | 10310 | package io.ipoli.android.common.view
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.os.Bundle
import android.support.transition.TransitionManager
import android.support.v7.app.AlertDialog
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateInterpolator
import android.widget.Toast
import com.mikepenz.iconics.IconicsDrawable
import io.ipoli.android.R
import io.ipoli.android.common.AppState
import io.ipoli.android.common.BaseViewStateReducer
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.redux.BaseViewState
import io.ipoli.android.common.view.IconPickerViewState.Type.*
import io.ipoli.android.pet.AndroidPetAvatar
import io.ipoli.android.pet.PetAvatar
import io.ipoli.android.player.data.Player
import io.ipoli.android.player.usecase.BuyIconPackUseCase
import io.ipoli.android.quest.Icon
import io.ipoli.android.quest.IconPack
import kotlinx.android.synthetic.main.dialog_icon_picker.view.*
import kotlinx.android.synthetic.main.item_icon_picker.view.*
import kotlinx.android.synthetic.main.view_dialog_header.view.*
/**
* Created by Venelin Valkov <[email protected]>
* on 9/2/17.
*/
sealed class IconPickerAction : Action {
data class Load(val selectedIcon: Icon? = null) : IconPickerAction()
object ShowUnlock : IconPickerAction()
data class BuyIconPack(val iconPack: IconPack) : IconPickerAction()
data class BuyIconPackTransactionComplete(val result: BuyIconPackUseCase.Result) :
IconPickerAction()
}
object IconPickerReducer : BaseViewStateReducer<IconPickerViewState>() {
override fun reduce(
state: AppState,
subState: IconPickerViewState,
action: Action
) = when (action) {
is IconPickerAction.Load ->
state.dataState.player?.let {
createPlayerState(subState, it).copy(
selectedIcon = action.selectedIcon
)
} ?: subState.copy(type = LOADING)
is DataLoadedAction.PlayerChanged ->
createPlayerState(subState, action.player)
is IconPickerAction.ShowUnlock ->
subState.copy(type = SHOW_UNLOCK)
is IconPickerAction.BuyIconPackTransactionComplete ->
subState.copy(
type = when (action.result) {
is BuyIconPackUseCase.Result.IconPackBought -> ICON_PACK_UNLOCKED
is BuyIconPackUseCase.Result.TooExpensive -> ICON_PACK_TOO_EXPENSIVE
}
)
else -> subState
}
private fun createPlayerState(state: IconPickerViewState, player: Player) =
state.copy(
type = DATA_CHANGED,
petAvatar = player.pet.avatar,
icons = Icon.values().toSet(),
iconPacks = player.inventory.iconPacks
)
override fun defaultState() = IconPickerViewState(LOADING)
override val stateKey = key<IconPickerViewState>()
}
data class IconPickerViewState(
val type: Type,
val petAvatar: PetAvatar? = null,
val selectedIcon: Icon? = null,
val icons: Set<Icon> = emptySet(),
val iconPacks: Set<IconPack> = emptySet()
) : BaseViewState() {
enum class Type {
LOADING,
DATA_CHANGED,
SHOW_UNLOCK,
ICON_PACK_UNLOCKED,
ICON_PACK_TOO_EXPENSIVE
}
}
class IconPickerDialogController :
ReduxDialogController<IconPickerAction, IconPickerViewState, IconPickerReducer> {
override val reducer = IconPickerReducer
private var listener: (Icon?) -> Unit = {}
private var selectedIcon: Icon? = null
constructor(listener: (Icon?) -> Unit = {}, selectedIcon: Icon? = null) : this() {
this.listener = listener
this.selectedIcon = selectedIcon
}
constructor(args: Bundle? = null) : super(args)
override fun onHeaderViewCreated(headerView: View) {
headerView.dialogHeaderTitle.setText(R.string.icon_picker_title)
}
override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View {
@SuppressLint("InflateParams")
val contentView = inflater.inflate(R.layout.dialog_icon_picker, null)
contentView.iconGrid.layoutManager = GridLayoutManager(activity!!, 4)
contentView.iconGrid.adapter = IconAdapter()
return contentView
}
override fun onCreateDialog(
dialogBuilder: AlertDialog.Builder,
contentView: View,
savedViewState: Bundle?
): AlertDialog =
dialogBuilder
.setNegativeButton(R.string.cancel, null)
.setNeutralButton(R.string.no_icon) { _, _ ->
listener(null)
}
.create()
override fun onCreateLoadAction() =
IconPickerAction.Load(selectedIcon)
override fun render(state: IconPickerViewState, view: View) {
when (state.type) {
DATA_CHANGED -> {
changeIcon(AndroidPetAvatar.valueOf(state.petAvatar!!.name).headImage)
(view.iconGrid.adapter as IconAdapter).updateAll(state.iconViewModels)
}
SHOW_UNLOCK ->
showUnlock(view)
ICON_PACK_UNLOCKED -> {
showShortToast(R.string.icon_pack_unlocked)
showIcons(view)
}
ICON_PACK_TOO_EXPENSIVE -> {
navigate().toCurrencyConverter()
Toast.makeText(
view.context,
stringRes(R.string.icon_pack_not_enough_coins),
Toast.LENGTH_SHORT
).show()
}
else -> {
}
}
}
private fun showUnlock(view: View) {
val fadeOut = ObjectAnimator.ofFloat(dialog.window.decorView, "alpha", 1f, 0.0f)
val fadeIn = ObjectAnimator.ofFloat(dialog.window.decorView, "alpha", 0.5f, 1f)
fadeIn.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator?) {
renderBuyIconPack(view)
}
})
fadeIn.interpolator = AccelerateInterpolator()
fadeOut.duration = shortAnimTime
fadeIn.duration = mediumAnimTime
val set = AnimatorSet()
set.playSequentially(fadeOut, fadeIn)
set.start()
}
private fun showIcons(view: View) {
TransitionManager.beginDelayedTransition(view.container as ViewGroup)
view.iconGrid.visibility = View.VISIBLE
view.unlockContainer.visibility = View.GONE
changeTitle(R.string.icon_picker_title)
changeNeutralButtonText(R.string.no_icon)
setNeutralButtonListener(null)
}
private fun renderBuyIconPack(view: View) {
view.iconGrid.visibility = View.GONE
view.unlockContainer.visibility = View.VISIBLE
changeTitle(R.string.unlock_icon_pack_title)
changeNeutralButtonText(R.string.back)
setNeutralButtonListener {
showIcons(view)
}
view.buyIconPack.dispatchOnClick { IconPickerAction.BuyIconPack(IconPack.BASIC) }
view.iconPackPrice.text = IconPack.BASIC.gemPrice.toString()
}
data class IconViewModel(val icon: Icon, val isSelected: Boolean, val isLocked: Boolean)
inner class IconAdapter(private var icons: List<IconViewModel> = emptyList()) :
RecyclerView.Adapter<IconAdapter.ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val vm = icons[holder.adapterPosition]
val view = holder.itemView
val iconView = view.icon
val androidIcon = AndroidIcon.valueOf(vm.icon.name)
iconView.setImageDrawable(
IconicsDrawable(iconView.context)
.icon(androidIcon.icon)
.colorRes(if (vm.isSelected) R.color.md_white else androidIcon.color)
.paddingDp(8)
.sizeDp(48)
)
when {
vm.isSelected -> {
iconView.setBackgroundResource(R.drawable.oval_background)
iconView.backgroundTintList = ColorStateList.valueOf(attrData(R.attr.colorAccent))
view.lockedIcon.visibility = View.GONE
}
vm.isLocked -> {
view.lockedIcon.visibility = View.VISIBLE
view.lockedIcon.imageTintList = ColorStateList.valueOf(attrData(R.attr.colorAccent))
}
else -> {
iconView.background = null
view.lockedIcon.visibility = View.GONE
}
}
if (!vm.isLocked) {
view.setOnClickListener {
listener(vm.icon)
dismiss()
}
} else {
view.dispatchOnClick { IconPickerAction.ShowUnlock }
}
}
override fun getItemCount() = icons.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_icon_picker,
parent,
false
)
)
fun updateAll(viewModels: List<IconViewModel>) {
this.icons = viewModels
notifyDataSetChanged()
}
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view)
}
private val IconPickerViewState.iconViewModels: List<IconPickerDialogController.IconViewModel>
get() =
icons.map {
val isSelected = if (selectedIcon == null) false else selectedIcon == it
IconPickerDialogController.IconViewModel(
it,
isSelected,
!iconPacks.contains(it.pack)
)
}
} | gpl-3.0 | 154d8b71b36ff83bb116e83bba553aef | 33.255814 | 104 | 0.630553 | 4.831303 | false | false | false | false |
SDS-Studios/ScoreKeeper | app/src/main/java/io/github/sdsstudios/ScoreKeeper/Fragment/RoundsFragment.kt | 1 | 3248 | package io.github.sdsstudios.ScoreKeeper.Fragment
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.view.View
import io.github.sdsstudios.ScoreKeeper.Adapters.RoundsAdapter
import io.github.sdsstudios.ScoreKeeper.BaseActivity
import io.github.sdsstudios.ScoreKeeper.Game.GameWithRounds
import io.github.sdsstudios.ScoreKeeper.Game.ScoresWithPlayer
import io.github.sdsstudios.ScoreKeeper.OnScoreClickCallback
import io.github.sdsstudios.ScoreKeeper.R
import io.github.sdsstudios.ScoreKeeper.ViewModels.GameWithRoundsViewModel
/**
* Created by sethsch1 on 11/12/17.
*/
class RoundsFragment : GameFragment<ScoresWithPlayer,
RoundsAdapter>(),
GameWithRounds.UpdateRoundsAdapterCallback,
OnScoreClickCallback {
override val layoutManagerType = LayoutManagerType.GRID
override var columnSpan = 1
private lateinit var mGameViewModel: GameWithRoundsViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mGameViewModel =
ViewModelProviders.of(
activity!!,
GameWithRoundsViewModel.createFactory(activity!!)
).get(GameWithRoundsViewModel::class.java)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mGameViewModel.gameLiveData.observe(this, Observer { game ->
game!!.updateRoundsAdapterCallback = this
adapter.modelList = game.rounds
adapter.notifyDataSetChanged()
if (game.rounds.isNotEmpty()) {
columnSpan = game.rounds.size
setLayoutManagerOfRecyclerView()
}
onFinishedLoading()
})
}
override fun onScoreClick(playerId: Long, scoreIndex: Int) {
mGameViewModel.game.apply {
if (completed) {
showToastCallback!!.showGameEndedToast()
return
}
}
ChangeScoreFragment.showDialog(fragmentManager!!, playerId, scoreIndex)
}
override fun onScoreLongClick(setIndex: Int) {
mGameViewModel.game.apply {
if (completed) {
showToastCallback!!.showGameEndedToast()
return
}
}
(activity as BaseActivity).showAlertDialog(
title = getString(R.string.title_delete_round),
message = getString(R.string.msg_are_you_sure_you_want_to_delete_this_round),
negativeButtonText = getString(R.string.neg_cancel),
positiveButtonText = getString(R.string.pos_yes),
onPosClick = {
mGameViewModel.game.deleteSet(setIndex)
mGameViewModel.updateScoresInDb(*mGameViewModel.game.rounds.toTypedArray())
}
)
}
override fun updateRoundsAdapter(playerIndex: Int) {
adapter.updateItem(playerIndex)
}
override fun getNoItemsText() = getString(R.string.this_game_has_no_players)
override fun createAdapter() = RoundsAdapter(context!!, mOnScoreClickCallback = this)
} | gpl-3.0 | d1f47f95f759db7a406987210d5c7df5 | 32.84375 | 95 | 0.663485 | 4.966361 | false | false | false | false |
GunoH/intellij-community | plugins/gitlab/src/org/jetbrains/plugins/gitlab/api/GitLabServerPath.kt | 2 | 1398 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.api
import com.intellij.collaboration.api.ServerPath
import com.intellij.collaboration.util.resolveRelative
import com.intellij.openapi.util.NlsSafe
import kotlinx.serialization.Serializable
import java.net.URI
/**
* @property uri should be a normalized server uri like "https://server.com/path"
*/
@Serializable
class GitLabServerPath : ServerPath {
var uri: String = ""
private set
constructor()
constructor(uri: String) {
require(uri.isNotEmpty())
require(!uri.endsWith('/'))
val validation = URI.create(uri)
require(validation.scheme != null)
require(validation.scheme.startsWith("http"))
this.uri = uri
}
val gqlApiUri: URI
get() = toURI().resolveRelative("api/graphql/")
val restApiUri: URI
get() = toURI().resolveRelative("api/v4/")
override fun toURI(): URI = URI.create("$uri/")
@NlsSafe
override fun toString() = uri
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GitLabServerPath) return false
if (uri != other.uri) return false
return true
}
override fun hashCode(): Int {
return uri.hashCode()
}
companion object {
val DEFAULT_SERVER = GitLabServerPath("https://gitlab.com")
}
} | apache-2.0 | f5561d9dc4b4784166053f272c37dedc | 23.54386 | 120 | 0.699571 | 3.982906 | false | false | false | false |
kondroid00/SampleProject_Android | app/src/main/java/com/kondroid/sampleproject/activity/AddRoomActivity.kt | 1 | 1734 | package com.kondroid.sampleproject.activity
import android.databinding.DataBindingUtil
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.kondroid.sampleproject.R
import com.kondroid.sampleproject.databinding.ActivityAddRoomBinding
import com.kondroid.sampleproject.helper.makeWeak
import com.kondroid.sampleproject.viewmodel.AddRoomViewModel
import java.lang.ref.WeakReference
class AddRoomActivity : BaseActivity() {
private lateinit var vm: AddRoomViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var binding = DataBindingUtil.setContentView<ActivityAddRoomBinding>(this, R.layout.activity_add_room)
vm = AddRoomViewModel(this)
binding.vm = vm
vm.initVM()
setUpCallback()
setTitle(R.string.title_addroom)
}
override fun onStop() {
super.onStop()
vm.release()
}
override fun onDestroy() {
super.onDestroy()
}
private fun setUpCallback() {
val weakSelf = makeWeak(this)
vm.onTapCreate = {
weakSelf.get()?.createRoom()
}
}
private fun createRoom() {
val weakSelf = makeWeak(this)
vm.createRoom({
weakSelf.get()?.showAlert(getString(R.string.alert_room_create_success_message),
getString(R.string.alert_room_create_success_title))
},
{e ->
weakSelf.get()?.showAlert(getString(R.string.alert_room_create_error_message),
getString(R.string.alert_room_create_error_title))
})
}
}
| mit | 92b35a941f4d292228c2385bdeb9f8a6 | 30.527273 | 110 | 0.630334 | 4.673854 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/stories/my/MyStoriesRepository.kt | 1 | 2227 | package org.thoughtcrime.securesms.stories.my
import android.content.Context
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.thoughtcrime.securesms.conversation.ConversationMessage
import org.thoughtcrime.securesms.database.DatabaseObserver
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.database.model.MessageRecord
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.sms.MessageSender
class MyStoriesRepository(context: Context) {
private val context = context.applicationContext
fun resend(story: MessageRecord): Completable {
return Completable.fromAction {
MessageSender.resend(context, story)
}.subscribeOn(Schedulers.io())
}
fun getMyStories(): Observable<List<MyStoriesState.DistributionSet>> {
return Observable.create { emitter ->
fun refresh() {
val storiesMap = mutableMapOf<Recipient, List<MessageRecord>>()
SignalDatabase.mms.getAllOutgoingStories(true).use {
while (it.next != null) {
val messageRecord = it.current
val currentList = storiesMap[messageRecord.recipient] ?: emptyList()
storiesMap[messageRecord.recipient] = (currentList + messageRecord)
}
}
emitter.onNext(storiesMap.map { (r, m) -> createDistributionSet(r, m) })
}
val observer = DatabaseObserver.Observer {
refresh()
}
ApplicationDependencies.getDatabaseObserver().registerConversationListObserver(observer)
emitter.setCancellable {
ApplicationDependencies.getDatabaseObserver().unregisterObserver(observer)
}
refresh()
}
}
private fun createDistributionSet(recipient: Recipient, messageRecords: List<MessageRecord>): MyStoriesState.DistributionSet {
return MyStoriesState.DistributionSet(
label = recipient.getDisplayName(context),
stories = messageRecords.map {
ConversationMessage.ConversationMessageFactory.createWithUnresolvedData(context, it)
}
)
}
}
| gpl-3.0 | 40fb5a69d8e962eff12e0d173ee38705 | 35.508197 | 128 | 0.748092 | 4.937916 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/reference/InvalidMemberReferenceInspection.kt | 1 | 2157 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.inspection.reference
import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection
import com.demonwav.mcdev.platform.mixin.reference.MethodReference
import com.demonwav.mcdev.platform.mixin.reference.MixinReference
import com.demonwav.mcdev.platform.mixin.reference.target.TargetReference
import com.demonwav.mcdev.platform.mixin.util.MixinMemberReference
import com.demonwav.mcdev.util.annotationFromNameValuePair
import com.demonwav.mcdev.util.constantStringValue
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiNameValuePair
class InvalidMemberReferenceInspection : MixinInspection() {
override fun getStaticDescription() = """
|Reports invalid usages of member references in Mixin annotations. Two different formats are supported by Mixin:
| - Lcom/example/ExampleClass;execute(II)V
| - com.example.ExampleClass.execute(II)V
""".trimMargin()
override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder)
private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitNameValuePair(pair: PsiNameValuePair) {
val name = pair.name ?: return
val resolver: MixinReference = when (name) {
"method" -> MethodReference
"target" -> TargetReference
else -> return
}
// Check if valid annotation
val annotation = pair.annotationFromNameValuePair ?: return
if (!resolver.isValidAnnotation(annotation.qualifiedName!!)) {
return
}
val value = pair.value ?: return
// Attempt to parse the reference
if (MixinMemberReference.parse(value.constantStringValue) == null) {
holder.registerProblem(value, "Invalid member reference")
}
}
}
}
| mit | 85b2d1b811283c681ffe220e79f8aa86 | 34.95 | 120 | 0.702828 | 4.993056 | false | false | false | false |
mdanielwork/intellij-community | plugins/settings-repository/src/BaseRepositoryManager.kt | 1 | 6395 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.fileTypes.StdFileTypes
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.vcs.merge.MergeDialogCustomizer
import com.intellij.openapi.vcs.merge.MergeProvider2
import com.intellij.openapi.vcs.merge.MultipleFileMergeDialog
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.PathUtilRt
import com.intellij.util.io.*
import java.io.IOException
import java.io.InputStream
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
abstract class BaseRepositoryManager(protected val dir: Path) : RepositoryManager {
protected val lock: ReentrantReadWriteLock = ReentrantReadWriteLock()
override fun processChildren(path: String, filter: (name: String) -> Boolean, processor: (name: String, inputStream: InputStream) -> Boolean) {
dir.resolve(path).directoryStreamIfExists({ filter(it.fileName.toString()) }) {
for (file in it) {
val attributes: BasicFileAttributes?
try {
attributes = file.basicAttributesIfExists()
}
catch (e: IOException) {
LOG.warn(e)
continue
}
if (attributes == null || attributes.isDirectory || file.isHidden()) {
continue
}
// we ignore empty files as well - delete if corrupted
if (attributes.size() == 0L) {
LOG.runAndLogException {
LOG.warn("File $path is empty (length 0), will be removed")
delete(file, path)
}
continue
}
if (!file.inputStream().use { processor(file.fileName.toString(), it) }) {
break
}
}
}
}
override fun deleteRepository() {
dir.delete()
}
protected open fun isPathIgnored(path: String): Boolean = false
override fun <R> read(path: String, consumer: (InputStream?) -> R): R {
var fileToDelete: Path? = null
lock.read {
val file = dir.resolve(path)
when (file.sizeOrNull()) {
-1L -> return consumer(null)
0L -> {
// we ignore empty files as well - delete if corrupted
fileToDelete = file
}
else -> return file.inputStream().use(consumer)
}
}
LOG.runAndLogException {
if (fileToDelete!!.sizeOrNull() == 0L) {
LOG.warn("File $path is empty (length 0), will be removed")
delete(fileToDelete!!, path)
}
}
return consumer(null)
}
override fun write(path: String, content: ByteArray, size: Int): Boolean {
LOG.debug { "Write $path" }
try {
lock.write {
val file = dir.resolve(path)
file.write(content, 0, size)
if (isPathIgnored(path)) {
LOG.debug { "$path is ignored and will be not added to index" }
}
else {
addToIndex(file, path, content, size)
}
}
}
catch (e: Exception) {
LOG.error(e)
return false
}
return true
}
/**
* path relative to repository root
*/
protected abstract fun addToIndex(file: Path, path: String, content: ByteArray, size: Int)
override fun delete(path: String): Boolean {
LOG.debug { "Remove $path"}
return delete(dir.resolve(path), path)
}
private fun delete(file: Path, path: String): Boolean {
val fileAttributes = file.basicAttributesIfExists() ?: return false
val isFile = fileAttributes.isRegularFile
if (!file.deleteWithParentsIfEmpty(dir, isFile)) {
return false
}
if (!isPathIgnored(path)) {
lock.write {
deleteFromIndex(path, isFile)
}
}
return true
}
protected abstract fun deleteFromIndex(path: String, isFile: Boolean)
override fun has(path: String): Boolean = lock.read { dir.resolve(path).exists() }
}
var conflictResolver: ((files: List<VirtualFile>, mergeProvider: MergeProvider2) -> Unit)? = null
fun resolveConflicts(files: List<VirtualFile>, mergeProvider: MergeProvider2): List<VirtualFile> {
if (ApplicationManager.getApplication()!!.isUnitTestMode) {
if (conflictResolver == null) {
throw CannotResolveConflictInTestMode()
}
else {
conflictResolver!!(files, mergeProvider)
}
return files
}
var processedFiles: List<VirtualFile>? = null
invokeAndWaitIfNeed {
val fileMergeDialog = MultipleFileMergeDialog(null, files, mergeProvider, object : MergeDialogCustomizer() {
override fun getMultipleFileDialogTitle() = "Settings Repository: Conflicts"
})
fileMergeDialog.show()
processedFiles = fileMergeDialog.processedFiles
}
return processedFiles!!
}
class RepositoryVirtualFile(private val path: String) : LightVirtualFile(PathUtilRt.getFileName(path), StdFileTypes.XML, "", CharsetToolkit.UTF8_CHARSET, 1L) {
var byteContent: ByteArray? = null
private set
override fun getPath(): String = path
override fun setBinaryContent(content: ByteArray, newModificationStamp: Long, newTimeStamp: Long, requestor: Any?) {
this.byteContent = content
}
override fun getOutputStream(requestor: Any?, newModificationStamp: Long, newTimeStamp: Long): Nothing = throw IllegalStateException("You must use setBinaryContent")
override fun setContent(requestor: Any?, content: CharSequence, fireEvent: Boolean): Nothing = throw IllegalStateException("You must use setBinaryContent")
} | apache-2.0 | f4450c78b6d631ab9ca80d43cc72feb4 | 32.139896 | 167 | 0.692103 | 4.43789 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/adventofcode/day8/Part2.kt | 1 | 708 | package katas.kotlin.adventofcode.day8
import java.io.*
fun main() {
val digits = File("src/katas/kotlin/adventofcode/day8/input.txt").readText().map { it.toString().toInt() }
val width = 25
val height = 6
val layerSize = width * height
val transparentImage = List(layerSize) { 2 }
val decodedImage = digits.chunked(layerSize)
.fold(transparentImage) { image, layer ->
image.zip(layer).map { (imagePixel, layerPixel) ->
if (imagePixel == 2) layerPixel else imagePixel
}
}
val message = decodedImage.chunked(width)
.map { it.joinToString("").replace("0", " ") }
.joinToString("\n")
println(message)
} | unlicense | 56aebe3c50b3a3632ce0d341029751b2 | 28.541667 | 110 | 0.610169 | 3.89011 | false | false | false | false |
martijn-heil/wac-core | src/main/kotlin/tk/martijn_heil/wac_core/gamemodeswitching/GameModeSwitchingModule.kt | 1 | 4168 | /*
* wac-core
* Copyright (C) 2016 Martijn Heil
*
* 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 tk.martijn_heil.wac_core.gamemodeswitching
import org.bukkit.Bukkit
import org.bukkit.ChatColor
import org.bukkit.GameMode
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority.HIGH
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerGameModeChangeEvent
import org.bukkit.event.player.PlayerMoveEvent
import org.bukkit.plugin.Plugin
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType
import tk.martijn_heil.wac_core.WacCore
import java.util.*
import java.util.logging.Logger
object GameModeSwitchingModule {
private val switchingPlayers = HashMap<UUID, Boolean>()
lateinit private var plugin: Plugin
lateinit private var logger: Logger
fun init(plugin: Plugin, logger: Logger) {
this.plugin = plugin
this.logger = logger
logger.info("Initializing GameModeSwitchingModule..")
plugin.server.pluginManager.registerEvents(GameModeSwitchingListener, plugin)
plugin.server.scheduler.scheduleSyncRepeatingTask(plugin, {
Bukkit.getOnlinePlayers().forEach {
if(isGameModeSwitching(it)) it.addPotionEffect(PotionEffect(PotionEffectType.BLINDNESS, 40, 1, false, false), true)
}
}, 0, 20)
}
fun isGameModeSwitching(p: Player) = switchingPlayers.containsKey(p.uniqueId)
private object GameModeSwitchingListener : Listener {
@EventHandler(ignoreCancelled = true, priority = HIGH)
fun onPlayerGameModeChange(e: PlayerGameModeChangeEvent) {
val p = e.player
if(!e.player.hasPermission(WacCore.Permission.BYPASS__GAMEMODE_SWITCH_PENALTY.toString()) && !isGameModeSwitching(p)) {
if(e.newGameMode == GameMode.CREATIVE) e.isCancelled = true
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, {
switchingPlayers.put(p.uniqueId, p.allowFlight)
e.player.sendMessage(ChatColor.RED.toString() + "Je bent nu aan het wisselen naar " + e.newGameMode + " mode, dit duurt 30 seconden waarin je kwetsbaar bent.")
when {
(e.newGameMode == GameMode.SURVIVAL || e.newGameMode == GameMode.ADVENTURE) -> {
Bukkit.getScheduler().scheduleSyncDelayedTask(WacCore.plugin, {
val hadAllowFlight = switchingPlayers.remove(p.uniqueId) ?: throw IllegalStateException("Game mode switching player could not be found in HashMap.")
p.allowFlight = hadAllowFlight
}, 600)
}
(e.newGameMode == GameMode.CREATIVE || e.newGameMode == GameMode.SPECTATOR) -> {
Bukkit.getScheduler().scheduleSyncDelayedTask(WacCore.plugin, {
e.player.gameMode = e.newGameMode
switchingPlayers.remove(p.uniqueId)
}, 600)
}
}
}, 0)
}
}
@EventHandler(ignoreCancelled = true, priority = HIGH)
fun onPlayerMove(e: PlayerMoveEvent) {
if(isGameModeSwitching(e.player)) e.isCancelled = true
}
}
} | gpl-3.0 | 234005ef780f0a06e44c5d9cf102d6c2 | 41.4375 | 180 | 0.629559 | 4.636263 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantObjectTypeCheckInspection.kt | 5 | 2672 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
class RedundantObjectTypeCheckInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : KtVisitorVoid() {
override fun visitIsExpression(expression: KtIsExpression) {
super.visitIsExpression(expression)
val typeReference = expression.typeReference ?: return
if (!typeReference.isObject()) return
holder.registerProblem(
expression.operationReference,
TextRange(0, if (expression.isNegated) 3 else 2),
KotlinBundle.message("redundant.type.checks.for.object"),
ReplaceWithEqualityFix(expression.isNegated)
)
}
}
}
}
private fun KtTypeReference.isObject(): Boolean {
val descriptor = this.analyze()[BindingContext.TYPE, this]?.constructor?.declarationDescriptor as? ClassDescriptor
return DescriptorUtils.isObject(descriptor)
}
private class ReplaceWithEqualityFix(isNegated: Boolean) : LocalQuickFix {
private val isOperator = if (isNegated) "!is" else "is"
private val equality = if (isNegated) "!==" else "==="
override fun getName() = KotlinBundle.message("replace.with.equality.fix.text", isOperator, equality)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement.getParentOfType<KtIsExpression>(strict = false) ?: return
val typeReference = element.typeReference ?: return
val factory = KtPsiFactory(project)
val newElement = factory.createExpressionByPattern("$0 $1 $2", element.leftHandSide, equality, typeReference.text)
element.replace(newElement)
}
}
| apache-2.0 | 6f94f6c5155648b0019011b37a4b691d | 42.803279 | 158 | 0.731662 | 5.128599 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/style/StyleProperty.kt | 13 | 3078 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl.customFrameDecorations.style
import com.intellij.openapi.diagnostic.Logger
import java.awt.Color
import java.awt.Insets
import javax.swing.AbstractButton
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.border.Border
sealed class StyleProperty(
private val setProperty: (JComponent, Any?) -> Unit,
val getProperty: (JComponent) -> Any?,
private val valueType: Class<out Any?>,
val componentType: Class<out Any?> = JComponent::class.java
) {
companion object {
fun getPropertiesSnapshot(component: JComponent): Properties {
val base = Properties()
for (p in arrayOf(FOREGROUND, BACKGROUND, OPAQUE, BORDER, ICON, MARGIN)) {
if (p.componentType.isInstance(component))
base.setValue(p, p.getProperty(component))
}
return base
}
}
object OPAQUE : StyleProperty(
{ component, isOpaque -> component.isOpaque = if (isOpaque == null) true else isOpaque as Boolean },
{ component -> component.isOpaque },
Boolean::class.java
)
object BACKGROUND : StyleProperty(
{ component, background -> component.background = background as Color? },
{ component -> component.background },
Color::class.java
)
object FOREGROUND : StyleProperty(
{ component, foreground -> component.foreground = foreground as Color? },
{ component -> component.foreground },
Color::class.java
)
object BORDER : StyleProperty(
{ component, border -> component.border = border as Border? },
{ component -> component.border },
Border::class.java
)
object ICON : StyleProperty(
{ component, icon -> (component as AbstractButton).icon = icon as Icon? },
{ component -> (component as AbstractButton).icon },
Icon::class.java,
AbstractButton::class.java
)
object MARGIN : StyleProperty(
{ component, margin -> (component as AbstractButton).margin = margin as Insets? },
{ component -> (component as AbstractButton).margin },
Insets::class.java,
AbstractButton::class.java
)
protected val log = Logger.getInstance(StyleProperty::class.java)
private fun checkTypes(component: JComponent, value: Any?): Boolean {
if (!componentType.isInstance(component)) {
log.warn(
javaClass.canonicalName + " Incorrect class type: " + component.javaClass.canonicalName + " instead of " + componentType.canonicalName)
return false
}
if (valueType == Boolean::class.java) {
return (value == true || value == false)
}
if (!(value == null || valueType.isInstance(value))) {
log.warn(
javaClass.canonicalName + " Incorrect value type: " + value.javaClass.canonicalName + " instead of " + valueType.canonicalName)
return false
}
return true
}
fun apply(component: JComponent, value: Any?) {
if (!checkTypes(component, value)) {
return
}
setProperty(component, value)
}
} | apache-2.0 | 43a2fe4481c5e0aef1323671062633cc | 32.835165 | 143 | 0.68681 | 4.409742 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceCallFixUtils.kt | 4 | 1986 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.types.typeUtil.isUnit
fun KtExpression.shouldHaveNotNullType(): Boolean {
val type = when (val parent = parent) {
is KtBinaryExpression -> parent.left?.let { it.getType(it.analyze()) }
is KtProperty -> parent.typeReference?.let { it.analyze()[BindingContext.TYPE, it] }
is KtReturnExpression -> parent.getTargetFunctionDescriptor(analyze())?.returnType
is KtValueArgument -> {
val call = parent.getStrictParentOfType<KtCallExpression>()?.resolveToCall()
(call?.getArgumentMapping(parent) as? ArgumentMatch)?.valueParameter?.type
}
is KtBlockExpression -> {
if (parent.statements.lastOrNull() != this) return false
val functionLiteral = parent.parent as? KtFunctionLiteral ?: return false
if (functionLiteral.parent !is KtLambdaExpression) return false
functionLiteral.analyze()[BindingContext.FUNCTION, functionLiteral]?.returnType
}
else -> null
} ?: return false
return !type.isMarkedNullable && !type.isUnit() && !type.isTypeParameter()
}
| apache-2.0 | 74a108fd2ad5a356e982a6c9461be74d | 52.675676 | 158 | 0.752769 | 4.820388 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/dynamodb/src/main/kotlin/com/kotlin/dynamodb/QueryTable.kt | 1 | 2789 | // snippet-sourcedescription:[QueryTable.kt demonstrates how to query an Amazon DynamoDB table.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon DynamoDB]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.dynamodb
// snippet-start:[dynamodb.kotlin.query.import]
import aws.sdk.kotlin.services.dynamodb.DynamoDbClient
import aws.sdk.kotlin.services.dynamodb.model.AttributeValue
import aws.sdk.kotlin.services.dynamodb.model.QueryRequest
import kotlin.system.exitProcess
// snippet-end:[dynamodb.kotlin.query.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<tableName>
Where:
tableName - The Amazon DynamoDB table to scan (for example, Music3).
partitionKeyName - The partition key name of the Amazon DynamoDB table (for example, Artist).
partitionKeyVal - The value of the partition key that should match (for example, Famous Band).
"""
if (args.size != 3) {
println(usage)
exitProcess(0)
}
val tableName = args[0]
val partitionKeyName = args[1]
val partitionKeyVal = args[2]
// For more information about an alias, see:
// https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html
val partitionAlias = "#a"
val count = queryDynTable(tableName, partitionKeyName, partitionKeyVal, partitionAlias)
print("There is $count item in $tableName")
}
// snippet-start:[dynamodb.kotlin.query.main]
suspend fun queryDynTable(
tableNameVal: String,
partitionKeyName: String,
partitionKeyVal: String,
partitionAlias: String
): Int {
val attrNameAlias = mutableMapOf<String, String>()
attrNameAlias[partitionAlias] = partitionKeyName
// Set up mapping of the partition name with the value.
val attrValues = mutableMapOf<String, AttributeValue>()
attrValues[":$partitionKeyName"] = AttributeValue.S(partitionKeyVal)
val request = QueryRequest {
tableName = tableNameVal
keyConditionExpression = "$partitionAlias = :$partitionKeyName"
expressionAttributeNames = attrNameAlias
this.expressionAttributeValues = attrValues
}
DynamoDbClient { region = "us-east-1" }.use { ddb ->
val response = ddb.query(request)
return response.count
}
}
// snippet-end:[dynamodb.kotlin.query.main]
| apache-2.0 | bf0572731fab1af05bde97d97019ed06 | 32.432099 | 113 | 0.701685 | 4.23217 | false | false | false | false |
ThePreviousOne/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateJob.kt | 1 | 1663 | package eu.kanade.tachiyomi.data.library
import com.evernote.android.job.Job
import com.evernote.android.job.JobManager
import com.evernote.android.job.JobRequest
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class LibraryUpdateJob : Job() {
override fun onRunJob(params: Params): Result {
LibraryUpdateService.start(context)
return Job.Result.SUCCESS
}
companion object {
const val TAG = "LibraryUpdate"
fun setupTask(prefInterval: Int? = null) {
val preferences = Injekt.get<PreferencesHelper>()
val interval = prefInterval ?: preferences.libraryUpdateInterval().getOrDefault()
if (interval > 0) {
val restrictions = preferences.libraryUpdateRestriction()
val acRestriction = "ac" in restrictions
val wifiRestriction = if ("wifi" in restrictions)
JobRequest.NetworkType.UNMETERED
else
JobRequest.NetworkType.CONNECTED
JobRequest.Builder(TAG)
.setPeriodic(interval * 60 * 60 * 1000L)
.setRequiredNetworkType(wifiRestriction)
.setRequiresCharging(acRestriction)
.setPersisted(true)
.setUpdateCurrent(true)
.build()
.schedule()
}
}
fun cancelTask() {
JobManager.instance().cancelAllForTag(TAG)
}
}
} | apache-2.0 | e6f60eef17cc6505ba42de6cb5e3cd3d | 34.404255 | 93 | 0.601323 | 5.180685 | false | false | false | false |
phylame/jem | jem-core/src/main/kotlin/jem/Books.kt | 1 | 4678 | /*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jem
import jclp.HierarchySupport
import jclp.ValueMap
import jclp.io.Flob
import jclp.log.Log
import jclp.release
import jclp.retain
import jclp.text.Text
import jem.Attributes.VALUE_SEPARATOR
open class Chapter(
title: String = "", text: Text? = null, cover: Flob? = null, intro: Text? = null, tag: Any? = null
) : HierarchySupport<Chapter>(), Cloneable {
var attributes = Attributes.newAttributes()
private set
var text: Text? = text
set(value) {
field.release()
field = value.retain()
}
var tag: Any? = tag
set(value) {
field.release()
field = value.retain()
}
init {
set(TITLE, title)
if (cover != null) {
set(COVER, cover)
}
if (intro != null) {
set(INTRO, intro)
}
}
constructor(chapter: Chapter, deepCopy: Boolean) : this() {
@Suppress("LeakingThis")
chapter.copyTo(this, deepCopy)
}
operator fun get(name: String) = attributes[name]
operator fun contains(name: String) = name in attributes
operator fun set(name: String, value: Any) = attributes.set(name, value)
fun getValues(name: String): List<String>?
= (attributes[name] as? CharSequence)?.split(Attributes.VALUE_SEPARATOR)
fun setValues(name: String, values: Collection<Any>)
= attributes.set(name, values.joinToString(VALUE_SEPARATOR))
val isSection inline get() = size != 0
fun clear(cleanup: Boolean) {
if (cleanup) forEach { it.cleanup() }
clear()
}
public override fun clone() = (super.clone() as Chapter).also {
copyTo(it, true)
}
protected open fun copyTo(chapter: Chapter, deepCopy: Boolean) {
chapter.tag = tag
chapter.text = text
chapter.parent = null
chapter.children = children
chapter.attributes = attributes
if (deepCopy) {
chapter.attributes = attributes.clone()
val list = ArrayList<Chapter>(children.size)
children.mapTo(list) { it.clone() }
chapter.children = list
text.retain()
tag.retain()
}
}
private var isCleaned = false
open fun cleanup() {
isCleaned = true
clear(true)
attributes.clear()
text = null
tag = null
}
protected fun finalize() {
if (!isCleaned) {
Log.w("Chapter") { "$title@${hashCode()} is not cleaned" }
}
}
override fun toString(): String {
val b = StringBuilder(javaClass.simpleName)
b.append("@0x").append(hashCode().toString(16))
b.append("%").append(attributes)
if (text != null) {
b.append(", text")
}
if (isSection) {
b.append(", ").append(size).append(" chapter(s)")
}
return b.toString()
}
}
fun Chapter.newChapter(title: String = "", text: Text? = null, cover: Flob? = null, intro: Text? = null): Chapter {
val chapter = Chapter(title, text, cover, intro)
append(chapter)
return chapter
}
open class Book : Chapter {
var extensions = ValueMap()
private set
constructor(title: String = "", author: String = "") : super(title) {
attributes[AUTHOR] = author
}
constructor(chapter: Chapter, deepCopy: Boolean) : super(chapter, deepCopy)
override fun cleanup() {
super.cleanup()
extensions.clear()
}
override fun copyTo(chapter: Chapter, deepCopy: Boolean) {
super.copyTo(chapter, deepCopy)
if (chapter is Book) {
chapter.extensions = if (deepCopy) extensions.clone() else extensions
}
}
override fun toString(): String {
val b = StringBuilder(super.toString())
if (extensions.isNotEmpty()) {
b.append(", #").append(extensions)
}
return b.toString()
}
}
fun Chapter.asBook() = this as? Book ?: Book(this, false)
| apache-2.0 | 3715f3a207be214a4997775996ebf316 | 26.680473 | 115 | 0.596836 | 4.147163 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/base/db/migrations/Migration6.kt | 1 | 2208 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.base.db.migrations
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.room.migration.Migration
import de.dreier.mytargets.shared.SharedApplicationInstance
import java.io.File
import java.io.IOException
object Migration6 : Migration(5, 6) {
override fun migrate(database: SupportSQLiteDatabase) {
val filesDir = SharedApplicationInstance.context.filesDir
// Migrate all bow images
var cur = database.query("SELECT image FROM BOW WHERE image IS NOT NULL")
if (cur.moveToFirst()) {
val fileName = cur.getString(0)
try {
val file = File.createTempFile("img_", ".png", filesDir)
File(fileName).copyTo(file, overwrite = true)
database.execSQL(
"UPDATE BOW SET image=\"" + file.name + "\" WHERE image=\"" +
fileName + "\""
)
} catch (e: IOException) {
e.printStackTrace()
}
}
cur.close()
// Migrate all arrows images
cur = database.query("SELECT image FROM ARROW WHERE image IS NOT NULL")
if (cur.moveToFirst()) {
val fileName = cur.getString(0)
try {
val file = File.createTempFile("img_", ".png", filesDir)
File(fileName).copyTo(file)
database.execSQL(
"UPDATE ARROW SET image=\"" + file.name + "\" WHERE image=\"" +
fileName + "\""
)
} catch (e: IOException) {
e.printStackTrace()
}
}
cur.close()
}
}
| gpl-2.0 | 9bfacdbd14b41c0de974d28e2f745248 | 33.5 | 83 | 0.586051 | 4.768898 | false | false | false | false |
innobead/pygradle | src/main/kotlin/com/innobead/gradle/task/PythonCleanTask.kt | 1 | 1498 | package com.innobead.gradle.task
import com.innobead.gradle.GradleSupport
import com.innobead.gradle.plugin.PythonPlugin
import com.innobead.gradle.plugin.PythonPluginExtension
import org.gradle.api.tasks.TaskAction
@GradleSupport
class PythonCleanTask : AbstractTask() {
init {
group = PythonPlugin.name
description = "Clean Python compiled things"
project.afterEvaluate {
project.getTasksByName("clean", false).firstOrNull()?.dependsOn(this)
}
}
@TaskAction
fun action() {
val pythonPluginExtension = project.extensions.getByName("python") as PythonPluginExtension
val sourceDirs = mutableListOf<String>()
if (pythonPluginExtension.sourceDirs != null) {
sourceDirs.addAll(pythonPluginExtension.sourceDirs?.map { it.absolutePath } ?: emptyList())
}
if (pythonPluginExtension.testReportDir != null) {
sourceDirs.addAll(pythonPluginExtension.testSourceDirs?.map { it.absolutePath } ?: emptyList())
}
logger.lifecycle("Cleaning Python compiled things")
if (sourceDirs.size == 0) {
return
}
val commands = mutableListOf("find ${sourceDirs.joinToString(" ") { "'$it'" }} -name '*.pyc' -delete")
project.exec {
it.commandLine(
listOf(
"bash", "-c",
commands.joinToString(";")
)
)
}.rethrowFailure()
}
} | apache-2.0 | 20f2b021d847320ac27ada151484ba96 | 30.229167 | 110 | 0.618158 | 4.81672 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/roots/IndexableEntityProviderMethods.kt | 3 | 3758 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.roots
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.indexing.roots.builders.IndexableIteratorBuilders
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.findModule
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.isModuleUnloaded
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity
object IndexableEntityProviderMethods {
fun createIterators(entity: ModuleEntity,
roots: List<VirtualFile>,
storage: EntityStorage): Collection<IndexableFilesIterator> {
if (roots.isEmpty()) return emptyList()
val module = entity.findModule(storage) ?: return emptyList()
return createIterators(module, roots)
}
fun createIterators(module: Module, roots: List<VirtualFile>): Set<IndexableFilesIterator> {
return setOf(ModuleIndexableFilesIteratorImpl(module, roots, true))
}
fun createIterators(entity: ModuleEntity, entityStorage: EntityStorage, project: Project): Collection<IndexableFilesIterator> {
@Suppress("DEPRECATION")
if (DefaultProjectIndexableFilesContributor.indexProjectBasedOnIndexableEntityProviders()) {
if (entity.isModuleUnloaded(entityStorage)) return emptyList()
val builders = mutableListOf<IndexableEntityProvider.IndexableIteratorBuilder>()
for (provider in IndexableEntityProvider.EP_NAME.extensionList) {
if (provider is IndexableEntityProvider.Existing) {
builders.addAll(provider.getIteratorBuildersForExistingModule(entity, entityStorage, project))
}
}
return IndexableIteratorBuilders.instantiateBuilders(builders, project, entityStorage)
}
else {
val module = entity.findModule(entityStorage)
if (module == null) {
return emptyList()
}
return ModuleIndexableFilesIteratorImpl.getModuleIterators(module)
}
}
fun createIterators(sdk: Sdk): Collection<IndexableFilesIterator> {
return listOf(SdkIndexableFilesIteratorImpl.createIterator(sdk))
}
private fun getLibIteratorsByName(libraryTable: LibraryTable, name: String): List<IndexableFilesIterator>? =
libraryTable.getLibraryByName(name)?.run { LibraryIndexableFilesIteratorImpl.createIteratorList(this) }
fun createLibraryIterators(name: String, project: Project): List<IndexableFilesIterator> = runReadAction {
val registrar = LibraryTablesRegistrar.getInstance()
getLibIteratorsByName(registrar.libraryTable, name)?.also { return@runReadAction it }
for (customLibraryTable in registrar.customLibraryTables) {
getLibIteratorsByName(customLibraryTable, name)?.also { return@runReadAction it }
}
val storage = WorkspaceModel.getInstance(project).entityStorage.current
return@runReadAction storage.entities(LibraryEntity::class.java).firstOrNull { it.name == name }?.let {
storage.libraryMap.getDataByEntity(it)
}?.run {
LibraryIndexableFilesIteratorImpl.createIteratorList(this)
} ?: emptyList()
}
} | apache-2.0 | 1129e402fa1cdcb1b35c40b3bdcfa59f | 49.797297 | 129 | 0.785524 | 5.078378 | false | false | false | false |
eugenkiss/kotlinfx | kotlinfx-core/src/main/kotlin/kotlinfx/builders/Chart.kt | 2 | 5477 | // http://docs.oracle.com/javase/8/javafx/api/javafx/scene/chart/package-summary.html
package kotlinfx.builders
public fun AreaChart<X,Y>(
xAxis: javafx.scene.chart.Axis<X>,
yAxis: javafx.scene.chart.Axis<Y>,
data: javafx.collections.ObservableList<javafx.scene.chart.XYChart.Series<X,Y>> = javafx.collections.FXCollections.emptyObservableList()!!,
f: javafx.scene.chart.AreaChart<X,Y>.() -> Unit = {}): javafx.scene.chart.AreaChart<X,Y>
{
val x = javafx.scene.chart.AreaChart<X,Y>(xAxis, yAxis, data)
x.f()
return x
}
// For abstract javafx.scene.chart.Axis<T> a builder does not make sense.
public fun TickMark<T>(
f: javafx.scene.chart.Axis.TickMark<T>.() -> Unit = {}): javafx.scene.chart.Axis.TickMark<T>
{
val x = javafx.scene.chart.Axis.TickMark<T>()
x.f()
return x
}
public fun BarChart<X,Y>(
xAxis: javafx.scene.chart.Axis<X>,
yAxis: javafx.scene.chart.Axis<Y>,
data: javafx.collections.ObservableList<javafx.scene.chart.XYChart.Series<X,Y>> = javafx.collections.FXCollections.emptyObservableList()!!,
categoryGap: Double = 10.0,
f: javafx.scene.chart.BarChart<X,Y>.() -> Unit = {}): javafx.scene.chart.BarChart<X,Y>
{
val x = javafx.scene.chart.BarChart<X,Y>(xAxis, yAxis, data, categoryGap)
x.f()
return x
}
public fun BubbleChart<X,Y>(
xAxis: javafx.scene.chart.Axis<X>,
yAxis: javafx.scene.chart.Axis<Y>,
data: javafx.collections.ObservableList<javafx.scene.chart.XYChart.Series<X,Y>> = javafx.collections.FXCollections.emptyObservableList()!!,
f: javafx.scene.chart.BubbleChart<X,Y>.() -> Unit = {}): javafx.scene.chart.BubbleChart<X,Y>
{
val x = javafx.scene.chart.BubbleChart<X,Y>(xAxis, yAxis, data)
x.f()
return x
}
public fun CategoryAxis(
categories: javafx.collections.ObservableList<String> = javafx.collections.FXCollections.emptyObservableList()!!,
f: javafx.scene.chart.CategoryAxis.() -> Unit = {}): javafx.scene.chart.CategoryAxis
{
val x = javafx.scene.chart.CategoryAxis(categories)
x.f()
return x
}
// For abstract javafx.scene.chart.Chart a builder does not make sense.
public fun LineChart<X,Y>(
xAxis: javafx.scene.chart.Axis<X>,
yAxis: javafx.scene.chart.Axis<Y>,
data: javafx.collections.ObservableList<javafx.scene.chart.XYChart.Series<X,Y>> = javafx.collections.FXCollections.emptyObservableList()!!,
f: javafx.scene.chart.LineChart<X,Y>.() -> Unit = {}): javafx.scene.chart.LineChart<X,Y>
{
val x = javafx.scene.chart.LineChart<X,Y>(xAxis, yAxis, data)
x.f()
return x
}
public fun NumberAxis(
lowerBound: Double,
upperBound: Double,
tickUnit: Double,
axisLabel: String,
f: javafx.scene.chart.NumberAxis.() -> Unit = {}): javafx.scene.chart.NumberAxis
{
val x = javafx.scene.chart.NumberAxis(axisLabel, lowerBound, upperBound, tickUnit)
x.f()
return x
}
public fun NumberAxis(
lowerBound: Double,
upperBound: Double,
tickUnit: Double,
f: javafx.scene.chart.NumberAxis.() -> Unit = {}): javafx.scene.chart.NumberAxis
{
val x = javafx.scene.chart.NumberAxis(lowerBound, upperBound, tickUnit)
x.f()
return x
}
public fun NumberAxis(
f: javafx.scene.chart.NumberAxis.() -> Unit = {}): javafx.scene.chart.NumberAxis
{
val x = javafx.scene.chart.NumberAxis()
x.f()
return x
}
// For immutable javafx.scene.chart.NumberAxis.DefaultFormatter a builder does not make sense.
public fun PieChart(
data: javafx.collections.ObservableList<javafx.scene.chart.PieChart.Data> = javafx.collections.FXCollections.emptyObservableList()!!,
f: javafx.scene.chart.PieChart.() -> Unit = {}): javafx.scene.chart.PieChart
{
val x = javafx.scene.chart.PieChart(data)
x.f()
return x
}
// For javafx.scene.chart.Piechart.Data a builder does not make sense.
public fun ScatterChart<X,Y>(
xAxis: javafx.scene.chart.Axis<X>,
yAxis: javafx.scene.chart.Axis<Y>,
data: javafx.collections.ObservableList<javafx.scene.chart.XYChart.Series<X,Y>> = javafx.collections.FXCollections.emptyObservableList()!!,
f: javafx.scene.chart.ScatterChart<X,Y>.() -> Unit = {}): javafx.scene.chart.ScatterChart<X,Y>
{
val x = javafx.scene.chart.ScatterChart<X,Y>(xAxis, yAxis, data)
x.f()
return x
}
public fun StackedAreaChart<X,Y>(
xAxis: javafx.scene.chart.Axis<X>,
yAxis: javafx.scene.chart.Axis<Y>,
data: javafx.collections.ObservableList<javafx.scene.chart.XYChart.Series<X,Y>> = javafx.collections.FXCollections.emptyObservableList()!!,
f: javafx.scene.chart.StackedAreaChart<X,Y>.() -> Unit = {}): javafx.scene.chart.StackedAreaChart<X,Y>
{
val x = javafx.scene.chart.StackedAreaChart<X,Y>(xAxis, yAxis, data)
x.f()
return x
}
public fun StackedBarChart<X,Y>(
xAxis: javafx.scene.chart.Axis<X>,
yAxis: javafx.scene.chart.Axis<Y>,
data: javafx.collections.ObservableList<javafx.scene.chart.XYChart.Series<X,Y>> = javafx.collections.FXCollections.emptyObservableList()!!,
categoryGap: Double = 10.0,
f: javafx.scene.chart.StackedBarChart<X,Y>.() -> Unit = {}): javafx.scene.chart.StackedBarChart<X,Y>
{
val x = javafx.scene.chart.StackedBarChart<X,Y>(xAxis, yAxis, data, categoryGap)
x.f()
return x
}
// For abstract javafx.scene.chart.XYChart<X,Y> a builder does not make sense.
// For javafx.scene.chart.XYChart<X,Y>.Data a builder does not make sense.
// For javafx.scene.chart.XYChart<X,Y>.Series a builder does not offer much.
| mit | ac0cf5419668c5af76c346fec9b55ff7 | 35.513333 | 143 | 0.699471 | 3.327461 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/PlainTextPasteImportResolver.kt | 1 | 11178 | // 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.conversion.copy
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.*
import com.intellij.psi.search.PsiShortNamesCache
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMapper
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.matches
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull
import org.jetbrains.kotlin.idea.base.util.runReadActionInSmartMode
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMemberDescriptor
import org.jetbrains.kotlin.idea.core.isVisible
import org.jetbrains.kotlin.idea.imports.canBeReferencedViaImport
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.psiUtil.referenceExpression
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
/**
* Tested with TextJavaToKotlinCopyPasteConversionTestGenerated
*/
class PlainTextPasteImportResolver(private val dataForConversion: DataForConversion, val targetFile: KtFile) {
private val file = dataForConversion.file
private val project = targetFile.project
private val importList = file.importList!!
// keep access to deprecated PsiElementFactory.SERVICE for bwc with <= 191
private val psiElementFactory = PsiElementFactory.getInstance(project)
private val bindingContext by lazy { targetFile.analyzeWithContent() }
private val resolutionFacade = targetFile.getResolutionFacade()
private val shortNameCache = PsiShortNamesCache.getInstance(project)
private val scope = file.resolveScope
private val failedToResolveReferenceNames = HashSet<String>()
private var ambiguityInResolution = false
private var couldNotResolve = false
val addedImports = mutableListOf<PsiImportStatementBase>()
private fun canBeImported(descriptor: DeclarationDescriptorWithVisibility?): Boolean {
return descriptor != null
&& descriptor.canBeReferencedViaImport()
&& descriptor.isVisible(targetFile, null, bindingContext, resolutionFacade)
}
private fun addImport(importStatement: PsiImportStatementBase, shouldAddToTarget: Boolean = false) {
file.importList?.let {
it.add(importStatement)
if (shouldAddToTarget)
addedImports.add(importStatement)
}
}
fun addImportsFromTargetFile() {
if (importList in dataForConversion.elementsAndTexts.toList()) return
val task = {
val addImportList = mutableListOf<PsiImportStatementBase>()
fun tryConvertKotlinImport(importDirective: KtImportDirective) {
val importPath = importDirective.importPath
val importedReference = importDirective.importedReference
if (importPath != null && !importPath.hasAlias() && importedReference is KtDotQualifiedExpression) {
val receiver = importedReference
.receiverExpression
.referenceExpression()
?.mainReference
?.resolve()
val selector = importedReference
.selectorExpression
?.referenceExpression()
?.mainReference
?.resolve()
val isPackageReceiver = receiver is PsiPackage
val isClassReceiver = receiver is PsiClass
val isClassSelector = selector is PsiClass
if (importPath.isAllUnder) {
when {
isClassReceiver ->
addImportList.add(psiElementFactory.createImportStaticStatement(receiver as PsiClass, "*"))
isPackageReceiver ->
addImportList.add(psiElementFactory.createImportStatementOnDemand((receiver as PsiPackage).qualifiedName))
}
} else {
when {
isClassSelector ->
addImportList.add(psiElementFactory.createImportStatement(selector as PsiClass))
isClassReceiver ->
addImportList.add(
psiElementFactory.createImportStaticStatement(
receiver as PsiClass,
importPath.importedName!!.asString()
)
)
}
}
}
}
runReadAction {
val importDirectives = targetFile.importDirectives
importDirectives.forEachIndexed { index, value ->
ProgressManager.checkCanceled()
ProgressManager.getInstance().progressIndicator?.fraction = 1.0 * index / importDirectives.size
tryConvertKotlinImport(value)
}
}
ApplicationManager.getApplication().invokeAndWait {
runWriteAction { addImportList.forEach { addImport(it) } }
}
}
ProgressManager.getInstance().runProcessWithProgressSynchronously(
task, KotlinBundle.message("copy.text.adding.imports"), true, project
)
}
fun tryResolveReferences() {
val task = {
fun performWriteAction(block: () -> Unit) {
ApplicationManager.getApplication().invokeAndWait { runWriteAction { block() } }
}
fun tryResolveReference(reference: PsiQualifiedReference): Boolean {
ProgressManager.checkCanceled()
if (runReadAction { reference.resolve() } != null) return true
val referenceName = runReadAction { reference.referenceName } ?: return false
if (referenceName in failedToResolveReferenceNames) return false
if (runReadAction { reference.qualifier } != null) return false
val classes = runReadAction {
shortNameCache.getClassesByName(referenceName, scope)
.mapNotNull { psiClass ->
val containingFile = psiClass.containingFile
if (RootKindFilter.everything.matches(containingFile)) {
psiClass to psiClass.getJavaMemberDescriptor() as? ClassDescriptor
} else null
}.filter { canBeImported(it.second) }
}
classes.find { (_, descriptor) ->
JavaToKotlinClassMapper.mapPlatformClass(descriptor!!).isNotEmpty()
}?.let { (psiClass, _) ->
performWriteAction { addImport(psiElementFactory.createImportStatement(psiClass)) }
}
if (runReadAction { reference.resolve() } != null) return true
classes.singleOrNull()?.let { (psiClass, _) ->
performWriteAction { addImport(psiElementFactory.createImportStatement(psiClass), true) }
}
when {
runReadAction { reference.resolve() } != null -> return true
classes.isNotEmpty() -> {
ambiguityInResolution = true
return false
}
}
val members = runReadAction {
(shortNameCache.getMethodsByName(referenceName, scope).asList() +
shortNameCache.getFieldsByName(referenceName, scope).asList())
.asSequence()
.map { it as PsiMember }
.filter { it.moduleInfoOrNull != null }
.map { it to it.getJavaMemberDescriptor(resolutionFacade) as? DeclarationDescriptorWithVisibility }
.filter { canBeImported(it.second) }
.toList()
}
ProgressManager.checkCanceled()
members.singleOrNull()?.let { (psiMember, _) ->
performWriteAction {
addImport(
psiElementFactory.createImportStaticStatement(psiMember.containingClass!!, psiMember.name!!),
true
)
}
}
when {
runReadAction { reference.resolve() } != null -> return false
members.isNotEmpty() -> ambiguityInResolution = true
else -> couldNotResolve = true
}
return false
}
val smartPointerManager = SmartPointerManager.getInstance(file.project)
val elementsWithUnresolvedRef = project.runReadActionInSmartMode {
PsiTreeUtil.collectElements(file) { element ->
element.reference != null
&& element.reference is PsiQualifiedReference
&& element.reference?.resolve() == null
}.map { smartPointerManager.createSmartPsiElementPointer(it) }
}
val reversed = elementsWithUnresolvedRef.reversed()
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator?.isIndeterminate = false
reversed.forEachIndexed { index, value ->
progressIndicator?.fraction = 1.0 * index / reversed.size
runReadAction { value.element?.reference?.safeAs<PsiQualifiedReference>() }?.let { reference ->
if (!tryResolveReference(reference)) {
runReadAction { reference.referenceName }?.let {
failedToResolveReferenceNames += it
}
}
}
}
}
ProgressManager.checkCanceled()
ProgressManager.getInstance().runProcessWithProgressSynchronously(
task, KotlinBundle.message("copy.text.resolving.references"), true, project
)
}
}
| apache-2.0 | 1e0f496a0e2cc99011683f840e636995 | 45.966387 | 158 | 0.598587 | 6.435233 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/cabal/completion/CabalCompletionContributor.kt | 1 | 3242 | package org.jetbrains.cabal.completion
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.*
import org.jetbrains.cabal.parser.*
import org.jetbrains.cabal.psi.*
import org.jetbrains.cabal.CabalInterface
import org.jetbrains.cabal.CabalFile
import java.util.*
open class CabalCompletionContributor : CompletionContributor() {
override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet): Unit {
if (parameters.completionType == CompletionType.BASIC) {
val values = ArrayList<String>()
val current = parameters.position
val parent = current.parent
if (parent == null) {
return
}
var caseSensitivity = true
when (parent) {
is CabalFile -> {
values.addAll(PKG_DESCR_FIELDS.keys.map { it + ":" })
values.addAll(TOP_SECTION_NAMES)
caseSensitivity = false
}
is RangedValue -> {
if ((parent is Name)) {
if (parent.isFlagNameInCondition()) {
values.addAll(parent.getAvailableValues().map({ it + ")" }))
caseSensitivity = false
} else if (parent.getParent() is InvalidField) {
values.addAll(parent.getAvailableValues().map({
if (it in SECTIONS.keys) it else it + ":"
}))
caseSensitivity = false
}
} else values.addAll(parent.getAvailableValues())
}
is InvalidValue -> {
if (parent.getParent() is BoolField) {
values.addAll(BOOL_VALS)
}
}
is Path -> {
val grandParent = parent.getParent()
if (grandParent is PathsField) {
val originalRootDir = parameters.originalFile.virtualFile!!.parent!!
values.addAll(grandParent.getNextAvailableFile(parent, originalRootDir))
}
}
is Identifier -> {
var parentField = parent
while ((parentField !is Field) && (parentField !is CabalFile) && (parentField != null)) {
parentField = parentField.parent
}
if (parentField is BuildDependsField) {
val project = current.project
values.addAll(CabalInterface(project).getInstalledPackagesList().map({ it.name }))
}
}
}
for (value in values) {
val lookupElemBuilder = LookupElementBuilder.create(value).withCaseSensitivity(caseSensitivity)!!
result.addElement(lookupElemBuilder)
}
}
}
}
| apache-2.0 | 4e3c9bc0e1bf1682a94bea75a29bc2a9 | 41.103896 | 113 | 0.524985 | 5.667832 | false | false | false | false |
JetBrains/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/TestModulePropertiesBridge.kt | 1 | 3375 | // 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.legacyBridge.module.roots
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.TestModuleProperties
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.findModule
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleId
import com.intellij.workspaceModel.storage.bridgeEntities.TestModulePropertiesEntity
import com.intellij.workspaceModel.storage.bridgeEntities.modifyEntity
class TestModulePropertiesBridge(private val currentModule: Module): TestModuleProperties() {
private val workspaceModel = WorkspaceModel.getInstance(currentModule.project)
override fun getProductionModuleName(): String? {
return getModuleEntity()?.testProperties?.productionModuleId?.name
}
override fun getProductionModule(): Module? {
val moduleId = getModuleEntity()?.testProperties?.productionModuleId ?: return null
val moduleEntity = workspaceModel.entityStorage.current.resolve(moduleId) ?: return null
return moduleEntity.findModule(workspaceModel.entityStorage.current)
}
override fun setProductionModuleName(moduleName: String?) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
val moduleEntity = getModuleEntity() ?: error("Module entity with name: ${currentModule.name} should be available")
if (moduleEntity.testProperties?.productionModuleId?.name == moduleName) return
workspaceModel.updateProjectModel("Linking production module with the test") { builder ->
moduleEntity.testProperties?.let { builder.removeEntity(it) }
if (moduleName == null) return@updateProjectModel
val productionModuleId = ModuleId(moduleName)
builder.resolve(productionModuleId) ?: error("Can't find module by name: $moduleName")
builder.modifyEntity(moduleEntity) {
this.testProperties = TestModulePropertiesEntity(productionModuleId, moduleEntity.entitySource)
}
}
}
fun setProductionModuleNameToBuilder(moduleName: String?, builder: MutableEntityStorage) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
val moduleEntity = builder.resolve(ModuleId(currentModule.name)) ?: error("Module entity with name: ${currentModule.name} should be available")
if (moduleEntity.testProperties?.productionModuleId?.name == moduleName) return
moduleEntity.testProperties?.let { builder.removeEntity(it) }
if (moduleName == null) return
val productionModuleId = ModuleId(moduleName)
if (builder.resolve(productionModuleId) == null) {
thisLogger().warn("Can't find module by name: $moduleName, but it can be a valid case e.g at gradle import")
}
builder.modifyEntity(moduleEntity) {
this.testProperties = TestModulePropertiesEntity(productionModuleId, moduleEntity.entitySource)
}
}
private fun getModuleEntity(): ModuleEntity? {
return workspaceModel.entityStorage.current.resolve(ModuleId(currentModule.name))
}
} | apache-2.0 | 852c22c02fc241a465cc242cf188a150 | 53.451613 | 147 | 0.792889 | 5.113636 | false | true | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/test/exceptions/WithContextExceptionHandlingTest.kt | 1 | 8579 | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.exceptions
import kotlinx.coroutines.*
import org.junit.Test
import org.junit.runner.*
import org.junit.runners.*
import kotlin.coroutines.*
import kotlin.test.*
@RunWith(Parameterized::class)
class WithContextExceptionHandlingTest(private val mode: Mode) : TestBase() {
enum class Mode { WITH_CONTEXT, ASYNC_AWAIT }
companion object {
@Parameterized.Parameters(name = "mode={0}")
@JvmStatic
fun params(): Collection<Array<Any>> = Mode.values().map { arrayOf<Any>(it) }
}
@Test
fun testCancellation() = runTest {
/*
* context cancelled without cause
* code itself throws TE2
* Result: TE2
*/
runCancellation(null, TestException2()) { e ->
assertTrue(e is TestException2)
assertNull(e.cause)
val suppressed = e.suppressed
assertTrue(suppressed.isEmpty())
}
}
@Test
fun testCancellationWithException() = runTest {
/*
* context cancelled with TCE
* block itself throws TE2
* Result: TE (CancellationException is always ignored)
*/
val cancellationCause = TestCancellationException()
runCancellation(cancellationCause, TestException2()) { e ->
assertTrue(e is TestException2)
assertNull(e.cause)
val suppressed = e.suppressed
assertTrue(suppressed.isEmpty())
}
}
@Test
fun testSameException() = runTest {
/*
* context cancelled with TCE
* block itself throws the same TCE
* Result: TCE
*/
val cancellationCause = TestCancellationException()
runCancellation(cancellationCause, cancellationCause) { e ->
assertTrue(e is TestCancellationException)
assertNull(e.cause)
val suppressed = e.suppressed
assertTrue(suppressed.isEmpty())
}
}
@Test
fun testSameCancellation() = runTest {
/*
* context cancelled with TestCancellationException
* block itself throws the same TCE
* Result: TCE
*/
val cancellationCause = TestCancellationException()
runCancellation(cancellationCause, cancellationCause) { e ->
assertSame(e, cancellationCause)
assertNull(e.cause)
val suppressed = e.suppressed
assertTrue(suppressed.isEmpty())
}
}
@Test
fun testSameCancellationWithException() = runTest {
/*
* context cancelled with CancellationException(TE)
* block itself throws the same TE
* Result: TE
*/
val cancellationCause = CancellationException()
val exception = TestException()
cancellationCause.initCause(exception)
runCancellation(cancellationCause, exception) { e ->
assertSame(exception, e)
assertNull(e.cause)
assertTrue(e.suppressed.isEmpty())
}
}
@Test
fun testConflictingCancellation() = runTest {
/*
* context cancelled with TCE
* block itself throws CE(TE)
* Result: TE (because cancellation exception is always ignored and not handled)
*/
val cancellationCause = TestCancellationException()
val thrown = CancellationException()
thrown.initCause(TestException())
runCancellation(cancellationCause, thrown) { e ->
assertSame(cancellationCause, e)
assertTrue(e.suppressed.isEmpty())
}
}
@Test
fun testConflictingCancellation2() = runTest {
/*
* context cancelled with TE
* block itself throws CE
* Result: TE
*/
val cancellationCause = TestCancellationException()
val thrown = CancellationException()
runCancellation(cancellationCause, thrown) { e ->
assertSame(cancellationCause, e)
val suppressed = e.suppressed
assertTrue(suppressed.isEmpty())
}
}
@Test
fun testConflictingCancellation3() = runTest {
/*
* context cancelled with TCE
* block itself throws TCE
* Result: TCE
*/
val cancellationCause = TestCancellationException()
val thrown = TestCancellationException()
runCancellation(cancellationCause, thrown) { e ->
assertSame(cancellationCause, e)
assertNull(e.cause)
assertTrue(e.suppressed.isEmpty())
}
}
@Test
fun testThrowingCancellation() = runTest {
val thrown = TestCancellationException()
runThrowing(thrown) { e ->
assertSame(thrown, e)
}
}
@Test
fun testThrowingCancellationWithCause() = runTest {
// Exception are never unwrapped, so if CE(TE) is thrown then it is the cancellation cause
val thrown = TestCancellationException()
thrown.initCause(TestException())
runThrowing(thrown) { e ->
assertSame(thrown, e)
}
}
@Test
fun testCancel() = runTest {
runOnlyCancellation(null) { e ->
val cause = e.cause as JobCancellationException // shall be recovered JCE
assertNull(cause.cause)
assertTrue(e.suppressed.isEmpty())
assertTrue(cause.suppressed.isEmpty())
}
}
@Test
fun testCancelWithCause() = runTest {
val cause = TestCancellationException()
runOnlyCancellation(cause) { e ->
assertSame(cause, e)
assertTrue(e.suppressed.isEmpty())
}
}
@Test
fun testCancelWithCancellationException() = runTest {
val cause = TestCancellationException()
runThrowing(cause) { e ->
assertSame(cause, e)
assertNull(e.cause)
assertTrue(e.suppressed.isEmpty())
}
}
private fun wrapperDispatcher(context: CoroutineContext): CoroutineContext {
val dispatcher = context[ContinuationInterceptor] as CoroutineDispatcher
return object : CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
dispatcher.dispatch(context, block)
}
}
}
private suspend fun runCancellation(
cancellationCause: CancellationException?,
thrownException: Throwable,
exceptionChecker: (Throwable) -> Unit
) {
expect(1)
try {
withCtx(wrapperDispatcher(coroutineContext)) { job ->
require(isActive) // not cancelled yet
job.cancel(cancellationCause)
require(!isActive) // now cancelled
expect(2)
throw thrownException
}
} catch (e: Throwable) {
exceptionChecker(e)
finish(3)
return
}
fail()
}
private suspend fun runThrowing(
thrownException: Throwable,
exceptionChecker: (Throwable) -> Unit
) {
expect(1)
try {
withCtx(wrapperDispatcher(coroutineContext).minusKey(Job)) {
require(isActive)
expect(2)
throw thrownException
}
} catch (e: Throwable) {
exceptionChecker(e)
finish(3)
return
}
fail()
}
private suspend fun withCtx(context: CoroutineContext, job: Job = Job(), block: suspend CoroutineScope.(Job) -> Nothing) {
when (mode) {
Mode.WITH_CONTEXT -> withContext(context + job) {
block(job)
}
Mode.ASYNC_AWAIT -> CoroutineScope(coroutineContext).async(context + job) {
block(job)
}.await()
}
}
private suspend fun runOnlyCancellation(
cancellationCause: CancellationException?,
exceptionChecker: (Throwable) -> Unit
) {
expect(1)
val job = Job()
try {
withContext(wrapperDispatcher(coroutineContext) + job) {
require(isActive) // still active
job.cancel(cancellationCause)
require(!isActive) // is already cancelled
expect(2)
}
} catch (e: Throwable) {
exceptionChecker(e)
finish(3)
return
}
fail()
}
} | apache-2.0 | f99ad6e420a5503ea9507d32e4445144 | 29.533808 | 126 | 0.579904 | 5.208865 | false | true | false | false |
leafclick/intellij-community | uast/uast-common/src/com/intellij/psi/UastPatternAdapter.kt | 1 | 1407 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi
import com.intellij.openapi.util.RecursionManager
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.ElementPatternCondition
import com.intellij.patterns.InitialPatternCondition
import com.intellij.util.ProcessingContext
import org.jetbrains.uast.UElement
internal class UastPatternAdapter(
val predicate: (UElement, ProcessingContext) -> Boolean,
private val supportedUElementTypes: List<Class<out UElement>>
) : ElementPattern<PsiElement> {
override fun accepts(o: Any?): Boolean = accepts(o, null)
override fun accepts(o: Any?, context: ProcessingContext?): Boolean = when (o) {
is PsiElement -> RecursionManager.doPreventingRecursion(this, false) {
getOrCreateCachedElement(o, context, supportedUElementTypes)
?.let { predicate(it, (context ?: ProcessingContext()).apply { put(REQUESTED_PSI_ELEMENT, o) }) }
?: false
} ?: false
else -> false
}
private val condition = ElementPatternCondition(object : InitialPatternCondition<PsiElement>(PsiElement::class.java) {
override fun accepts(o: Any?, context: ProcessingContext?): Boolean = [email protected](o, context)
})
override fun getCondition(): ElementPatternCondition<PsiElement> = condition
} | apache-2.0 | ff616461336641f5f992ae22c213c21b | 44.419355 | 140 | 0.766169 | 4.553398 | false | false | false | false |
zdary/intellij-community | platform/service-container/src/com/intellij/serviceContainer/ConstructorParameterResolver.kt | 1 | 5085 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.serviceContainer
import com.intellij.diagnostic.PluginException
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.extensions.PluginId
import org.picocontainer.ComponentAdapter
import java.lang.reflect.Constructor
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
private val badAppLevelClasses = java.util.Set.of(
"com.intellij.execution.executors.DefaultDebugExecutor",
"org.apache.http.client.HttpClient",
"org.apache.http.impl.client.CloseableHttpClient",
"com.intellij.openapi.project.Project"
)
internal class ConstructorParameterResolver {
fun isResolvable(componentManager: ComponentManagerImpl,
requestorKey: Any,
requestorClass: Class<*>,
requestorConstructor: Constructor<*>,
expectedType: Class<*>,
pluginId: PluginId,
isExtensionSupported: Boolean): Boolean {
if (isLightService(expectedType) ||
expectedType === ComponentManager::class.java ||
findTargetAdapter(componentManager, expectedType, requestorKey, requestorClass, requestorConstructor, pluginId) != null) {
return true
}
return isExtensionSupported && componentManager.extensionArea.findExtensionByClass(expectedType) != null
}
fun resolveInstance(componentManager: ComponentManagerImpl,
requestorKey: Any,
requestorClass: Class<*>,
requestorConstructor: Constructor<*>,
expectedType: Class<*>,
pluginId: PluginId): Any? {
if (expectedType === ComponentManager::class.java) {
return componentManager
}
if (isLightService(expectedType)) {
throw PluginException(
"Do not use constructor injection for light services (requestorClass=$requestorClass, requestedService=$expectedType)", pluginId
)
}
val adapter = findTargetAdapter(componentManager, expectedType, requestorKey, requestorClass, requestorConstructor, pluginId)
?: return handleUnsatisfiedDependency(componentManager, requestorClass, expectedType, pluginId)
return when {
adapter is BaseComponentAdapter -> {
// project level service Foo wants application level service Bar - adapter component manager should be used instead of current
adapter.getInstance(adapter.componentManager, null)
}
componentManager.parent == null -> adapter.getComponentInstance(componentManager)
else -> componentManager.getComponentInstance(adapter.componentKey)
}
}
private fun handleUnsatisfiedDependency(componentManager: ComponentManagerImpl, requestorClass: Class<*>, expectedType: Class<*>, pluginId: PluginId): Any? {
val extension = componentManager.extensionArea.findExtensionByClass(expectedType) ?: return null
val message = "Do not use constructor injection to get extension instance (requestorClass=${requestorClass.name}, extensionClass=${expectedType.name})"
val app = componentManager.getApplication()
@Suppress("SpellCheckingInspection")
if (app != null && app.isUnitTestMode && pluginId.idString != "org.jetbrains.kotlin" && pluginId.idString != "Lombook Plugin") {
throw PluginException(message, pluginId)
}
else {
LOG.warn(message)
}
return extension
}
}
private fun findTargetAdapter(componentManager: ComponentManagerImpl,
expectedType: Class<*>,
requestorKey: Any,
requestorClass: Class<*>,
requestorConstructor: Constructor<*>,
@Suppress("UNUSED_PARAMETER") pluginId: PluginId): ComponentAdapter? {
val byKey = componentManager.getComponentAdapter(expectedType)
if (byKey != null && requestorKey != byKey.componentKey) {
return byKey
}
val className = expectedType.name
if (componentManager.parent == null) {
if (badAppLevelClasses.contains(className)) {
return null
}
}
else if (className == "com.intellij.configurationStore.StreamProvider" ||
className == "com.intellij.openapi.roots.LanguageLevelModuleExtensionImpl" ||
className == "com.intellij.openapi.roots.impl.CompilerModuleExtensionImpl" ||
className == "com.intellij.openapi.roots.impl.JavaModuleExternalPathsImpl") {
return null
}
if (componentManager.isGetComponentAdapterOfTypeCheckEnabled) {
LOG.error(PluginException("getComponentAdapterOfType is used to get ${expectedType.name} (requestorClass=${requestorClass.name}, requestorConstructor=${requestorConstructor})." +
"\n\nProbably constructor should be marked as NonInjectable.", pluginId))
}
return componentManager.getComponentAdapterOfType(expectedType) ?: componentManager.parent?.getComponentAdapterOfType(expectedType)
} | apache-2.0 | 97aa39684fa699ab3f1373cc78306cb4 | 46.981132 | 182 | 0.700688 | 5.485437 | false | false | false | false |
leafclick/intellij-community | plugins/git4idea/src/git4idea/config/GitExecutableProblemHandlers.kt | 1 | 4145 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.config
import com.intellij.CommonBundle
import com.intellij.execution.process.ProcessOutput
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SystemInfo
import git4idea.GitVcs
import git4idea.config.GitExecutableProblemsNotifier.getPrettyErrorMessage
import git4idea.i18n.GitBundle
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.Nls.Capitalization.Sentence
import org.jetbrains.annotations.Nls.Capitalization.Title
fun findGitExecutableProblemHandler(project: Project): GitExecutableProblemHandler {
return when {
SystemInfo.isWindows -> WindowsExecutableProblemHandler(project)
SystemInfo.isMac -> MacExecutableProblemHandler(project)
else -> DefaultExecutableProblemHandler(project)
}
}
interface GitExecutableProblemHandler {
@CalledInAwt
fun showError(exception: Throwable, errorNotifier: ErrorNotifier, onErrorResolved: () -> Unit)
@CalledInAwt
fun showError(exception: Throwable, errorNotifier: ErrorNotifier) {
showError(exception, errorNotifier, {})
}
}
interface ErrorNotifier {
@CalledInAny
fun showError(@Nls(capitalization = Sentence) text: String,
@Nls(capitalization = Sentence) description: String? = null,
fixOption: FixOption)
@CalledInAny
fun showError(@Nls(capitalization = Sentence) text: String, fixOption: FixOption) {
showError(text, null, fixOption)
}
@CalledInAny
fun showError(@Nls(capitalization = Sentence) text: String)
@CalledInAwt
fun executeTask(@Nls(capitalization = Title) title: String, cancellable: Boolean, action: () -> Unit)
@CalledInAny
fun changeProgressTitle(@Nls(capitalization = Title) text: String)
@CalledInAny
fun showMessage(@Nls(capitalization = Sentence) text: String)
@CalledInAny
fun hideProgress()
@CalledInAny
fun resetGitExecutable() {
GitVcsApplicationSettings.getInstance().setPathToGit(null)
GitExecutableManager.getInstance().dropExecutableCache()
}
sealed class FixOption(@Nls(capitalization = Title) val text: String, @CalledInAwt val fix: () -> Unit) {
class Standard(@Nls(capitalization = Title) text: String, @CalledInAwt fix: () -> Unit) : FixOption(text, fix)
// todo probably change to "Select on disk" instead of opening Preferences
internal class Configure(val project: Project) : FixOption(CommonBundle.message("action.text.configure.ellipsis"), {
ShowSettingsUtil.getInstance().showSettingsDialog(project, GitVcs.NAME)
})
}
}
@CalledInAwt
internal fun showUnsupportedVersionError(project: Project, version: GitVersion, errorNotifier: ErrorNotifier) {
errorNotifier.showError(unsupportedVersionMessage(version), unsupportedVersionDescription(), getLinkToConfigure(project))
}
internal fun unsupportedVersionMessage(version: GitVersion): String =
GitBundle.message("git.executable.validation.error.version.title", version.presentation)
internal fun unsupportedVersionDescription(): String =
GitBundle.message("git.executable.validation.error.version.message", GitVersion.MIN.presentation)
internal fun getLinkToConfigure(project: Project): ErrorNotifier.FixOption = ErrorNotifier.FixOption.Configure(project)
internal fun ProcessOutput.dumpToString() = "output: ${stdout}, error output: ${stderr}"
internal fun getErrorTitle(text: String, description: String?) =
if (description == null) GitBundle.getString("git.executable.validation.error.start.title") else text
internal fun getErrorMessage(text: String, description: String?) = description ?: text
private class DefaultExecutableProblemHandler(val project: Project) : GitExecutableProblemHandler {
override fun showError(exception: Throwable, errorNotifier: ErrorNotifier, onErrorResolved: () -> Unit) {
errorNotifier.showError(getPrettyErrorMessage(exception), getLinkToConfigure(project))
}
}
| apache-2.0 | b67530e95e326abf86703ea550a83b79 | 38.855769 | 140 | 0.784318 | 4.715586 | false | true | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-generator/src/main/kotlin/slatekit/generator/Creator.kt | 1 | 4396 | package slatekit.generator
import slatekit.context.Context
import slatekit.common.io.Uris
import slatekit.common.ext.toId
import slatekit.common.log.Logger
import slatekit.common.utils.Props
import java.io.File
/**
* This processes all the [Action]s supported
*/
class Creator(val context: Context, val ctx: GeneratorContext, val template: Template, val cls:Class<*>, val logger: Logger) {
/**
* Creates the directory after first interpreting the path.
* For example: "~/git/app1"
*/
fun create(path:String, interpret:Boolean ): File {
val finalPath = if(interpret) Uris.interpret(path) else path
val dest = File( finalPath )
createDir(dest)
return dest
}
/**
* Creates the directory
*/
fun createDir(dest: File): File {
if(!dest.exists()) {
log("creating ${dest.absolutePath}")
dest.mkdir()
}
return dest
}
/**
* Creates the directory
*/
fun createFile(dest: File, content:String): File {
log("creating ${dest.absolutePath}")
dest.writeText(content)
return dest
}
/**
* Creates the directory from the root directory supplied
*/
fun dir(root: File, action: Action.MkDir) {
//log("Dir : " + action.path)
val packagePath = ctx.packageName.replace(".", Props.pathSeparator)
val target = File(root, action.path.replace("@app.package", packagePath))
createDir(target)
}
/**
* Creates the file from the root directory supplied
*/
fun copy(root: File, action: Action.Copy) {
when(action.fileType){
is FileType.Code -> code(root, action)
else -> file(root, action)
}
}
/**
* Creates the file from the root directory supplied
*/
fun file(root: File, action: Action.Copy) {
//log("${action.fileType}: " + action.target)
val content = read(action.source)
val target = File(root, action.target)
createFile(target, content)
}
/**
* Creates the source code from the root directory supplied
*/
fun code(root: File, action: Action.Copy) {
//log("Code: " + action.target)
val content = read(action.source)
val packagePath = ctx.packageName.replace(".", Props.pathSeparator)
val target = File(root, action.target.replace("@app.package", packagePath))
createFile(target, content)
}
/**
* Reads a file from resources
*/
fun read(path:String):String {
//val url = cls.getResource(path)
val finalPath = "files" + File.separatorChar + path
val text = File(template.dir, finalPath).readText()
val converted = replace(text)
return converted
}
/**
* Reads a file from resources
*/
fun replace(content:String):String {
val converted = content
.replace("\${app.id}", ctx.name.toId())
.replace("\${app.name}", ctx.name)
.replace("\${app.desc}", ctx.desc)
.replace("\${app.package}", ctx.packageName)
.replace("\${app.packagePath}", ctx.packageName.replace(".", "/"))
.replace("\${app.url}", ctx.name)
.replace("\${app.company}", ctx.company)
.replace("\${app.area}", ctx.area)
.replace("\${build.slatekit.version}", ctx.settings.tool.slatekitVersion)
.replace("\${build.slatekit.version.beta}", ctx.settings.tool.slatekitVersionBeta)
.replace("\${build.kotlin.version}", ctx.settings.build.kotlinVersion)
return converted
}
private fun log(msg:String){
logger.info(msg )
}
/**
* Build a list of [Action.Dir] actions to create directories based on package name.
*/
fun makeDirs(targetDir:File, path:String, partsFilter: (List<String>) -> List<String>):File {
val partsRaw = path.split("/").filter { !it.isNullOrEmpty() }
val parts = partsFilter(partsRaw)
val finalPath = parts.reduce { acc, curr ->
val file = File(targetDir, acc)
if(!file.exists()) {
file.mkdir()
}
"$acc/$curr"
}
val finalDir = File(targetDir, finalPath)
finalDir.mkdir()
return finalDir
}
} | apache-2.0 | 031dbe463ea7429965c5ff3be4a2736d | 28.709459 | 126 | 0.57848 | 4.322517 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/delegatedProperty/local/capturedLocalVar.kt | 3 | 440 | package foo
import kotlin.reflect.KProperty
inline fun <T> run(f: () -> T) = f()
class Delegate {
var inner = 1
operator fun getValue(t: Any?, p: KProperty<*>): Int = inner
operator fun setValue(t: Any?, p: KProperty<*>, i: Int) {
inner = i
}
}
fun box(): String {
var prop: Int by Delegate()
run { prop = 2 }
if (prop != 2) return "fail get"
return run { if (prop != 2) "fail set" else "OK" }
}
| apache-2.0 | 71df7561ea8e18f4c5fdd9a51f94e24a | 21 | 64 | 0.565909 | 3.235294 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/collections/SetOperationsTest/plusAssign.kt | 2 | 533 | import kotlin.test.*
fun box() {
// lets use a mutable variable
var set = setOf("a")
val setOriginal = set
set += "foo"
set += listOf("beer", "a")
set += arrayOf("cheese", "beer")
set += sequenceOf("bar", "foo")
assertEquals(setOf("a", "foo", "beer", "cheese", "bar"), set)
assertTrue(set !== setOriginal)
val mset = mutableSetOf("a")
mset += "foo"
mset += listOf("beer", "a")
mset += arrayOf("cheese", "beer")
mset += sequenceOf("bar", "foo")
assertEquals(set, mset)
}
| apache-2.0 | b95f2617f531d7675ea39eee0800245d | 24.380952 | 65 | 0.555347 | 3.529801 | false | false | false | false |
blokadaorg/blokada | android5/app/src/engine/kotlin/engine/PacketLoopService.kt | 1 | 7740 | /*
* This file is part of Blokada.
*
* 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 https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package engine
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import model.BlokadaException
import model.Dns
import model.Gateway
import model.PrivateKey
import service.ConnectivityService
import service.DozeService
import utils.Logger
import java.net.DatagramSocket
object PacketLoopService {
private val log = Logger("PacketLoop")
private val connectivity = ConnectivityService
private val doze = DozeService
private val engine = EngineService
private val screenOn = ScreenOnService
private var lastLoopStart = 0L
var onCreateSocket = {
log.e("Created unprotected socket for the packet loop")
DatagramSocket()
}
var onStoppedUnexpectedly = {
log.e("Thread stopped unexpectedly, but nobody listening")
}
private var loop: Pair<PacketLoopConfig, Thread?>? = null
@Synchronized get
@Synchronized set
init {
// When connectivity is back restart the loop for faster recovery.
connectivity.onConnectivityChanged = { isConected ->
if (isConected) maybeRestartLoop()
}
// Listen to device wake events and restart the loop if running.
// This is an attempt to improve the conn issues on some devices after device wake
// caused by the loop not doing the handshake until it times out.
screenOn.onScreenOn = {
maybeRestartLoop()
}
}
private fun maybeRestartLoop() {
loop?.let {
val (config, thread) = it
if (thread == null) {
log.w("Connectivity changed, recreating packet loop")
loop = createLoop(config)
startSupportingServices(config)
} else {
log.w("Connectivity changed, loop was running, restarting it")
stopUnexpectedly()
}
}
}
suspend fun startLibreMode(useDoh: Boolean, dns: Dns, tunnelConfig: SystemTunnelConfig) {
log.v("Requested to start packet loop (libre mode)")
if (loop != null) {
log.w("Packet loop thread already running, stopping")
stop()
}
val cfg = PacketLoopConfig(false, dns, useDoh, tunnelConfig)
loop = createLoop(cfg)
startSupportingServices(cfg)
}
suspend fun startPlusMode(useDoh: Boolean, dns: Dns, tunnelConfig: SystemTunnelConfig,
privateKey: PrivateKey, gateway: Gateway) {
log.v("Requested to start packet loop for gateway: ${gateway.niceName()}")
if (loop != null) {
log.w("Packet loop thread already running, stopping")
stop()
}
val cfg = PacketLoopConfig(true, dns, useDoh, tunnelConfig, privateKey, gateway)
loop = createLoop(cfg)
startSupportingServices(cfg)
}
suspend fun startSlimMode(useDoh: Boolean, dns: Dns, tunnelConfig: SystemTunnelConfig) {
log.v("Requested to start packet loop (slim mode)")
if (loop != null) {
log.w("Packet loop thread already running, stopping")
stop()
}
val cfg = PacketLoopConfig(false, dns, useDoh, tunnelConfig, useFiltering = false)
loop = createLoop(cfg)
startSupportingServices(cfg)
}
private fun createLoop(config: PacketLoopConfig): Pair<PacketLoopConfig, Thread> {
val thread = when {
config.usePlusMode && config.useDoh -> {
val gw = config.requireGateway()
PacketLoopForPlusDoh(
deviceIn = config.tunnelConfig.deviceIn,
deviceOut = config.tunnelConfig.deviceOut,
userBoringtunPrivateKey = config.requirePrivateKey(),
gatewayId = gw.public_key,
gatewayIp = gw.ipv4,
gatewayPort = gw.port,
createSocket = onCreateSocket,
stoppedUnexpectedly = this::stopUnexpectedly
)
}
config.usePlusMode -> {
val gw = config.requireGateway()
PacketLoopForPlus(
deviceIn = config.tunnelConfig.deviceIn,
deviceOut = config.tunnelConfig.deviceOut,
userBoringtunPrivateKey = config.requirePrivateKey(),
gatewayId = gw.public_key,
gatewayIp = gw.ipv4,
gatewayPort = gw.port,
createSocket = onCreateSocket,
stoppedUnexpectedly = this::stopUnexpectedly,
useRewriter = true
)
}
else -> {
PacketLoopForLibre(
deviceIn = config.tunnelConfig.deviceIn,
deviceOut = config.tunnelConfig.deviceOut,
createSocket = onCreateSocket,
stoppedUnexpectedly = this::stopUnexpectedly,
filter = config.useFiltering
)
}
}
thread.start()
lastLoopStart = System.currentTimeMillis()
return config to thread
}
private fun startSupportingServices(config: PacketLoopConfig) {
MetricsService.startMetrics(
onNoConnectivity = this::stopUnexpectedly
)
}
private fun stopUnexpectedly() {
loop?.let {
log.w("Packet loop stopped unexpectedly")
val (config, thread) = it
if (thread != null) {
thread.interrupt()
MetricsService.stopMetrics()
if (System.currentTimeMillis() - lastLoopStart < 30000) {
log.w("Packet loop restarted recently, performing a full engine restart")
loop = config to null
GlobalScope.launch { engine.forceReload() }
} else if (connectivity.isDeviceInOfflineMode()) {
log.w("Device is offline, not bringing packet loop back for now")
loop = config to null
} else {
log.w("Device is online, bringing packet loop back")
loop = createLoop(config)
startSupportingServices(config)
}
}
}
}
suspend fun stop() {
log.v("Requested to stop packet loop")
lastLoopStart = 0
loop?.let {
loop = null
val (_, thread) = it
thread?.interrupt()
MetricsService.stopMetrics()
// log.w("Waiting after stopping packet loop as a workaround")
// delay(4000)
}
}
fun getStatus() = (loop?.second as? PacketLoopForPlusDoh)?.gatewayId ?:
(loop?.second as? PacketLoopForPlus)?.gatewayId
}
private class PacketLoopConfig(
val usePlusMode: Boolean,
val dns: Dns,
val useDoh: Boolean,
val tunnelConfig: SystemTunnelConfig,
val privateKey: PrivateKey? = null,
val gateway: Gateway? = null,
val useFiltering: Boolean = true
) {
fun requirePrivateKey(): PrivateKey {
return if (usePlusMode) privateKey!! else throw BlokadaException("Not Blocka configuration")
}
fun requireGateway(): Gateway {
return if (usePlusMode) gateway!! else throw BlokadaException("Not Blocka configuration")
}
} | mpl-2.0 | 50fe0a5d36af8aa9df8fa50a90494c2a | 33.70852 | 100 | 0.584572 | 4.836875 | false | true | false | false |
AndroidX/androidx | wear/compose/compose-material/benchmark/src/androidTest/java/androidx/wear/compose/material/benchmark/ToggleChipBenchmark.kt | 3 | 3193 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material.benchmark
import androidx.compose.runtime.Composable
import androidx.compose.testutils.LayeredComposeTestCase
import androidx.compose.testutils.benchmark.ComposeBenchmarkRule
import androidx.compose.testutils.benchmark.benchmarkDrawPerf
import androidx.compose.testutils.benchmark.benchmarkFirstCompose
import androidx.compose.testutils.benchmark.benchmarkFirstDraw
import androidx.compose.testutils.benchmark.benchmarkFirstLayout
import androidx.compose.testutils.benchmark.benchmarkFirstMeasure
import androidx.compose.testutils.benchmark.benchmarkLayoutPerf
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.SplitToggleChip
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.ToggleChipDefaults
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Benchmark for Wear Compose ToggleChip.
*/
@LargeTest
@RunWith(AndroidJUnit4::class)
class ToggleChipBenchmark {
@get:Rule
val benchmarkRule = ComposeBenchmarkRule()
private val toggleChipCaseFactory = { ToggleChipTestCase() }
@Test
fun first_compose() {
benchmarkRule.benchmarkFirstCompose(toggleChipCaseFactory)
}
@Test
fun first_measure() {
benchmarkRule.benchmarkFirstMeasure(toggleChipCaseFactory)
}
@Test
fun first_layout() {
benchmarkRule.benchmarkFirstLayout(toggleChipCaseFactory)
}
@Test
fun first_draw() {
benchmarkRule.benchmarkFirstDraw(toggleChipCaseFactory)
}
@Test
fun layout() {
benchmarkRule.benchmarkLayoutPerf(toggleChipCaseFactory)
}
@Test
fun draw() {
benchmarkRule.benchmarkDrawPerf(toggleChipCaseFactory)
}
}
internal class ToggleChipTestCase : LayeredComposeTestCase() {
@Composable
override fun MeasuredContent() {
SplitToggleChip(
checked = true,
onCheckedChange = {},
enabled = false,
label = { Text("Label") },
toggleControl = {
Icon(
imageVector = ToggleChipDefaults.checkboxIcon(checked = true),
contentDescription = null
)
},
onClick = {},
)
}
@Composable
override fun ContentWrappers(content: @Composable () -> Unit) {
MaterialTheme {
content()
}
}
} | apache-2.0 | a9bea83f25bc1733e5691b1a10d79438 | 28.850467 | 82 | 0.717194 | 4.794294 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/eval4j/src/org/jetbrains/eval4j/interpreterLoop.kt | 6 | 11783 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.eval4j
import org.jetbrains.eval4j.ExceptionThrown.ExceptionKind
import org.jetbrains.eval4j.jdi.jdiName
import org.jetbrains.org.objectweb.asm.Opcodes.*
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.tree.*
import org.jetbrains.org.objectweb.asm.tree.analysis.Frame
import org.jetbrains.org.objectweb.asm.util.Printer
import java.util.*
interface InterpreterResult {
override fun toString(): String
}
class ExceptionThrown(val exception: ObjectValue, val kind: ExceptionKind) : InterpreterResult {
override fun toString(): String = "Thrown $exception: $kind"
enum class ExceptionKind {
FROM_EVALUATED_CODE,
FROM_EVALUATOR,
BROKEN_CODE
}
}
data class ValueReturned(val result: Value) : InterpreterResult {
override fun toString(): String = "Returned $result"
}
class AbnormalTermination(val message: String) : InterpreterResult {
override fun toString(): String = "Terminated abnormally: $message"
}
interface InterpretationEventHandler {
object NONE : InterpretationEventHandler {
override fun instructionProcessed(insn: AbstractInsnNode): InterpreterResult? = null
override fun exceptionThrown(currentState: Frame<Value>, currentInsn: AbstractInsnNode, exception: Value): InterpreterResult? = null
override fun exceptionCaught(currentState: Frame<Value>, currentInsn: AbstractInsnNode, exception: Value): InterpreterResult? = null
}
// If a non-null value is returned, interpreter loop is terminated and that value is used as a result
fun instructionProcessed(insn: AbstractInsnNode): InterpreterResult?
fun exceptionThrown(currentState: Frame<Value>, currentInsn: AbstractInsnNode, exception: Value): InterpreterResult?
fun exceptionCaught(currentState: Frame<Value>, currentInsn: AbstractInsnNode, exception: Value): InterpreterResult?
}
abstract class ThrownFromEvalExceptionBase(cause: Throwable) : RuntimeException(cause) {
override fun toString(): String = "Thrown by evaluator: ${cause}"
}
class BrokenCode(cause: Throwable) : ThrownFromEvalExceptionBase(cause)
// Interpreting exceptions should not be sent to EA
class Eval4JInterpretingException(override val cause: Throwable) : RuntimeException(cause)
class ThrownFromEvaluatedCodeException(val exception: ObjectValue) : RuntimeException() {
override fun toString(): String = "Thrown from evaluated code: $exception"
}
fun interpreterLoop(
m: MethodNode,
initialState: Frame<Value>,
eval: Eval,
handler: InterpretationEventHandler = InterpretationEventHandler.NONE
): InterpreterResult {
val firstInsn = m.instructions.first
if (firstInsn == null) throw IllegalArgumentException("Empty method")
var currentInsn = firstInsn
fun goto(nextInsn: AbstractInsnNode?) {
if (nextInsn == null) throw IllegalArgumentException("Instruction flow ended with no RETURN")
currentInsn = nextInsn
}
val interpreter = SingleInstructionInterpreter(eval)
val frame = Frame(initialState)
val handlers = computeHandlers(m)
class ResultException(val result: InterpreterResult) : RuntimeException()
fun exceptionCaught(exceptionValue: Value, instanceOf: (Type) -> Boolean): Boolean {
val catchBlocks = handlers[m.instructions.indexOf(currentInsn)] ?: listOf()
for (catch in catchBlocks) {
val exceptionTypeInternalName = catch.type
if (exceptionTypeInternalName != null) {
val exceptionType = Type.getObjectType(exceptionTypeInternalName)
if (instanceOf(exceptionType)) {
val handled = handler.exceptionCaught(frame, currentInsn, exceptionValue)
if (handled != null) throw ResultException(handled)
frame.clearStack()
frame.push(exceptionValue)
goto(catch.handler)
return true
}
}
}
return false
}
fun exceptionCaught(exceptionValue: Value): Boolean = exceptionCaught(exceptionValue) { exceptionType ->
eval.isInstanceOf(exceptionValue, exceptionType)
}
fun exceptionFromEvalCaught(exception: Throwable, exceptionValue: Value): Boolean {
return exceptionCaught(exceptionValue) { exceptionType ->
try {
val exceptionClass = exception::class.java
val clazz = Class.forName(
exceptionType.jdiName,
true,
exceptionClass.classLoader
)
clazz.isAssignableFrom(exceptionClass)
} catch (e: ClassNotFoundException) {
// If the class is not available in this VM, it can not be a superclass of an exception thrown in it
false
}
}
}
try {
loop@ while (true) {
val insnOpcode = currentInsn.opcode
when (currentInsn.type) {
AbstractInsnNode.LABEL,
AbstractInsnNode.FRAME,
AbstractInsnNode.LINE -> {
// skip to the next instruction
}
else -> {
when (insnOpcode) {
GOTO -> {
goto((currentInsn as JumpInsnNode).label)
continue@loop
}
RET -> {
val varNode = currentInsn as VarInsnNode
val address = frame.getLocal(varNode.`var`)
goto((address as LabelValue).value)
continue@loop
}
// TODO: switch
LOOKUPSWITCH -> throw UnsupportedByteCodeException("LOOKUPSWITCH is not supported yet")
TABLESWITCH -> throw UnsupportedByteCodeException("TABLESWITCH is not supported yet")
IRETURN, LRETURN, FRETURN, DRETURN, ARETURN -> {
val value = frame.getStackTop()
val expectedType = Type.getReturnType(m.desc)
if (expectedType.sort == Type.OBJECT || expectedType.sort == Type.ARRAY) {
val coerced = if (value != NULL_VALUE && value.asmType != expectedType)
ObjectValue(value.obj(), expectedType)
else value
return ValueReturned(coerced)
}
if (value.asmType != expectedType) {
assert(insnOpcode == IRETURN) { "Only ints should be coerced: ${Printer.OPCODES[insnOpcode]}" }
val coerced = when (expectedType.sort) {
Type.BOOLEAN -> boolean(value.boolean)
Type.BYTE -> byte(value.int.toByte())
Type.SHORT -> short(value.int.toShort())
Type.CHAR -> char(value.int.toChar())
Type.INT -> int(value.int)
else -> throw UnsupportedByteCodeException("Should not be coerced: $expectedType")
}
return ValueReturned(coerced)
}
return ValueReturned(value)
}
RETURN -> return ValueReturned(VOID_VALUE)
IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, IFNULL, IFNONNULL -> {
if (interpreter.checkUnaryCondition(frame.getStackTop(), insnOpcode)) {
frame.execute(currentInsn, interpreter)
goto((currentInsn as JumpInsnNode).label)
continue@loop
}
}
IF_ICMPEQ, IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, IF_ACMPEQ, IF_ACMPNE -> {
if (interpreter.checkBinaryCondition(frame.getStackTop(1), frame.getStackTop(0), insnOpcode)) {
frame.execute(currentInsn, interpreter)
goto((currentInsn as JumpInsnNode).label)
continue@loop
}
}
ATHROW -> {
val exceptionValue = frame.getStackTop() as ObjectValue
val handled = handler.exceptionThrown(frame, currentInsn, exceptionValue)
if (handled != null) return handled
if (exceptionCaught(exceptionValue)) continue@loop
return ExceptionThrown(exceptionValue, ExceptionKind.FROM_EVALUATED_CODE)
}
// Workaround for a bug in Kotlin: NoPatterMatched exception is thrown otherwise!
else -> {
}
}
try {
frame.execute(currentInsn, interpreter)
} catch (e: ThrownFromEvalExceptionBase) {
val exception = e.cause!!
val exceptionValue = ObjectValue(exception, Type.getType(exception::class.java))
val handled = handler.exceptionThrown(
frame, currentInsn,
exceptionValue
)
if (handled != null) return handled
if (exceptionFromEvalCaught(exception, exceptionValue)) continue@loop
val exceptionType = if (e is BrokenCode) ExceptionKind.BROKEN_CODE else ExceptionKind.FROM_EVALUATOR
return ExceptionThrown(exceptionValue, exceptionType)
} catch (e: ThrownFromEvaluatedCodeException) {
val handled = handler.exceptionThrown(frame, currentInsn, e.exception)
if (handled != null) return handled
if (exceptionCaught(e.exception)) continue@loop
return ExceptionThrown(e.exception, ExceptionKind.FROM_EVALUATED_CODE)
}
}
}
val handled = handler.instructionProcessed(currentInsn)
if (handled != null) return handled
goto(currentInsn.next)
}
} catch (e: ResultException) {
return e.result
}
}
private fun <T : Value> Frame<T>.getStackTop(i: Int = 0) = this.getStack(this.stackSize - 1 - i) ?: throwBrokenCodeException(
IllegalArgumentException("Couldn't get value with index = $i from top of stack")
)
// Copied from org.jetbrains.org.objectweb.asm.tree.analysis.Analyzer.analyze()
fun computeHandlers(m: MethodNode): Array<out List<TryCatchBlockNode>?> {
val instructions = m.instructions
val handlers = Array<MutableList<TryCatchBlockNode>?>(instructions.size()) { null }
for (tcb in m.tryCatchBlocks) {
val begin = instructions.indexOf(tcb.start)
val end = instructions.indexOf(tcb.end)
for (i in begin until end) {
val insnHandlers = handlers[i] ?: ArrayList()
handlers[i] = insnHandlers
insnHandlers.add(tcb)
}
}
return handlers
} | apache-2.0 | 7ae6657fae6ba7732bf50fdd1f6a893a | 44.323077 | 158 | 0.572435 | 5.312444 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/changeSignature/FunctionsAddRemoveArgumentsConflictBefore.kt | 13 | 315 | protected fun foo(x1: Int = 1, x2: Float, x3: ((Int) -> Int)?) {
foo(<caret>2, 3.5, null);
val y1 = x1;
val y2 = x2;
val y3 = x3;
foo(x3 = null, x2 = 5.5, x1 = 4);
}
fun bar() {
foo(x1 = 2, x2 = 3.5, x3 = null);
foo(x3 = null, x1 = 3, x2 = 4.5);
foo(x3 = null, x2 = 5.5, x1 = 4);
}
| apache-2.0 | e7e8a43f3a5dc736b7d71fa53644d7d4 | 23.230769 | 64 | 0.450794 | 2.045455 | false | false | false | false |
android/compose-samples | Crane/app/src/main/java/androidx/compose/samples/crane/calendar/model/AnimationDirection.kt | 1 | 818 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.samples.crane.calendar.model
enum class AnimationDirection {
FORWARDS,
BACKWARDS;
fun isBackwards() = this == BACKWARDS
fun isForwards() = this == FORWARDS
}
| apache-2.0 | 03955c5d3b1447e26ab659f11f7958ef | 31.72 | 75 | 0.733496 | 4.194872 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt | 1 | 3842 | package info.nightscout.androidaps.plugins.insulin
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Iob
import info.nightscout.androidaps.db.Treatment
import info.nightscout.androidaps.interfaces.InsulinInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.utils.resources.ResourceHelper
/**
* Created by adrian on 13.08.2017.
*
* parameters are injected from child class
*
*/
abstract class InsulinOrefBasePlugin(
injector: HasAndroidInjector,
resourceHelper: ResourceHelper,
val profileFunction: ProfileFunction,
val rxBus: RxBusWrapper, aapsLogger: AAPSLogger
) : PluginBase(PluginDescription()
.mainType(PluginType.INSULIN)
.fragmentClass(InsulinFragment::class.java.name)
.pluginIcon(R.drawable.ic_insulin)
.shortName(R.string.insulin_shortname)
.visibleByDefault(false),
aapsLogger, resourceHelper, injector
), InsulinInterface {
private var lastWarned: Long = 0
override val dia
get(): Double {
val dia = userDefinedDia
return if (dia >= MIN_DIA) {
dia
} else {
sendShortDiaNotification(dia)
MIN_DIA
}
}
open fun sendShortDiaNotification(dia: Double) {
if (System.currentTimeMillis() - lastWarned > 60 * 1000) {
lastWarned = System.currentTimeMillis()
val notification = Notification(Notification.SHORT_DIA, String.format(notificationPattern, dia, MIN_DIA), Notification.URGENT)
rxBus.send(EventNewNotification(notification))
}
}
private val notificationPattern: String
get() = resourceHelper.gs(R.string.dia_too_short)
open val userDefinedDia: Double
get() {
val profile = profileFunction.getProfile()
return profile?.dia ?: MIN_DIA
}
override fun iobCalcForTreatment(treatment: Treatment, time: Long, dia: Double): Iob {
val result = Iob()
val peak = peak
if (treatment.insulin != 0.0) {
val bolusTime = treatment.date
val t = (time - bolusTime) / 1000.0 / 60.0
val td = dia * 60 //getDIA() always >= MIN_DIA
val tp = peak.toDouble()
// force the IOB to 0 if over DIA hours have passed
if (t < td) {
val tau = tp * (1 - tp / td) / (1 - 2 * tp / td)
val a = 2 * tau / td
val S = 1 / (1 - a + (1 + a) * Math.exp(-td / tau))
result.activityContrib = treatment.insulin * (S / Math.pow(tau, 2.0)) * t * (1 - t / td) * Math.exp(-t / tau)
result.iobContrib = treatment.insulin * (1 - S * (1 - a) * ((Math.pow(t, 2.0) / (tau * td * (1 - a)) - t / tau - 1) * Math.exp(-t / tau) + 1))
}
}
return result
}
override val comment
get(): String {
var comment = commentStandardText()
val userDia = userDefinedDia
if (userDia < MIN_DIA) {
comment += "\n" + resourceHelper.gs(R.string.dia_too_short, userDia, MIN_DIA)
}
return comment
}
abstract val peak: Int
abstract fun commentStandardText(): String
companion object {
const val MIN_DIA = 5.0
}
} | agpl-3.0 | b9e43e38f8796bdf4baf70a35add7025 | 35.951923 | 158 | 0.63847 | 4.189749 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/libs/TrackingClientType.kt | 1 | 4462 | package com.kickstarter.libs
import com.kickstarter.libs.utils.AnalyticEventsUtils.userProperties
import com.kickstarter.libs.utils.MapUtils
import com.kickstarter.models.User
import org.json.JSONArray
import java.util.Locale
abstract class TrackingClientType {
enum class Type(val tag: String) {
SEGMENT("\uD83C\uDF81 Segment Analytics");
}
protected abstract var config: Config?
protected abstract val isGooglePlayServicesAvailable: Boolean
protected abstract val isTalkBackOn: Boolean
protected abstract var isInitialized: Boolean
protected abstract var loggedInUser: User?
abstract fun optimizely(): ExperimentsClientType?
abstract fun loggedInUser(): User?
protected abstract fun brand(): String
protected abstract fun buildNumber(): Int
protected abstract fun currentVariants(): Array<String>?
protected abstract fun deviceDistinctId(): String
protected abstract fun deviceFormat(): String
protected abstract fun deviceOrientation(): String
protected abstract fun enabledFeatureFlags(): JSONArray
protected abstract fun manufacturer(): String
protected abstract fun model(): String
protected abstract fun OSVersion(): String
protected abstract fun sessionCountry(): String
protected abstract fun time(): Long
abstract fun type(): Type
protected abstract fun userAgent(): String?
protected abstract fun userCountry(user: User): String
protected abstract fun versionName(): String
protected abstract fun wifiConnection(): Boolean
abstract fun track(eventName: String, additionalProperties: Map<String, Any>)
abstract fun identify(u: User)
abstract fun reset()
abstract fun isEnabled(): Boolean
/**
* Will call initialize for the clients, method useful
* if the initialization needs to be tied to some concrete moment
* on the Application lifecycle and not by the Dagger injection
*
* for Segment should be called on Application.OnCreate
*/
abstract fun initialize()
fun track(eventName: String) {
track(eventName, HashMap())
}
private fun genericProperties(): Map<String, Any> {
val hashMap = hashMapOf<String, Any>()
loggedInUser()?.let {
hashMap.putAll(userProperties(it))
hashMap["user_country"] = userCountry(it)
}
hashMap.putAll(sessionProperties(loggedInUser() != null))
hashMap.putAll(contextProperties())
return hashMap
}
private fun contextProperties(): Map<String, Any> {
val properties = hashMapOf<String, Any>()
properties["timestamp"] = time()
return MapUtils.prefixKeys(properties, "context_")
}
private fun sessionProperties(userIsLoggedIn: Boolean): Map<String, Any> {
val properties = hashMapOf<String, Any>()
properties.apply {
this["app_build_number"] = buildNumber()
this["app_release_version"] = versionName()
this["platform"] = "native_android"
this["client"] = "native"
this["variants_internal"] = currentVariants() ?: ""
this["country"] = sessionCountry()
this["device_distinct_id"] = deviceDistinctId()
this["device_type"] = deviceFormat()
this["device_manufacturer"] = manufacturer()
this["device_model"] = model()
this["device_orientation"] = deviceOrientation()
this["display_language"] = Locale.getDefault().language
this["enabled_features"] = enabledFeatureFlags()
this["is_voiceover_running"] = isTalkBackOn
this["mp_lib"] = "kickstarter_android"
this["os"] = "android"
this["os_version"] = OSVersion()
this["user_agent"] = userAgent() ?: ""
this["user_is_logged_in"] = userIsLoggedIn
// - Add the optimizely experiments as part of the session properties
optimizely()?.let {
this.putAll(it.getTrackingProperties())
}
this["wifi_connection"] = wifiConnection()
}
return MapUtils.prefixKeys(properties, "session_")
}
/**
* We use the same properties for Segment and DataLake
*/
fun combinedProperties(additionalProperties: Map<String, Any>): Map<String, Any> {
return HashMap(additionalProperties).apply {
putAll(genericProperties())
}
}
}
| apache-2.0 | a304be0c1434efe34df9b55c7d767c84 | 37.465517 | 86 | 0.657777 | 5.041808 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.