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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AllanWang/Frost-for-Facebook | app/src/main/kotlin/com/pitchedapps/frost/settings/Experimental.kt | 1 | 1705 | /*
* Copyright 2018 Allan Wang
*
* 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.pitchedapps.frost.settings
import android.util.Log
import ca.allanwang.kau.kpref.activity.KPrefAdapterBuilder
import ca.allanwang.kau.logging.KL
import com.pitchedapps.frost.R
import com.pitchedapps.frost.activities.SettingsActivity
import com.pitchedapps.frost.utils.REQUEST_RESTART_APPLICATION
/** Created by Allan Wang on 2017-06-29. */
fun SettingsActivity.getExperimentalPrefs(): KPrefAdapterBuilder.() -> Unit = {
plainText(R.string.disclaimer) { descRes = R.string.experimental_disclaimer_info }
// Experimental content starts here ------------------
// Experimental content ends here --------------------
checkbox(
R.string.verbose_logging,
prefs::verboseLogging,
{
prefs.verboseLogging = it
KL.shouldLog = { it != Log.VERBOSE }
}
) {
descRes = R.string.verbose_logging_desc
}
plainText(R.string.restart_frost) {
descRes = R.string.restart_frost_desc
onClick = {
setFrostResult(REQUEST_RESTART_APPLICATION)
finish()
}
}
}
| gpl-3.0 | bc714f2be3fbdc29c9b9e0036ab77d69 | 31.788462 | 84 | 0.716129 | 4.118357 | false | false | false | false |
michael-johansen/workshop-jb | src/iv_builders/_25_HtmlBuilders.kt | 5 | 1036 | package iv_builders
import iv_builders.data.getProducts
import iv_builders.htmlLibrary.*
import util.TODO
fun getTitleColor() = "#b9c9fe"
fun getCellColor(index: Int, row: Int) = if ((index + row) %2 == 0) "#dce4ff" else "#eff2ff"
fun todoTask25() = TODO(
"""
Task 25.
1) Fill the table with the proper values from products.
2) Color the table like a chess board (using getTitleColor() and getCellColor() functions above).
Pass a color as an argument to functions 'tr', 'td'.
You can run the 'Html Demo' configuration in IntelliJ to see the rendered table.
"""
)
fun renderProductTable(): String {
return html {
table {
tr {
td {
text("Product")
}
td {
text("Price")
}
td {
text("Popularity")
}
}
val products = getProducts()
todoTask25()
}
}.toString()
}
| mit | f285bef4c921949e0b70d295e3ac36ed | 26.263158 | 105 | 0.517375 | 4.389831 | false | false | false | false |
ac-opensource/Matchmaking-App | app/src/main/java/com/youniversals/playupgo/notifications/NotificationView.kt | 1 | 1042 | package com.youniversals.playupgo.notifications
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import com.youniversals.playupgo.R
import com.youniversals.playupgo.data.Notification
import kotlinx.android.synthetic.main.notification_list_view_item.view.*
class NotificationView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {
var notificationCard: View? = null
var data: Notification? = null
var message: String? = null
set(value) {
field = value
notificationMessageTextView.text = value
}
var date: String? = null
set(value) {
field = value
notificationDateTextView.text = value
}
init {
init()
}
private fun init() {
orientation = LinearLayout.VERTICAL
View.inflate(context, R.layout.notification_list_view_item, this)
notificationCard = notificationCardView
}
fun clear() {
}
} | agpl-3.0 | fb041d00616b0845b2734e1642976252 | 23.833333 | 94 | 0.676583 | 4.530435 | false | false | false | false |
SimpleMobileTools/Simple-Camera | app/src/main/kotlin/com/simplemobiletools/camera/models/VideoQuality.kt | 1 | 2221 | package com.simplemobiletools.camera.models
import android.content.Context
import androidx.annotation.DrawableRes
import androidx.annotation.IdRes
import com.simplemobiletools.camera.R
enum class VideoQuality(val width: Int, val height: Int) {
UHD(3840, 2160),
FHD(1920, 1080),
HD(1280, 720),
SD(720, 480);
val pixels: Int = width * height
val megaPixels: String = String.format("%.1f", (width * height.toFloat()) / VideoQuality.ONE_MEGA_PIXEL)
val ratio = width / height.toFloat()
private fun isSixteenToNine() = ratio == 16 / 9f
private fun isFiveToThree() = ratio == 5 / 3f
private fun isFourToThree() = ratio == 4 / 3f
private fun isTwoToOne() = ratio == 2f
private fun isThreeToFour() = ratio == 3 / 4f
private fun isThreeToTwo() = ratio == 3 / 2f
private fun isSixToFive() = ratio == 6 / 5f
private fun isNineteenToNine() = ratio == 19 / 9f
private fun isNineteenToEight() = ratio == 19 / 8f
private fun isOneNineToOne() = ratio == 1.9f
private fun isSquare() = width == height
fun getAspectRatio(context: Context) = when {
isSixteenToNine() -> "16:9"
isFiveToThree() -> "5:3"
isFourToThree() -> "4:3"
isThreeToFour() -> "3:4"
isThreeToTwo() -> "3:2"
isSixToFive() -> "6:5"
isOneNineToOne() -> "1.9:1"
isNineteenToNine() -> "19:9"
isNineteenToEight() -> "19:8"
isSquare() -> "1:1"
isTwoToOne() -> "2:1"
else -> context.resources.getString(R.string.other)
}
@DrawableRes
fun getImageResId(): Int = when (this) {
UHD -> R.drawable.ic_video_uhd_vector
FHD -> R.drawable.ic_video_fhd_vector
HD -> R.drawable.ic_video_hd_vector
SD -> R.drawable.ic_video_sd_vector
}
@IdRes
fun getButtonId(): Int = when (this) {
UHD -> R.id.video_uhd
FHD -> R.id.video_fhd
HD -> R.id.video_hd
SD -> R.id.video_sd
}
fun toResolutionOption(): ResolutionOption {
return ResolutionOption(buttonViewId = getButtonId(), imageDrawableResId = getImageResId())
}
companion object {
private const val ONE_MEGA_PIXEL = 1000000
}
}
| gpl-3.0 | 6efec6930af899a932b1bf6ff2b92c11 | 26.7625 | 108 | 0.607384 | 3.443411 | false | false | false | false |
opentok/opentok-android-sdk-samples | Advanced-Audio-Driver-Kotlin/app/src/main/java/com/tokbox/sample/advancedaudiodriver/OpenTokConfig.kt | 1 | 1349 | package com.tokbox.sample.advancedaudiodriver
import android.text.TextUtils
object OpenTokConfig {
/*
Fill the following variables using your own Project info from the OpenTok dashboard
https://dashboard.tokbox.com/projects
Note that this application will ignore credentials in the `OpenTokConfig` file when `CHAT_SERVER_URL` contains a
valid URL.
*/
/*
Fill the following variables using your own Project info from the OpenTok dashboard
https://dashboard.tokbox.com/projects
Note that this application will ignore credentials in the `OpenTokConfig` file when `CHAT_SERVER_URL` contains a
valid URL.
*/
// Replace with a API key
const val API_KEY = ""
// Replace with a generated Session ID
const val SESSION_ID = ""
// Replace with a generated token (from the dashboard or using an OpenTok server SDK)
const val TOKEN = ""
// *** The code below is to validate this configuration file. You do not need to modify it ***
val isValid: Boolean
get() = !(TextUtils.isEmpty(API_KEY) || TextUtils.isEmpty(SESSION_ID) || TextUtils.isEmpty(TOKEN))
val description: String
get() = """
OpenTokConfig:
API_KEY: $API_KEY
SESSION_ID: $SESSION_ID
TOKEN: $TOKEN
""".trimIndent()
} | mit | 25ad2b6fed0a518b733881468ec1221b | 31.926829 | 116 | 0.659748 | 4.557432 | false | true | false | false |
sangcomz/FishBun | FishBun/src/main/java/com/sangcomz/fishbun/ui/detail/adapter/DetailViewPagerAdapter.kt | 1 | 1465 | package com.sangcomz.fishbun.ui.detail.adapter
import android.net.Uri
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.sangcomz.fishbun.Fishton
import com.sangcomz.fishbun.R
import com.sangcomz.fishbun.adapter.image.ImageAdapter
/**
* Created by sangcomz on 15/06/2017.
*/
class DetailViewPagerAdapter(private val imageAdapter: ImageAdapter) : PagerAdapter() {
private var images: List<Uri> = emptyList()
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val itemView =
LayoutInflater.from(container.context).inflate(R.layout.detail_item, container, false)
container.addView(itemView)
imageAdapter.loadDetailImage(itemView.findViewById(R.id.img_detail_image), images[position])
return itemView
}
override fun getCount(): Int = images.size
override fun destroyItem(container: ViewGroup, position: Int, targetObject: Any) {
if (container is ViewPager) {
container.removeView(targetObject as ConstraintLayout)
}
}
override fun isViewFromObject(view: View, targetObject: Any): Boolean {
return view == targetObject
}
fun setImages(images: List<Uri>) {
this.images = images
notifyDataSetChanged()
}
} | apache-2.0 | 610a494af51874fd6304a95a107c6ad3 | 29.541667 | 100 | 0.730375 | 4.439394 | false | false | false | false |
tkiapril/Weisseliste | src/main/kotlin/kotlin/sql/Session.kt | 1 | 12231 | package kotlin.sql
import org.h2.jdbc.JdbcConnection
import java.sql.Connection
import java.sql.PreparedStatement
import java.util.*
import java.util.regex.Pattern
import kotlin.dao.Entity
import kotlin.dao.EntityCache
public class Key<T>()
@Suppress("UNCHECKED_CAST")
open class UserDataHolder() {
private val userdata = HashMap<Key<*>, Any?>()
public fun <T:Any> putUserData(key: Key<T>, value: T?) {
userdata[key] = value
}
public fun <T:Any> getUserData(key: Key<T>) : T? {
return userdata[key] as T?
}
public fun <T:Any> getOrCreate(key: Key<T>, init: ()->T): T {
if (userdata.containsKey(key)) {
return userdata[key] as T
}
val new = init()
userdata[key] = new
return new
}
}
class Session (val db: Database, val connector: ()-> Connection): UserDataHolder() {
private var _connection: Connection? = null
val connection: Connection get() {
if (_connection == null) {
_connection = connector()
}
return _connection!!
}
val identityQuoteString by lazy(LazyThreadSafetyMode.NONE) { connection.metaData!!.identifierQuoteString!! }
val extraNameCharacters by lazy(LazyThreadSafetyMode.NONE) {connection.metaData!!.extraNameCharacters!!}
val identifierPattern = Pattern.compile("^[a-zA-Z_][a-zA-Z0-9_.]*$")
val keywords = arrayListOf("key")
val logger = CompositeSqlLogger()
var statementCount: Int = 0
var duration: Long = 0
var warnLongQueriesDuration: Long = 2000
var debug = false
var selectsForUpdate = false
val statements = StringBuilder()
// prepare statement as key and count to execution time as value
val statementStats = hashMapOf<String, Pair<Int,Long>>()
val outerSession = threadLocal.get()
init {
logger.addLogger(Slf4jSqlLogger())
threadLocal.set(this)
}
val vendor: DatabaseVendor by lazy {
val url = connection.metaData!!.url!!
when {
url.startsWith("jdbc:mysql") -> DatabaseVendor.MySql
url.startsWith("jdbc:oracle") -> DatabaseVendor.Oracle
url.startsWith("jdbc:sqlserver") -> DatabaseVendor.SQLServer
url.startsWith("jdbc:postgresql") -> DatabaseVendor.PostgreSQL
url.startsWith("jdbc:h2") -> DatabaseVendor.H2
else -> error("Unknown database type $url")
}
}
fun vendorSupportsForUpdate(): Boolean {
return vendor != DatabaseVendor.H2
}
fun vendorCompatibleWith(): DatabaseVendor {
if (vendor == DatabaseVendor.H2) {
return ((connection as? JdbcConnection)?.session as? org.h2.engine.Session)?.database?.mode?.let { mode ->
DatabaseVendor.values.singleOrNull { it.name.equals(mode.name, true) }
} ?: vendor
}
return vendor
}
fun commit() {
val created = flushCache()
_connection?.let {
it.commit()
}
EntityCache.invalidateGlobalCaches(created)
}
fun flushCache(): List<Entity> {
with(EntityCache.getOrCreate(this)) {
val newEntities = inserts.flatMap { it.value }
flush()
return newEntities
}
}
fun rollback() {
_connection?. let {
if (!it.isClosed) it.rollback()
}
}
private fun describeStatement(args: List<Pair<ColumnType, Any?>>, delta: Long, stmt: String): String {
return "[${delta}ms] ${expandArgs(stmt, args).take(1024)}\n\n"
}
inner class BatchContext {
var stmt: String = ""
var args: List<Pair<ColumnType, Any?>> = listOf()
fun log(stmt: String, args: List<Pair<ColumnType, Any?>>) {
this.stmt = stmt
this.args = args
logger.log(stmt, args)
}
}
fun <T> execBatch(body: BatchContext.() -> T): T {
val context = BatchContext()
statementCount++
val start = System.currentTimeMillis()
val answer = context.body()
val delta = System.currentTimeMillis() - start
duration += delta
if (debug) {
statements.append(describeStatement(context.args, delta, context.stmt))
statementStats.getOrElse(context.stmt, { 0 to 0 }).let { pair ->
statementStats[context.stmt] = (pair.first + 1) to (pair.second + delta)
}
}
if (delta > warnLongQueriesDuration) {
exposedLogger.warn("Long query: ${describeStatement(context.args, delta, context.stmt)}", RuntimeException())
}
return answer
}
fun <T> exec(stmt: String, args: List<Pair<ColumnType, Any?>> = listOf(), body: () -> T): T {
return execBatch {
log(stmt, args)
body()
}
}
fun createStatements (vararg tables: Table) : List<String> {
val statements = ArrayList<String>()
if (tables.isEmpty())
return statements
val newTables = ArrayList<Table>()
for (table in tables) {
if(table.exists()) continue else newTables.add(table)
// create table
val ddl = table.ddl
statements.add(ddl)
// create indices
for (table_index in table.indices) {
statements.add(createIndex(table_index.first, table_index.second))
}
}
for (table in newTables) {
// foreign keys
for (column in table.columns) {
if (column.referee != null) {
statements.add(createFKey(column))
}
}
}
return statements
}
fun create(vararg tables: Table) {
val statements = createStatements(*tables)
for (statement in statements) {
exec(statement) {
connection.createStatement().executeUpdate(statement)
}
}
dialect.resetCaches()
}
private fun addMissingColumnsStatements (vararg tables: Table): List<String> {
val statements = ArrayList<String>()
if (tables.isEmpty())
return statements
val existingTableColumns = logTimeSpent("Extracting table columns") {
dialect.tableColumns()
}
for (table in tables) {
//create columns
val missingTableColumns = table.columns.filterNot { existingTableColumns[table.tableName]?.map { it.first }?.contains(it.name) ?: true }
for (column in missingTableColumns) {
statements.add(column.ddl)
}
// create indexes with new columns
for (table_index in table.indices) {
if (table_index.first.any { missingTableColumns.contains(it) }) {
val alterTable = createIndex(table_index.first, table_index.second)
statements.add(alterTable)
}
}
// sync nullability of existing columns
val incorrectNullabilityColumns = table.columns.filter { existingTableColumns[table.tableName]?.contains(it.name to !it.columnType.nullable) ?: false}
for (column in incorrectNullabilityColumns) {
statements.add(column.modifyStatement())
}
}
val existingColumnConstraint = logTimeSpent("Extracting column constraints") {
dialect.columnConstraints(*tables)
}
for (table in tables) {
for (column in table.columns) {
if (column.referee != null) {
val existingConstraint = existingColumnConstraint.get(Pair(table.tableName, column.name))?.firstOrNull()
if (existingConstraint == null) {
statements.add(createFKey(column))
} else if (existingConstraint.referencedTable != column.referee!!.table.tableName
|| (column.onDelete ?: ReferenceOption.RESTRICT) != existingConstraint.deleteRule) {
statements.add(existingConstraint.dropStatement())
statements.add(createFKey(column))
}
}
}
}
return statements
}
fun createMissingTablesAndColumns(vararg tables: Table) {
withDataBaseLock {
dialect.resetCaches()
val statements = logTimeSpent("Preparing create statements") {
createStatements(*tables) + addMissingColumnsStatements(*tables)
}
logTimeSpent("Executing create statements") {
for (statement in statements) {
exec(statement) {
connection.createStatement().executeUpdate(statement)
}
}
}
logTimeSpent("Checking mapping consistence") {
for (statement in checkMappingConsistence(*tables).filter { it !in statements }) {
exec(statement) {
connection.createStatement().executeUpdate(statement)
}
}
}
}
}
fun <T>withDataBaseLock(body: () -> T) {
connection.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS BusyTable(busy bit unique)")
val isBusy = connection.createStatement().executeQuery("SELECT * FROM BusyTable FOR UPDATE").next()
if (!isBusy) {
connection.createStatement().executeUpdate("INSERT INTO BusyTable (busy) VALUES (1)")
try {
body()
} finally {
connection.createStatement().executeUpdate("DELETE FROM BusyTable")
connection.commit()
}
}
}
fun drop(vararg tables: Table) {
for (table in tables) {
val ddl = table.dropStatement()
exec(ddl) {
connection.createStatement().executeUpdate(ddl)
}
}
}
private fun needQuotes (identity: String) : Boolean {
return keywords.contains (identity) || !identifierPattern.matcher(identity).matches()
}
private fun quoteIfNecessary (identity: String) : String {
return (identity.split('.') map {quoteTokenIfNecessary(it)}).joinToString(".")
}
private fun quoteTokenIfNecessary(token: String) : String {
return if (needQuotes(token)) "$identityQuoteString$token$identityQuoteString" else token
}
fun identity(table: Table): String {
return (table as? Alias<*>)?.let { "${identity(it.delegate)} AS ${quoteIfNecessary(it.alias)}"} ?: quoteIfNecessary(table.tableName)
}
fun fullIdentity(column: Column<*>): String {
return "${quoteIfNecessary(column.table.tableName)}.${quoteIfNecessary(column.name)}"
}
fun identity(column: Column<*>): String {
return quoteIfNecessary(column.name)
}
fun createFKey(reference: Column<*>): String = ForeignKeyConstraint.from(reference).createStatement()
fun createIndex(columns: Array<out Column<*>>, isUnique: Boolean): String = Index.forColumns(*columns, unique = isUnique).createStatement()
fun autoIncrement(column: Column<*>): String {
return when (vendor) {
DatabaseVendor.MySql,
DatabaseVendor.SQLServer,
DatabaseVendor.H2 -> {
"AUTO_INCREMENT"
}
else -> throw UnsupportedOperationException("Unsupported driver: " + vendor)
}
}
fun prepareStatement(sql: String, autoincs: List<String>? = null): PreparedStatement {
return if (autoincs == null) {
connection.prepareStatement(sql)!!
} else {
connection.prepareStatement(sql, autoincs.toTypedArray())!!
}
}
fun close() {
threadLocal.set(outerSession)
_connection?.close()
}
companion object {
val threadLocal = ThreadLocal<Session>()
fun hasSession(): Boolean = tryGet() != null
fun tryGet(): Session? = threadLocal.get()
fun get(): Session {
return tryGet() ?: error("No session in context. Use transaction?")
}
}
}
| agpl-3.0 | d19d48b1405a696799de43d1ed394554 | 32.509589 | 162 | 0.581473 | 4.768421 | false | false | false | false |
rock3r/detekt | detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/Debt.kt | 1 | 1411 | package io.gitlab.arturbosch.detekt.api
/**
* Debt describes the estimated amount of work needed to fix a given issue.
*/
@Suppress("MagicNumber")
data class Debt(val days: Int = 0, val hours: Int = 0, val mins: Int = 0) {
init {
require(days >= 0 && hours >= 0 && mins >= 0)
require(!(days == 0 && hours == 0 && mins == 0))
}
/**
* Adds the other debt to this debt.
* This recalculates the potential overflow resulting from the addition.
*/
operator fun plus(other: Debt): Debt {
var minutes = mins + other.mins
var hours = hours + other.hours
var days = days + other.days
hours += minutes / MINUTES_PER_HOUR
minutes %= MINUTES_PER_HOUR
days += hours / HOURS_PER_DAY
hours %= HOURS_PER_DAY
return Debt(days, hours, minutes)
}
companion object {
val TWENTY_MINS: Debt =
Debt(0, 0, 20)
val TEN_MINS: Debt =
Debt(0, 0, 10)
val FIVE_MINS: Debt =
Debt(0, 0, 5)
private const val HOURS_PER_DAY = 24
private const val MINUTES_PER_HOUR = 60
}
override fun toString(): String {
return with(StringBuilder()) {
if (days > 0) append("${days}d ")
if (hours > 0) append("${hours}h ")
if (mins > 0) append("${mins}min")
toString()
}.trimEnd()
}
}
| apache-2.0 | 686effc795fc1c4ed66cfea1642fed58 | 28.395833 | 76 | 0.540043 | 3.908587 | false | false | false | false |
mixitconf/mixit | src/main/kotlin/mixit/mixette/handler/MixetteHandler.kt | 1 | 2473 | package mixit.mixette.handler
import kotlinx.coroutines.reactor.awaitSingle
import mixit.MixitProperties
import mixit.event.handler.AdminEventHandler.Companion.CURRENT_EVENT
import mixit.event.handler.AdminEventHandler.Companion.TIMEZONE
import mixit.event.model.EventService
import mixit.mixette.repository.MixetteDonationRepository
import mixit.routes.MustacheI18n.TITLE
import mixit.routes.MustacheTemplate.MixetteDashboard
import mixit.util.frenchTalkTimeFormatter
import mixit.util.language
import org.springframework.http.MediaType
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.ServerResponse.ok
import org.springframework.web.reactive.function.server.body
import reactor.core.publisher.Mono
import java.time.LocalTime
import java.time.ZoneId
@Component
class MixetteHandler(
private val repository: MixetteDonationRepository,
private val eventService: EventService,
private val properties: MixitProperties
) {
suspend fun mixette(req: ServerRequest): ServerResponse {
val organizations = eventService.coFindByYear(CURRENT_EVENT.toInt()).organizations
val donationByOrgas = repository.coFindAllByYear(CURRENT_EVENT)
.groupBy { donation ->
organizations.first { it.login == donation.organizationLogin }.let {
MixetteOrganizationDonationDto(name = it.company, login = it.login)
}
}
.map { entry ->
entry.key.populate(
number = entry.value.size,
quantity = entry.value.sumOf { it.quantity },
amount = entry.value.sumOf { it.quantity * properties.mixetteValue.toDouble() }
)
}
val params = mapOf(
"organizations" to (organizations.map { it.toSponsorDto(req.language()) }),
"donations" to donationByOrgas,
"loadAt" to LocalTime.now(ZoneId.of(TIMEZONE)).format(frenchTalkTimeFormatter),
TITLE to "mixette.dashboard.title"
)
return ok().render(MixetteDashboard.template, params).awaitSingle()
}
fun mixetteRealTime(req: ServerRequest): Mono<ServerResponse> =
ok().contentType(MediaType.TEXT_EVENT_STREAM).body(repository.findByYearAfterNow(CURRENT_EVENT))
}
| apache-2.0 | cc95e7a3ce797dd621a80e82a433443f | 42.385965 | 104 | 0.723413 | 4.545956 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/entity/vanilla/ExperienceOrbEntityProtocol.kt | 1 | 1784 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.entity.vanilla
import org.lanternpowered.api.data.Keys
import org.lanternpowered.server.entity.LanternEntity
import org.lanternpowered.server.network.entity.EmptyEntityUpdateContext
import org.lanternpowered.server.network.entity.EntityProtocolUpdateContext
import org.lanternpowered.server.network.vanilla.packet.type.play.DestroyEntitiesPacket
import org.lanternpowered.server.network.vanilla.packet.type.play.SpawnExperienceOrbPacket
class ExperienceOrbEntityProtocol<E : LanternEntity>(entity: E) : EntityProtocol<E>(entity) {
private var lastQuantity = 0
override fun spawn(context: EntityProtocolUpdateContext) {
this.spawn(context, this.entity.get(Keys.EXPERIENCE).orElse(1))
}
private fun spawn(context: EntityProtocolUpdateContext, quantity: Int) {
if (quantity == 0) {
context.sendToAll { DestroyEntitiesPacket(this.rootEntityId) }
} else {
context.sendToAll { SpawnExperienceOrbPacket(this.rootEntityId, quantity, this.entity.position) }
}
}
override fun update(context: EntityProtocolUpdateContext) {
val quantity: Int = this.entity.get(Keys.EXPERIENCE).orElse(1)
if (this.lastQuantity != quantity) {
this.spawn(context, quantity)
super.update(EmptyEntityUpdateContext)
this.lastQuantity = quantity
} else {
super.update(context)
}
}
}
| mit | 056ce6855ee0395a64645e75640fde27 | 37.782609 | 109 | 0.722534 | 4.187793 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/test/kotlin/org/wfanet/measurement/reporting/service/api/v1alpha/EventGroupsServiceTest.kt | 1 | 18188 | // Copyright 2022 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.reporting.service.api.v1alpha
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.extensions.proto.ProtoTruth.assertThat
import com.google.protobuf.Any
import com.google.protobuf.ByteString
import com.google.protobuf.DescriptorProtos.FileDescriptorSet
import com.google.protobuf.Descriptors.Descriptor
import com.google.protobuf.Descriptors.FileDescriptor
import io.grpc.Status
import io.grpc.StatusRuntimeException
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.test.assertFailsWith
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.kotlin.any
import org.mockito.kotlin.stub
import org.wfanet.measurement.api.v2alpha.EventGroupKt as CmmsEventGroup
import org.wfanet.measurement.api.v2alpha.EventGroupMetadataDescriptorsGrpcKt.EventGroupMetadataDescriptorsCoroutineImplBase
import org.wfanet.measurement.api.v2alpha.EventGroupMetadataDescriptorsGrpcKt.EventGroupMetadataDescriptorsCoroutineStub
import org.wfanet.measurement.api.v2alpha.EventGroupsGrpcKt.EventGroupsCoroutineImplBase
import org.wfanet.measurement.api.v2alpha.EventGroupsGrpcKt.EventGroupsCoroutineStub
import org.wfanet.measurement.api.v2alpha.ListEventGroupsRequestKt
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerKey
import org.wfanet.measurement.api.v2alpha.batchGetEventGroupMetadataDescriptorsRequest
import org.wfanet.measurement.api.v2alpha.batchGetEventGroupMetadataDescriptorsResponse
import org.wfanet.measurement.api.v2alpha.encryptionPublicKey
import org.wfanet.measurement.api.v2alpha.eventGroup as cmmsEventGroup
import org.wfanet.measurement.api.v2alpha.eventGroupMetadataDescriptor
import org.wfanet.measurement.api.v2alpha.event_group_metadata.testing.TestMetadataMessageKt.age
import org.wfanet.measurement.api.v2alpha.event_group_metadata.testing.TestMetadataMessageKt.duration
import org.wfanet.measurement.api.v2alpha.event_group_metadata.testing.TestMetadataMessageKt.name
import org.wfanet.measurement.api.v2alpha.event_group_metadata.testing.testMetadataMessage
import org.wfanet.measurement.api.v2alpha.event_group_metadata.testing.testParentMetadataMessage
import org.wfanet.measurement.api.v2alpha.listEventGroupsRequest as cmmsListEventGroupsRequest
import org.wfanet.measurement.api.v2alpha.listEventGroupsResponse as cmmsListEventGroupsResponse
import org.wfanet.measurement.api.v2alpha.signedData
import org.wfanet.measurement.common.crypto.tink.TinkPrivateKeyHandle
import org.wfanet.measurement.common.crypto.tink.TinkPublicKeyHandle
import org.wfanet.measurement.common.crypto.tink.loadPrivateKey
import org.wfanet.measurement.common.crypto.tink.loadPublicKey
import org.wfanet.measurement.common.getRuntimePath
import org.wfanet.measurement.common.grpc.testing.GrpcTestServerRule
import org.wfanet.measurement.common.grpc.testing.mockService
import org.wfanet.measurement.common.testing.verifyProtoArgument
import org.wfanet.measurement.config.reporting.measurementConsumerConfig
import org.wfanet.measurement.consent.client.common.toEncryptionPublicKey
import org.wfanet.measurement.consent.client.dataprovider.encryptMetadata
import org.wfanet.measurement.reporting.v1alpha.EventGroupKt.metadata
import org.wfanet.measurement.reporting.v1alpha.eventGroup
import org.wfanet.measurement.reporting.v1alpha.listEventGroupsRequest
import org.wfanet.measurement.reporting.v1alpha.listEventGroupsResponse
private const val API_AUTHENTICATION_KEY = "nR5QPN7ptx"
private val CONFIG = measurementConsumerConfig { apiKey = API_AUTHENTICATION_KEY }
private val SECRET_FILES_PATH: Path =
checkNotNull(
getRuntimePath(
Paths.get("wfa_measurement_system", "src", "main", "k8s", "testing", "secretfiles")
)
)
private val ENCRYPTION_PRIVATE_KEY = loadEncryptionPrivateKey("mc_enc_private.tink")
private val ENCRYPTION_PUBLIC_KEY = loadEncryptionPublicKey("mc_enc_public.tink")
private const val MEASUREMENT_CONSUMER_REFERENCE_ID = "measurementConsumerRefId"
private val MEASUREMENT_CONSUMER_NAME =
MeasurementConsumerKey(MEASUREMENT_CONSUMER_REFERENCE_ID).toName()
private val ENCRYPTION_KEY_PAIR_STORE =
InMemoryEncryptionKeyPairStore(
mapOf(
MEASUREMENT_CONSUMER_NAME to
listOf(ENCRYPTION_PUBLIC_KEY.toByteString() to ENCRYPTION_PRIVATE_KEY)
)
)
private val TEST_MESSAGE = testMetadataMessage {
name = name { value = "Bob" }
age = age { value = 15 }
duration = duration { value = 20 }
}
private const val CMMS_EVENT_GROUP_ID = "AAAAAAAAAHs"
private val CMMS_EVENT_GROUP = cmmsEventGroup {
name = "$DATA_PROVIDER_NAME/eventGroups/$CMMS_EVENT_GROUP_ID"
measurementConsumer = MEASUREMENT_CONSUMER_NAME
eventGroupReferenceId = EVENT_GROUP_REFERENCE_ID
measurementConsumerPublicKey = signedData {
data = ENCRYPTION_PUBLIC_KEY.toEncryptionPublicKey().toByteString()
}
encryptedMetadata =
encryptMetadata(
CmmsEventGroup.metadata {
eventGroupMetadataDescriptor = METADATA_NAME
metadata = Any.pack(TEST_MESSAGE)
},
ENCRYPTION_PUBLIC_KEY.toEncryptionPublicKey()
)
}
private val TEST_MESSAGE_2 = testMetadataMessage {
name = name { value = "Alice" }
age = age { value = 5 }
duration = duration { value = 20 }
}
private const val CMMS_EVENT_GROUP_ID_2 = "AAAAAAAAAGs"
private val CMMS_EVENT_GROUP_2 = cmmsEventGroup {
name = "$DATA_PROVIDER_NAME/eventGroups/$CMMS_EVENT_GROUP_ID_2"
measurementConsumer = MEASUREMENT_CONSUMER_NAME
eventGroupReferenceId = "id2"
measurementConsumerPublicKey = signedData {
data = ENCRYPTION_PUBLIC_KEY.toEncryptionPublicKey().toByteString()
}
encryptedMetadata =
encryptMetadata(
CmmsEventGroup.metadata {
eventGroupMetadataDescriptor = METADATA_NAME
metadata = Any.pack(TEST_MESSAGE_2)
},
ENCRYPTION_PUBLIC_KEY.toEncryptionPublicKey()
)
}
private val EVENT_GROUP = eventGroup {
name =
EventGroupKey(
MEASUREMENT_CONSUMER_REFERENCE_ID,
DATA_PROVIDER_REFERENCE_ID,
CMMS_EVENT_GROUP_ID
)
.toName()
dataProvider = DATA_PROVIDER_NAME
eventGroupReferenceId = EVENT_GROUP_REFERENCE_ID
metadata = metadata {
eventGroupMetadataDescriptor = METADATA_NAME
metadata = Any.pack(TEST_MESSAGE)
}
}
private const val PAGE_TOKEN = "base64encodedtoken"
private const val NEXT_PAGE_TOKEN = "base64encodedtoken2"
private const val DATA_PROVIDER_REFERENCE_ID = "123"
private const val DATA_PROVIDER_NAME = "dataProviders/$DATA_PROVIDER_REFERENCE_ID"
private const val EVENT_GROUP_REFERENCE_ID = "edpRefId1"
private const val EVENT_GROUP_PARENT =
"measurementConsumers/$MEASUREMENT_CONSUMER_REFERENCE_ID/dataProviders/$DATA_PROVIDER_REFERENCE_ID"
private const val METADATA_NAME = "$DATA_PROVIDER_NAME/eventGroupMetadataDescriptors/abc"
private val EVENT_GROUP_METADATA_DESCRIPTOR = eventGroupMetadataDescriptor {
name = METADATA_NAME
descriptorSet = TEST_MESSAGE.descriptorForType.getFileDescriptorSet()
}
@RunWith(JUnit4::class)
class EventGroupsServiceTest {
private val cmmsEventGroupsServiceMock: EventGroupsCoroutineImplBase =
mockService() {
onBlocking { listEventGroups(any()) }
.thenReturn(
cmmsListEventGroupsResponse {
eventGroups += listOf(CMMS_EVENT_GROUP, CMMS_EVENT_GROUP_2)
nextPageToken = NEXT_PAGE_TOKEN
}
)
}
private val cmmsEventGroupMetadataDescriptorsServiceMock:
EventGroupMetadataDescriptorsCoroutineImplBase =
mockService() {
onBlocking { batchGetEventGroupMetadataDescriptors(any()) }
.thenReturn(
batchGetEventGroupMetadataDescriptorsResponse {
eventGroupMetadataDescriptors += EVENT_GROUP_METADATA_DESCRIPTOR
}
)
}
@get:Rule
val grpcTestServerRule = GrpcTestServerRule {
addService(cmmsEventGroupsServiceMock)
addService(cmmsEventGroupMetadataDescriptorsServiceMock)
}
@Test
fun `listEventGroups returns list with no filter`() {
val eventGroupsService =
EventGroupsService(
EventGroupsCoroutineStub(grpcTestServerRule.channel),
EventGroupMetadataDescriptorsCoroutineStub(grpcTestServerRule.channel),
ENCRYPTION_KEY_PAIR_STORE
)
val result =
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME, CONFIG) {
runBlocking {
eventGroupsService.listEventGroups(
listEventGroupsRequest {
parent = EVENT_GROUP_PARENT
pageSize = 10
pageToken = PAGE_TOKEN
}
)
}
}
assertThat(result)
.isEqualTo(
listEventGroupsResponse {
eventGroups +=
listOf(
EVENT_GROUP,
eventGroup {
name =
EventGroupKey(
MeasurementConsumerKey.fromName(CMMS_EVENT_GROUP_2.measurementConsumer)!!
.measurementConsumerId,
DATA_PROVIDER_REFERENCE_ID,
CMMS_EVENT_GROUP_ID_2
)
.toName()
dataProvider = DATA_PROVIDER_NAME
eventGroupReferenceId = "id2"
metadata = metadata {
eventGroupMetadataDescriptor = METADATA_NAME
metadata = Any.pack(TEST_MESSAGE_2)
}
}
)
nextPageToken = NEXT_PAGE_TOKEN
}
)
val expectedCmmsEventGroupsRequest = cmmsListEventGroupsRequest {
parent = DATA_PROVIDER_NAME
pageSize = 10
pageToken = PAGE_TOKEN
filter =
ListEventGroupsRequestKt.filter {
measurementConsumers += MEASUREMENT_CONSUMER_REFERENCE_ID
}
}
verifyProtoArgument(cmmsEventGroupsServiceMock, EventGroupsCoroutineImplBase::listEventGroups)
.isEqualTo(expectedCmmsEventGroupsRequest)
}
@Test
fun `listEventGroups returns list with filter`() {
val eventGroupsService =
EventGroupsService(
EventGroupsCoroutineStub(grpcTestServerRule.channel),
EventGroupMetadataDescriptorsCoroutineStub(grpcTestServerRule.channel),
ENCRYPTION_KEY_PAIR_STORE
)
val result =
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME, CONFIG) {
runBlocking {
eventGroupsService.listEventGroups(
listEventGroupsRequest {
parent = EVENT_GROUP_PARENT
filter = "age.value > 10"
pageToken = PAGE_TOKEN
}
)
}
}
assertThat(result)
.isEqualTo(
listEventGroupsResponse {
eventGroups += EVENT_GROUP
nextPageToken = NEXT_PAGE_TOKEN
}
)
val expectedCmmsMetadataDescriptorRequest = batchGetEventGroupMetadataDescriptorsRequest {
parent = DATA_PROVIDER_NAME
names += setOf(METADATA_NAME)
}
verifyProtoArgument(
cmmsEventGroupMetadataDescriptorsServiceMock,
EventGroupMetadataDescriptorsCoroutineImplBase::batchGetEventGroupMetadataDescriptors
)
.isEqualTo(expectedCmmsMetadataDescriptorRequest)
val expectedCmmsEventGroupsRequest = cmmsListEventGroupsRequest {
parent = DATA_PROVIDER_NAME
pageSize = 0
pageToken = PAGE_TOKEN
filter =
ListEventGroupsRequestKt.filter {
measurementConsumers += MEASUREMENT_CONSUMER_REFERENCE_ID
}
}
verifyProtoArgument(cmmsEventGroupsServiceMock, EventGroupsCoroutineImplBase::listEventGroups)
.isEqualTo(expectedCmmsEventGroupsRequest)
}
@Test
fun `listEventGroups throws FAILED_PRECONDITION if message descriptor not found`() {
val eventGroupInvalidMetadata = cmmsEventGroup {
name = "$DATA_PROVIDER_NAME/eventGroups/$CMMS_EVENT_GROUP_ID"
measurementConsumer = MEASUREMENT_CONSUMER_NAME
eventGroupReferenceId = "id1"
measurementConsumerPublicKey = signedData {
data = ENCRYPTION_PUBLIC_KEY.toEncryptionPublicKey().toByteString()
}
encryptedMetadata =
encryptMetadata(
CmmsEventGroup.metadata {
eventGroupMetadataDescriptor = METADATA_NAME
metadata = Any.pack(testParentMetadataMessage { name = "name" })
},
ENCRYPTION_PUBLIC_KEY.toEncryptionPublicKey()
)
}
cmmsEventGroupsServiceMock.stub {
onBlocking { listEventGroups(any()) }
.thenReturn(
cmmsListEventGroupsResponse {
eventGroups += listOf(CMMS_EVENT_GROUP, CMMS_EVENT_GROUP_2, eventGroupInvalidMetadata)
}
)
}
val eventGroupsService =
EventGroupsService(
EventGroupsCoroutineStub(grpcTestServerRule.channel),
EventGroupMetadataDescriptorsCoroutineStub(grpcTestServerRule.channel),
ENCRYPTION_KEY_PAIR_STORE
)
val result =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME, CONFIG) {
runBlocking {
eventGroupsService.listEventGroups(
listEventGroupsRequest {
parent = EVENT_GROUP_PARENT
filter = "age.value > 10"
}
)
}
}
}
assertThat(result.status.code).isEqualTo(Status.Code.FAILED_PRECONDITION)
}
@Test
fun `listEventGroups throws FAILED_PRECONDITION if private key not found`() {
val eventGroupInvalidPublicKey = cmmsEventGroup {
name = "$DATA_PROVIDER_NAME/eventGroups/$CMMS_EVENT_GROUP_ID"
measurementConsumer = MEASUREMENT_CONSUMER_NAME
eventGroupReferenceId = "id1"
measurementConsumerPublicKey = signedData {
data = encryptionPublicKey { data = ByteString.copyFromUtf8("consumerkey") }.toByteString()
}
encryptedMetadata =
encryptMetadata(
CmmsEventGroup.metadata {
eventGroupMetadataDescriptor = METADATA_NAME
metadata = Any.pack(testParentMetadataMessage { name = "name" })
},
ENCRYPTION_PUBLIC_KEY.toEncryptionPublicKey()
)
}
cmmsEventGroupsServiceMock.stub {
onBlocking { listEventGroups(any()) }
.thenReturn(
cmmsListEventGroupsResponse {
eventGroups += listOf(CMMS_EVENT_GROUP, CMMS_EVENT_GROUP_2, eventGroupInvalidPublicKey)
}
)
}
val eventGroupsService =
EventGroupsService(
EventGroupsCoroutineStub(grpcTestServerRule.channel),
EventGroupMetadataDescriptorsCoroutineStub(grpcTestServerRule.channel),
ENCRYPTION_KEY_PAIR_STORE
)
val result =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME, CONFIG) {
runBlocking {
eventGroupsService.listEventGroups(
listEventGroupsRequest {
parent = EVENT_GROUP_PARENT
filter = "age.value > 10"
}
)
}
}
}
assertThat(result.status.code).isEqualTo(Status.Code.FAILED_PRECONDITION)
}
@Test
fun `listEventGroups throws FAILED_PRECONDITION if parent not found`() {
val eventGroupsService =
EventGroupsService(
EventGroupsCoroutineStub(grpcTestServerRule.channel),
EventGroupMetadataDescriptorsCoroutineStub(grpcTestServerRule.channel),
ENCRYPTION_KEY_PAIR_STORE
)
val result =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME, CONFIG) {
runBlocking {
eventGroupsService.listEventGroups(
listEventGroupsRequest {
filter = "age.value > 10"
pageToken = PAGE_TOKEN
ENCRYPTION_KEY_PAIR_STORE
}
)
}
}
}
assertThat(result.status.code).isEqualTo(Status.Code.FAILED_PRECONDITION)
}
@Test
fun `listEventGroups throws UNAUTHENTICATED if principal not found`() {
val eventGroupsService =
EventGroupsService(
EventGroupsCoroutineStub(grpcTestServerRule.channel),
EventGroupMetadataDescriptorsCoroutineStub(grpcTestServerRule.channel),
ENCRYPTION_KEY_PAIR_STORE
)
val result =
assertFailsWith<StatusRuntimeException> {
runBlocking {
eventGroupsService.listEventGroups(
listEventGroupsRequest {
parent = EVENT_GROUP_PARENT
filter = "age.value > 10"
}
)
}
}
assertThat(result.status.code).isEqualTo(Status.Code.UNAUTHENTICATED)
}
}
fun Descriptor.getFileDescriptorSet(): FileDescriptorSet {
val fileDescriptors = mutableSetOf<FileDescriptor>()
val toVisit = mutableListOf<FileDescriptor>(file)
while (toVisit.isNotEmpty()) {
val fileDescriptor = toVisit.removeLast()
if (!fileDescriptors.contains(fileDescriptor)) {
fileDescriptors.add(fileDescriptor)
fileDescriptor.dependencies.forEach {
if (!fileDescriptors.contains(it)) {
toVisit.add(it)
}
}
}
}
return FileDescriptorSet.newBuilder().addAllFile(fileDescriptors.map { it.toProto() }).build()
}
fun loadEncryptionPrivateKey(fileName: String): TinkPrivateKeyHandle {
return loadPrivateKey(SECRET_FILES_PATH.resolve(fileName).toFile())
}
fun loadEncryptionPublicKey(fileName: String): TinkPublicKeyHandle {
return loadPublicKey(SECRET_FILES_PATH.resolve(fileName).toFile())
}
| apache-2.0 | 7c6c46194c04de07d9a855b9781317be | 36.81289 | 124 | 0.715362 | 4.588295 | false | true | false | false |
mercadopago/px-android | px-checkout/src/main/java/com/mercadopago/android/px/internal/datasource/CongratsRepositoryImpl.kt | 1 | 7591 | package com.mercadopago.android.px.internal.datasource
import com.mercadopago.android.px.addons.ESCManagerBehaviour
import com.mercadopago.android.px.internal.core.FlowIdProvider
import com.mercadopago.android.px.internal.features.payment_result.remedies.AlternativePayerPaymentMethodsMapper
import com.mercadopago.android.px.internal.features.payment_result.remedies.RemediesBodyMapper
import com.mercadopago.android.px.internal.repository.*
import com.mercadopago.android.px.internal.repository.CongratsRepository.PostPaymentCallback
import com.mercadopago.android.px.internal.services.CongratsService
import com.mercadopago.android.px.internal.services.Response
import com.mercadopago.android.px.internal.services.awaitCallback
import com.mercadopago.android.px.internal.util.StatusHelper
import com.mercadopago.android.px.internal.util.TextUtil
import com.mercadopago.android.px.internal.viewmodel.BusinessPaymentModel
import com.mercadopago.android.px.internal.viewmodel.PaymentModel
import com.mercadopago.android.px.model.*
import com.mercadopago.android.px.model.internal.CongratsResponse
import com.mercadopago.android.px.model.internal.InitResponse
import com.mercadopago.android.px.model.internal.remedies.RemediesResponse
import com.mercadopago.android.px.services.BuildConfig
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class CongratsRepositoryImpl(
private val congratsService: CongratsService, private val initService: InitRepository,
private val paymentSetting: PaymentSettingRepository, private val platform: String,
private val flowIdProvider: FlowIdProvider, private val userSelectionRepository: UserSelectionRepository,
private val amountRepository: AmountRepository,
private val disabledPaymentMethodRepository: DisabledPaymentMethodRepository,
private val payerComplianceRepository: PayerComplianceRepository,
private val escManagerBehaviour: ESCManagerBehaviour) : CongratsRepository {
private val paymentRewardCache = HashMap<String, CongratsResponse>()
private val remediesCache = HashMap<String, RemediesResponse>()
private val privateKey = paymentSetting.privateKey
override fun getPostPaymentData(payment: IPaymentDescriptor, paymentResult: PaymentResult,
callback: PostPaymentCallback) {
val hasAccessToken = TextUtil.isNotEmpty(privateKey)
val hasToReturnEmptyResponse = !hasAccessToken
val isSuccess = StatusHelper.isSuccess(payment)
CoroutineScope(Dispatchers.IO).launch {
val paymentId = payment.paymentIds?.get(0) ?: payment.id.toString()
val paymentReward = when {
hasToReturnEmptyResponse || !isSuccess -> CongratsResponse.EMPTY
paymentRewardCache.containsKey(paymentId) -> paymentRewardCache[paymentId]!!
else -> getPaymentReward(payment, paymentResult).apply { paymentRewardCache[paymentId] = this }
}
val remediesResponse = when {
hasToReturnEmptyResponse || isSuccess -> RemediesResponse.EMPTY
remediesCache.containsKey(paymentId) -> remediesCache[paymentId]!!
else -> {
getRemedies(payment, paymentResult.paymentData).apply { remediesCache[paymentId] = this }
}
}
withContext(Dispatchers.Main) {
handleResult(payment, paymentResult, paymentReward, remediesResponse, paymentSetting.currency, callback)
}
}
}
private suspend fun getPaymentReward(payment: IPaymentDescriptor, paymentResult: PaymentResult) =
try {
val joinedPaymentIds = TextUtil.join(payment.paymentIds)
val joinedPaymentMethodsIds = paymentResult.paymentDataList
.joinToString(TextUtil.CSV_DELIMITER) { p -> (p.paymentMethod.id) }
val campaignId = paymentResult.paymentData.campaign?.run { id } ?: ""
val response = congratsService.getCongrats(BuildConfig.API_ENVIRONMENT, privateKey,
joinedPaymentIds, platform, campaignId, payerComplianceRepository.turnedIFPECompliant(),
joinedPaymentMethodsIds, flowIdProvider.flowId).await()
if (response.isSuccessful) {
response.body()!!
} else {
CongratsResponse.EMPTY
}
} catch (e: Exception) {
CongratsResponse.EMPTY
}
private fun getPayerPaymentMethods(response: InitResponse?) =
mutableListOf<Triple<SecurityCode?, String, CustomSearchItem>>()
.also { mapPayerPaymentMethods ->
response?.run {
customSearchItems.forEach { customSearchItem ->
express.find { it.customOptionId == customSearchItem.id }?.let { expressMetadata ->
mapPayerPaymentMethods.add(
Triple(getCardById(customSearchItem.id)?.securityCode, expressMetadata.customOptionId,
customSearchItem)
)
}
}
}
}.filter { !disabledPaymentMethodRepository.hasPaymentMethodId(it.second) }
private suspend fun loadInitResponse() =
when (val callbackResult = initService.init().awaitCallback<InitResponse>()) {
is Response.Success<*> -> callbackResult.result as InitResponse
is Response.Failure<*> -> null
}
private suspend fun getRemedies(payment: IPaymentDescriptor, paymentData: PaymentData) =
try {
val initResponse = loadInitResponse()
val payerPaymentMethods = getPayerPaymentMethods(initResponse)
val hasOneTap = initResponse?.hasExpressCheckoutMetadata() ?: false
val customOptionId = paymentData.token?.cardId ?: paymentData.paymentMethod.id
val escCardIds = escManagerBehaviour.escCardIds
val body = RemediesBodyMapper(
userSelectionRepository,
amountRepository,
customOptionId,
escCardIds.contains(customOptionId),
AlternativePayerPaymentMethodsMapper(escCardIds).map(payerPaymentMethods.filter { it.second != customOptionId })
).map(paymentData)
val response = congratsService.getRemedies(
BuildConfig.API_ENVIRONMENT_NEW,
payment.id.toString(),
privateKey,
hasOneTap,
body
).await()
if (response.isSuccessful) {
response.body()!!
} else {
RemediesResponse.EMPTY
}
} catch (e: Exception) {
RemediesResponse.EMPTY
}
private fun handleResult(payment: IPaymentDescriptor, paymentResult: PaymentResult, congratsResponse: CongratsResponse,
remedies: RemediesResponse, currency: Currency, callback: PostPaymentCallback) {
payment.process(object : IPaymentDescriptorHandler {
override fun visit(payment: IPaymentDescriptor) {
callback.handleResult(PaymentModel(payment, paymentResult, congratsResponse, remedies, currency))
}
override fun visit(businessPayment: BusinessPayment) {
callback.handleResult(BusinessPaymentModel(businessPayment, paymentResult, congratsResponse, remedies,
currency))
}
})
}
} | mit | 6f439bed09b4106e6188806fbeae2ef4 | 50.646259 | 128 | 0.684363 | 5.057295 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/platform/IoMultiplexingExecutor.kt | 1 | 3324 | package io.rover.sdk.experiences.platform
import android.annotation.SuppressLint
import android.os.Build
import java.util.concurrent.Executor
import java.util.concurrent.ForkJoinPool
import java.util.concurrent.SynchronousQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
/**
* A builder that will produce an [Executor] suitable for multiplexing across many blocking I/O
* operations.
*/
internal class IoMultiplexingExecutor {
companion object {
/**
* This will produce an [Executor] tuned for multiplexing I/O, not for computation.
*
* Try to avoid doing computation on it.
*/
@SuppressLint("NewApi")
@JvmStatic
fun build(executorName: String): Executor {
val alwaysUseLegacyThreadPool = false
val cpuCount = Runtime.getRuntime().availableProcessors()
val useModernThreadPool = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !alwaysUseLegacyThreadPool
return if (useModernThreadPool) {
// The below is equivalent to:
// Executors.newWorkStealingPool(availableProcessors * 100)
// It's specifically meant for use in a ForkJoinTask work-stealing workload, but as a
// side-effect it also configures an Executor that does a fair job of enforcing a
// maximum thread pool size, which is difficult to do with the stock Executors due to an
// odd design decision by the Java team a few decades ago:
// https://github.com/kimchy/kimchy.github.com/blob/master/_posts/2008-11-23-juc-executorservice-gotcha.textile
ForkJoinPool(
cpuCount * 100,
ForkJoinPool.ForkJoinWorkerThreadFactory { pool ->
ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool).apply {
// include our executor name in the worker thread names.
this.name = "Rover/IoMultiplexingExecutor($executorName)-${this.name}"
}
},
null, true)
} else {
// we'll use an unbounded thread pool on Android versions older than 21.
// while one would expect that you could set a maxPoolSize value and have sane
// scale-up-and-down behaviour, that is not how it works out. ThreadPoolExecutor
// actually will only create new threads (up to the max), when the queue you give it
// reports itself as being full by means of the [Queue.offer] interface. A common
// workaround is to use SynchronousQueue, which always reports itself as full.
// Unfortunately, this workaround prohibits the thread pool maximum size being enforced.
// However, on casual testing for our use case it appears that for our I/O multiplexing
// thread pool we can largely get away with this.
ThreadPoolExecutor(
10,
Int.MAX_VALUE,
2,
TimeUnit.SECONDS,
SynchronousQueue<Runnable>()
)
}
}
}
} | apache-2.0 | 2d55b91548a7ecd588b5b326f4e1a8cd | 46.5 | 127 | 0.609206 | 5.17757 | false | false | false | false |
Flank/fladle | buildSrc/src/test/java/com/osacky/flank/gradle/validation/ValidateOptionsTest.kt | 1 | 4991 | package com.osacky.flank.gradle.validation
import com.google.common.truth.Truth.assertThat
import com.osacky.flank.gradle.FladleConfig
import com.osacky.flank.gradle.FlankGradleExtension
import com.osacky.flank.gradle.integration.gradleRunner
import com.osacky.flank.gradle.integration.writeBuildDotGradle
import org.gradle.testfixtures.ProjectBuilder
import org.junit.Assert.assertThrows
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class ValidateOptionsTest {
@get:Rule
var testProjectRoot = TemporaryFolder()
private val objects = ProjectBuilder.builder().withName("project").build().objects
private lateinit var config: FladleConfig
@Before
fun setUp() {
testProjectRoot.newFile("flank-gradle-service.json").writeText("{}")
config = FlankGradleExtension(objects)
}
@Test
fun `should throw an error when unavailable option used`() {
config.outputStyle.set("single")
assertThrows(IllegalStateException::class.java) { validateOptionsUsed(config, "20.05.0") }.run {
assertThat(message).containsMatch("Option outputStyle is available since flank 20.6.0, which is higher than used 20.5.0")
}
}
@Test
fun `should not throw an error when available option used`() {
config.testRunnerClass.set("any")
validateOptionsUsed(config, "20.09.10")
}
@Test
fun `should throw an error when unavailable option used -- multi config`() {
testProjectRoot.writeBuildDotGradle(
"""
|plugins {
| id "com.osacky.fladle"
|}
|
|fladle {
| serviceAccountCredentials = layout.projectDirectory.file("flank-gradle-service.json")
| debugApk = "foo.apk"
| instrumentationApk = "test.apk"
| flankVersion.set("20.05.0")
| configs {
| newNetwork {
| outputStyle.set("verbose")
| }
| noSharding {
| disableSharding.set(true)
| }
| }
|}
""".trimMargin()
)
val runner = testProjectRoot.gradleRunner()
runner.withArguments("printYml").buildAndFail().run {
assertThat(output).contains("FAILED")
assertThat(output).contains("Option outputStyle is available since flank 20.6.0, which is higher than used 20.5.0")
}
runner.withArguments("printYmlNewNetwork").buildAndFail().run {
assertThat(output).contains("FAILED")
assertThat(output).contains("Option outputStyle is available since flank 20.6.0, which is higher than used 20.5.0")
}
runner.withArguments("printYmlNoSharding").buildAndFail().run {
assertThat(output).contains("FAILED")
assertThat(output).contains("Option outputStyle is available since flank 20.6.0, which is higher than used 20.5.0")
}
}
@Test
fun `should not throw an error if none unavailable option used`() {
testProjectRoot.writeBuildDotGradle(
"""
|plugins {
| id "com.osacky.fladle"
|}
|
|fladle {
| serviceAccountCredentials = layout.projectDirectory.file("flank-gradle-service.json")
| debugApk = "foo.apk"
| instrumentationApk = "test.apk"
| flankVersion.set("20.20.20")
| configs {
| noRecord {
| recordVideo.set(false)
| }
| }
|}
""".trimMargin()
)
val runner = testProjectRoot.gradleRunner()
val result = runner.withArguments("printYml").build()
assertThat(result.output).contains("BUILD SUCCESSFUL")
assertThat(result.output).contains(
"""
|gcloud:
| app: foo.apk
| test: test.apk
| device:
| - model: NexusLowRes
| version: 28
|
| use-orchestrator: false
| auto-google-login: false
| record-video: true
| performance-metrics: true
| timeout: 15m
| num-flaky-test-attempts: 0
|
|flank:
| keep-file-path: false
| ignore-failed-tests: false
| disable-sharding: false
| smart-flank-disable-upload: false
| legacy-junit-result: false
| full-junit-result: false
| output-style: single
""".trimMargin()
)
val resultOrange = runner.withArguments("printYmlNoRecord").build()
assertThat(resultOrange.output).contains("BUILD SUCCESSFUL")
assertThat(resultOrange.output).contains(
"""
|gcloud:
| app: foo.apk
| test: test.apk
| device:
| - model: NexusLowRes
| version: 28
|
| use-orchestrator: false
| auto-google-login: false
| record-video: false
| performance-metrics: true
| timeout: 15m
| num-flaky-test-attempts: 0
|
|flank:
| keep-file-path: false
| ignore-failed-tests: false
| disable-sharding: false
| smart-flank-disable-upload: false
| legacy-junit-result: false
| full-junit-result: false
| output-style: single
""".trimMargin()
)
}
}
| apache-2.0 | cc92c6e6b523d356d7433c6a43fec769 | 28.532544 | 127 | 0.636546 | 3.973726 | false | true | false | false |
ken-kentan/student-portal-plus | app/src/main/java/jp/kentan/studentportalplus/data/model/LectureInformation.kt | 1 | 1587 | package jp.kentan.studentportalplus.data.model
import androidx.recyclerview.widget.DiffUtil
import jp.kentan.studentportalplus.data.component.LectureAttend
import jp.kentan.studentportalplus.util.Murmur3
import java.util.*
data class LectureInformation(
override val id: Long = -1,
val grade: String, // 学部名など
val semester: String, // 学期
override val subject: String, // 授業科目名
override val instructor: String, // 担当教員名
override val week: String, // 曜日
override val period: String, // 時限
val category: String, // 分類
val detailText: String, // 連絡事項(Text)
val detailHtml: String, // 連絡事項(Html)
val createdDate: Date, // 初回掲示日
val updatedDate: Date, // 最終更新日
override val isRead: Boolean = false,
override val attend: LectureAttend = LectureAttend.UNKNOWN,
val hash: Long = Murmur3.hash64("$grade$semester$subject$instructor$week$period$category$detailHtml$createdDate$updatedDate")
) : Lecture(detailText, updatedDate) {
companion object {
val DIFF_CALLBACK = object : DiffUtil.ItemCallback<LectureInformation>() {
override fun areItemsTheSame(oldItem: LectureInformation, newItem: LectureInformation): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: LectureInformation, newItem: LectureInformation): Boolean {
return oldItem == newItem
}
}
}
} | gpl-3.0 | 1b53d4bebf1cd22ae849f1ca9caa5f91 | 40.833333 | 133 | 0.666445 | 4.100817 | false | false | false | false |
NextFaze/dev-fun | test/src/test/java/com/nextfaze/devfun/test/tests/TestMetaAnnotations.kt | 1 | 1055 | package com.nextfaze.devfun.test.tests
import com.nextfaze.devfun.internal.log.*
import com.nextfaze.devfun.test.AbstractKotlinKapt3Tester
import com.nextfaze.devfun.test.TestContext
import com.nextfaze.devfun.test.singleFileTests
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
import tested.meta_annotations.MetaCategories
import tested.meta_annotations.MetaDevFunctions
import tested.meta_annotations.MetaGroupingCategory
import java.lang.reflect.Method
@Test(groups = ["kapt", "compile", "supported", "meta", "category"])
class TestMetaAnnotations : AbstractKotlinKapt3Tester() {
private val log = logger()
@DataProvider(name = "testMetaAnnotationsData")
fun testMetaAnnotationsData(testMethod: Method) =
singleFileTests(
testMethod,
MetaCategories::class,
MetaGroupingCategory::class,
MetaDevFunctions::class
)
@Test(dataProvider = "testMetaAnnotationsData")
fun testMetaAnnotations(test: TestContext) = test.testInvocations(log)
}
| apache-2.0 | 5a30597492ef79eb4e8c3fc1e538429a | 35.37931 | 74 | 0.762085 | 4.32377 | false | true | false | false |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/find/shuju/post/QidianshujuPostAdapter.kt | 1 | 2065 | package cc.aoeiuv020.panovel.find.shuju.post
import android.annotation.SuppressLint
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.find.shuju.list.QidianshujuListActivity
import java.util.concurrent.TimeUnit
/**
* Created by AoEiuV020 on 2021.09.06-23:09:42.
*/
class QidianshujuPostAdapter : RecyclerView.Adapter<QidianshujuPostAdapter.ViewHolder>() {
private val data = mutableListOf<Post>()
@SuppressLint("NotifyDataSetChanged")
fun setData(data: List<Post>) {
this.data.clear()
this.data.addAll(data)
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return data.count()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_qidianshuju_post, parent, false)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = data[position]
holder.bind(item)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val tvTitle: TextView = itemView.findViewById(R.id.tvTitle)
private val tvNum: TextView = itemView.findViewById(R.id.tvNum)
private val tvDate: TextView = itemView.findViewById(R.id.tvDate)
fun bind(item: Post) {
itemView.setOnClickListener {
QidianshujuListActivity.start(it.context, item.url)
}
tvTitle.text = item.title
tvNum.text = item.num
tvDate.text = item.date?.let { date ->
DateUtils.getRelativeTimeSpanString(
date.time,
System.currentTimeMillis(),
TimeUnit.SECONDS.toMillis(1)
)
} ?: ""
}
}
} | gpl-3.0 | 52a521b20867f4f740d09bc7f8c40c3e | 32.322581 | 90 | 0.65569 | 4.384289 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-sonarqube/src/test/java/net/nemerosa/ontrack/extension/sonarqube/SonarQubeIT.kt | 1 | 32643 | package net.nemerosa.ontrack.extension.sonarqube
import com.nhaarman.mockitokotlin2.*
import net.nemerosa.ontrack.common.RunProfile
import net.nemerosa.ontrack.extension.api.support.TestBranchModelMatcherProvider
import net.nemerosa.ontrack.extension.general.BuildLinkDisplayProperty
import net.nemerosa.ontrack.extension.general.BuildLinkDisplayPropertyType
import net.nemerosa.ontrack.extension.general.ReleaseProperty
import net.nemerosa.ontrack.extension.general.ReleasePropertyType
import net.nemerosa.ontrack.extension.sonarqube.client.SonarQubeClient
import net.nemerosa.ontrack.extension.sonarqube.client.SonarQubeClientFactory
import net.nemerosa.ontrack.extension.sonarqube.configuration.SonarQubeConfiguration
import net.nemerosa.ontrack.extension.sonarqube.configuration.SonarQubeConfigurationService
import net.nemerosa.ontrack.extension.sonarqube.measures.SonarQubeMeasures
import net.nemerosa.ontrack.extension.sonarqube.measures.SonarQubeMeasuresCollectionService
import net.nemerosa.ontrack.extension.sonarqube.measures.SonarQubeMeasuresInformationExtension
import net.nemerosa.ontrack.extension.sonarqube.measures.SonarQubeMeasuresSettings
import net.nemerosa.ontrack.extension.sonarqube.property.SonarQubeProperty
import net.nemerosa.ontrack.extension.sonarqube.property.SonarQubePropertyType
import net.nemerosa.ontrack.it.AbstractDSLTestJUnit4Support
import net.nemerosa.ontrack.model.metrics.MetricsExportService
import net.nemerosa.ontrack.model.security.GlobalSettings
import net.nemerosa.ontrack.model.structure.Build
import net.nemerosa.ontrack.model.structure.Project
import net.nemerosa.ontrack.model.structure.ValidationRunStatusID
import net.nemerosa.ontrack.test.TestUtils.uid
import net.nemerosa.ontrack.test.assertIs
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.context.annotation.Profile
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
class SonarQubeIT : AbstractDSLTestJUnit4Support() {
@Autowired
private lateinit var sonarQubeConfigurationService: SonarQubeConfigurationService
@Autowired
private lateinit var sonarQubeMeasuresCollectionService: SonarQubeMeasuresCollectionService
@Autowired
private lateinit var metricsExportService: MetricsExportService
@Autowired
private lateinit var informationExtension: SonarQubeMeasuresInformationExtension
@Test
fun `Launching the collection on validation run`() {
val returnedMeasures = mapOf(
"measure-1" to 12.3,
"measure-2" to 45.0
)
testCollectionWithListener(
actualMeasures = mapOf(
"measure-1" to 12.3,
"measure-2" to 45.0
),
returnedMeasures = returnedMeasures
) { build ->
// Checks that metrics are exported
returnedMeasures.forEach { (name, value) ->
verify(metricsExportService).exportMetrics(
metric = eq("ontrack_sonarqube_measure"),
tags = eq(mapOf(
"project" to build.project.name,
"branch" to build.branch.name,
"status" to "PASSED",
"measure" to name
)),
fields = eq(mapOf(
"value" to value
)),
timestamp = any()
)
}
// Checks the entity information
val information = informationExtension.getInformation(build)
assertNotNull(information) {
assertIs<SonarQubeMeasures>(it.data) { q ->
assertEquals(
returnedMeasures,
q.measures
)
}
}
}
}
@Test
fun `Launching the collection on validation run without any measure`() {
testCollectionWithListener(
actualMeasures = null,
returnedMeasures = null
)
}
@Test
fun `Launching the collection on validation run using a non default validation stamp`() {
testCollectionWithListener(
validationStamp = "sonar-qube",
actualMeasures = mapOf(
"measure-1" to 12.3,
"measure-2" to 45.0
),
returnedMeasures = mapOf(
"measure-1" to 12.3,
"measure-2" to 45.0
)
)
}
@Test
fun `Launching the collection on validation run can be disabled at global level`() {
testCollectionWithListener(
globalDisabled = true,
actualMeasures = mapOf(
"measure-1" to 12.3,
"measure-2" to 45.0
),
returnedMeasures = null,
)
}
@Test
fun `Launching the collection on validation run with global settings`() {
testCollectionWithListener(
globalMeasures = listOf("measure-2"),
actualMeasures = mapOf(
"measure-1" to 12.3,
"measure-2" to 45.0
),
returnedMeasures = mapOf(
"measure-2" to 45.0
)
)
}
@Test
fun `Launching the collection on validation run with global settings completed by project`() {
testCollectionWithListener(
globalMeasures = listOf("measure-2"),
projectMeasures = listOf("measure-1"),
actualMeasures = mapOf(
"measure-1" to 12.3,
"measure-2" to 45.0
),
returnedMeasures = mapOf(
"measure-1" to 12.3,
"measure-2" to 45.0
)
)
}
@Test
fun `Launching the collection on validation run with global settings overridden by project`() {
testCollectionWithListener(
globalMeasures = listOf("measure-2"),
projectMeasures = listOf("measure-1"),
projectOverride = true,
actualMeasures = mapOf(
"measure-1" to 12.3,
"measure-2" to 45.0
),
returnedMeasures = mapOf(
"measure-1" to 12.3
)
)
}
@Test
fun `Launching the collection on validation run using build label`() {
testCollectionWithListener(
useLabel = true,
buildName = "release-1.0.0",
buildLabel = "1.0.0",
actualMeasures = mapOf(
"measure-1" to 12.3,
"measure-2" to 45.0
),
returnedMeasures = mapOf(
"measure-1" to 12.3,
"measure-2" to 45.0
)
)
}
@Test
fun `Launching the collection on validation run with missing measures`() {
testCollectionWithListener(
actualMeasures = mapOf(
"measure-1" to 12.3
),
returnedMeasures = mapOf(
"measure-1" to 12.3
)
)
}
private fun testCollectionWithListener(
globalMeasures: List<String> = listOf("measure-1", "measure-2"),
globalDisabled: Boolean = false,
validationStamp: String = "sonarqube",
projectMeasures: List<String> = emptyList(),
projectOverride: Boolean = false,
useLabel: Boolean = false,
buildVersion: String = "1.0.0",
buildName: String = "1.0.0",
buildLabel: String? = null,
actualMeasures: Map<String, Double>?,
returnedMeasures: Map<String, Double>?,
code: (Build) -> Unit = {}
) {
withSonarQubeSettings(measures = globalMeasures, disabled = globalDisabled) {
val key = uid("p")
// Mocking the measures
if (actualMeasures != null) {
mockSonarQubeMeasures(
key,
buildVersion,
*actualMeasures.toList().toTypedArray()
)
}
withConfiguredProject(key = key, stamp = validationStamp, measures = projectMeasures, override = projectOverride) {
if (useLabel) {
setProperty(
this,
BuildLinkDisplayPropertyType::class.java,
BuildLinkDisplayProperty(true)
)
}
branch {
val vs = validationStamp(validationStamp)
build(buildName) {
// Label for the build
if (buildLabel != null) {
setProperty(
this,
ReleasePropertyType::class.java,
ReleaseProperty(buildLabel)
)
}
// Validates to launch the collection
validate(vs)
// Checks that some SonarQube metrics are attached to this build
val measures = sonarQubeMeasuresCollectionService.getMeasures(this)
if (returnedMeasures != null) {
assertNotNull(measures) {
assertEquals(
returnedMeasures,
it.measures
)
}
} else {
assertNull(measures, "No measure is expected to be returned")
}
// Additional checks
code(this)
}
}
}
}
}
@Test
fun `Collecting a build measures without a validation stamp`() {
withDisabledConfigurationTest {
withSonarQubeSettings {
val key = uid("p")
withConfiguredProject(key) {
branch {
build {
val result = sonarQubeMeasuresCollectionService.collect(
this,
getProperty(project, SonarQubePropertyType::class.java)
)
assertFalse(result.ok, "Nothing was collected")
assertEquals("Validation stamp sonarqube cannot be found in ${branch.entityDisplayName}", result.message)
}
}
}
}
}
}
@Test
fun `Project using all branches`() {
withDisabledConfigurationTest {
withSonarQubeSettings {
val key = uid("p")
withConfiguredProject(key) {
val build1 = branch<Build>("release-1.0") {
val vs = validationStamp("sonarqube")
build("1.0.0") {
validate(vs)
}
}
val build2 = branch<Build>("feature-test") {
val vs = validationStamp("sonarqube")
build("abdcefg") {
validate(vs)
}
}
// Setting the configuration of the project now, builds are still not scanned
mockSonarQubeMeasures(key, "1.0.0",
"measure-1" to 1.0,
"measure-2" to 1.1
)
mockSonarQubeMeasures(key, "abdcefg",
"measure-1" to 2.0,
"measure-2" to 2.1
)
// Scanning of the project
sonarQubeMeasuresCollectionService.collect(this) { println(it) }
// Checks the measures attached to the builds
assertNotNull(sonarQubeMeasuresCollectionService.getMeasures(build1)) {
assertEquals(
mapOf(
"measure-1" to 1.0,
"measure-2" to 1.1
),
it.measures
)
}
assertNotNull(sonarQubeMeasuresCollectionService.getMeasures(build2)) {
assertEquals(
mapOf(
"measure-1" to 2.0,
"measure-2" to 2.1
),
it.measures
)
}
}
}
}
}
@Test
fun `Project using branch pattern`() {
withDisabledConfigurationTest {
withSonarQubeSettings {
val key = uid("p")
withConfiguredProject(key, branchPattern = "release-.*") {
val build1 = branch<Build>("release-1.0") {
val vs = validationStamp("sonarqube")
build("1.0.0") {
validate(vs)
}
}
val build2 = branch<Build>("feature-test") {
val vs = validationStamp("sonarqube")
build("abdcefg") {
validate(vs)
}
}
// Setting the configuration of the project now, builds are still not scanned
mockSonarQubeMeasures(key, "1.0.0",
"measure-1" to 1.0,
"measure-2" to 1.1
)
mockSonarQubeMeasures(key, "abdcefg",
"measure-1" to 2.0,
"measure-2" to 2.1
)
// Scanning of the project
sonarQubeMeasuresCollectionService.collect(this) { println(it) }
// Checks the measures attached to the builds
assertNotNull(sonarQubeMeasuresCollectionService.getMeasures(build1)) {
assertEquals(
mapOf(
"measure-1" to 1.0,
"measure-2" to 1.1
),
it.measures
)
}
assertNull(sonarQubeMeasuresCollectionService.getMeasures(build2))
}
}
}
}
@Test
fun `Project using branch model`() {
withDisabledConfigurationTest {
withSonarQubeSettings {
val key = uid("p")
withConfiguredProject(key, branchModel = true) {
// Registers the project as having a branching model
testBranchModelMatcherProvider.projects += name
val build1 = branch<Build>("release-1.0") {
val vs = validationStamp("sonarqube")
build("1.0.0") {
validate(vs)
}
}
val build2 = branch<Build>("feature-test") {
val vs = validationStamp("sonarqube")
build("abdcefg") {
validate(vs)
}
}
// Setting the configuration of the project now, builds are still not scanned
mockSonarQubeMeasures(key, "1.0.0",
"measure-1" to 1.0,
"measure-2" to 1.1
)
mockSonarQubeMeasures(key, "abdcefg",
"measure-1" to 2.0,
"measure-2" to 2.1
)
// Scanning of the project
sonarQubeMeasuresCollectionService.collect(this) { println(it) }
// Checks the measures attached to the builds
assertNotNull(sonarQubeMeasuresCollectionService.getMeasures(build1)) {
assertEquals(
mapOf(
"measure-1" to 1.0,
"measure-2" to 1.1
),
it.measures
)
}
assertNull(sonarQubeMeasuresCollectionService.getMeasures(build2))
}
}
}
}
@Test
fun `Builds require a validation`() {
withDisabledConfigurationTest {
withSonarQubeSettings {
val key = uid("p")
withConfiguredProject(key) {
val build1 = branch<Build>("release-1.0") {
validationStamp("sonarqube")
build("1.0.0") // No validation for this one
}
val build2 = branch<Build>("feature-test") {
val vs = validationStamp("sonarqube")
build("abdcefg") {
validate(vs)
}
}
// Setting the configuration of the project now, builds are still not scanned
mockSonarQubeMeasures(key, "1.0.0",
"measure-1" to 1.0,
"measure-2" to 1.1
)
mockSonarQubeMeasures(key, "abdcefg",
"measure-1" to 2.0,
"measure-2" to 2.1
)
// Scanning of the project
sonarQubeMeasuresCollectionService.collect(this) { println(it) }
// Checks the measures attached to the builds
assertNull(sonarQubeMeasuresCollectionService.getMeasures(build1))
assertNotNull(sonarQubeMeasuresCollectionService.getMeasures(build2)) {
assertEquals(
mapOf(
"measure-1" to 2.0,
"measure-2" to 2.1
),
it.measures
)
}
}
}
}
}
@Test
fun `Builds do not require a passed validation`() {
withDisabledConfigurationTest {
withSonarQubeSettings {
val key = uid("p")
withConfiguredProject(key) {
val build1 = branch<Build>("release-1.0") {
val vs = validationStamp("sonarqube")
build("1.0.0") {
validate(vs, ValidationRunStatusID.STATUS_FAILED)
}
}
val build2 = branch<Build>("feature-test") {
val vs = validationStamp("sonarqube")
build("abdcefg") {
validate(vs)
}
}
// Setting the configuration of the project now, builds are still not scanned
mockSonarQubeMeasures(key, "1.0.0",
"measure-1" to 1.0,
"measure-2" to 1.1
)
mockSonarQubeMeasures(key, "abdcefg",
"measure-1" to 2.0,
"measure-2" to 2.1
)
// Scanning of the project
sonarQubeMeasuresCollectionService.collect(this) { println(it) }
// Checks the measures attached to the builds
assertNotNull(sonarQubeMeasuresCollectionService.getMeasures(build1)) {
assertEquals(
mapOf(
"measure-1" to 1.0,
"measure-2" to 1.1
),
it.measures
)
}
assertNotNull(sonarQubeMeasuresCollectionService.getMeasures(build2)) {
assertEquals(
mapOf(
"measure-1" to 2.0,
"measure-2" to 2.1
),
it.measures
)
}
}
}
}
}
@Test
fun `Branches require a validation`() {
withDisabledConfigurationTest {
withSonarQubeSettings {
val key = uid("p")
withConfiguredProject(key) {
val build1 = branch<Build>("release-1.0") {
build("1.0.0") // No validation for this one
}
val build2 = branch<Build>("feature-test") {
val vs = validationStamp("sonarqube")
build("abdcefg") {
validate(vs)
}
}
// Setting the configuration of the project now, builds are still not scanned
mockSonarQubeMeasures(key, "1.0.0",
"measure-1" to 1.0,
"measure-2" to 1.1
)
mockSonarQubeMeasures(key, "abdcefg",
"measure-1" to 2.0,
"measure-2" to 2.1
)
// Scanning of the project
sonarQubeMeasuresCollectionService.collect(this) { println(it) }
// Checks the measures attached to the builds
assertNull(sonarQubeMeasuresCollectionService.getMeasures(build1))
assertNotNull(sonarQubeMeasuresCollectionService.getMeasures(build2)) {
assertEquals(
mapOf(
"measure-1" to 2.0,
"measure-2" to 2.1
),
it.measures
)
}
}
}
}
}
@Test
fun `Adding a new SonarQube configuration`() {
withDisabledConfigurationTest {
val name = uid("S")
asUserWith<GlobalSettings> {
val saved = sonarQubeConfigurationService.newConfiguration(
SonarQubeConfiguration(
name,
"https://sonarqube.nemerosa.net",
"my-ultra-secret-token"
)
)
assertEquals(name, saved.name)
assertEquals("https://sonarqube.nemerosa.net", saved.url)
assertEquals("", saved.password)
// Gets the list of configurations
val configs = sonarQubeConfigurationService.configurations
// Checks we find the one we just created
assertNotNull(
configs.find {
it.name == name
}
)
// Getting it by name
val found = sonarQubeConfigurationService.getConfiguration(name)
assertEquals(name, found.name)
assertEquals("https://sonarqube.nemerosa.net", found.url)
assertEquals("my-ultra-secret-token", found.password)
}
}
}
@Test
fun `Project SonarQube property`() {
withDisabledConfigurationTest {
// Creates a configuration
val name = uid("S")
val configuration = createSonarQubeConfiguration(name)
project {
// Property
setProperty(this, SonarQubePropertyType::class.java,
SonarQubeProperty(
configuration,
"my:key",
"sonarqube",
listOf("measure-1"),
false,
branchModel = true,
branchPattern = "master|develop"
)
)
// Gets the property back
val property: SonarQubeProperty? = getProperty(this, SonarQubePropertyType::class.java)
assertNotNull(property) {
assertEquals(name, it.configuration.name)
assertEquals("https://sonarqube.nemerosa.net", it.configuration.url)
assertEquals("my-ultra-secret-token", it.configuration.password)
assertEquals("my:key", it.key)
assertEquals("https://sonarqube.nemerosa.net/dashboard?id=my%3Akey", it.projectUrl)
assertEquals(listOf("measure-1"), it.measures)
assertEquals(false, it.override)
assertEquals(true, it.branchModel)
assertEquals("master|develop", it.branchPattern)
}
}
}
}
@Test
fun `Project property deleted when configuration is deleted`() {
withDisabledConfigurationTest {
val configuration = createSonarQubeConfiguration()
project {
// Sets the property
setSonarQubeProperty(configuration, "my:key")
// Deleting the configuration
asAdmin {
sonarQubeConfigurationService.deleteConfiguration(configuration.name)
}
// Gets the property of the project
val property: SonarQubeProperty? = getProperty(this, SonarQubePropertyType::class.java)
assertNull(property, "Project property has been removed")
}
}
}
/**
* Creating a new configuration
*/
private fun createSonarQubeConfiguration(name: String = uid("S")) =
asUserWith<GlobalSettings, SonarQubeConfiguration> {
sonarQubeConfigurationService.newConfiguration(
SonarQubeConfiguration(
name,
"https://sonarqube.nemerosa.net",
"my-ultra-secret-token"
)
)
}
/**
* Sets a project property
*/
private fun Project.setSonarQubeProperty(
configuration: SonarQubeConfiguration,
key: String,
stamp: String = "sonarqube",
measures: List<String> = emptyList(),
override: Boolean = false,
branchModel: Boolean = false,
branchPattern: String? = null
) {
setProperty(this, SonarQubePropertyType::class.java,
SonarQubeProperty(
configuration = configuration,
key = key,
validationStamp = stamp,
measures = measures,
override = override,
branchModel = branchModel,
branchPattern = branchPattern
)
)
}
/**
* Testing with some SonarQube measures
*/
private fun withSonarQubeSettings(
measures: List<String> = listOf("measure-1", "measure-2"),
disabled: Boolean = false,
code: () -> Unit
) {
val settings = settingsService.getCachedSettings(SonarQubeMeasuresSettings::class.java)
try {
// Sets the settings
asAdmin {
settingsManagerService.saveSettings(
SonarQubeMeasuresSettings(
measures = measures,
disabled = disabled,
coverageThreshold = 80,
blockerThreshold = 5
)
)
}
// Runs the code
code()
} finally {
// Restores the initial settings (only in case of success)
asAdmin {
settingsManagerService.saveSettings(settings)
}
}
}
/**
* Testing with a project configured for SonarQube
*/
private fun withConfiguredProject(
key: String,
stamp: String = "sonarqube",
measures: List<String> = emptyList(),
override: Boolean = false,
branchModel: Boolean = false,
branchPattern: String? = null,
code: Project.() -> Unit
) {
withDisabledConfigurationTest {
val config = createSonarQubeConfiguration()
project {
setSonarQubeProperty(
configuration = config,
key = key,
stamp = stamp,
measures = measures,
override = override,
branchModel = branchModel,
branchPattern = branchPattern
)
code()
}
}
}
private fun mockSonarQubeMeasures(key: String, version: String, vararg measures: Pair<String, Double>) {
whenever(client.getMeasuresForVersion(
eq(key),
any(),
eq(version),
any()
)).then { invocation ->
// List of desired measures
@Suppress("UNCHECKED_CAST")
val measureList: List<String> = invocation.arguments[3] as List<String>
// Map of measures
val index = measures.toMap()
// Results
val result = mutableMapOf<String, Double?>()
// Collect all results
measureList.forEach { measure ->
result[measure] = index[measure]
}
// OK
result
}
}
@Autowired
private lateinit var client: SonarQubeClient
@Autowired
private lateinit var testBranchModelMatcherProvider: TestBranchModelMatcherProvider
@Configuration
@Profile(RunProfile.UNIT_TEST)
class SonarQubeITConfiguration {
/**
* Export of metrics
*/
@Bean
@Primary
fun metricsExportService() = mock<MetricsExportService>()
/**
* Client mock
*/
@Bean
fun sonarQubeClient() = mock<SonarQubeClient>()
/**
* Factory
*/
@Bean
@Primary
fun sonarQubeClientFactory(client: SonarQubeClient) = object : SonarQubeClientFactory {
override fun getClient(configuration: SonarQubeConfiguration): SonarQubeClient {
return client
}
}
/**
* Model matcher
*/
@Bean
fun testBranchModelMatcherProvider() = TestBranchModelMatcherProvider()
}
} | mit | cde661d5a8ba6d25fcdfb35b676fce00 | 38.520581 | 133 | 0.462978 | 5.962192 | false | true | false | false |
lindelea/lindale | app/src/main/java/org/lindelin/lindale/activities/ui/task/TaskFragment.kt | 1 | 3729 | package org.lindelin.lindale.activities.ui.task
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.DividerItemDecoration
import org.lindelin.lindale.R
import org.lindelin.lindale.activities.ui.favorite.MyFavoriteRecyclerViewAdapter
import org.lindelin.lindale.activities.ui.home.HomeViewModel
import org.lindelin.lindale.activities.ui.task.dummy.DummyContent
import org.lindelin.lindale.activities.ui.task.dummy.DummyContent.DummyItem
import org.lindelin.lindale.models.Task
/**
* A fragment representing a list of Items.
* Activities containing this fragment MUST implement the
* [TaskFragment.OnListFragmentInteractionListener] interface.
*/
class TaskFragment : Fragment() {
private lateinit var homeViewModel: HomeViewModel
private var columnCount = 1
private var listener: OnListFragmentInteractionListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
columnCount = it.getInt(ARG_COLUMN_COUNT)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_task_list, container, false)
homeViewModel = activity?.run {
ViewModelProviders.of(this)[HomeViewModel::class.java]
} ?: throw Exception("Invalid Activity")
// Set the adapter
if (view is RecyclerView) {
with(view) {
layoutManager = when {
columnCount <= 1 -> LinearLayoutManager(context)
else -> GridLayoutManager(context, columnCount)
}
view.addItemDecoration(DividerItemDecoration(view.context, DividerItemDecoration.VERTICAL))
homeViewModel.getMyTasks().observe(this@TaskFragment, Observer {
adapter = MyTaskRecyclerViewAdapter(it.data, listener)
})
}
}
return view
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnListFragmentInteractionListener) {
listener = context
} else {
throw RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson
* [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html)
* for more information.
*/
interface OnListFragmentInteractionListener {
fun onListFragmentInteraction(item: Task?)
}
companion object {
const val ARG_COLUMN_COUNT = "task-column-count"
@JvmStatic
fun newInstance(columnCount: Int) =
TaskFragment().apply {
arguments = Bundle().apply {
putInt(ARG_COLUMN_COUNT, columnCount)
}
}
}
}
| mit | b1036aec9c2eaf5e435326883b50a2c5 | 32.9 | 118 | 0.683293 | 5.012097 | false | false | false | false |
hypercube1024/firefly | firefly-net/src/main/kotlin/com/fireflysource/net/http/server/impl/AbstractHttpServerResponse.kt | 1 | 6937 | package com.fireflysource.net.http.server.impl
import com.fireflysource.common.`object`.Assert
import com.fireflysource.common.coroutine.asVoidFuture
import com.fireflysource.common.io.BufferUtils
import com.fireflysource.common.io.flipToFill
import com.fireflysource.common.io.flipToFlush
import com.fireflysource.common.io.useAwait
import com.fireflysource.common.sys.Result
import com.fireflysource.net.http.common.codec.CookieGenerator
import com.fireflysource.net.http.common.exception.HttpServerResponseNotCommitException
import com.fireflysource.net.http.common.model.*
import com.fireflysource.net.http.server.HttpServerConnection
import com.fireflysource.net.http.server.HttpServerContentProvider
import com.fireflysource.net.http.server.HttpServerOutputChannel
import com.fireflysource.net.http.server.HttpServerResponse
import kotlinx.coroutines.future.asCompletableFuture
import kotlinx.coroutines.future.await
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Supplier
abstract class AbstractHttpServerResponse(private val httpServerConnection: HttpServerConnection) : HttpServerResponse {
companion object {
const val contentProviderBufferSize = 8 * 1024
}
val response: MetaData.Response = MetaData.Response(HttpVersion.HTTP_1_1, HttpStatus.OK_200, HttpFields())
private var contentProvider: HttpServerContentProvider? = null
private var cookieList: List<Cookie>? = null
private val committed = AtomicBoolean(false)
private val callCommit = AtomicBoolean(false)
private var serverOutputChannel: HttpServerOutputChannel? = null
private val mutex = Mutex()
override fun getStatus(): Int = response.status
override fun setStatus(status: Int) {
response.status = status
}
override fun getReason(): String = response.reason
override fun setReason(reason: String) {
response.reason = reason
}
override fun getHttpVersion(): HttpVersion = response.httpVersion
override fun setHttpVersion(httpVersion: HttpVersion) {
response.httpVersion = httpVersion
}
override fun getHttpFields(): HttpFields = response.fields
override fun setHttpFields(httpFields: HttpFields) {
response.fields.clear()
response.fields.addAll(httpFields)
}
override fun getCookies(): List<Cookie> = cookieList ?: listOf()
override fun setCookies(cookies: List<Cookie>) {
cookieList = cookies
}
override fun getContentProvider(): HttpServerContentProvider? = contentProvider
override fun setContentProvider(contentProvider: HttpServerContentProvider) {
Assert.state(!isCommitted, "Set content provider must before commit response.")
this.contentProvider = contentProvider
}
override fun getTrailerSupplier(): Supplier<HttpFields> = response.trailerSupplier
override fun setTrailerSupplier(supplier: Supplier<HttpFields>) {
response.trailerSupplier = supplier
}
override fun isCommitted(): Boolean = callCommit.get()
override fun commit(): CompletableFuture<Void> {
callCommit.set(true)
return httpServerConnection.coroutineScope
.launch { commitAwait() }
.asCompletableFuture()
.thenCompose { Result.DONE }
}
private suspend fun commitAwait() {
if (committed.get()) return
mutex.withLock {
if (committed.get()) return@commitAwait
createOutputChannelAndCommit()
committed.set(true)
}
}
private suspend fun createOutputChannelAndCommit() {
if (response.fields[HttpHeader.CONNECTION] == null && httpVersion == HttpVersion.HTTP_1_1) {
response.fields.put(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE)
}
cookies.map { CookieGenerator.generateSetCookie(it) }
.forEach { response.fields.add(HttpHeader.SET_COOKIE, it) }
val provider = contentProvider
if (provider != null && provider.length() >= 0) {
response.fields.put(HttpHeader.CONTENT_LENGTH, provider.length().toString())
}
val contentEncoding = Optional
.ofNullable(response.fields[HttpHeader.CONTENT_ENCODING])
.flatMap { ContentEncoding.from(it) }
val output = if (contentEncoding.isPresent) {
val out = createHttpServerOutputChannel(response)
CompressedServerOutputChannel(out, contentEncoding.get())
} else createHttpServerOutputChannel(response)
if (provider != null) {
output.useAwait {
it.commit().await()
writeContent(provider, it)
}
} else {
output.commit().await()
}
this.serverOutputChannel = output
}
/**
* Create the HTTP server output channel. It outputs the HTTP response.
*
* @return The HTTP server output channel.
*/
abstract fun createHttpServerOutputChannel(response: MetaData.Response): HttpServerOutputChannel
private suspend fun writeContent(provider: HttpServerContentProvider, outputChannel: HttpServerOutputChannel) {
val size = provider.getContentProviderBufferSize()
writeLoop@ while (true) {
val buffer = BufferUtils.allocate(size)
val position = buffer.flipToFill()
val length = provider.read(buffer).await()
buffer.flipToFlush(position)
when {
length > 0 -> outputChannel.write(buffer).await()
length < 0 -> break@writeLoop
}
}
provider.closeAsync().await()
}
private fun HttpServerContentProvider.getContentProviderBufferSize(): Int {
return if (this.length() > 0) this.length().coerceAtMost(contentProviderBufferSize.toLong()).toInt()
else contentProviderBufferSize
}
override fun getOutputChannel(): HttpServerOutputChannel {
val outputChannel = serverOutputChannel
if (outputChannel == null) {
throw HttpServerResponseNotCommitException("The response not commit")
} else {
Assert.state(
contentProvider == null,
"The content provider is not null. The server has used content provider to output content."
)
return outputChannel
}
}
override fun closeAsync(): CompletableFuture<Void> {
val provider = contentProvider
return if (provider == null) {
httpServerConnection.coroutineScope.launch {
commit().await()
outputChannel.closeAsync().await()
}.asVoidFuture()
} else Result.DONE
}
override fun close() {
closeAsync()
}
} | apache-2.0 | 3f22d56a6d074da9eaf998c1c03fecc4 | 35.135417 | 120 | 0.68805 | 5.012283 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/validation/rules/VariableDefaultValuesOfCorrectType.kt | 1 | 1354 | package graphql.validation.rules
import graphql.language.VariableDefinition
import graphql.schema.GraphQLNonNull
import graphql.validation.IValidationContext
import graphql.validation.ValidationError
import graphql.validation.ValidationErrorType
import graphql.validation.*
class VariableDefaultValuesOfCorrectType(validationContext: IValidationContext,
validationErrorCollector: ValidationErrorCollector)
: AbstractRule(validationContext, validationErrorCollector) {
override fun checkVariableDefinition(variableDefinition: VariableDefinition) {
val inputType = validationContext.inputType ?: return
if (inputType is GraphQLNonNull && variableDefinition.defaultValue != null) {
val message = "Missing value for non null type"
addError(ValidationError(ValidationErrorType.DefaultForNonNullArgument, variableDefinition.sourceLocation, message))
}
if (variableDefinition.defaultValue != null && !validationUtil.isValidLiteralValue(variableDefinition.defaultValue, inputType)) {
val message = String.format("Bad default value %s for type %s", variableDefinition.defaultValue, inputType.name)
addError(ValidationError(ValidationErrorType.BadValueForDefaultArg, variableDefinition.sourceLocation, message))
}
}
}
| mit | 453eb50b1855a74c53c6f420f8a169f4 | 49.148148 | 137 | 0.76514 | 5.618257 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/core/types/ty/TyFunction.kt | 1 | 849 | package org.rust.lang.core.types.ty
import com.intellij.openapi.project.Project
data class TyFunction(val paramTypes: List<Ty>, val retType: Ty) : Ty {
override fun canUnifyWith(other: Ty, project: Project, mapping: TypeMapping?): Boolean = merge(mapping) {
other is TyFunction && paramTypes.size == other.paramTypes.size &&
paramTypes.zip(other.paramTypes).all { (type1, type2) -> type1.canUnifyWith(type2, project, it) } &&
retType.canUnifyWith(other.retType, project, it)
}
override fun toString(): String {
val params = paramTypes.joinToString(", ", "fn(", ")")
return if (retType === TyUnit) params else "$params -> $retType"
}
override fun substitute(map: TypeArguments): TyFunction =
TyFunction(paramTypes.map { it.substitute(map) }, retType.substitute(map))
}
| mit | d5ced1ffe92d463c8fe0df760a918be4 | 41.45 | 112 | 0.6702 | 4.042857 | false | false | false | false |
milos85vasic/Garage-Lab-Bosch-meetup | Meet_the_Kotlin_lecture/src/main/kotlin/net/milosvasic/conferences/bosch/meetup1/3. Collections.kt | 1 | 1185 | package net.milosvasic.conferences.bosch.meetup1
/**
* Differences between mutable and immutable collections are the easiest to explain on example of lists.
* Immutable lists implement interface List<out T> which gives class the following functionalities: size i get.
* Mutable abilities are gained by implementing MutableList<T> interface, which gives add, addAll and remove features.
*
*
* Immutable collections:
*/
val carList = listOf<String>() // Can't add new members!
val carList2 = listOf("Bmw", "Fiat")
val carSet = setOf<String>() // Can't add new members!
val carSet2 = setOf("Bmw", "Fiat", "Fiat", "Fiat") // Contains only 2 members!
val carMap = mapOf<String, String>() // Empty, and can't add new members as well!
val carMap2 = mapOf(
Pair("Bmw", "Diesel"),
Pair("Fiat", "Benin")
)
/**
* Mutable collections (we can add new members):
*/
val mCarList = mutableListOf<String>()
val mCarList2 = mutableListOf("Bmw", "Fiat")
val mCarSet = mutableSetOf<String>()
val mCarSet2 = mutableSetOf("Bmw", "Fiat")
val mCarMap = mutableMapOf<String, String>()
val mCcarMap2 = mutableMapOf(
Pair("Bmw", "Diesel"),
Pair("Fiat", "Benin")
)
| apache-2.0 | 188802b08e77a434093e5bb551e740e4 | 31.027027 | 118 | 0.694515 | 3.623853 | false | false | false | false |
goodwinnk/intellij-community | platform/diff-impl/src/com/intellij/openapi/vcs/ex/LineStatusTrackerBase.kt | 1 | 12093 | /*
* 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.openapi.vcs.ex
import com.intellij.diff.util.DiffUtil
import com.intellij.diff.util.Side
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoConstants
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.openapi.localVcs.UpToDateLineNumberProvider.ABSENT_LINE_NUMBER
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.ex.DocumentTracker.Block
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.nullize
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.annotations.TestOnly
import java.util.*
abstract class LineStatusTrackerBase<R : Range> {
protected val application: Application = ApplicationManager.getApplication()
open val project: Project?
val document: Document
val vcsDocument: Document
protected val disposable: Disposable = Disposer.newDisposable()
protected val documentTracker: DocumentTracker
protected abstract val renderer: LineStatusMarkerRenderer
var isReleased: Boolean = false
private set
protected var isInitialized: Boolean = false
private set
protected val blocks: List<Block> get() = documentTracker.blocks
internal val LOCK: DocumentTracker.Lock get() = documentTracker.LOCK
constructor(project: Project?, document: Document) {
this.project = project
this.document = document
vcsDocument = DocumentImpl(this.document.immutableCharSequence)
vcsDocument.putUserData(UndoConstants.DONT_RECORD_UNDO, true)
vcsDocument.setReadOnly(true)
documentTracker = DocumentTracker(vcsDocument, this.document, createDocumentTrackerHandler())
Disposer.register(disposable, documentTracker)
}
@CalledInAwt
protected open fun isDetectWhitespaceChangedLines(): Boolean = false
@CalledInAwt
protected open fun fireFileUnchanged() {}
protected open fun fireLinesUnchanged(startLine: Int, endLine: Int) {}
open val virtualFile: VirtualFile? get() = null
abstract protected fun Block.toRange(): R
protected open fun createDocumentTrackerHandler(): DocumentTracker.Handler = MyDocumentTrackerHandler()
fun getRanges(): List<R>? {
application.assertReadAccessAllowed()
LOCK.read {
if (!isValid()) return null
return blocks.filter { !it.range.isEmpty }.map { it.toRange() }
}
}
@CalledInAwt
open fun setBaseRevision(vcsContent: CharSequence) {
setBaseRevision(vcsContent, null)
}
@CalledInAwt
protected fun setBaseRevision(vcsContent: CharSequence, beforeUnfreeze: (() -> Unit)?) {
application.assertIsDispatchThread()
if (isReleased) return
documentTracker.doFrozen(Side.LEFT) {
updateDocument(Side.LEFT) {
vcsDocument.setText(vcsContent)
}
beforeUnfreeze?.invoke()
}
if (!isInitialized) {
isInitialized = true
updateHighlighters()
}
}
@CalledInAwt
fun dropBaseRevision() {
application.assertIsDispatchThread()
if (isReleased) return
isInitialized = false
updateHighlighters()
}
@CalledInAwt
protected fun updateDocument(side: Side, task: (Document) -> Unit): Boolean {
return updateDocument(side, null, task)
}
@CalledInAwt
protected fun updateDocument(side: Side, commandName: String?, task: (Document) -> Unit): Boolean {
if (side.isLeft) {
vcsDocument.setReadOnly(false)
try {
runWriteAction {
CommandProcessor.getInstance().runUndoTransparentAction {
task(vcsDocument)
}
}
return true
}
finally {
vcsDocument.setReadOnly(true)
}
}
else {
return DiffUtil.executeWriteCommand(document, project, commandName, { task(document) })
}
}
@CalledInAwt
fun doFrozen(task: Runnable) {
documentTracker.doFrozen({ task.run() })
}
fun release() {
val runnable = Runnable {
if (isReleased) return@Runnable
isReleased = true
Disposer.dispose(disposable)
}
if (!application.isDispatchThread || LOCK.isHeldByCurrentThread) {
application.invokeLater(runnable)
}
else {
runnable.run()
}
}
protected open inner class MyDocumentTrackerHandler : DocumentTracker.Handler {
override fun onRangeShifted(before: Block, after: Block) {
after.ourData.innerRanges = before.ourData.innerRanges
}
override fun afterRangeChange() {
updateHighlighters()
}
override fun afterBulkRangeChange() {
checkIfFileUnchanged()
calcInnerRanges()
updateHighlighters()
}
override fun onUnfreeze(side: Side) {
calcInnerRanges()
updateHighlighters()
}
private fun checkIfFileUnchanged() {
if (blocks.isEmpty()) {
fireFileUnchanged()
}
}
private fun calcInnerRanges() {
if (isDetectWhitespaceChangedLines() &&
!documentTracker.isFrozen()) {
for (block in blocks) {
if (block.ourData.innerRanges == null) {
block.ourData.innerRanges = calcInnerRanges(block)
}
}
}
}
}
private fun calcInnerRanges(block: Block): List<Range.InnerRange> {
if (block.start == block.end || block.vcsStart == block.vcsEnd) return emptyList()
return createInnerRanges(block.range,
vcsDocument.immutableCharSequence, document.immutableCharSequence,
vcsDocument.lineOffsets, document.lineOffsets)
}
protected fun updateHighlighters() {
renderer.scheduleUpdate()
}
@CalledInAwt
protected fun updateInnerRanges() {
LOCK.write {
if (isDetectWhitespaceChangedLines()) {
for (block in blocks) {
block.ourData.innerRanges = calcInnerRanges(block)
}
}
else {
for (block in blocks) {
block.ourData.innerRanges = null
}
}
updateHighlighters()
}
}
fun isOperational(): Boolean = LOCK.read {
return isInitialized && !isReleased
}
fun isValid(): Boolean = LOCK.read {
return isOperational() && !documentTracker.isFrozen()
}
fun findRange(range: Range): R? = findBlock(range)?.toRange()
protected fun findBlock(range: Range): Block? {
LOCK.read {
if (!isValid()) return null
for (block in blocks) {
if (block.start == range.line1 &&
block.end == range.line2 &&
block.vcsStart == range.vcsLine1 &&
block.vcsEnd == range.vcsLine2) {
return block
}
}
return null
}
}
fun getNextRange(line: Int): R? {
LOCK.read {
if (!isValid()) return null
for (block in blocks) {
if (line < block.end && !block.isSelectedByLine(line)) {
return block.toRange()
}
}
return null
}
}
fun getPrevRange(line: Int): R? {
LOCK.read {
if (!isValid()) return null
for (block in blocks.reversed()) {
if (line > block.start && !block.isSelectedByLine(line)) {
return block.toRange()
}
}
return null
}
}
fun getRangesForLines(lines: BitSet): List<R>? {
LOCK.read {
if (!isValid()) return null
val result = ArrayList<R>()
for (block in blocks) {
if (block.isSelectedByLine(lines)) {
result.add(block.toRange())
}
}
return result
}
}
fun getRangeForLine(line: Int): R? {
LOCK.read {
if (!isValid()) return null
for (block in blocks) {
if (block.isSelectedByLine(line)) {
return block.toRange()
}
}
return null
}
}
@CalledInAwt
fun rollbackChanges(range: Range) {
val newRange = findBlock(range)
if (newRange != null) {
runBulkRollback { it == newRange }
}
}
@CalledInAwt
fun rollbackChanges(lines: BitSet) {
runBulkRollback { it.isSelectedByLine(lines) }
}
@CalledInAwt
protected fun runBulkRollback(condition: (Block) -> Boolean) {
if (!isValid()) return
updateDocument(Side.RIGHT, VcsBundle.message("command.name.rollback.change")) {
documentTracker.partiallyApplyBlocks(Side.RIGHT, condition) { block, shift ->
fireLinesUnchanged(block.start + shift, block.start + shift + (block.vcsEnd - block.vcsStart))
}
}
}
fun isLineModified(line: Int): Boolean {
return isRangeModified(line, line + 1)
}
fun isRangeModified(startLine: Int, endLine: Int): Boolean {
if (startLine == endLine) return false
assert(startLine < endLine)
LOCK.read {
if (!isValid()) return false
for (block in blocks) {
if (block.start >= endLine) return false
if (block.end > startLine) return true
}
return false
}
}
fun transferLineToFromVcs(line: Int, approximate: Boolean): Int {
return transferLine(line, approximate, true)
}
fun transferLineToVcs(line: Int, approximate: Boolean): Int {
return transferLine(line, approximate, false)
}
private fun transferLine(line: Int, approximate: Boolean, fromVcs: Boolean): Int {
LOCK.read {
if (!isValid()) return if (approximate) line else ABSENT_LINE_NUMBER
var result = line
for (block in blocks) {
val startLine1 = if (fromVcs) block.vcsStart else block.start
val endLine1 = if (fromVcs) block.vcsEnd else block.end
val startLine2 = if (fromVcs) block.start else block.vcsStart
val endLine2 = if (fromVcs) block.end else block.vcsEnd
if (line in startLine1 until endLine1) {
return if (approximate) startLine2 else ABSENT_LINE_NUMBER
}
if (endLine1 > line) return result
val length1 = endLine1 - startLine1
val length2 = endLine2 - startLine2
result += length2 - length1
}
return result
}
}
protected open class BlockData(internal var innerRanges: List<Range.InnerRange>? = null)
open protected fun createBlockData(): BlockData = BlockData()
open protected val Block.ourData: BlockData get() = getBlockData(this)
protected fun getBlockData(block: Block): BlockData {
if (block.data == null) block.data = createBlockData()
return block.data as BlockData
}
protected val Block.innerRanges: List<Range.InnerRange>? get() = this.ourData.innerRanges.nullize()
companion object {
@JvmStatic protected val LOG: Logger = Logger.getInstance("#com.intellij.openapi.vcs.ex.LineStatusTracker")
@JvmStatic protected val Block.start: Int get() = range.start2
@JvmStatic protected val Block.end: Int get() = range.end2
@JvmStatic protected val Block.vcsStart: Int get() = range.start1
@JvmStatic protected val Block.vcsEnd: Int get() = range.end1
@JvmStatic protected fun Block.isSelectedByLine(line: Int): Boolean = DiffUtil.isSelectedByLine(line, this.range.start2, this.range.end2)
@JvmStatic protected fun Block.isSelectedByLine(lines: BitSet): Boolean = DiffUtil.isSelectedByLine(lines, this.range.start2, this.range.end2)
}
@TestOnly
fun getDocumentTrackerInTestMode(): DocumentTracker = documentTracker
}
| apache-2.0 | 121f32f42e539be915d9d83179cd3db8 | 27.320843 | 146 | 0.676921 | 4.426428 | false | false | false | false |
tag-them/metoothanks | app/src/main/java/org/itiswednesday/metoothanks/activities/Welcome.kt | 1 | 1648 | package org.itiswednesday.metoothanks.activities
import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Button
import org.itiswednesday.metoothanks.R
import java.io.FileNotFoundException
const val IMAGE_PATH = "image"
const val GITHUB_RELEASES_PAGE = "https://github.com/it-is-wednesday/metoothanks/releases/latest"
class Welcome : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_welcome)
findViewById<Button>(R.id.button_empty_canvas).setOnClickListener {
val intent = Intent(this, Edit::class.java)
startActivity(intent)
}
findViewById<Button>(R.id.button_load_from_galley).setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, OPEN_IMAGE_REQUEST_CODE)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK)
when (requestCode) {
OPEN_IMAGE_REQUEST_CODE -> if (data != null)
try {
val intent = Intent(this, Edit::class.java)
intent.putExtra(IMAGE_PATH, data.data)
startActivity(intent)
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
}
}
}
| mpl-2.0 | ae459e38494ccb8be4b08a091463b281 | 35.622222 | 97 | 0.635316 | 4.577778 | false | false | false | false |
soywiz/korge | korge/src/commonTest/kotlin/com/soywiz/korge/input/KeysEventsTest.kt | 1 | 1510 | package com.soywiz.korge.input
import com.soywiz.klock.*
import com.soywiz.korev.*
import com.soywiz.korge.tests.*
import com.soywiz.korge.time.*
import com.soywiz.korge.view.*
import kotlin.test.*
class KeysEventsTest : ViewsForTesting() {
@Test
fun testDownUp() = viewsTest {
val log = arrayListOf<String>()
solidRect(100, 100).keys {
justDown(Key.SPACE) { log.add("justDown") }
down(Key.SPACE) { log.add("down") }
up(Key.SPACE) { log.add("up") }
}
keyDown(Key.SPACE)
keyDown(Key.SPACE)
keyDown(Key.SPACE)
keyUp(Key.SPACE)
assertEquals(listOf("down", "justDown", "down", "down", "up"), log)
}
@Test
fun testDownRepeating() = viewsTest {
var calledTimes = 0
solidRect(100, 100).keys {
downRepeating(Key.SPACE, maxDelay = 500.milliseconds, minDelay = 100.milliseconds, delaySteps = 4) { calledTimes++ }
}
assertEquals(0, calledTimes)
keyDown(Key.SPACE)
assertEquals(1, calledTimes)
for ((index, delay) in listOf(500, 400, 300, 200, 100, 100).withIndex()) {
delay(delay.milliseconds)
assertEquals(index + 2, calledTimes)
}
assertEquals(7, calledTimes)
keyUp(Key.SPACE)
delay(1000.milliseconds)
assertEquals(7, calledTimes)
calledTimes = 0
keyDown(Key.SPACE)
delay(3000.milliseconds)
assertEquals(21, calledTimes)
}
}
| apache-2.0 | 2557b20ea1763209fd4840ad8bf9dbdb | 28.607843 | 128 | 0.596689 | 3.813131 | false | true | false | false |
martin-nordberg/KatyDOM | Katydid-Samples/src/main/kotlin/js/katydid/samples/wipcards/board/BoardNameUi.kt | 1 | 6458 | //
// (C) Copyright 2019 Martin E. Nordberg III
// Apache 2.0 License
//
package js.katydid.samples.wipcards.board
import js.katydid.samples.wipcards.domain.model.Board
import js.katydid.samples.wipcards.domain.model.WipCardsDomain
import js.katydid.samples.wipcards.domain.update.RenameBoardAction
import js.katydid.samples.wipcards.infrastructure.Uuid
import o.katydid.css.colors.lightseagreen
import o.katydid.css.measurements.px
import o.katydid.css.styles.builders.*
import o.katydid.css.stylesheets.KatydidStyleSheet
import o.katydid.css.types.EDisplay
import o.katydid.css.types.EFontWeight
import o.katydid.css.types.EPosition
import o.katydid.events.eventhandling.*
import o.katydid.vdom.builders.KatydidFlowContentBuilder
//---------------------------------------------------------------------------------------------------------------------
// MODEL
//---------------------------------------------------------------------------------------------------------------------
/** Description of a WIP Cards board. */
data class BoardNameViewModel(
val isEditButtonShown : Boolean = false,
val isEditingInProgress : Boolean = false,
val domain: WipCardsDomain,
val boardUuid: Uuid<Board>
) {
val name = domain.boardWithUuid(boardUuid)?.name ?: ""
}
//---------------------------------------------------------------------------------------------------------------------
// UPDATE
//---------------------------------------------------------------------------------------------------------------------
/** Message related to changing a board's name. */
sealed class BoardNameMsg
//---------------------------------------------------------------------------------------------------------------------
/** Message when a board is to be renamed. */
private class BoardNameRenameMsg(
boardUuid: Uuid<Board>,
oldName: String,
newName: String
) : BoardNameMsg() {
val action = RenameBoardAction(boardUuid, newName, oldName)
}
//---------------------------------------------------------------------------------------------------------------------
/** Message when a board name is to be edited. */
private object BoardNameStartEditingMsg : BoardNameMsg()
//---------------------------------------------------------------------------------------------------------------------
/** Message when the mouse is hovering over the board name. */
private object BoardNameStartHoveringMsg : BoardNameMsg()
//---------------------------------------------------------------------------------------------------------------------
/** Message when a board is no longer being edited. */
private object BoardNameStopEditingMsg : BoardNameMsg()
//---------------------------------------------------------------------------------------------------------------------
/** Message when a board name is no longer being hovered over. */
private object BoardNameStopHoveringMsg : BoardNameMsg()
//---------------------------------------------------------------------------------------------------------------------
/**
* Creates a new board name state modified from given [boardName] by the given [message].
*/
fun updateBoardName(
boardName: BoardNameViewModel,
message: BoardNameMsg
): BoardNameViewModel {
return when (message) {
is BoardNameRenameMsg -> boardName.copy(domain = message.action.apply(boardName.domain))
is BoardNameStartEditingMsg -> boardName.copy(isEditButtonShown = false, isEditingInProgress = true)
is BoardNameStartHoveringMsg -> boardName.copy(isEditButtonShown = true)
is BoardNameStopEditingMsg -> boardName.copy(isEditingInProgress = false)
is BoardNameStopHoveringMsg -> boardName.copy(isEditButtonShown = false)
}
}
//---------------------------------------------------------------------------------------------------------------------
// VIEW
//---------------------------------------------------------------------------------------------------------------------
private const val cssClassName = "wipcards-board-name"
//---------------------------------------------------------------------------------------------------------------------
/**
* Generates the board name heading of the WIP Cards board.
*/
internal fun <Msg> KatydidFlowContentBuilder<Msg>.viewBoardName(
boardName: BoardNameViewModel,
makeMsg: (msg: BoardNameMsg) -> Msg
) {
if (boardName.isEditingInProgress) {
dialog(".$cssClassName", open = true) {
inputText(value = boardName.name, autofocus = true) {
onblur {
listOf(makeMsg(BoardNameStopEditingMsg))
}
onchange { event ->
val newValue = event.getTargetAttribute<String>("value").toString()
listOf(
makeMsg(BoardNameStopEditingMsg),
makeMsg(BoardNameRenameMsg(boardName.boardUuid, boardName.name, newValue))
)
}
}
}
}
else {
onmouseenter {
listOf(makeMsg(BoardNameStartHoveringMsg))
}
onmouseleave {
listOf(makeMsg(BoardNameStopHoveringMsg))
}
h1(".$cssClassName") {
+boardName.name
if (boardName.isEditButtonShown) {
button {
onclick {
listOf(makeMsg(BoardNameStartEditingMsg))
}
+"Edit"
}
}
}
}
}
//---------------------------------------------------------------------------------------------------------------------
// STYLE
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyleSheet.boardNameStyles() {
/* DIALOG */
"dialog.$cssClassName" {
backgroundColor(lightseagreen)
borderColor(lightseagreen)
display(EDisplay.inlineTable)
padding(2.px)
position(EPosition.relative)
"input" {
borderColor(lightseagreen)
fontSize(22.px)
fontWeight(EFontWeight.bold)
}
}
/* H1 */
"h1.$cssClassName" {
fontSize(25.px)
margin(5.px, 0.px, 5.px, 5.px)
}
}
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | b1c7140f62c0be459d18f6f105138dee | 28.623853 | 119 | 0.452307 | 5.766071 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/test/java/com/ichi2/testutils/JsonUtils.kt | 1 | 2603 | /*
* Copyright (c) 2021 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.testutils
import com.ichi2.utils.JSONArray
import com.ichi2.utils.JSONObject
import org.json.JSONException
import org.json.JSONStringer
object JsonUtils {
/**
* Returns the string, using a well-defined order for the keys
* COULD_BE_BETTER: This would be much better as a Matcher for JSON
* COULD_BE_BETTER: Only handles one level of ordering
*/
@JvmStatic
fun JSONObject.toOrderedString(): String {
val stringer = JSONStringer()
writeTo(stringer)
return stringer.toString()
}
@JvmStatic
fun JSONArray.toOrderedString(): String {
val stringer = JSONStringer()
writeTo(stringer)
return stringer.toString()
}
private fun JSONArray.values() = sequence {
var i = 0
while (i < [email protected]()) {
yield(this@values[i])
i++
}
}
private fun JSONArray.writeTo(stringer: JSONStringer) {
stringer.array()
for (value in this.values()) {
stringer.value(toOrderedString(value))
}
stringer.endArray()
}
private fun JSONObject.iterateEntries() = sequence {
for (k in this@iterateEntries) {
yield(Pair(k, [email protected](k)))
}
}
@Throws(JSONException::class)
private fun JSONObject.writeTo(stringer: JSONStringer) {
stringer.`object`()
for ((key, value) in this.iterateEntries().toList().sortedBy { x -> x.first }) {
stringer.key(key).value(toOrderedString(value))
}
stringer.endObject()
}
private fun toOrderedString(value: Any): Any {
return when (value) {
is JSONObject -> { JSONObject(value.toOrderedString()) }
is JSONArray -> { JSONArray(value.toOrderedString()) }
else -> { value }
}
}
}
| gpl-3.0 | 672cd4216a806b6b84342b8e03c61fcc | 30.743902 | 88 | 0.641183 | 4.125198 | false | false | false | false |
kjkrol/kotlin4fun-eshop-app | ordering-service/src/main/kotlin/kotlin4fun/eshop/ordering/order/item/OrderItem.kt | 1 | 1389 | package kotlin4fun.eshop.ordering.order.item
import org.hibernate.annotations.Type
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import java.io.Serializable
import java.util.UUID
import java.util.UUID.randomUUID
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.IdClass
import javax.persistence.Table
@Entity
@Table(name = "orders_products")
@IdClass(OrderItemId::class)
data class OrderItem(
@Id
@Column(name = "order_id", nullable = false)
@Type(type = "uuid-char")
val orderId: UUID,
@Id
@Column(name = "product_id", nullable = false)
@Type(type = "uuid-char")
val productId: UUID,
@Column(name = "quantity", nullable = false)
val quantity: Int
// @ManyToOne(fetch = FetchType.LAZY)
// @JoinColumn(name = "product_id", nullable = false, insertable = false, updatable = false)
// val product: Product
)
class OrderItemId(val orderId: UUID, val productId: UUID) : Serializable {
constructor() : this(orderId = randomUUID(), productId = randomUUID())
}
interface OrderItemRepository : JpaRepository<OrderItem, OrderItemId> {
fun findByOrderId(orderId: UUID, pageable: Pageable): Page<OrderItem>
}
| apache-2.0 | c12f345b14ed3e8df1347853790f5f8d | 29.195652 | 99 | 0.712743 | 3.923729 | false | false | false | false |
panpf/sketch | sample/src/main/java/com/github/panpf/sketch/sample/ui/base/ToolbarFragment.kt | 1 | 2810 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.sample.ui.base
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.widget.Toolbar
import androidx.core.view.updateLayoutParams
import com.github.panpf.sketch.sample.R
import com.github.panpf.tools4a.display.ktx.getStatusBarHeight
@Suppress("MemberVisibilityCanBePrivate")
abstract class ToolbarFragment : BaseFragment() {
protected var toolbar: Toolbar? = null
final override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = inflater.inflate(R.layout.toolbar_fragment, container, false).apply {
val toolbar = findViewById<Toolbar>(R.id.toolbarToolbar)
val contentContainer = findViewById<FrameLayout>(R.id.toolbarContent)
setTransparentStatusBar(toolbar)
val view = createView(toolbar, inflater, contentContainer)
contentContainer.addView(view)
[email protected] = toolbar
}
@SuppressLint("ObsoleteSdkInt")
private fun setTransparentStatusBar(toolbar: Toolbar) {
val window = requireActivity().window
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
&& window.decorView.systemUiVisibility == View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
) {
toolbar.updateLayoutParams<ViewGroup.MarginLayoutParams> {
topMargin += requireContext().getStatusBarHeight()
}
}
}
protected abstract fun createView(
toolbar: Toolbar,
inflater: LayoutInflater,
parent: ViewGroup?
): View
final override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
onViewCreated(this.toolbar!!, savedInstanceState)
}
protected open fun onViewCreated(
toolbar: Toolbar,
savedInstanceState: Bundle?
) {
}
override fun onDestroyView() {
this.toolbar = null
super.onDestroyView()
}
} | apache-2.0 | 9f5cb7f353b60e0958a2d228461ff37d | 32.070588 | 91 | 0.7121 | 4.787053 | false | false | false | false |
TeamWizardry/LibrarianLib | buildSrc/src/main/kotlin/com/teamwizardry/gradle/util/Replacer.kt | 1 | 2467 | package com.teamwizardry.gradle.util
import java.util.regex.Matcher
import java.util.regex.MatchResult
class Replacer {
private val replacements = mutableListOf<Replacement>()
fun add(oldString: String, newString: String) {
replacements.add(Replacement.Literal(oldString, newString))
}
fun add(oldRegex: Regex, newString: String) {
replacements.add(Replacement.PatternString(oldRegex, newString))
}
fun add(oldRegex: Regex, newString: (MatchResult) -> String) {
replacements.add(Replacement.PatternCallback(oldRegex, newString))
}
fun apply(input: String): String {
for(replacement in replacements) {
replacement.matcher.reset(input)
}
val builder = StringBuilder(input.length) // the output is probably going to have a similar length
val buffer = StringBuffer()
var start = 0
while(start < input.length) {
var match: Replacement? = null
for(replacement in replacements) {
if(replacement.matcher.find(start)) {
if(match == null || replacement.matcher.start() < match.matcher.start()) {
match = replacement
}
}
}
if(match == null) {
builder.append(input, start, input.length)
break
}
builder.append(input, start, match.matcher.start())
when(match) {
is Replacement.Literal -> builder.append(match.newString)
is Replacement.PatternString -> {
match.matcher.appendReplacement(buffer, match.newString)
builder.append(buffer)
buffer.setLength(0)
}
is Replacement.PatternCallback -> {
builder.append(match.result(match.matcher.toMatchResult()))
}
}
start = match.matcher.end()
}
return builder.toString()
}
sealed class Replacement(regex: Regex) {
val matcher: Matcher = regex.toPattern().matcher("")
class Literal(oldString: String, val newString: String): Replacement(Regex.escape(oldString).toRegex())
class PatternString(pattern: Regex, val newString: String): Replacement(pattern)
class PatternCallback(pattern: Regex, val result: (MatchResult) -> String): Replacement(pattern)
}
} | lgpl-3.0 | c4fb4c745850adb4b189cf2a1166e2d3 | 33.277778 | 111 | 0.588974 | 4.904573 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/crate/impl/FakeCrate.kt | 2 | 2891 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.crate.impl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.openapi.vfs.VirtualFile
import org.rust.cargo.CfgOptions
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.cargo.project.workspace.CargoWorkspaceData
import org.rust.cargo.project.workspace.FeatureState
import org.rust.cargo.project.workspace.PackageOrigin
import org.rust.lang.core.crate.Crate
import org.rust.lang.core.crate.CratePersistentId
import org.rust.lang.core.psi.RsFile
/** Fake crate for [RsFile] outside of module tree. */
class FakeDetachedCrate(
override val rootMod: RsFile,
override val id: CratePersistentId,
override val dependencies: Collection<Crate.Dependency>,
) : FakeCrate() {
override val flatDependencies: LinkedHashSet<Crate> = dependencies.flattenTopSortedDeps()
override val rootModFile: VirtualFile? get() = rootMod.virtualFile
override val presentableName: String get() = "Fake for ${rootModFile?.path}"
override val project: Project get() = rootMod.project
}
/** Fake crate for cases when something is very wrong */
class FakeInvalidCrate(override val project: Project) : FakeCrate() {
override val id: CratePersistentId? get() = null
override val dependencies: Collection<Crate.Dependency> get() = emptyList()
override val flatDependencies: LinkedHashSet<Crate> get() = linkedSetOf()
override val rootModFile: VirtualFile? get() = null
override val rootMod: RsFile? get() = null
override val presentableName: String get() = "Fake"
}
abstract class FakeCrate : UserDataHolderBase(), Crate {
override val reverseDependencies: List<Crate> get() = emptyList()
override val cargoProject: CargoProject? get() = null
override val cargoTarget: CargoWorkspace.Target? get() = null
override val cargoWorkspace: CargoWorkspace? get() = null
override val kind: CargoWorkspace.TargetKind get() = CargoWorkspace.TargetKind.Test
override val cfgOptions: CfgOptions get() = CfgOptions.EMPTY
override val features: Map<String, FeatureState> get() = emptyMap()
override val evaluateUnknownCfgToFalse: Boolean get() = true
override val env: Map<String, String> get() = emptyMap()
override val outDir: VirtualFile? get() = null
override val origin: PackageOrigin get() = PackageOrigin.WORKSPACE
override val edition: CargoWorkspace.Edition get() = CargoWorkspace.Edition.DEFAULT
override val areDoctestsEnabled: Boolean get() = false
override val normName: String get() = "__fake__"
override val procMacroArtifact: CargoWorkspaceData.ProcMacroArtifact? get() = null
override fun toString(): String = presentableName
}
| mit | 2b3e3fc00d5630cb1bb91107a470d690 | 42.80303 | 93 | 0.759253 | 4.373676 | false | false | false | false |
brianwernick/RecyclerExt | library/src/main/kotlin/com/devbrackets/android/recyclerext/decoration/header/StickyHeaderTouchInterceptor.kt | 1 | 3228 | /*
* Copyright (C) 2017 - 2018 Brian Wernick
*
* 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.devbrackets.android.recyclerext.decoration.header
import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener
/**
* Handles intercepting touch events in the RecyclerView to handle interaction in the
* sticky header.
*/
class StickyHeaderTouchInterceptor(protected var stickyHeaderCallback: StickyHeaderCallback) : OnItemTouchListener {
interface StickyHeaderCallback {
val stickyView: View?
}
protected var allowInterception = true
protected var capturedTouchDown = false
protected val interceptView: View?
get() = if (!allowInterception) {
null
} else stickyHeaderCallback.stickyView
override fun onInterceptTouchEvent(recyclerView: RecyclerView, event: MotionEvent): Boolean {
// Ignores touch events we don't want to intercept
if (event.action != MotionEvent.ACTION_DOWN && !capturedTouchDown) {
return false
}
val stickyView = interceptView
if (stickyView == null) {
capturedTouchDown = false
return false
}
// Makes sure to un-register capturing so that we don't accidentally interfere with scrolling
if (event.action == MotionEvent.ACTION_UP) {
capturedTouchDown = false
}
// Determine if the event is boxed by the view and pass the event through
val bounded = event.x >= stickyView.x &&
event.x <= stickyView.x + stickyView.measuredWidth &&
event.y >= stickyView.y &&
event.y <= stickyView.y + stickyView.measuredHeight
if (!bounded) {
return false
}
// Updates the filter
if (event.action == MotionEvent.ACTION_DOWN) {
capturedTouchDown = true
}
return dispatchChildTouchEvent(recyclerView, stickyView, event)
}
override fun onTouchEvent(recyclerView: RecyclerView, event: MotionEvent) {
// Makes sure to un-register capturing so that we don't accidentally interfere with scrolling
if (event.action == MotionEvent.ACTION_UP) {
capturedTouchDown = false
}
val stickyView = interceptView ?: return
dispatchChildTouchEvent(recyclerView, stickyView, event)
}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
allowInterception = !disallowIntercept
}
protected fun dispatchChildTouchEvent(recyclerView: RecyclerView, child: View, event: MotionEvent): Boolean {
// Pass the event through
val handledEvent = child.dispatchTouchEvent(event)
if (handledEvent) {
recyclerView.postInvalidate()
}
return handledEvent
}
} | apache-2.0 | 80e0945bd8cb84ba37de84b990b7bc19 | 32.28866 | 116 | 0.728315 | 4.69186 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/social/challenges/ChallengesFilterRecyclerViewAdapter.kt | 1 | 2436 | package com.habitrpg.android.habitica.ui.adapter.social.challenges
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import androidx.recyclerview.widget.RecyclerView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.models.social.Group
class ChallengesFilterRecyclerViewAdapter(entries: List<Group>) : RecyclerView.Adapter<ChallengesFilterRecyclerViewAdapter.ChallengeViewHolder>() {
private val entries: List<Group>
private val holderList: MutableList<ChallengeViewHolder>
val checkedEntries: List<Group>
get() {
val result = ArrayList<Group>()
for (h in holderList) {
if (h.checkbox.isChecked) {
h.group?.let {
result.add(it)
}
}
}
return result
}
init {
this.entries = ArrayList(entries)
this.holderList = ArrayList()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChallengeViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.dialog_challenge_filter_group_item, parent, false)
val challengeViewHolder = ChallengeViewHolder(view)
holderList.add(challengeViewHolder)
return challengeViewHolder
}
override fun onBindViewHolder(holder: ChallengeViewHolder, position: Int) {
holder.bind(entries[position])
}
override fun getItemCount(): Int {
return entries.size
}
fun deSelectAll() {
for (h in holderList) {
h.checkbox.isChecked = false
}
}
fun selectAll() {
for (h in holderList) {
h.checkbox.isChecked = true
}
}
fun selectAll(groupsToCheck: List<Group>) {
for (h in holderList) {
h.checkbox.isChecked = groupsToCheck.find { g -> h.group?.id == g.id } != null
}
}
class ChallengeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal val checkbox: CheckBox = itemView.findViewById(R.id.challenge_filter_group_checkbox)
var group: Group? = null
fun bind(group: Group) {
this.group = group
checkbox.text = group.name
}
}
}
| gpl-3.0 | fd4ac181ee34a1f0a92f5670037a5821 | 28.074074 | 147 | 0.609606 | 4.702703 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/ui/fancy/ContainerStartupProgressLine.kt | 1 | 10765 | /*
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.ui.fancy
import batect.config.BuildImage
import batect.config.Container
import batect.config.PullImage
import batect.config.SetupCommand
import batect.docker.client.DockerImageBuildProgress
import batect.docker.pull.DockerImageProgress
import batect.execution.model.events.ContainerBecameHealthyEvent
import batect.execution.model.events.ContainerBecameReadyEvent
import batect.execution.model.events.ContainerCreatedEvent
import batect.execution.model.events.ContainerStartedEvent
import batect.execution.model.events.ImageBuildProgressEvent
import batect.execution.model.events.ImageBuiltEvent
import batect.execution.model.events.ImagePullProgressEvent
import batect.execution.model.events.ImagePulledEvent
import batect.execution.model.events.RunningSetupCommandEvent
import batect.execution.model.events.StepStartingEvent
import batect.execution.model.events.TaskEvent
import batect.execution.model.events.TaskNetworkCreatedEvent
import batect.execution.model.steps.BuildImageStep
import batect.execution.model.steps.CreateContainerStep
import batect.execution.model.steps.PullImageStep
import batect.execution.model.steps.RunContainerStep
import batect.execution.model.steps.TaskStep
import batect.os.Command
import batect.ui.text.Text
import batect.ui.text.TextRun
data class ContainerStartupProgressLine(val container: Container, val dependencies: Set<Container>, val isTaskContainer: Boolean) {
private var isBuilding = false
private var lastBuildProgressUpdate: DockerImageBuildProgress? = null
private var isPulling = false
private var lastProgressUpdate: DockerImageProgress? = null
private var hasBeenBuilt = false
private var hasBeenPulled = false
private var isCreating = false
private var hasBeenCreated = false
private var isStarting = false
private var hasStarted = false
private var isReady = false
private var isHealthy = false
private var isRunning = false
private var command: Command? = null
private var networkHasBeenCreated = false
private var setupCommandState: SetupCommandState = if (container.setupCommands.isEmpty()) {
SetupCommandState.None
} else {
SetupCommandState.NotStarted
}
private val readyContainers = mutableSetOf<Container>()
fun print(): TextRun {
val description = when {
isReady || (isHealthy && setupCommandState == SetupCommandState.None) -> TextRun("running")
setupCommandState is SetupCommandState.Running -> descriptionWhenRunningSetupCommand()
isHealthy && setupCommandState == SetupCommandState.NotStarted -> TextRun("running setup commands...")
isRunning -> descriptionWhenRunning()
hasStarted -> TextRun("container started, waiting for it to become healthy...")
isStarting -> TextRun("starting container...")
hasBeenCreated -> descriptionWhenWaitingToStart()
isCreating -> TextRun("creating container...")
hasBeenBuilt && networkHasBeenCreated -> TextRun("image built, ready to create container")
hasBeenBuilt && !networkHasBeenCreated -> TextRun("image built, waiting for network to be ready...")
hasBeenPulled && networkHasBeenCreated -> TextRun("image pulled, ready to create container")
hasBeenPulled && !networkHasBeenCreated -> TextRun("image pulled, waiting for network to be ready...")
isBuilding && lastBuildProgressUpdate == null -> TextRun("building image...")
isBuilding && lastBuildProgressUpdate != null -> descriptionWhenBuilding()
isPulling -> descriptionWhenPulling()
else -> descriptionWhenWaitingToBuildOrPull()
}
return Text.white(Text.bold(container.name) + Text(": ") + description)
}
private fun descriptionWhenRunningSetupCommand(): TextRun {
val state = setupCommandState as SetupCommandState.Running
return Text("running setup command ") + Text.bold(state.command.command.originalCommand) + Text(" (${state.index + 1} of ${container.setupCommands.size})...")
}
private fun descriptionWhenWaitingToBuildOrPull(): TextRun {
return when (container.imageSource) {
is BuildImage -> TextRun("ready to build image")
is PullImage -> TextRun("ready to pull image")
}
}
private val containerImageName by lazy { (container.imageSource as PullImage).imageName }
private fun descriptionWhenPulling(): TextRun {
val progressInformation = if (lastProgressUpdate == null) {
Text("...")
} else {
Text(": " + lastProgressUpdate!!.toStringForDisplay())
}
return Text("pulling ") + Text.bold(containerImageName) + progressInformation
}
private fun descriptionWhenBuilding(): TextRun {
val progressInformation = if (lastBuildProgressUpdate!!.progress != null) {
": " + lastBuildProgressUpdate!!.progress!!.toStringForDisplay()
} else {
""
}
return TextRun("building image: step ${lastBuildProgressUpdate!!.currentStep} of ${lastBuildProgressUpdate!!.totalSteps}: ${lastBuildProgressUpdate!!.message}" + progressInformation)
}
private fun descriptionWhenWaitingToStart(): TextRun {
val remainingDependencies = dependencies - readyContainers
if (remainingDependencies.isEmpty()) {
return TextRun("ready to start")
}
val noun = if (remainingDependencies.size == 1) {
"dependency"
} else {
"dependencies"
}
val formattedDependencyNames = remainingDependencies.map { Text.bold(it.name) }
return Text("waiting for $noun ") + humanReadableList(formattedDependencyNames) + Text(" to be ready...")
}
private fun descriptionWhenRunning(): TextRun {
if (command == null) {
return TextRun("running")
}
return Text("running ") + Text.bold(command!!.originalCommand.replace('\n', ' '))
}
fun onEventPosted(event: TaskEvent) {
when (event) {
is ImageBuildProgressEvent -> onImageBuildProgressEventPosted(event)
is ImageBuiltEvent -> onImageBuiltEventPosted(event)
is ImagePullProgressEvent -> onImagePullProgressEventPosted(event)
is ImagePulledEvent -> onImagePulledEventPosted(event)
is TaskNetworkCreatedEvent -> networkHasBeenCreated = true
is ContainerCreatedEvent -> onContainerCreatedEventPosted(event)
is ContainerStartedEvent -> onContainerStartedEventPosted(event)
is ContainerBecameHealthyEvent -> onContainerBecameHealthyEventPosted(event)
is ContainerBecameReadyEvent -> onContainerBecameReadyEventPosted(event)
is RunningSetupCommandEvent -> onRunningSetupCommandEventPosted(event)
is StepStartingEvent -> onStepStarting(event.step)
}
}
private fun onStepStarting(step: TaskStep) {
when (step) {
is BuildImageStep -> onBuildImageStepStarting(step)
is PullImageStep -> onPullImageStepStarting(step)
is CreateContainerStep -> onCreateContainerStepStarting(step)
is RunContainerStep -> onRunContainerStepStarting(step)
}
}
private fun onBuildImageStepStarting(step: BuildImageStep) {
if (step.source == container.imageSource) {
isBuilding = true
}
}
private fun onPullImageStepStarting(step: PullImageStep) {
if (step.source == container.imageSource) {
isPulling = true
}
}
private fun onCreateContainerStepStarting(step: CreateContainerStep) {
if (step.container == container) {
isCreating = true
command = step.config.command
}
}
private fun onRunContainerStepStarting(step: RunContainerStep) {
if (step.container == container) {
if (isTaskContainer) {
isRunning = true
} else {
isStarting = true
}
}
}
private fun onImageBuildProgressEventPosted(event: ImageBuildProgressEvent) {
if (container.imageSource == event.source) {
isBuilding = true
lastBuildProgressUpdate = event.buildProgress
}
}
private fun onImageBuiltEventPosted(event: ImageBuiltEvent) {
if (container.imageSource == event.source) {
hasBeenBuilt = true
}
}
private fun onImagePullProgressEventPosted(event: ImagePullProgressEvent) {
if (container.imageSource == event.source) {
isPulling = true
lastProgressUpdate = event.progress
}
}
private fun onImagePulledEventPosted(event: ImagePulledEvent) {
if (container.imageSource == PullImage(event.image.id)) {
hasBeenPulled = true
}
}
private fun onContainerCreatedEventPosted(event: ContainerCreatedEvent) {
if (event.container == container) {
hasBeenCreated = true
}
}
private fun onContainerStartedEventPosted(event: ContainerStartedEvent) {
if (event.container == container && !isTaskContainer) {
hasStarted = true
}
}
private fun onContainerBecameHealthyEventPosted(event: ContainerBecameHealthyEvent) {
if (event.container == container) {
isHealthy = true
}
}
private fun onContainerBecameReadyEventPosted(event: ContainerBecameReadyEvent) {
readyContainers.add(event.container)
if (event.container == container) {
isReady = true
}
}
private fun onRunningSetupCommandEventPosted(event: RunningSetupCommandEvent) {
if (event.container == container) {
setupCommandState = SetupCommandState.Running(event.command, event.commandIndex)
}
}
private sealed class SetupCommandState {
data class Running(val command: SetupCommand, val index: Int) : SetupCommandState()
object None : SetupCommandState()
object NotStarted : SetupCommandState()
}
}
| apache-2.0 | a4f0cea4ee23764b664a0d61fe1ac08a | 38.577206 | 190 | 0.68732 | 5.271792 | false | false | false | false |
androidx/androidx | camera/integration-tests/diagnosetestapp/src/main/java/androidx/camera/integration/diagnose/OverlayView.kt | 3 | 3435 | /*
* 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
*
* 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.camera.integration.diagnose
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PointF
import android.util.AttributeSet
import android.util.Log
import android.widget.FrameLayout
/**
* Overlay View for drawing alignment result and target grid line to {@link Canvas} in
* diagnosis mode.
*/
class OverlayView(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {
private val unalignedTargetGridPaint = Paint()
private var alignedTargetGridPaint = Paint()
private var thresholdPaint = Paint()
// TODO: should it be nullable? only drawing when there are 4 barcodes
private var result: Calibration? = null
init {
// TODO: scale density of the width with the screen's pixel density
unalignedTargetGridPaint.color = Color.RED
unalignedTargetGridPaint.strokeWidth = 8F
alignedTargetGridPaint.color = Color.GREEN
alignedTargetGridPaint.strokeWidth = 8F
thresholdPaint.color = Color.WHITE
}
fun setCalibrationResult(result: Calibration) {
this.result = result
}
private fun drawGridLines(canvas: Canvas, line: Pair<PointF, PointF>, paint: Paint) {
canvas.drawLine(line.first.x, line.first.y, line.second.x, line.second.y, paint)
}
private fun getGridLinePaint(isAligned: Boolean?): Paint {
return if (isAligned == true) {
alignedTargetGridPaint
} else {
unalignedTargetGridPaint
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
Log.d(TAG, "calling on draw")
result?.let {
val paintColor = getGridLinePaint(result!!.isAligned)
result!!.topGrid?.let {
drawGridLines(canvas, it, paintColor)
}
result!!.bottomGrid?.let {
drawGridLines(canvas, it, paintColor)
}
result!!.rightGrid?.let {
drawGridLines(canvas, it, paintColor)
}
result!!.leftGrid?.let {
drawGridLines(canvas, it, paintColor)
}
// drawing threshold box
result!!.thresholdTopLeft?.let {
canvas.drawRect(it, thresholdPaint)
}
result!!.thresholdTopRight?.let {
canvas.drawRect(it, thresholdPaint)
}
result!!.thresholdBottomLeft?.let {
canvas.drawRect(it, thresholdPaint)
}
result!!.thresholdBottomRight?.let {
canvas.drawRect(it, thresholdPaint)
}
}
Log.d(TAG, "finished drawing")
}
companion object {
private const val TAG = "OverlayView"
}
} | apache-2.0 | b58dfa05fdb1a7265d280506cf7b0da9 | 32.038462 | 89 | 0.641921 | 4.531662 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/notifications/v2/NotificationBuilder.kt | 1 | 18616 | package org.thoughtcrime.securesms.notifications.v2
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.app.NotificationCompat
import androidx.core.app.RemoteInput
import androidx.core.content.LocusIdCompat
import androidx.core.graphics.drawable.IconCompat
import org.signal.core.util.PendingIntentFlags.mutable
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.conversation.ConversationIntents
import org.thoughtcrime.securesms.database.GroupDatabase
import org.thoughtcrime.securesms.database.RecipientDatabase
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.notifications.NotificationChannels
import org.thoughtcrime.securesms.notifications.ReplyMethod
import org.thoughtcrime.securesms.preferences.widgets.NotificationPrivacyPreference
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientUtil
import org.thoughtcrime.securesms.service.KeyCachingService
import org.thoughtcrime.securesms.util.AvatarUtil
import org.thoughtcrime.securesms.util.BubbleUtil
import org.thoughtcrime.securesms.util.ConversationUtil
import org.thoughtcrime.securesms.util.TextSecurePreferences
import java.util.Optional
import androidx.core.app.Person as PersonCompat
private const val BIG_PICTURE_DIMEN = 500
/**
* Wraps the compat and OS versions of the Notification builders so we can more easily access native
* features in newer versions. Also provides some domain specific helpers.
*
* Note: All business logic should exist in the base builder or the models that drive the notifications
* like NotificationConversation and NotificationItemV2.
*/
sealed class NotificationBuilder(protected val context: Context) {
private val privacy: NotificationPrivacyPreference = SignalStore.settings().messageNotificationsPrivacy
private val isNotLocked: Boolean = !KeyCachingService.isLocked(context)
abstract fun setSmallIcon(@DrawableRes drawable: Int)
abstract fun setColor(@ColorInt color: Int)
abstract fun setCategory(category: String)
abstract fun setGroup(group: String)
abstract fun setGroupAlertBehavior(behavior: Int)
abstract fun setChannelId(channelId: String)
abstract fun setContentTitle(contentTitle: CharSequence)
abstract fun setLargeIcon(largeIcon: Bitmap?)
abstract fun setContentInfo(contentInfo: String)
abstract fun setNumber(number: Int)
abstract fun setContentText(contentText: CharSequence?)
abstract fun setContentIntent(pendingIntent: PendingIntent?)
abstract fun setDeleteIntent(deleteIntent: PendingIntent?)
abstract fun setSortKey(sortKey: String)
abstract fun setOnlyAlertOnce(onlyAlertOnce: Boolean)
abstract fun setGroupSummary(isGroupSummary: Boolean)
abstract fun setSubText(subText: String)
abstract fun addMarkAsReadActionActual(state: NotificationState)
abstract fun setPriority(priority: Int)
abstract fun setAlarms(recipient: Recipient?)
abstract fun setTicker(ticker: CharSequence?)
abstract fun addTurnOffJoinedNotificationsAction(pendingIntent: PendingIntent?)
abstract fun setAutoCancel(autoCancel: Boolean)
abstract fun setLocusIdActual(locusId: String)
abstract fun build(): Notification
protected abstract fun addPersonActual(recipient: Recipient)
protected abstract fun setShortcutIdActual(shortcutId: String)
protected abstract fun setWhen(timestamp: Long)
protected abstract fun addActions(replyMethod: ReplyMethod, conversation: NotificationConversation)
protected abstract fun addMessagesActual(conversation: NotificationConversation, includeShortcut: Boolean)
protected abstract fun addMessagesActual(state: NotificationState)
protected abstract fun setBubbleMetadataActual(conversation: NotificationConversation, bubbleState: BubbleUtil.BubbleState)
protected abstract fun setLights(@ColorInt color: Int, onTime: Int, offTime: Int)
fun addPerson(recipient: Recipient) {
if (privacy.isDisplayContact) {
addPersonActual(recipient)
}
}
fun setLocusId(locusId: String) {
if (privacy.isDisplayContact && isNotLocked) {
setLocusIdActual(locusId)
}
}
fun setShortcutId(shortcutId: String) {
if (privacy.isDisplayContact && isNotLocked) {
setShortcutIdActual(shortcutId)
}
}
fun setWhen(conversation: NotificationConversation) {
if (conversation.getWhen() != 0L) {
setWhen(conversation.getWhen())
}
}
fun setWhen(notificationItem: NotificationItem?) {
if (notificationItem != null && notificationItem.timestamp != 0L) {
setWhen(notificationItem.timestamp)
}
}
fun addReplyActions(conversation: NotificationConversation) {
if (privacy.isDisplayMessage && isNotLocked && !conversation.recipient.isPushV1Group && RecipientUtil.isMessageRequestAccepted(context, conversation.recipient)) {
if (conversation.recipient.isPushV2Group) {
val group: Optional<GroupDatabase.GroupRecord> = SignalDatabase.groups.getGroup(conversation.recipient.requireGroupId())
if (group.isPresent && group.get().isAnnouncementGroup && !group.get().isAdmin(Recipient.self())) {
return
}
}
addActions(ReplyMethod.forRecipient(context, conversation.recipient), conversation)
}
}
fun addMarkAsReadAction(state: NotificationState) {
if (privacy.isDisplayMessage && isNotLocked) {
addMarkAsReadActionActual(state)
}
}
fun addMessages(conversation: NotificationConversation) {
addMessagesActual(conversation, privacy.isDisplayContact)
}
fun addMessages(state: NotificationState) {
if (privacy.isDisplayNothing) {
return
}
addMessagesActual(state)
}
fun setBubbleMetadata(conversation: NotificationConversation, bubbleState: BubbleUtil.BubbleState) {
if (privacy.isDisplayContact && isNotLocked) {
setBubbleMetadataActual(conversation, bubbleState)
}
}
fun setSummaryContentText(recipient: Recipient?) {
if (privacy.isDisplayContact && recipient != null) {
setContentText(context.getString(R.string.MessageNotifier_most_recent_from_s, recipient.getDisplayName(context)))
}
recipient?.notificationChannel?.let { channel -> setChannelId(channel) }
}
fun setLights() {
val ledColor: String = SignalStore.settings().messageLedColor
if (ledColor != "none") {
var blinkPattern = SignalStore.settings().messageLedBlinkPattern
if (blinkPattern == "custom") {
blinkPattern = TextSecurePreferences.getNotificationLedPatternCustom(context)
}
val (onTime: Int, offTime: Int) = blinkPattern.parseBlinkPattern()
setLights(Color.parseColor(ledColor), onTime, offTime)
}
}
private fun String.parseBlinkPattern(): Pair<Int, Int> {
return split(",").let { parts -> parts[0].toInt() to parts[1].toInt() }
}
companion object {
fun create(context: Context): NotificationBuilder {
return NotificationBuilderCompat(context)
}
}
/**
* Notification builder using solely androidx/compat libraries.
*/
private class NotificationBuilderCompat(context: Context) : NotificationBuilder(context) {
val builder: NotificationCompat.Builder = NotificationCompat.Builder(context, NotificationChannels.getMessagesChannel(context))
override fun addActions(replyMethod: ReplyMethod, conversation: NotificationConversation) {
val extender: NotificationCompat.WearableExtender = NotificationCompat.WearableExtender()
val markAsRead: PendingIntent? = conversation.getMarkAsReadIntent(context)
if (markAsRead != null) {
val markAsReadAction: NotificationCompat.Action =
NotificationCompat.Action.Builder(R.drawable.check, context.getString(R.string.MessageNotifier_mark_read), markAsRead)
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
.setShowsUserInterface(false)
.build()
builder.addAction(markAsReadAction)
extender.addAction(markAsReadAction)
}
if (conversation.mostRecentNotification.canReply(context)) {
val quickReply: PendingIntent? = conversation.getQuickReplyIntent(context)
val remoteReply: PendingIntent? = conversation.getRemoteReplyIntent(context, replyMethod)
val actionName: String = context.getString(R.string.MessageNotifier_reply)
val label: String = context.getString(replyMethod.toLongDescription())
val replyAction: NotificationCompat.Action? = if (Build.VERSION.SDK_INT >= 24 && remoteReply != null) {
NotificationCompat.Action.Builder(R.drawable.ic_reply_white_36dp, actionName, remoteReply)
.addRemoteInput(RemoteInput.Builder(DefaultMessageNotifier.EXTRA_REMOTE_REPLY).setLabel(label).build())
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
.setShowsUserInterface(false)
.build()
} else if (quickReply != null) {
NotificationCompat.Action(R.drawable.ic_reply_white_36dp, actionName, quickReply)
} else {
null
}
builder.addAction(replyAction)
if (remoteReply != null) {
val wearableReplyAction = NotificationCompat.Action.Builder(R.drawable.ic_reply, actionName, remoteReply)
.addRemoteInput(RemoteInput.Builder(DefaultMessageNotifier.EXTRA_REMOTE_REPLY).setLabel(label).build())
.build()
extender.addAction(wearableReplyAction)
}
}
builder.extend(extender)
}
override fun addMarkAsReadActionActual(state: NotificationState) {
val markAsRead: PendingIntent? = state.getMarkAsReadIntent(context)
if (markAsRead != null) {
val markAllAsReadAction = NotificationCompat.Action(R.drawable.check, context.getString(R.string.MessageNotifier_mark_all_as_read), markAsRead)
builder.addAction(markAllAsReadAction)
builder.extend(NotificationCompat.WearableExtender().addAction(markAllAsReadAction))
}
}
override fun addTurnOffJoinedNotificationsAction(pendingIntent: PendingIntent?) {
if (pendingIntent != null) {
val turnOffTheseNotifications = NotificationCompat.Action(
R.drawable.check,
context.getString(R.string.MessageNotifier_turn_off_these_notifications),
pendingIntent
)
builder.addAction(turnOffTheseNotifications)
}
}
override fun addMessagesActual(conversation: NotificationConversation, includeShortcut: Boolean) {
if (Build.VERSION.SDK_INT < 24) {
val bigPictureUri: Uri? = conversation.getSlideBigPictureUri(context)
if (bigPictureUri != null) {
builder.setStyle(
NotificationCompat.BigPictureStyle()
.bigPicture(bigPictureUri.toBitmap(context, BIG_PICTURE_DIMEN))
.setSummaryText(conversation.getContentText(context))
.bigLargeIcon(null)
)
return
}
}
val self: PersonCompat = PersonCompat.Builder()
.setBot(false)
.setName(if (includeShortcut) Recipient.self().getDisplayName(context) else context.getString(R.string.SingleRecipientNotificationBuilder_you))
.setIcon(if (includeShortcut) Recipient.self().getContactDrawable(context).toLargeBitmap(context).toIconCompat() else null)
.setKey(ConversationUtil.getShortcutId(Recipient.self().id))
.build()
val messagingStyle: NotificationCompat.MessagingStyle = NotificationCompat.MessagingStyle(self)
messagingStyle.conversationTitle = conversation.getConversationTitle(context)
messagingStyle.isGroupConversation = conversation.isGroup
conversation.notificationItems.forEach { notificationItem ->
var person: PersonCompat? = null
if (!notificationItem.isPersonSelf) {
val personBuilder: PersonCompat.Builder = PersonCompat.Builder()
.setBot(false)
.setName(notificationItem.getPersonName(context))
.setUri(notificationItem.getPersonUri())
.setIcon(notificationItem.getPersonIcon(context).toIconCompat())
if (includeShortcut) {
personBuilder.setKey(ConversationUtil.getShortcutId(notificationItem.individualRecipient))
}
person = personBuilder.build()
}
val (dataUri: Uri?, mimeType: String?) = notificationItem.getThumbnailInfo(context)
messagingStyle.addMessage(NotificationCompat.MessagingStyle.Message(notificationItem.getPrimaryText(context), notificationItem.timestamp, person).setData(mimeType, dataUri))
}
builder.setStyle(messagingStyle)
}
override fun addMessagesActual(state: NotificationState) {
if (Build.VERSION.SDK_INT >= 24) {
return
}
val style: NotificationCompat.InboxStyle = NotificationCompat.InboxStyle()
for (notificationItem: NotificationItem in state.notificationItems) {
val line: CharSequence? = notificationItem.getInboxLine(context)
if (line != null) {
style.addLine(line)
}
addPerson(notificationItem.individualRecipient)
}
builder.setStyle(style)
}
override fun setAlarms(recipient: Recipient?) {
if (NotificationChannels.supported()) {
return
}
val ringtone: Uri? = recipient?.messageRingtone
val vibrate = recipient?.messageVibrate
val defaultRingtone: Uri = SignalStore.settings().messageNotificationSound
val defaultVibrate: Boolean = SignalStore.settings().isMessageVibrateEnabled
if (ringtone == null && !TextUtils.isEmpty(defaultRingtone.toString())) {
builder.setSound(defaultRingtone)
} else if (ringtone != null && ringtone.toString().isNotEmpty()) {
builder.setSound(ringtone)
}
if (vibrate == RecipientDatabase.VibrateState.ENABLED || vibrate == RecipientDatabase.VibrateState.DEFAULT && defaultVibrate) {
builder.setDefaults(Notification.DEFAULT_VIBRATE)
}
}
override fun setBubbleMetadataActual(conversation: NotificationConversation, bubbleState: BubbleUtil.BubbleState) {
if (Build.VERSION.SDK_INT < ConversationUtil.CONVERSATION_SUPPORT_VERSION) {
return
}
val intent: PendingIntent? = NotificationPendingIntentHelper.getActivity(
context,
0,
ConversationIntents.createBubbleIntent(context, conversation.recipient.id, conversation.thread.threadId),
mutable()
)
if (intent != null) {
val bubbleMetadata = NotificationCompat.BubbleMetadata.Builder(intent, AvatarUtil.getIconCompatForShortcut(context, conversation.recipient))
.setAutoExpandBubble(bubbleState === BubbleUtil.BubbleState.SHOWN)
.setDesiredHeight(600)
.setSuppressNotification(bubbleState === BubbleUtil.BubbleState.SHOWN)
.build()
builder.bubbleMetadata = bubbleMetadata
}
}
override fun setLights(@ColorInt color: Int, onTime: Int, offTime: Int) {
if (NotificationChannels.supported()) {
return
}
builder.setLights(color, onTime, offTime)
}
override fun setSmallIcon(drawable: Int) {
builder.setSmallIcon(drawable)
}
override fun setColor(@ColorInt color: Int) {
builder.color = color
}
override fun setCategory(category: String) {
builder.setCategory(category)
}
override fun setGroup(group: String) {
if (Build.VERSION.SDK_INT < 24) {
return
}
builder.setGroup(group)
}
override fun setGroupAlertBehavior(behavior: Int) {
if (Build.VERSION.SDK_INT < 24) {
return
}
builder.setGroupAlertBehavior(behavior)
}
override fun setChannelId(channelId: String) {
builder.setChannelId(channelId)
}
override fun setContentTitle(contentTitle: CharSequence) {
builder.setContentTitle(contentTitle)
}
override fun setLargeIcon(largeIcon: Bitmap?) {
builder.setLargeIcon(largeIcon)
}
override fun setShortcutIdActual(shortcutId: String) {
builder.setShortcutId(shortcutId)
}
override fun setContentInfo(contentInfo: String) {
builder.setContentInfo(contentInfo)
}
override fun setNumber(number: Int) {
builder.setNumber(number)
}
override fun setContentText(contentText: CharSequence?) {
builder.setContentText(contentText)
}
override fun setTicker(ticker: CharSequence?) {
builder.setTicker(ticker)
}
override fun setContentIntent(pendingIntent: PendingIntent?) {
builder.setContentIntent(pendingIntent)
}
override fun setDeleteIntent(deleteIntent: PendingIntent?) {
builder.setDeleteIntent(deleteIntent)
}
override fun setSortKey(sortKey: String) {
builder.setSortKey(sortKey)
}
override fun setOnlyAlertOnce(onlyAlertOnce: Boolean) {
builder.setOnlyAlertOnce(onlyAlertOnce)
}
override fun setPriority(priority: Int) {
if (!NotificationChannels.supported()) {
builder.priority = priority
}
}
override fun setAutoCancel(autoCancel: Boolean) {
builder.setAutoCancel(autoCancel)
}
override fun build(): Notification {
return builder.build()
}
override fun addPersonActual(recipient: Recipient) {
builder.addPerson(recipient.contactUri.toString())
}
override fun setWhen(timestamp: Long) {
builder.setWhen(timestamp)
builder.setShowWhen(true)
}
override fun setGroupSummary(isGroupSummary: Boolean) {
builder.setGroupSummary(isGroupSummary)
}
override fun setSubText(subText: String) {
builder.setSubText(subText)
}
override fun setLocusIdActual(locusId: String) {
builder.setLocusId(LocusIdCompat(locusId))
}
}
}
private fun Bitmap?.toIconCompat(): IconCompat? {
return if (this != null) {
IconCompat.createWithBitmap(this)
} else {
null
}
}
@StringRes
private fun ReplyMethod.toLongDescription(): Int {
return when (this) {
ReplyMethod.GroupMessage -> R.string.MessageNotifier_reply
ReplyMethod.SecureMessage -> R.string.MessageNotifier_signal_message
ReplyMethod.UnsecuredSmsMessage -> R.string.MessageNotifier_unsecured_sms
}
}
| gpl-3.0 | e44af513cdc0ee91fc114fd5f3010cad | 35.573674 | 181 | 0.730447 | 4.755045 | false | false | false | false |
androidx/androidx | compose/foundation/foundation-layout/samples/src/main/java/androidx/compose/foundation/layout/samples/WindowInsetsPaddingSample.kt | 3 | 15655 | /*
* 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
*
* 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.foundation.layout.samples
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.Sampled
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.MutableWindowInsets
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.captionBarPadding
import androidx.compose.foundation.layout.consumedWindowInsets
import androidx.compose.foundation.layout.displayCutoutPadding
import androidx.compose.foundation.layout.exclude
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.layout.mandatorySystemGesturesPadding
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeContent
import androidx.compose.foundation.layout.safeContentPadding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.safeGesturesPadding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.systemGesturesPadding
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.waterfallPadding
import androidx.compose.foundation.layout.withConsumedWindowInsets
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
@Sampled
fun captionBarPaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
Box(Modifier.captionBarPadding()) {
// app content
}
}
}
}
}
@Sampled
fun systemBarsPaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
Box(Modifier.systemBarsPadding()) {
// app content
}
}
}
}
}
@Sampled
fun displayCutoutPaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
Box(
Modifier
.background(Color.Blue)
.statusBarsPadding()) {
Box(
Modifier
.background(Color.Yellow)
.displayCutoutPadding()) {
// app content
}
}
}
}
}
}
@Sampled
fun statusBarsAndNavigationBarsPaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
Box(
Modifier
.background(Color.Blue)
.statusBarsPadding()) {
Box(
Modifier
.background(Color.Green)
.navigationBarsPadding()) {
// app content
}
}
}
}
}
}
@Sampled
fun imePaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
Box(
Modifier
.background(Color.Blue)
.systemBarsPadding()) {
Box(Modifier.imePadding()) {
// app content
}
}
}
}
}
}
@Sampled
fun waterfallPaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
Box(
Modifier
.background(Color.Blue)
.systemBarsPadding()) {
// The app content shouldn't spill over the edges. They will be green.
Box(
Modifier
.background(Color.Green)
.waterfallPadding()) {
// app content
}
}
}
}
}
}
@Sampled
fun systemGesturesPaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
Box(
Modifier
.background(Color.Blue)
.systemBarsPadding()) {
// The app content won't interfere with the system gestures area.
// It will just be white.
Box(
Modifier
.background(Color.White)
.systemGesturesPadding()) {
// app content
}
}
}
}
}
}
@Sampled
fun mandatorySystemGesturesPaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
Box(
Modifier
.background(Color.Blue)
.systemBarsPadding()) {
// The app content won't interfere with the mandatory system gestures area.
// It will just be white.
Box(
Modifier
.background(Color.White)
.mandatorySystemGesturesPadding()) {
// app content
}
}
}
}
}
}
@Sampled
fun safeDrawingPaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
Box(
Modifier
.background(Color.Black)
.systemBarsPadding()) {
// The app content won't have anything drawing over it, but all the
// background not in the status bars will be white.
Box(
Modifier
.background(Color.White)
.safeDrawingPadding()) {
// app content
}
}
}
}
}
}
@Sampled
fun safeGesturesPaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
Box(
Modifier
.background(Color.Black)
.systemBarsPadding()) {
// The app content will only be drawn where there is no possible
// gesture confusion. The rest will be plain white
Box(
Modifier
.background(Color.White)
.safeGesturesPadding()) {
// app content
}
}
}
}
}
}
@Sampled
fun safeContentPaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
Box(
Modifier
.background(Color.Black)
.systemBarsPadding()) {
// The app content will only be drawn where there is no possible
// gesture confusion and content will not be drawn over.
// The rest will be plain white
Box(
Modifier
.background(Color.White)
.safeContentPadding()) {
// app content
}
}
}
}
}
}
@Sampled
fun insetsPaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
val insets = WindowInsets.systemBars.union(WindowInsets.ime)
Box(
Modifier
.background(Color.White)
.fillMaxSize()
.windowInsetsPadding(insets)) {
// app content
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Sampled
fun consumedInsetsPaddingSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
with(LocalDensity.current) {
val paddingValues = PaddingValues(horizontal = 20.dp)
Box(
Modifier
.padding(paddingValues)
.consumedWindowInsets(paddingValues)
) {
// app content
}
}
}
}
}
}
@Sampled
fun insetsInt() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
// Make sure we are at least 10 pixels away from the top.
val insets = WindowInsets.statusBars.union(WindowInsets(top = 10))
Box(Modifier.windowInsetsPadding(insets)) {
// app content
}
}
}
}
}
@Sampled
fun insetsDp() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
// Make sure we are at least 10 DP away from the top.
val insets = WindowInsets.statusBars.union(WindowInsets(top = 10.dp))
Box(Modifier.windowInsetsPadding(insets)) {
// app content
}
}
}
}
}
@Sampled
fun paddingValuesSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
LazyColumn(
contentPadding = WindowInsets.navigationBars.asPaddingValues()
) {
// items
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Sampled
fun consumedInsetsSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
Box(Modifier.padding(WindowInsets.navigationBars.asPaddingValues())) {
Box(Modifier.consumedWindowInsets(WindowInsets.navigationBars)) {
// app content
}
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Sampled
fun withConsumedInsetsSample() {
class SampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
val remainingInsets = remember { MutableWindowInsets() }
val safeContent = WindowInsets.safeContent
Box(
Modifier
.navigationBarsPadding()
.withConsumedWindowInsets { consumedWindowInsets ->
remainingInsets.insets = safeContent.exclude(consumedWindowInsets)
}) {
// padding can be used without recomposition when insets change.
val padding = remainingInsets.asPaddingValues()
Box(Modifier.padding(padding))
}
}
}
}
}
| apache-2.0 | 22bd511a2c7a30b687af76c019f54108 | 34.3386 | 95 | 0.561482 | 6.115234 | false | false | false | false |
androidx/androidx | camera/camera-video/src/test/java/androidx/camera/video/QualitySelectorTest.kt | 3 | 13715 | /*
* 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.camera.video
import android.os.Build
import androidx.camera.testing.CamcorderProfileUtil
import androidx.camera.testing.CamcorderProfileUtil.PROFILE_1080P
import androidx.camera.testing.CamcorderProfileUtil.PROFILE_2160P
import androidx.camera.testing.CamcorderProfileUtil.PROFILE_480P
import androidx.camera.testing.CamcorderProfileUtil.PROFILE_720P
import androidx.camera.testing.CamcorderProfileUtil.RESOLUTION_2160P
import androidx.camera.testing.CamcorderProfileUtil.RESOLUTION_720P
import androidx.camera.testing.fakes.FakeCamcorderProfileProvider
import androidx.camera.testing.fakes.FakeCameraInfoInternal
import com.google.common.truth.Truth.assertThat
import org.junit.Assert.assertThrows
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.internal.DoNotInstrument
private const val CAMERA_ID_0 = "0"
private const val CAMERA_ID_1 = "1"
private val CAMERA_0_PROFILE_HIGH = CamcorderProfileUtil.asHighQuality(PROFILE_2160P)
private val CAMERA_0_PROFILE_LOW = CamcorderProfileUtil.asLowQuality(PROFILE_720P)
private val CAMERA_1_PROFILE_HIGH = CamcorderProfileUtil.asHighQuality(PROFILE_1080P)
private val CAMERA_1_PROFILE_LOW = CamcorderProfileUtil.asLowQuality(PROFILE_480P)
@RunWith(RobolectricTestRunner::class)
@DoNotInstrument
@Config(minSdk = Build.VERSION_CODES.LOLLIPOP)
class QualitySelectorTest {
private val cameraInfo0 = FakeCameraInfoInternal(CAMERA_ID_0).apply {
camcorderProfileProvider = FakeCamcorderProfileProvider.Builder()
.addProfile(
CAMERA_0_PROFILE_HIGH,
PROFILE_2160P,
PROFILE_720P,
CAMERA_0_PROFILE_LOW
).build()
}
private val cameraInfo1 = FakeCameraInfoInternal(CAMERA_ID_1).apply {
camcorderProfileProvider = FakeCamcorderProfileProvider.Builder()
.addProfile(
CAMERA_1_PROFILE_HIGH,
PROFILE_1080P,
PROFILE_480P,
CAMERA_1_PROFILE_LOW
).build()
}
@Test
fun getSortedQualities_fromLargeToSmall() {
val sortedQualities = Quality.getSortedQualities()
assertThat(sortedQualities[0]).isEqualTo(Quality.UHD)
assertThat(sortedQualities[1]).isEqualTo(Quality.FHD)
assertThat(sortedQualities[2]).isEqualTo(Quality.HD)
assertThat(sortedQualities[3]).isEqualTo(Quality.SD)
}
@Test
fun getSupportedQualities_fromLargeToSmall() {
// camera0 supports 2160P(UHD) and 720P(HD)
val supportedQualities = QualitySelector.getSupportedQualities(cameraInfo0)
assertThat(supportedQualities[0]).isEqualTo(Quality.UHD)
assertThat(supportedQualities[1]).isEqualTo(Quality.HD)
}
@Test
fun isQualitySupported_returnCorrectResult() {
// camera0 supports 2160P(UHD) and 720P(HD)
assertThat(QualitySelector.isQualitySupported(cameraInfo0, Quality.HIGHEST)).isTrue()
assertThat(QualitySelector.isQualitySupported(cameraInfo0, Quality.LOWEST)).isTrue()
assertThat(QualitySelector.isQualitySupported(cameraInfo0, Quality.UHD)).isTrue()
assertThat(QualitySelector.isQualitySupported(cameraInfo0, Quality.FHD)).isFalse()
assertThat(QualitySelector.isQualitySupported(cameraInfo0, Quality.HD)).isTrue()
assertThat(QualitySelector.isQualitySupported(cameraInfo0, Quality.SD)).isFalse()
}
@Test
fun getResolution_returnCorrectResolution() {
// camera0 supports 2160P(UHD) and 720P(HD)
assertThat(
QualitySelector.getResolution(cameraInfo0, Quality.HIGHEST)
).isEqualTo(RESOLUTION_2160P)
assertThat(
QualitySelector.getResolution(cameraInfo0, Quality.LOWEST)
).isEqualTo(RESOLUTION_720P)
assertThat(
QualitySelector.getResolution(cameraInfo0, Quality.UHD)
).isEqualTo(RESOLUTION_2160P)
assertThat(
QualitySelector.getResolution(cameraInfo0, Quality.FHD)
).isNull()
assertThat(
QualitySelector.getResolution(cameraInfo0, Quality.HD)
).isEqualTo(RESOLUTION_720P)
assertThat(
QualitySelector.getResolution(cameraInfo0, Quality.SD)
).isNull()
}
@Test
fun fromOrderedList_containNull_throwException() {
// Assert.
assertThrows(IllegalArgumentException::class.java) {
// Act.
QualitySelector.fromOrderedList(listOf(Quality.FHD, null))
}
}
@Test
fun fromOrderedList_setEmptyQualityList_throwException() {
// Assert.
assertThrows(IllegalArgumentException::class.java) {
// Act.
QualitySelector.fromOrderedList(emptyList())
}
}
@Test
fun getPrioritizedQualities_selectSingleQuality() {
// Arrange.
// camera0 supports 2160P(UHD) and 720P(HD)
val qualitySelector = QualitySelector.from(Quality.UHD)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo0)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.UHD))
}
@Test
fun getPrioritizedQualities_selectQualityByOrder() {
// Arrange.
// camera0 supports 2160P(UHD) and 720P(HD)
val qualitySelector =
QualitySelector.fromOrderedList(listOf(Quality.FHD, Quality.UHD, Quality.HD))
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo0)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.UHD, Quality.HD))
}
@Test
fun getPrioritizedQualities_noFallbackStrategy() {
// Arrange.
// camera0 supports 2160P(UHD) and 720P(HD)
val qualitySelector = QualitySelector.from(Quality.FHD)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo0)
// Assert.
assertThat(qualities).isEmpty()
}
@Test
fun getPrioritizedQualities_withFallbackStrategy() {
// Arrange.
// camera0 supports 2160P(UHD) and 720P(HD)
val qualitySelector = QualitySelector.from(
Quality.FHD,
FallbackStrategy.lowerQualityOrHigherThan(Quality.FHD)
)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo0)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.HD, Quality.UHD))
}
@Test
fun getPrioritizedQualities_containHighestQuality_addAll() {
// Arrange.
// camera0 supports 2160P(UHD) and 720P(HD)
val qualitySelector = QualitySelector.fromOrderedList(listOf(Quality.FHD, Quality.HIGHEST))
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo0)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.UHD, Quality.HD))
}
@Test
fun getPrioritizedQualities_containLowestQuality_addAllReversely() {
// Arrange.
// camera0 supports 2160P(UHD) and 720P(HD)
val qualitySelector = QualitySelector.fromOrderedList(listOf(Quality.FHD, Quality.LOWEST))
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo0)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.HD, Quality.UHD))
}
@Test
fun getPrioritizedQualities_addDuplicateQuality_getSingleQualityWithCorrectOrder() {
// Arrange.
// camera0 supports 2160P(UHD) and 720P(HD)
val qualitySelector = QualitySelector.fromOrderedList(
listOf(
Quality.SD,
Quality.FHD,
Quality.HD,
Quality.UHD,
// start duplicate qualities
Quality.SD,
Quality.HD,
Quality.FHD,
Quality.UHD,
Quality.LOWEST,
Quality.HIGHEST
),
FallbackStrategy.higherQualityThan(Quality.LOWEST)
)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo0)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.HD, Quality.UHD))
}
@Test
fun getPrioritizedQualities_fallbackLowerOrHigher_getLower() {
// Arrange.
// camera0 supports 2160P(UHD) and 720P(HD)
val qualitySelector = QualitySelector.from(
Quality.FHD,
FallbackStrategy.lowerQualityOrHigherThan(Quality.FHD)
)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo0)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.HD, Quality.UHD))
}
@Test
fun getPrioritizedQualities_fallbackLowerOrHigher_fallbackQualityNotIncluded() {
// Arrange.
// camera0 supports 2160P(UHD) and 720P(HD)
val qualitySelector = QualitySelector.from(
Quality.SD,
FallbackStrategy.higherQualityThan(Quality.HD)
)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo0)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.UHD))
}
@Test
fun getPrioritizedQualities_fallbackLowerOrHigher_getHigher() {
// Arrange.
// camera0 supports 2160P(UHD) and 720P(HD)
val qualitySelector = QualitySelector.from(
Quality.SD,
FallbackStrategy.lowerQualityOrHigherThan(Quality.SD)
)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo0)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.HD, Quality.UHD))
}
@Test
fun getPrioritizedQualities_fallbackLower_getLower() {
// Arrange.
// camera0 supports 2160P(UHD) and 720P(HD)
val qualitySelector = QualitySelector.from(
Quality.FHD,
FallbackStrategy.lowerQualityThan(Quality.FHD)
)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo0)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.HD))
}
@Test
fun getPrioritizedQualities_fallbackLower_getNone() {
// Arrange.
// camera0 supports 2160P(UHD) and 720P(HD)
val qualitySelector = QualitySelector.from(
Quality.SD,
FallbackStrategy.lowerQualityThan(Quality.SD)
)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo0)
// Assert.
assertThat(qualities).isEmpty()
}
@Test
fun getPrioritizedQualities_fallbackHigherOrLower_getHigher() {
// Arrange.
// camera1 supports 1080P(FHD) and 480P(SD)
val qualitySelector = QualitySelector.from(
Quality.HD,
FallbackStrategy.higherQualityOrLowerThan(Quality.HD)
)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo1)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.FHD, Quality.SD))
}
@Test
fun getPrioritizedQualities_fallbackHigher_fallbackQualityNotIncluded() {
// Arrange.
// camera1 supports 1080P(FHD) and 480P(SD)
val qualitySelector = QualitySelector.from(
Quality.UHD,
FallbackStrategy.higherQualityThan(Quality.SD)
)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo1)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.FHD))
}
@Test
fun getPrioritizedQualities_fallbackHigherOrLower_getLower() {
// Arrange.
// camera1 supports 1080P(FHD) and 480P(SD)
val qualitySelector = QualitySelector.from(
Quality.UHD,
FallbackStrategy.higherQualityOrLowerThan(Quality.UHD)
)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo1)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.FHD, Quality.SD))
}
@Test
fun getPrioritizedQualities_fallbackHigher_getHigher() {
// Arrange.
// camera1 supports 1080P(FHD) and 480P(SD)
val qualitySelector = QualitySelector.from(
Quality.HD,
FallbackStrategy.higherQualityThan(Quality.HD)
)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo1)
// Assert.
assertThat(qualities).isEqualTo(listOf(Quality.FHD))
}
@Test
fun getPrioritizedQualities_fallbackHigher_getNone() {
// Arrange.
// camera1 supports 1080P(FHD) and 480P(SD)
val qualitySelector = QualitySelector.from(
Quality.UHD,
FallbackStrategy.higherQualityThan(Quality.UHD)
)
// Act.
val qualities = qualitySelector.getPrioritizedQualities(cameraInfo1)
// Assert.
assertThat(qualities).isEmpty()
}
}
| apache-2.0 | b58844aa1e76194f4471a4e89a88b0ed | 32.615196 | 99 | 0.665038 | 4.674506 | false | true | false | false |
nrizzio/Signal-Android | sms-exporter/lib/src/main/java/org/signal/smsexporter/internal/mms/GetOrCreateMmsThreadIdsUseCase.kt | 1 | 1540 | package org.signal.smsexporter.internal.mms
import android.content.Context
import com.klinker.android.send_message.Utils
import org.signal.core.util.Try
import org.signal.smsexporter.ExportableMessage
/**
* Given a list of messages, gets or creates the threadIds for each different recipient set.
* Returns a list of outputs that tie a given message to a thread id.
*
* This method will also filter out messages that do not have addresses.
*/
internal object GetOrCreateMmsThreadIdsUseCase {
fun execute(
context: Context,
mms: ExportableMessage.Mms<*>,
threadCache: MutableMap<Set<String>, Long>
): Try<Output> {
return try {
val recipients = getRecipientSet(mms)
val threadId = getOrCreateThreadId(context, recipients, threadCache)
Try.success(Output(mms, threadId))
} catch (e: Exception) {
Try.failure(e)
}
}
private fun getOrCreateThreadId(context: Context, recipients: Set<String>, cache: MutableMap<Set<String>, Long>): Long {
return if (cache.containsKey(recipients)) {
cache[recipients]!!
} else {
val threadId = Utils.getOrCreateThreadId(context, recipients)
cache[recipients] = threadId
threadId
}
}
private fun getRecipientSet(mms: ExportableMessage.Mms<*>): Set<String> {
val recipients = mms.addresses
if (recipients.isEmpty()) {
error("Expected non-empty recipient count.")
}
return HashSet(recipients.map { it })
}
data class Output(val mms: ExportableMessage.Mms<*>, val threadId: Long)
}
| gpl-3.0 | eebb4f13c63adaa40cc6eb37a989d1b0 | 29.8 | 122 | 0.707792 | 4.063325 | false | false | false | false |
Sylvilagus/SylvaBBSClient | SylvaBBSClient/app/src/main/java/com/sylva/sylvabbsclient/view/fragment/MyFavouriteTopicsFragment.kt | 1 | 1590 | package com.sylva.sylvabbsclient.view.fragment
import android.graphics.Rect
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.sylva.sylvabbsclient.R
import com.sylva.sylvabbsclient.bean.Topic
import com.sylva.sylvabbsclient.global.find
import com.sylva.sylvabbsclient.view.TDefaultRecyclerView
import com.sylva.sylvabbsclient.view.adapter.MyFavouriteTopicAdapter
import com.sylva.sylvabbsclient.view.adapter.holder.MyFavouriteTopicViewHolder
import kotlinx.android.synthetic.main.part_recyclerview.*
import java.util.*
/**
* Created by sylva on 2016/3/30.
*/
class MyFavouriteTopicsFragment: BaseFragment(),TDefaultRecyclerView<Topic,MyFavouriteTopicViewHolder,MyFavouriteTopicAdapter> {
private val list:List<Topic> by lazy{ ArrayList<Topic>() }
override val recyclerView: RecyclerView by lazy{activity.find<RecyclerView>(R.id.recycler_view)}
private val mItemSpacing = 10
override val recyclerViewAdapter: MyFavouriteTopicAdapter by lazy{MyFavouriteTopicAdapter(activity,list)}
override val itemDecoration: RecyclerView.ItemDecoration
get() = object : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
if (parent.getChildAdapterPosition(view) != 0)
outRect.top = mItemSpacing
}
};
override val layoutManager: RecyclerView.LayoutManager by lazy{
val llm= LinearLayoutManager(activity)
llm
}
} | apache-2.0 | f6b844d7805ea7247c3791ce160ba885 | 44.457143 | 128 | 0.77044 | 4.066496 | false | false | false | false |
sxhya/roots | src/primitives/RootSystems.kt | 1 | 3181 | /**
* Created by user on 1/17/15.
*/
class RootSystems {
companion object {
val e8base = Matrix(arrayOf(doubleArrayOf(-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5),
doubleArrayOf( 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0),
doubleArrayOf( 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0),
doubleArrayOf( 0.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0),
doubleArrayOf( 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0),
doubleArrayOf( 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0, 0.0),
doubleArrayOf( 0.0, 1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0),
doubleArrayOf( 1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)))
val e7base = Matrix(arrayOf(doubleArrayOf(-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, Math.sqrt(2.0) / 2),
doubleArrayOf( 0.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0),
doubleArrayOf( 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0),
doubleArrayOf( 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0),
doubleArrayOf( 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0),
doubleArrayOf( 0.0, 1.0, -1.0, 0.0, 0.0, 0.0, 0.0),
doubleArrayOf( 1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0)))
val e6base = Matrix(arrayOf(doubleArrayOf( 1.0, -1.0, 0.0, 0.0, 0.0, 0.0),
doubleArrayOf( 0.0, 0.0, 0.0, 1.0, -1.0, 0.0),
doubleArrayOf( 0.0, 1.0, -1.0, 0.0, 0.0, 0.0),
doubleArrayOf( 0.0, 0.0, 1.0, -1.0, 0.0, 0.0),
doubleArrayOf( 0.0, 0.0, 0.0, 1.0, 1.0, 0.0),
doubleArrayOf(-0.5, -0.5, -0.5, -0.5, -0.5, Math.sqrt(3.0) / 2)))
val f4base = Matrix(arrayOf(doubleArrayOf( 1.0, -1.0, 0.0, 0.0),
doubleArrayOf( 0.0, 1.0, -1.0, 0.0),
doubleArrayOf( 0.0, 0.0, 1.0, 0.0),
doubleArrayOf(-0.5, -0.5, -0.5, -0.5)))
fun dlbase(l: Int): Matrix {
val coos = Array(l) { DoubleArray(l) }
for (i in 0 until l) {
coos[i][i] = 1.0
if (i < l - 1) coos[i][i + 1] = -1.0
}
coos[l - 1][l - 2] = 1.0
return Matrix(coos)
}
fun albase(l: Int): Matrix {
val coos = Array(l) { DoubleArray(l) }
for (i in 0 until l - 1) {
coos[i][i] = 1.0
coos[i][i + 1] = -1.0
}
val b = (l - 1 + Math.sqrt((l + 1).toDouble())) / l
for (i in 0 until l - 1) coos[l - 1][i] = b - 1
coos[l - 1][l - 1] = b
return Matrix(coos)
}
fun blbase(l: Int): Matrix {
val coos = clbase(l).myCoo
coos[l - 1][l - 1] = 1.0
return Matrix(coos)
}
fun clbase(l: Int): Matrix {
val coos = Array(l) { DoubleArray(l) }
for (i in 0 until l - 1) {
coos[i][i] = 1.0
coos[i][i + 1] = -1.0
}
for (i in 0 until l - 2) coos[l - 1][i] = 0.0
coos[l - 1][l - 1] = 2.0
return Matrix(coos)
}
}
}
| apache-2.0 | 8a03608eef1bc534e2cde54d75b25601 | 38.7625 | 106 | 0.393901 | 2.354552 | false | false | false | false |
wealthfront/magellan | magellan-library/src/main/java/com/wealthfront/magellan/init/Magellan.kt | 1 | 1639 | package com.wealthfront.magellan.init
import androidx.annotation.RestrictTo
import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX
import com.wealthfront.magellan.init.Magellan.customDefaultTransition
import com.wealthfront.magellan.init.Magellan.disableAnimations
import com.wealthfront.magellan.init.Magellan.logDebugInfo
import com.wealthfront.magellan.navigation.NavigationOverrideProvider
import com.wealthfront.magellan.transitions.DefaultTransition
import com.wealthfront.magellan.transitions.MagellanTransition
public object Magellan {
internal var logDebugInfo: Boolean = false
internal var disableAnimations: Boolean = false
internal var customDefaultTransition: MagellanTransition = DefaultTransition()
private var navigationOverrideProvider: NavigationOverrideProvider? = null
@JvmStatic
@JvmOverloads
public fun init(
disableAnimations: Boolean = false,
logDebugInfo: Boolean = false,
defaultTransition: MagellanTransition = DefaultTransition(),
navigationOverrideProvider: NavigationOverrideProvider? = null
) {
this.logDebugInfo = logDebugInfo
this.disableAnimations = disableAnimations
this.customDefaultTransition = defaultTransition
this.navigationOverrideProvider = navigationOverrideProvider
}
public fun getNavigationOverrideProvider(): NavigationOverrideProvider? {
return navigationOverrideProvider
}
}
internal fun shouldRunAnimations(): Boolean = !disableAnimations
internal fun shouldLogDebugInfo(): Boolean = logDebugInfo
@RestrictTo(LIBRARY_GROUP_PREFIX)
public fun getDefaultTransition(): MagellanTransition = customDefaultTransition
| apache-2.0 | 15fabf23f9521c47bc91f05b8ff90e57 | 37.116279 | 80 | 0.829774 | 5.090062 | false | false | false | false |
smichel17/simpletask-android | app/src/main/java/nl/mpcjanssen/simpletask/util/ActionQueues.kt | 1 | 1249 | package nl.mpcjanssen.simpletask.util
import android.os.Handler
import android.os.Looper
import android.util.Log
open class ActionQueue(val qName: String) : Thread() {
private var mHandler: Handler? = null
private val TAG = "ActionQueue"
override fun run() {
Looper.prepare()
mHandler = Handler() // the Handler hooks up to the current Thread
Looper.loop()
}
fun hasPending(): Boolean {
return mHandler?.hasMessages(0) ?: false
}
fun add(description: String, r: () -> Unit) {
while (mHandler == null) {
Log.d(TAG, "Queue handler is null, waiting")
try {
Thread.sleep(100)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
Log.i(qName, "-> $description")
mHandler?.post(LoggingRunnable(qName,description, Runnable(r)))
}
}
object FileStoreActionQueue : ActionQueue("FSQ")
class LoggingRunnable(val queuName : String, val description: String, val runnable: Runnable) : Runnable {
override fun toString(): String {
return description
}
override fun run() {
Log.i(queuName, "<- $description")
runnable.run()
}
}
| gpl-3.0 | 7006918e0ba92cf24ef38077af9f44c1 | 23.019231 | 106 | 0.59968 | 4.292096 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/comment/psi/LuaDocPsiImplUtil.kt | 2 | 9311 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UNUSED_PARAMETER")
package com.tang.intellij.lua.comment.psi
import com.intellij.icons.AllIcons
import com.intellij.navigation.ItemPresentation
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.PsiReference
import com.intellij.psi.StubBasedPsiElement
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.util.PsiTreeUtil
import com.tang.intellij.lua.comment.LuaCommentUtil
import com.tang.intellij.lua.comment.reference.LuaClassNameReference
import com.tang.intellij.lua.comment.reference.LuaDocParamNameReference
import com.tang.intellij.lua.comment.reference.LuaDocSeeReference
import com.tang.intellij.lua.psi.LuaClassMember
import com.tang.intellij.lua.psi.LuaElementFactory
import com.tang.intellij.lua.psi.Visibility
import com.tang.intellij.lua.search.SearchContext
import com.tang.intellij.lua.ty.*
import javax.swing.Icon
/**
* Created by TangZX on 2016/11/24.
*/
fun getReference(paramNameRef: LuaDocParamNameRef): PsiReference {
return LuaDocParamNameReference(paramNameRef)
}
fun getReference(docClassNameRef: LuaDocClassNameRef): PsiReference {
return LuaClassNameReference(docClassNameRef)
}
fun resolveType(nameRef: LuaDocClassNameRef): ITy {
return Ty.create(nameRef.text)
}
fun getName(identifierOwner: PsiNameIdentifierOwner): String? {
val id = identifierOwner.nameIdentifier
return id?.text
}
fun setName(identifierOwner: PsiNameIdentifierOwner, newName: String): PsiElement {
val oldId = identifierOwner.nameIdentifier
if (oldId != null) {
val newId = LuaElementFactory.createDocIdentifier(identifierOwner.project, newName)
oldId.replace(newId)
return newId
}
return identifierOwner
}
fun getTextOffset(identifierOwner: PsiNameIdentifierOwner): Int {
val id = identifierOwner.nameIdentifier
return id?.textOffset ?: identifierOwner.node.startOffset
}
fun getNameIdentifier(tagField: LuaDocTagField): PsiElement? {
return tagField.id
}
fun getNameIdentifier(tagClass: LuaDocTagClass): PsiElement {
return tagClass.id
}
fun guessType(tagField: LuaDocTagField, context: SearchContext): ITy {
val stub = tagField.stub
if (stub != null)
return stub.type
return tagField.ty?.getType() ?: Ty.UNKNOWN
}
fun guessParentType(tagField: LuaDocTagField, context: SearchContext): ITy {
val parent = tagField.parent
val classDef = PsiTreeUtil.findChildOfType(parent, LuaDocTagClass::class.java)
return classDef?.type ?: Ty.UNKNOWN
}
fun getVisibility(tagField: LuaDocTagField): Visibility {
val stub = tagField.stub
if (stub != null)
return stub.visibility
val v = tagField.accessModifier?.let { Visibility.get(it.text) }
return v ?: Visibility.PUBLIC
}
/**
* 猜测参数的类型
* @param tagParamDec 参数定义
* *
* @return 类型集合
*/
fun getType(tagParamDec: LuaDocTagParam): ITy {
val type = tagParamDec.ty?.getType()
if (type != null) {
val substitutor = LuaCommentUtil.findContainer(tagParamDec).createSubstitutor()
if (substitutor != null)
return type.substitute(substitutor)
}
return type ?: Ty.UNKNOWN
}
fun getType(vararg: LuaDocTagVararg): ITy {
return vararg.ty?.getType() ?: Ty.UNKNOWN
}
fun getType(vararg: LuaDocVarargParam): ITy {
return vararg.ty?.getType() ?: Ty.UNKNOWN
}
/**
* 获取返回类型
* @param tagReturn 返回定义
*
* @return 类型集合
*/
fun resolveTypeAt(tagReturn: LuaDocTagReturn, index: Int): ITy {
val typeList = tagReturn.typeList
if (typeList != null) {
val list = typeList.tyList
if (list.size > index) {
return list[index].getType()
}
}
return Ty.UNKNOWN
}
fun getType(tagReturn: LuaDocTagReturn): ITy {
val tyList = tagReturn.typeList?.tyList
if (tyList != null && tyList.isNotEmpty()) {
val tupleList = tyList.map { it.getType() }
return if (tupleList.size == 1) tupleList.first() else TyTuple(tupleList)
}
return Ty.VOID
}
/**
* 优化:从stub中取名字
* @param tagClass LuaDocClassDef
* *
* @return string
*/
fun getName(tagClass: LuaDocTagClass): String {
val stub = tagClass.stub
if (stub != null)
return stub.className
return tagClass.id.text
}
/**
* for Goto Class
* @param tagClass class def
* *
* @return ItemPresentation
*/
fun getPresentation(tagClass: LuaDocTagClass): ItemPresentation {
return object : ItemPresentation {
override fun getPresentableText(): String? {
return tagClass.name
}
override fun getLocationString(): String? {
return tagClass.containingFile.name
}
override fun getIcon(b: Boolean): Icon? {
return AllIcons.Nodes.Class
}
}
}
fun getType(tagClass: LuaDocTagClass): ITyClass {
val stub = tagClass.stub
return stub?.classType ?: TyPsiDocClass(tagClass)
}
fun isDeprecated(tagClass: LuaDocTagClass): Boolean {
val stub = tagClass.stub
return stub?.isDeprecated ?: LuaCommentUtil.findContainer(tagClass).isDeprecated
}
/**
* 猜测类型
* @param tagType 类型定义
* *
* @return 类型集合
*/
fun getType(tagType: LuaDocTagType): ITy {
return tagType.ty?.getType() ?: Ty.UNKNOWN
}
@Suppress("UNUSED_PARAMETER")
fun toString(stubElement: StubBasedPsiElement<out StubElement<*>>): String {
return "[STUB]"// + stubElement.getNode().getElementType().toString();
}
fun getName(tagField: LuaDocTagField): String? {
val stub = tagField.stub
if (stub != null)
return stub.name
return getName(tagField as PsiNameIdentifierOwner)
}
fun getFieldName(tagField: LuaDocTagField): String? {
val stub = tagField.stub
if (stub != null)
return stub.name
return tagField.name
}
fun getPresentation(tagField: LuaDocTagField): ItemPresentation {
return object : ItemPresentation {
override fun getPresentableText(): String? {
return tagField.name
}
override fun getLocationString(): String? {
return tagField.containingFile.name
}
override fun getIcon(b: Boolean): Icon? {
return AllIcons.Nodes.Field
}
}
}
fun getType(luaDocArrTy: LuaDocArrTy): ITy {
val baseTy = luaDocArrTy.ty.getType()
return TyArray(baseTy)
}
fun getType(luaDocGeneralTy: LuaDocGeneralTy): ITy {
return resolveType(luaDocGeneralTy.classNameRef)
}
fun getType(luaDocFunctionTy: LuaDocFunctionTy): ITy {
return TyDocPsiFunction(luaDocFunctionTy)
}
fun getReturnType(luaDocFunctionTy: LuaDocFunctionTy): ITy {
val list = luaDocFunctionTy.typeList?.tyList?.map { it.getType() }
return when {
list == null -> Ty.VOID
list.isEmpty() -> Ty.VOID
list.size == 1 -> list.first()
else -> TyTuple(list)
}
}
fun getType(luaDocGenericTy: LuaDocGenericTy): ITy {
return TyDocGeneric(luaDocGenericTy)
}
fun getType(luaDocParTy: LuaDocParTy): ITy {
return luaDocParTy.ty?.getType() ?: Ty.UNKNOWN
}
fun getType(stringLiteral: LuaDocStringLiteralTy): ITy {
val text = stringLiteral.text
return TyStringLiteral(if (text.length >= 2) text.substring(1, text.length - 1) else "")
}
fun getType(unionTy: LuaDocUnionTy): ITy {
val list = unionTy.tyList
var retTy: ITy = Ty.UNKNOWN
for (ty in list) {
retTy = retTy.union(ty.getType())
}
return retTy
}
fun getReference(see: LuaDocTagSee): PsiReference? {
if (see.id == null) return null
return LuaDocSeeReference(see)
}
fun getType(tbl: LuaDocTableTy): ITy {
return TyDocTable(tbl.tableDef)
}
fun guessParentType(f: LuaDocTableField, context: SearchContext): ITy {
val p = f.parent as LuaDocTableDef
return TyDocTable(p)
}
fun getVisibility(f: LuaDocTableField): Visibility {
return Visibility.PUBLIC
}
fun getWorth(m: LuaClassMember): Int = LuaClassMember.WORTH_DOC
fun getNameIdentifier(f: LuaDocTableField): PsiElement? {
return f.id
}
fun getName(f:LuaDocTableField): String {
val stub = f.stub
return stub?.name ?: f.id.text
}
fun guessType(f:LuaDocTableField, context: SearchContext): ITy {
val stub = f.stub
val ty = if (stub != null) stub.docTy else f.ty?.getType()
return ty ?: Ty.UNKNOWN
}
fun getNameIdentifier(g: LuaDocGenericDef): PsiElement? {
return g.id
}
fun isDeprecated(member: LuaClassMember): Boolean {
return false
}
fun getNameIdentifier(g: LuaDocTagAlias): PsiElement? {
return g.id
}
fun getType(alias: LuaDocTagAlias): ITy {
val stub = alias.stub
val ty = stub?.type ?: alias.ty?.getType()
return ty ?: Ty.UNKNOWN
} | apache-2.0 | 09868eebfebac68136b000016fca69d7 | 25.862974 | 92 | 0.705199 | 3.885702 | false | false | false | false |
saki4510t/libcommon | app/src/main/java/com/serenegiant/libcommon/NumberKeyboardFragment.kt | 1 | 2770 | package com.serenegiant.libcommon
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import com.serenegiant.system.KeyboardDelegater
import com.serenegiant.view.ViewUtils
import com.serenegiant.widget.KeyboardView
/**
* NumberKeyboardテスト用フラグメント
*/
class NumberKeyboardFragment : BaseFragment() {
private var mInputEditText: EditText? = null
private var mKeyboardView: KeyboardView? = null
private var mDelegater: KeyboardDelegater? = null
override fun onAttach(context: Context) {
super.onAttach(context)
requireActivity().title = getString(R.string.title_number_keyboard)
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (DEBUG) Log.v(TAG, "onCreateView:")
val customInflater
= ViewUtils.createCustomLayoutInflater(requireContext(), inflater, R.style.AppTheme_NumberKeyboard)
return customInflater.inflate(R.layout.fragment_numberkeyboard, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (DEBUG) Log.v(TAG, "onViewCreated:")
initView(view)
}
override fun internalOnResume() {
super.internalOnResume()
mDelegater!!.showKeyboard()
}
override fun internalOnPause() {
mDelegater!!.hideKeyboard()
super.internalOnPause()
}
private fun initView(rootView: View) {
mInputEditText = rootView.findViewById(R.id.edittext)
mKeyboardView = rootView.findViewById(R.id.number_keyboardview)
mDelegater = object : KeyboardDelegater(
mInputEditText!!, mKeyboardView!!, R.xml.keyboard_number) {
override fun onCancelClick() {
if (DEBUG) Log.v(TAG, "onCancelClick:")
}
override fun onOkClick() {
if (DEBUG) Log.v(TAG, "onOkClick:")
}
}
}
companion object {
private const val DEBUG = true // TODO set false on release
private val TAG = NumberKeyboardFragment::class.java.simpleName
}
}
| apache-2.0 | 4f3e1bb9802a86ec67a74f12117e6474 | 29.21978 | 102 | 0.754909 | 3.782669 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/customization/AvatarCustomizationFragment.kt | 1 | 15308 | package com.habitrpg.android.habitica.ui.fragments.inventory.customization
import android.graphics.PorterDuff
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import androidx.core.content.ContextCompat
import androidx.core.view.doOnLayout
import androidx.lifecycle.lifecycleScope
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.android.flexbox.AlignItems
import com.google.android.flexbox.FlexDirection.ROW
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.CustomizationRepository
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.databinding.BottomSheetBackgroundsFilterBinding
import com.habitrpg.android.habitica.databinding.FragmentRefreshRecyclerviewBinding
import com.habitrpg.android.habitica.extensions.setTintWith
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.models.CustomizationFilter
import com.habitrpg.android.habitica.models.inventory.Customization
import com.habitrpg.android.habitica.models.user.OwnedCustomization
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.adapter.CustomizationRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.helpers.MarginDecoration
import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator
import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaBottomSheetDialog
import com.habitrpg.common.habitica.extensions.dpToPx
import com.habitrpg.common.habitica.extensions.getThemeColor
import io.reactivex.rxjava3.core.BackpressureStrategy
import io.reactivex.rxjava3.kotlin.combineLatest
import io.reactivex.rxjava3.subjects.BehaviorSubject
import io.reactivex.rxjava3.subjects.PublishSubject
import kotlinx.coroutines.launch
import javax.inject.Inject
class AvatarCustomizationFragment :
BaseMainFragment<FragmentRefreshRecyclerviewBinding>(),
SwipeRefreshLayout.OnRefreshListener {
private var filterMenuItem: MenuItem? = null
override var binding: FragmentRefreshRecyclerviewBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentRefreshRecyclerviewBinding {
return FragmentRefreshRecyclerviewBinding.inflate(inflater, container, false)
}
@Inject
lateinit var customizationRepository: CustomizationRepository
@Inject
lateinit var inventoryRepository: InventoryRepository
@Inject
lateinit var userViewModel: MainUserViewModel
var type: String? = null
var category: String? = null
private var activeCustomization: String? = null
internal var adapter: CustomizationRecyclerViewAdapter = CustomizationRecyclerViewAdapter()
internal var layoutManager: FlexboxLayoutManager = FlexboxLayoutManager(activity, ROW)
private val currentFilter = BehaviorSubject.create<CustomizationFilter>()
private val ownedCustomizations = PublishSubject.create<List<OwnedCustomization>>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
showsBackButton = true
compositeSubscription.add(
adapter.getSelectCustomizationEvents()
.flatMap { customization ->
if (customization.type == "background") {
userRepository.unlockPath(customization)
//TODO: .flatMap { userRepository.retrieveUser(false, true, true) }
} else {
userRepository.useCustomization(customization.type ?: "", customization.category, customization.identifier ?: "")
}
}
.subscribe({ }, ExceptionHandler.rx())
)
compositeSubscription.add(
this.inventoryRepository.getInAppRewards()
.map { rewards -> rewards.map { it.key } }
.subscribe({ adapter.setPinnedItemKeys(it) }, ExceptionHandler.rx())
)
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
val args = AvatarCustomizationFragmentArgs.fromBundle(it)
type = args.type
if (args.category.isNotEmpty()) {
category = args.category
}
}
adapter.customizationType = type
binding?.refreshLayout?.setOnRefreshListener(this)
layoutManager = FlexboxLayoutManager(activity, ROW)
layoutManager.justifyContent = JustifyContent.CENTER
layoutManager.alignItems = AlignItems.FLEX_START
binding?.recyclerView?.layoutManager = layoutManager
binding?.recyclerView?.addItemDecoration(MarginDecoration(context))
binding?.recyclerView?.adapter = adapter
binding?.recyclerView?.itemAnimator = SafeDefaultItemAnimator()
this.loadCustomizations()
userViewModel.user.observe(viewLifecycleOwner) { updateUser(it) }
currentFilter.onNext(CustomizationFilter(false, type != "background"))
binding?.recyclerView?.doOnLayout {
adapter.columnCount = it.width / (80.dpToPx(context))
}
}
override fun onDestroy() {
customizationRepository.close()
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_list_customizations, menu)
filterMenuItem = menu.findItem(R.id.action_filter)
updateFilterIcon()
}
private fun updateFilterIcon() {
if (currentFilter.value?.isFiltering != true) {
filterMenuItem?.setIcon(R.drawable.ic_action_filter_list)
context?.let {
val filterIcon = ContextCompat.getDrawable(it, R.drawable.ic_action_filter_list)
filterIcon?.setTintWith(it.getThemeColor(R.attr.headerTextColor), PorterDuff.Mode.MULTIPLY)
filterMenuItem?.setIcon(filterIcon)
}
} else {
context?.let {
val filterIcon = ContextCompat.getDrawable(it, R.drawable.ic_filters_active)
filterIcon?.setTintWith(it.getThemeColor(R.attr.textColorPrimaryDark), PorterDuff.Mode.MULTIPLY)
filterMenuItem?.setIcon(filterIcon)
}
}
}
@Suppress("ReturnCount")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_filter -> {
showFilterDialog()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun loadCustomizations() {
val type = this.type ?: return
compositeSubscription.add(
customizationRepository.getCustomizations(type, category, false)
.combineLatest(
currentFilter.toFlowable(BackpressureStrategy.DROP),
ownedCustomizations.toFlowable(BackpressureStrategy.DROP)
)
.subscribe(
{ (customizations, filter, ownedCustomizations) ->
adapter.ownedCustomizations = ownedCustomizations.map { it.key + "_" + it.type + "_" + it.category }
if (filter.isFiltering) {
val displayedCustomizations = mutableListOf<Customization>()
for (customization in customizations) {
if (shouldSkip(filter, ownedCustomizations, customization)) continue
displayedCustomizations.add(customization)
}
adapter.setCustomizations(
if (!filter.ascending) {
displayedCustomizations.reversed()
} else {
displayedCustomizations
}
)
} else {
adapter.setCustomizations(
if (!filter.ascending) {
customizations.reversed()
} else {
customizations
}
)
}
},
ExceptionHandler.rx()
)
)
if (type == "hair" && (category == "beard" || category == "mustache")) {
val otherCategory = if (category == "mustache") "beard" else "mustache"
compositeSubscription.add(customizationRepository.getCustomizations(type, otherCategory, true).subscribe({ adapter.additionalSetItems = it }, ExceptionHandler.rx()))
}
}
private fun shouldSkip(
filter: CustomizationFilter,
ownedCustomizations: List<OwnedCustomization>,
customization: Customization
): Boolean {
return if (filter.onlyPurchased && ownedCustomizations.find { it.key == customization.identifier } == null) {
true
} else filter.months.isNotEmpty() && !filter.months.contains(customization.customizationSet?.substringAfter('.'))
}
fun updateUser(user: User?) {
if (user == null) return
this.updateActiveCustomization(user)
ownedCustomizations.onNext(user.purchased?.customizations?.filter { it.type == this.type && it.purchased })
this.adapter.userSize = user.preferences?.size
this.adapter.hairColor = user.preferences?.hair?.color
this.adapter.gemBalance = user.gemCount
this.adapter.avatar = user
adapter.notifyDataSetChanged()
}
private fun updateActiveCustomization(user: User) {
if (this.type == null || user.preferences == null) {
return
}
val prefs = user.preferences
val activeCustomization = when (this.type) {
"skin" -> prefs?.skin
"shirt" -> prefs?.shirt
"background" -> prefs?.background
"chair" -> prefs?.chair
"hair" -> when (this.category) {
"bangs" -> prefs?.hair?.bangs.toString()
"base" -> prefs?.hair?.base.toString()
"color" -> prefs?.hair?.color
"flower" -> prefs?.hair?.flower.toString()
"beard" -> prefs?.hair?.beard.toString()
"mustache" -> prefs?.hair?.mustache.toString()
else -> ""
}
else -> ""
}
if (activeCustomization != null) {
this.activeCustomization = activeCustomization
this.adapter.activeCustomization = activeCustomization
}
}
override fun onRefresh() {
lifecycleScope.launch(ExceptionHandler.coroutine()) {
userRepository.retrieveUser(true, true)
binding?.refreshLayout?.isRefreshing = false
}
}
fun showFilterDialog() {
val filter = currentFilter.value ?: CustomizationFilter()
val context = context ?: return
val dialog = HabiticaBottomSheetDialog(context)
val binding = BottomSheetBackgroundsFilterBinding.inflate(layoutInflater)
binding.showMeWrapper.check(if (filter.onlyPurchased) R.id.show_purchased_button else R.id.show_all_button)
binding.showMeWrapper.setOnCheckedChangeListener { _, checkedId ->
filter.onlyPurchased = checkedId == R.id.show_purchased_button
currentFilter.onNext(filter)
}
binding.clearButton.setOnClickListener {
currentFilter.onNext(CustomizationFilter(false, type != "background"))
dialog.dismiss()
}
if (type == "background") {
binding.sortByWrapper.check(if (filter.ascending) R.id.oldest_button else R.id.newest_button)
binding.sortByWrapper.setOnCheckedChangeListener { _, checkedId ->
filter.ascending = checkedId == R.id.oldest_button
currentFilter.onNext(filter)
}
configureMonthFilterButton(binding.januaryButton, 1, filter)
configureMonthFilterButton(binding.febuaryButton, 2, filter)
configureMonthFilterButton(binding.marchButton, 3, filter)
configureMonthFilterButton(binding.aprilButton, 4, filter)
configureMonthFilterButton(binding.mayButton, 5, filter)
configureMonthFilterButton(binding.juneButton, 6, filter)
configureMonthFilterButton(binding.julyButton, 7, filter)
configureMonthFilterButton(binding.augustButton, 8, filter)
configureMonthFilterButton(binding.septemberButton, 9, filter)
configureMonthFilterButton(binding.octoberButton, 10, filter)
configureMonthFilterButton(binding.novemberButton, 11, filter)
configureMonthFilterButton(binding.decemberButton, 12, filter)
} else {
binding.sortByTitle.visibility = View.GONE
binding.sortByWrapper.visibility = View.GONE
binding.monthReleasedTitle.visibility = View.GONE
binding.monthReleasedWrapper.visibility = View.GONE
}
dialog.setContentView(binding.root)
dialog.setOnDismissListener { updateFilterIcon() }
dialog.show()
}
private fun configureMonthFilterButton(button: CheckBox, value: Int, filter: CustomizationFilter) {
val identifier = value.toString().padStart(2, '0')
button.isChecked = filter.months.contains(identifier)
button.text
button.setOnCheckedChangeListener { _, isChecked ->
if (!isChecked && filter.months.contains(identifier)) {
button.typeface = Typeface.create("sans-serif", Typeface.NORMAL)
filter.months.remove(identifier)
} else if (isChecked && !filter.months.contains(identifier)) {
button.typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
filter.months.add(identifier)
}
currentFilter.onNext(filter)
}
}
}
| gpl-3.0 | f10b5a7b82fec7a4f79273d0e1ee8b14 | 43.559524 | 177 | 0.635942 | 5.390141 | false | false | false | false |
midhunhk/random-contact | app/src/main/java/com/ae/apps/randomcontact/fragments/RandomContactFragment.kt | 1 | 5120 | package com.ae.apps.randomcontact.fragments
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ae.apps.lib.api.contacts.ContactsApiGateway
import com.ae.apps.lib.api.contacts.types.ContactInfoFilterOptions
import com.ae.apps.lib.api.contacts.types.ContactsDataConsumer
import com.ae.apps.lib.common.models.ContactInfo
import com.ae.apps.lib.common.utils.CommonUtils
import com.ae.apps.lib.common.utils.ContactUtils.showContactInAddressBook
import com.ae.apps.randomcontact.R
import com.ae.apps.randomcontact.adapters.ContactDetailsRecyclerAdapter
import com.ae.apps.randomcontact.contacts.RandomContactApiGatewayImpl
import com.ae.apps.randomcontact.contacts.RandomContactsApiGatewayFactory
import com.ae.apps.randomcontact.databinding.FragmentRandomContactBinding
import com.ae.apps.randomcontact.preferences.AppPreferences
import com.ae.apps.randomcontact.room.AppDatabase
import com.ae.apps.randomcontact.room.repositories.ContactGroupRepositoryImpl
import com.ae.apps.randomcontact.utils.PACKAGE_NAME_WHATSAPP
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
/**
* A simple [Fragment] subclass.
*/
class RandomContactFragment : Fragment(R.layout.fragment_random_contact), ContactsDataConsumer {
companion object {
@Volatile
private var INSTANCE: RandomContactFragment? = null
fun getInstance(): RandomContactFragment =
INSTANCE ?: synchronized(this) {
INSTANCE ?: RandomContactFragment().also { INSTANCE = it }
}
}
private lateinit var contactsApi: ContactsApiGateway
private var currentContact: ContactInfo? = null
private lateinit var binding: FragmentRandomContactBinding
private lateinit var recyclerAdapter: ContactDetailsRecyclerAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentRandomContactBinding.bind(view)
setupRecyclerView()
setupViews()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setUpContactsApi()
}
private fun setUpContactsApi() {
val context = requireActivity()
val repo = ContactGroupRepositoryImpl.getInstance(
AppDatabase.getInstance(context).contactGroupDao()
)
val factory = RandomContactsApiGatewayFactory()
val appPreferences = AppPreferences.getInstance(context)
contactsApi = RandomContactApiGatewayImpl.getInstance(context, repo, factory, appPreferences)
// Initialize the random contact api
contactsApi.initializeAsync(ContactInfoFilterOptions.of(true), this)
}
override fun onContactsRead() {
showRandomContact()
}
private fun setupViews() {
binding.btnRefresh.setOnClickListener {
showRandomContact()
}
binding.btnAddressBook.setOnClickListener {
Toast.makeText(requireContext(), "Opening contact in Contacts app", Toast.LENGTH_SHORT).show()
showContactInAddressBook(requireActivity(), currentContact?.id)
}
}
private fun setupRecyclerView() {
var whatsAppInstalled = false
if (null != requireActivity().packageManager) {
whatsAppInstalled = CommonUtils.checkIfPackageIsInstalled(requireContext(), PACKAGE_NAME_WHATSAPP)
}
recyclerAdapter = ContactDetailsRecyclerAdapter(
emptyList(),
requireContext(),
R.layout.contact_info_item,
whatsAppInstalled
)
val recyclerView: RecyclerView = binding.list
recyclerView.setHasFixedSize(true)
recyclerView.adapter = recyclerAdapter
recyclerView.layoutManager = LinearLayoutManager(requireContext())
recyclerView.itemAnimator = DefaultItemAnimator()
}
private fun showRandomContact() {
// Running the getRandomNumber() method in a background thread as we need to access the database
doAsync {
val randomContact: ContactInfo? = contactsApi.randomContact
// Run the validation on the UI Thread
uiThread {
if (null == randomContact) {
Toast.makeText(
context, resources.getString(R.string.str_empty_contact_list),
Toast.LENGTH_LONG
).show()
} else {
displayContact(randomContact)
}
}
}
}
private fun displayContact(contactInfo: ContactInfo) {
binding.contactName.text = contactInfo.name
binding.contactImage.setImageBitmap(contactInfo.picture)
val phoneNumbersList = contactInfo.phoneNumbersList
recyclerAdapter.setList(phoneNumbersList)
currentContact = contactInfo
}
} | apache-2.0 | 17bcfc0b2b0fedd82c11512c48939cec | 35.841727 | 110 | 0.708008 | 5.054294 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/nfc/NFCSignTransactionActivity.kt | 1 | 3031 | package org.walleth.nfc
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.kethereum.crypto.toAddress
import org.kethereum.extensions.transactions.encode
import org.kethereum.extensions.transactions.encodeLegacyTxRLP
import org.kethereum.keccakshortcut.keccak
import org.kethereum.model.SignedTransaction
import org.koin.android.ext.android.inject
import org.komputing.khex.extensions.toHexString
import org.walleth.data.AppDatabase
import org.walleth.data.REQUEST_CODE_NFC
import org.walleth.data.transactions.TransactionState
import org.walleth.data.transactions.toEntity
import org.walleth.kethereum.android.TransactionParcel
import org.walleth.khartwarewallet.KHardwareChannel
import java.lang.IllegalStateException
private const val KEY_TRANSACTION = "TX"
fun Activity.startNFCSigningActivity(transactionParcel: TransactionParcel) {
val nfcIntent = Intent(this, NFCSignTransactionActivity::class.java).putExtra(KEY_TRANSACTION, transactionParcel)
startActivityForResult(nfcIntent, REQUEST_CODE_NFC)
}
class NFCSignTransactionActivity : NFCBaseActivityWithPINHandling() {
private val appDatabase: AppDatabase by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.subtitle = "Sign Transaction via NFC"
}
override fun afterCorrectPin(channel: KHardwareChannel) {
val address = channel.toPublicKey().toAddress()
val transaction = intent.getParcelableExtra<TransactionParcel>("TX")
when {
transaction == null -> {
throw IllegalStateException("Got no transaction from intent in afterCorrectPin(channel)")
}
transaction.transaction.from != address -> {
setText("The given card does not match the account")
}
else -> {
setText("signing")
val oldHash = transaction.transaction.txHash
val signedTransaction: SignedTransaction = channel.signTransaction(transaction.transaction)
setText("signed")
lifecycleScope.launch(Dispatchers.Main) {
withContext(Dispatchers.Default) {
transaction.transaction.txHash = signedTransaction.encode().keccak().toHexString()
appDatabase.runInTransaction {
oldHash?.let { appDatabase.transactions.deleteByHash(it) }
appDatabase.transactions.upsert(transaction.transaction.toEntity(signedTransaction.signatureData, TransactionState()))
}
}
setResult(RESULT_OK, Intent().apply { putExtra("TXHASH", transaction.transaction.txHash) })
finish()
}
}
}
}
}
| gpl-3.0 | 463134671d83f13253f55ff7983102ed | 37.367089 | 146 | 0.69647 | 5.111298 | false | false | false | false |
realm/realm-java | realm-transformer/src/main/kotlin/io/realm/analytics/UrlEncodedAnalytics.kt | 1 | 2029 | /*
* Copyright 2021 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.analytics
import io.realm.transformer.Utils
import java.io.UnsupportedEncodingException
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.SocketException
import java.net.URL
import java.security.NoSuchAlgorithmException
class UrlEncodedAnalytics private constructor(private val prefix: String, private val suffix: String) {
/**
* Send the analytics event to the server.
*/
fun execute(analytics: AnalyticsData) {
try {
val url = getUrl(analytics)
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.connect()
connection.responseCode
} catch (ignored: Exception) {
}
}
@Throws(
MalformedURLException::class,
SocketException::class,
NoSuchAlgorithmException::class,
UnsupportedEncodingException::class
)
private fun getUrl(analytics: AnalyticsData): URL {
return URL(prefix + Utils.base64Encode(analytics.generateJson()) + suffix)
}
companion object {
fun create(): UrlEncodedAnalytics {
val ADDRESS_PREFIX =
"https://data.mongodb-api.com/app/realmsdkmetrics-zmhtm/endpoint/metric_webhook/metric?data="
val ADDRESS_SUFFIX = ""
return UrlEncodedAnalytics(ADDRESS_PREFIX, ADDRESS_SUFFIX)
}
}
}
| apache-2.0 | 3f5b58cfe8638225733b3018134864af | 32.816667 | 109 | 0.691966 | 4.685912 | false | false | false | false |
k9mail/k-9 | backend/imap/src/main/java/com/fsck/k9/backend/imap/CommandDownloadMessage.kt | 2 | 2198 | package com.fsck.k9.backend.imap
import com.fsck.k9.backend.api.BackendStorage
import com.fsck.k9.mail.FetchProfile
import com.fsck.k9.mail.FetchProfile.Item.BODY
import com.fsck.k9.mail.FetchProfile.Item.ENVELOPE
import com.fsck.k9.mail.FetchProfile.Item.FLAGS
import com.fsck.k9.mail.FetchProfile.Item.STRUCTURE
import com.fsck.k9.mail.MessageDownloadState
import com.fsck.k9.mail.helper.fetchProfileOf
import com.fsck.k9.mail.store.imap.ImapFolder
import com.fsck.k9.mail.store.imap.ImapMessage
import com.fsck.k9.mail.store.imap.ImapStore
import com.fsck.k9.mail.store.imap.OpenMode
internal class CommandDownloadMessage(private val backendStorage: BackendStorage, private val imapStore: ImapStore) {
fun downloadMessageStructure(folderServerId: String, messageServerId: String) {
val folder = imapStore.getFolder(folderServerId)
try {
folder.open(OpenMode.READ_ONLY)
val message = folder.getMessage(messageServerId)
// fun fact: ImapFolder.fetch can't handle getting STRUCTURE at same time as headers
fetchMessage(folder, message, fetchProfileOf(FLAGS, ENVELOPE))
fetchMessage(folder, message, fetchProfileOf(STRUCTURE))
val backendFolder = backendStorage.getFolder(folderServerId)
backendFolder.saveMessage(message, MessageDownloadState.ENVELOPE)
} finally {
folder.close()
}
}
fun downloadCompleteMessage(folderServerId: String, messageServerId: String) {
val folder = imapStore.getFolder(folderServerId)
try {
folder.open(OpenMode.READ_ONLY)
val message = folder.getMessage(messageServerId)
fetchMessage(folder, message, fetchProfileOf(FLAGS, BODY))
val backendFolder = backendStorage.getFolder(folderServerId)
backendFolder.saveMessage(message, MessageDownloadState.FULL)
} finally {
folder.close()
}
}
private fun fetchMessage(remoteFolder: ImapFolder, message: ImapMessage, fetchProfile: FetchProfile) {
val maxDownloadSize = 0
remoteFolder.fetch(listOf(message), fetchProfile, null, maxDownloadSize)
}
}
| apache-2.0 | 97dfb7b81f13f5c109b39f8816576ae0 | 38.963636 | 117 | 0.721565 | 4.14717 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/analysis/DependencyNode.kt | 1 | 4805 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.analysis
import arcs.core.data.AccessPath
import arcs.core.data.expression.Expression
/** Field [Identifier]. */
private typealias Identifier = String
/** Lists of [Identifier]s imply an [AccessPath]. */
private typealias Path = List<Identifier>
/**
* [DependencyNode]s make up a directed-acyclic-graph that describes how input handle connections
* map to output connections in particle specs with Paxel [Expression]s.
*
* - [DependencyNode.Input] represents an input handle connection and access path.
* - [DependencyNode.DerivedFrom] indicates that an input has been modified in the Paxel expression.
* - [DependencyNode.AssociationNode] connects fields to other nodes in the graph. These are used to
* form left-hand-side / right-hand-side relations between handle connections.
*
* Example:
* ```
* particle HousePets
* input: reads PetData { cats: Number, dogs: Number, household: Text }
* output: writes PetStats {
* ratio: inline Domestication {trained: Number, total: Number},
* family: Text,
* limit: Number
* } = new PetStats {
* ratio: new Domestication {
* trained: input.cats,
* total: input.cats + input.dogs,
* },
* family: input.household,
* limit: 5
* }
* ```
*
* This can be translated to:
*
* ```
* DependencyNode.AssociationNode(
* "ratio" to DependencyNode.AssociationNode(
* "trained" to DependencyNode.Input("input", "cats"),
* "total" to DependencyNode.DerivedFrom(
* DependencyNode.Input("input", "cats"),
* DependencyNode.Input("input", "dogs")
* )
* ),
* "family" to DependencyNode.Input("input", "household"),
* "limit" to DependencyNode.LITERAL
* )
* ```
*
* We can represent this DAG graphically:
*
* (root)
* __________|______
* / | \
* / / _(ratio)_
* / / | \
* (limit) (family) (trained) (total)
* | | | / |
* | | | / |
* x (household) (cats) (dogs)
*
* This internal representation, in turn, can be translated into the following claims:
*
* ```
* claim output.ratio.trained derives from input.cats
* claim output.ratio.total derives from input.cats and derives from input.dogs
* claim output.family derives from input.household
* ```
*/
sealed class DependencyNode {
/** An unmodified input (from a handle connection) used in a Paxel [Expression]. */
data class Input(val path: Path = emptyList()) : DependencyNode() {
constructor(vararg fields: Identifier) : this(listOf(*fields))
}
/** Represents derivation from a group of [Input]s in an [Expression]. */
data class DerivedFrom(val inputs: Set<Input> = emptySet()) : DependencyNode() {
constructor(vararg paths: Path) : this(paths.map { Input(it) }.toSet())
/** Produce a new [DerivedFrom] with a flattened set of [Input]s. */
constructor(vararg nodes: DependencyNode) : this(flatten(*nodes))
companion object {
/** Flatten nested sets of [DependencyNode]s.*/
private fun flatten(vararg nodes: DependencyNode): Set<Input> {
return nodes.flatMap { node ->
when (node) {
is Input -> setOf(node)
is DerivedFrom -> node.inputs
else -> throw IllegalArgumentException(
"Nodes must be a 'Input' or 'DerivedFrom'."
)
}
}.toSet()
}
}
}
/** Associates [Identifier]s with [DependencyNode]s. */
data class AssociationNode(
val associations: Map<Identifier, DependencyNode> = emptyMap()
) : DependencyNode() {
/** Construct an [AssociationNode] from associations of [Identifier]s to [DependencyNode]s. */
constructor(vararg pairs: Pair<Identifier, DependencyNode>) : this(pairs.toMap())
/** Replace the associations of an [AssociationNode] with new mappings. */
fun add(vararg other: Pair<Identifier, DependencyNode>): DependencyNode = AssociationNode(
associations + other
)
/** Returns the [DependencyNode] associated with the input [Identifier]. */
fun lookup(key: Identifier): DependencyNode = requireNotNull(associations[key]) {
"Identifier '$key' is not found in AssociationNode."
}
}
companion object {
/** A [DependencyNode] case to represent literals. */
val LITERAL = DerivedFrom()
}
}
| bsd-3-clause | be7336c073ac87c1527c7d1b8cfb502b | 33.568345 | 100 | 0.626847 | 3.95148 | false | false | false | false |
Tandrial/Advent_of_Code | src/Utils.kt | 1 | 2312 | import java.io.File
import java.util.regex.Pattern
import kotlin.math.abs
import kotlin.system.measureTimeMillis
/**
* Returns the alphabetically sorted String
*
* @return The string sorted alphabetically
*/
fun String.sort(): String = this.toCharArray().sorted().joinToString()
/**
* Parses the File contents into a 2D Int
*
* @param delim The delimiter by which the [Int]s are sperated in each line
* @return The file contents parsed to a 2D Int structure
*/
fun File.to2DIntArr(delim: Pattern = "\\s+".toPattern()): List<List<Int>> {
return this.readLines().map { it.toIntList(delim) }
}
/**
* Splits the string into a [List] of [Int].
*
* @param delim The delimiter by which the [Int]s in the string are sperated
* @return [List] of [Int]s
*/
fun String.toIntList(delim: Pattern = "\\s+".toPattern()): List<Int> = this.split(delim).map { it.toInt() }
/**
* Splits the [String] into a [List] or words, where a word is matched bs \w+
*
* @return [List] of matched words
*/
fun String.getWords(): List<String> = Regex("\\w+").findAll(this).toList().map { it.value }
/**
* Splits the [String] into a [List] or numbers, where a word is matched bs -?\d+
*
* @return [List] of matched numbers
*/
fun String.getNumbers(): List<Int> = Regex("-?\\d+").findAll(this).toList().map { it.value.toInt() }
/**
* Converts the [Int]s in the [Iterable] into their hex-Representation and joints them together
*
* @return a [String] of hexValuess
*/
fun Iterable<Int>.toHexString(): String = joinToString(separator = "") { it.toString(16).padStart(2, '0') }
/**
* Combination of [take] and [remove]
*
* @param take How many elements to remove from the [MutableList]
*
* @return a [List] of the taken elements
*/
fun <T : Any> MutableList<T>.removeTake(take: Int): List<T> {
val removed = this.take(take)
repeat(take) { this.removeAt(0) }
return removed
}
fun timeIt(block: () -> Unit) {
println("${measureTimeMillis(block)}ms")
}
/**
* Calculates the difference between the [max] and [min] Value of the elemnts of the List, transfomred by [block]
*
* @param block What to do calculate the difference of
*
* @return difference
*/
fun <T : Any> List<T>.diffBy(block: (T) -> Long): Long {
val values = map(block)
return abs((values.max() ?: 0L) - (values.min() ?: 0L))
}
| mit | 10903c03c8bbafa824471c87528a8741 | 28.265823 | 113 | 0.668685 | 3.256338 | false | false | false | false |
PolymerLabs/arcs | java/arcs/android/host/parcelables/ParcelableAnnotation.kt | 1 | 2502 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.host.parcelables
import android.os.Parcel
import android.os.Parcelable
import arcs.core.data.Annotation
/** [Parcelable] variant of [Annotation]. */
data class ParcelableAnnotation(override val actual: Annotation) : ActualParcelable<Annotation> {
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(actual.name)
parcel.writeMap(
actual.params.mapValues { ParcelableAnnotationParam(it.value) }
)
}
override fun describeContents(): Int = 0
companion object CREATOR : Parcelable.Creator<ParcelableAnnotation> {
override fun createFromParcel(parcel: Parcel): ParcelableAnnotation {
val name = requireNotNull(parcel.readString()) {
"No annotation name found in Parcel"
}
val params = mutableMapOf<String, ParcelableAnnotationParam>()
parcel.readMap(params as Map<*, *>, this::class.java.classLoader)
return ParcelableAnnotation(Annotation(name, params.mapValues { it.value.actual }))
}
override fun newArray(size: Int): Array<ParcelableAnnotation?> = arrayOfNulls(size)
}
}
/** Wraps a [Annotation] as a [ParcelableAnnotation]. */
fun Annotation.toParcelable() = ParcelableAnnotation(this)
/** Writes a [Annotation] to a [Parcel]. */
fun Parcel.writeAnnotation(annotation: Annotation, flags: Int) {
writeTypedObject(annotation.toParcelable(), flags)
}
/** Writes a [Annotation] to a [Parcel]. */
fun Parcel.writeAnnotations(annotations: List<Annotation>, flags: Int) {
writeInt(annotations.size)
annotations.forEach { writeTypedObject(it.toParcelable(), flags) }
}
/** Reads a [Annotation] from a [Parcel]. */
fun Parcel.readAnnotation(): Annotation? {
return readTypedObject(ParcelableAnnotation)?.actual
}
/** Reads a list of [Annotation]s from a [Parcel]. */
fun Parcel.readAnnotations(): List<Annotation> {
val size = requireNotNull(readInt()) {
"No size of Annotations found in Parcel"
}
val annotations = mutableListOf<Annotation>()
repeat(size) { index ->
annotations.add(
requireNotNull(readAnnotation()) {
"No Annotation found at index $index in Parcel, expected length: $size."
}
)
}
return annotations
}
| bsd-3-clause | a3b4a1d0d9ed1df1151e65e0aeaf5e12 | 31.493506 | 97 | 0.719424 | 4.233503 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/data/AccessPath.kt | 1 | 3933 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.data
typealias StoreId = String
/**
* Specifies an access path in a claim or a check.
*
* Examples of access paths are `input.app.packageName`, `store.rawText`, store.entites[i], etc.
*/
data class AccessPath(val root: Root, val selectors: List<Selector> = emptyList()) {
private val hashCode by lazy { 31 * root.hashCode() + selectors.hashCode() }
/**
* Constructs an [AccessPath] starting at a connection in [particle] identified
* by [connectionSpec] followed by [selectors].
*/
constructor(
particle: Recipe.Particle,
connectionSpec: HandleConnectionSpec,
selectors: List<Selector> = emptyList()
) : this(Root.HandleConnection(particle, connectionSpec), selectors)
/** Constructs an [AccessPath] representing a [ParticleSpec.HandleConnectionSpec]. */
constructor(
particleSpecName: String,
connectionSpec: HandleConnectionSpec,
selectors: List<Selector> = emptyList()
) : this(Root.HandleConnectionSpec(particleSpecName, connectionSpec), selectors)
/** Constructs an [AccessPath] representing a [Recipe.Handle]. */
constructor(
handle: Recipe.Handle,
selectors: List<Selector> = emptyList()
) : this(Root.Handle(handle), selectors)
/**
* Represents the root of an [AccessPath].
*
* Some examples of roots are as follows:
* `input` is the root of `input.app.packageName`
* `store` is the root of `store.rawText`
*/
sealed class Root {
data class Handle(val handle: Recipe.Handle) : Root() {
override fun toString() = "h:${handle.name}"
}
data class HandleConnection(
val particle: Recipe.Particle,
val connectionSpec: arcs.core.data.HandleConnectionSpec
) : Root() {
override fun toString() = "hc:${particle.spec.name}.${connectionSpec.name}"
}
data class HandleConnectionSpec(
val particleSpecName: String,
val connectionSpec: arcs.core.data.HandleConnectionSpec
) : Root() {
override fun toString() = "hcs:$particleSpecName.${connectionSpec.name}"
}
data class Store(val storeId: StoreId) : Root() {
override fun toString() = "s:$storeId"
}
}
/** Represents an access to a part of the data (like a field). */
sealed class Selector {
data class Field(val field: FieldName) : Selector() {
override fun toString() = "$field"
}
// TODO(bgogul): Indexing, Dereferencing(?).
}
override fun toString(): String {
if (selectors.isEmpty()) return "$root"
return selectors.joinToString(separator = ".", prefix = "$root.")
}
/** Returns true if this [AccessPath] is a prefix of [other]. */
fun isPrefixOf(other: AccessPath) = when {
root != other.root -> false
selectors.size > other.selectors.size -> false
else -> selectors == other.selectors.subList(0, selectors.size)
}
/**
* Converts an [AccessPath] with [Root.HandleConnectionSpec] as root into a
* [AccessPath] with the corresponding [Root.HandleConnection] as root.
*/
fun instantiateFor(particle: Recipe.Particle): AccessPath {
if (root !is Root.HandleConnectionSpec) return this
require(particle.spec.name == root.particleSpecName) {
"Instantiating an access path for an incompatible particle!"
}
return AccessPath(Root.HandleConnection(particle, root.connectionSpec), selectors)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is AccessPath) return false
if (root != other.root) return false
if (selectors != other.selectors) return false
return true
}
override fun hashCode(): Int = hashCode
}
| bsd-3-clause | 693b57c42c1b580061f82b794f4f0abc | 31.504132 | 96 | 0.682431 | 4.118325 | false | false | false | false |
JStege1206/AdventOfCode | aoc-2017/src/main/kotlin/nl/jstege/adventofcode/aoc2017/days/Day15.kt | 1 | 1819 | package nl.jstege.adventofcode.aoc2017.days
import nl.jstege.adventofcode.aoccommon.days.Day
/**
*
* @author Jelle Stege
*/
class Day15 : Day(title = "Dueling Generators") {
private companion object Configuration {
private const val MASK = 0xFFFFL
private const val DIVISOR = 2147483647
private const val FACTOR_A = 16807L
private const val FACTOR_B = 48271L
private const val FIRST_ITERATIONS = 40_000_000
private const val SECOND_ITERATIONS = 5_000_000
private const val SECOND_MULTIPLES_A = 4L
private const val SECOND_MULTIPLES_B = 8L
}
override fun first(input: Sequence<String>): Any {
return input
.map { it.split(" ") }
.map { (_, _, _, _, init) -> init.toLong() }
.toList()
.let { (a, b) -> Generator(a, FACTOR_A) to Generator(b, FACTOR_B) }
.let { (a, b) ->
(0 until FIRST_ITERATIONS).count { a.next() and MASK == b.next() and MASK }
}
}
override fun second(input: Sequence<String>): Any {
return input
.map { it.split(" ") }
.map { (_, _, _, _, init) -> init.toLong() }
.toList()
.let { (a, b) -> Generator(a, FACTOR_A) to Generator(b, FACTOR_B) }
.let { (a, b) ->
(0 until SECOND_ITERATIONS).count {
a.next(SECOND_MULTIPLES_A) and MASK == b.next(SECOND_MULTIPLES_B) and MASK
}
}
}
private class Generator(init: Long, val factor: Long) {
var current = init
fun next(multiples: Long = 1): Long {
do {
current = (current * factor % DIVISOR)
} while (current % multiples != 0L)
return current
}
}
}
| mit | cf5a5c1efae59d0ee06644ec720793c4 | 30.362069 | 94 | 0.526663 | 3.878465 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/component/HorizontalSliderBuilder.kt | 1 | 1635 | package org.hexworks.zircon.api.builder.component
import org.hexworks.zircon.api.component.Slider
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.internal.component.impl.DefaultHorizontalSlider
import org.hexworks.zircon.internal.component.renderer.HorizontalSliderRenderer
import org.hexworks.zircon.internal.dsl.ZirconDsl
import kotlin.jvm.JvmStatic
@Suppress("UNCHECKED_CAST")
/**
* Builder for a horizontal [Slider]. By default, it creates a slider with
* - [minValue]: `0`
* - [maxValue]: `100`
* - [numberOfSteps]: `10`
*/
@ZirconDsl
class HorizontalSliderBuilder private constructor() : SliderBuilder<Slider, HorizontalSliderBuilder>(
initialRenderer = HorizontalSliderRenderer()
) {
override var numberOfSteps: Int = 10
set(value) {
require(value in 1..maxValue) { "Number of steps must be greater than 0 and smaller than the maxValue" }
preferredContentSize = Size.create(
width = value + 1,
height = 1
)
field = value
}
override fun build(): Slider = DefaultHorizontalSlider(
componentMetadata = createMetadata(),
renderingStrategy = createRenderingStrategy(),
minValue = minValue,
maxValue = maxValue,
numberOfSteps = numberOfSteps,
).attachListeners()
override fun createCopy() = newBuilder()
.withProps(props.copy())
.withMinValue(minValue)
.withMaxValue(maxValue)
.withNumberOfSteps(numberOfSteps)
companion object {
@JvmStatic
fun newBuilder() = HorizontalSliderBuilder()
}
}
| apache-2.0 | 6b0f4d1ad58e2ca03347d2f032e75391 | 31.058824 | 116 | 0.681346 | 4.579832 | false | false | false | false |
android/architecture-components-samples | GithubBrowserSample/app/src/test-common/java/com/android/example/github/util/TestUtil.kt | 1 | 2038 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.github.util
import com.android.example.github.vo.Contributor
import com.android.example.github.vo.Repo
import com.android.example.github.vo.User
object TestUtil {
fun createUser(login: String) = User(
login = login,
avatarUrl = null,
name = "$login name",
company = null,
reposUrl = null,
blog = null
)
fun createRepos(count: Int, owner: String, name: String, description: String): List<Repo> {
return (0 until count).map {
createRepo(
owner = owner + it,
name = name + it,
description = description + it
)
}
}
fun createRepo(owner: String, name: String, description: String) = createRepo(
id = Repo.UNKNOWN_ID,
owner = owner,
name = name,
description = description
)
fun createRepo(id: Int, owner: String, name: String, description: String) = Repo(
id = id,
name = name,
fullName = "$owner/$name",
description = description,
owner = Repo.Owner(owner, null),
stars = 3
)
fun createContributor(repo: Repo, login: String, contributions: Int) = Contributor(
login = login,
contributions = contributions,
avatarUrl = null
).apply {
repoName = repo.name
repoOwner = repo.owner.login
}
}
| apache-2.0 | d307b0fefcb0c4b403226b5625839d0f | 28.970588 | 95 | 0.623651 | 4.272537 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/BlockListItem.kt | 1 | 14093 | package org.wordpress.android.ui.stats.refresh.lists.sections
import android.view.View
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ListItemWithIcon.IconStyle.NORMAL
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.ACTION_CARD
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Text.Clickable
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.ACTIVITY_ITEM
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.BAR_CHART
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.BIG_TITLE
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.CHART_LEGEND
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.CHART_LEGENDS_BLUE
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.CHART_LEGENDS_PURPLE
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.CHIPS
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.COLUMNS
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.DIALOG_BUTTONS
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.DIVIDER
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.EMPTY
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.EXPANDABLE_ITEM
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.GUIDE_CARD
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.HEADER
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.IMAGE_ITEM
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.INFO
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.LINE_CHART
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.LINK
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.LIST_ITEM
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.LIST_ITEM_WITH_ICON
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.LIST_ITEM_WITH_IMAGE
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.LOADING_ITEM
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.MAP
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.MAP_LEGEND
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.PIE_CHART
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.QUICK_SCAN_ITEM
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.REFERRED_ITEM
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.TABS
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.TAG_ITEM
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.TEXT
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.TITLE
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.TITLE_WITH_MORE
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.VALUES_ITEM
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.VALUE_ITEM
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.VALUE_WITH_CHART_ITEM
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValueItem.State.POSITIVE
import org.wordpress.android.ui.utils.ListItemInteraction
sealed class BlockListItem(val type: Type) {
fun id(): Int {
return type.ordinal + Type.values().size * this.itemId
}
open val itemId: Int = 0
enum class Type {
TITLE,
TITLE_WITH_MORE,
BIG_TITLE,
TAG_ITEM,
IMAGE_ITEM,
VALUE_ITEM,
VALUE_WITH_CHART_ITEM,
VALUES_ITEM,
LIST_ITEM,
LIST_ITEM_WITH_ICON,
LIST_ITEM_WITH_IMAGE,
INFO,
EMPTY,
TEXT,
COLUMNS,
CHIPS,
LINK,
BAR_CHART,
PIE_CHART,
LINE_CHART,
CHART_LEGEND,
CHART_LEGENDS_BLUE,
CHART_LEGENDS_PURPLE,
TABS,
HEADER,
MAP,
MAP_LEGEND,
EXPANDABLE_ITEM,
DIVIDER,
LOADING_ITEM,
ACTIVITY_ITEM,
REFERRED_ITEM,
QUICK_SCAN_ITEM,
DIALOG_BUTTONS,
ACTION_CARD,
GUIDE_CARD
}
data class Title(
@StringRes val textResource: Int? = null,
val text: String? = null,
val menuAction: ((View) -> Unit)? = null
) : BlockListItem(TITLE)
data class TitleWithMore(
@StringRes val textResource: Int? = null,
val text: String? = null,
val navigationAction: ListItemInteraction? = null
) : BlockListItem(TITLE_WITH_MORE)
data class BigTitle(
@StringRes val textResource: Int
) : BlockListItem(BIG_TITLE)
data class Tag(
@StringRes val textResource: Int
) : BlockListItem(TAG_ITEM)
data class ImageItem(
@DrawableRes val imageResource: Int
) : BlockListItem(IMAGE_ITEM)
data class ReferredItem(
@StringRes val label: Int,
val itemTitle: String,
val navigationAction: ListItemInteraction? = null
) : BlockListItem(REFERRED_ITEM)
data class ValueItem(
val value: String,
@StringRes val unit: Int,
val isFirst: Boolean = false,
val change: String? = null,
val state: State = POSITIVE,
val contentDescription: String
) : BlockListItem(VALUE_ITEM) {
enum class State { POSITIVE, NEGATIVE, NEUTRAL }
}
data class ValuesItem(
val selectedItem: Int,
val value1: String? = null,
@StringRes val unit1: Int,
val contentDescription1: String? = null,
val value2: String? = null,
@StringRes val unit2: Int,
val contentDescription2: String? = null
) : BlockListItem(VALUES_ITEM)
data class ListItem(
val text: String,
val value: String,
val showDivider: Boolean = true,
val contentDescription: String
) : BlockListItem(LIST_ITEM) {
override val itemId: Int
get() = text.hashCode()
}
data class ListItemWithIcon(
@DrawableRes val icon: Int? = null,
val iconUrl: String? = null,
val iconStyle: IconStyle = NORMAL,
@StringRes val textResource: Int? = null,
val text: String? = null,
@StringRes val valueResource: Int? = null,
val value: String? = null,
val barWidth: Int? = null,
val showDivider: Boolean = true,
val textStyle: TextStyle = TextStyle.NORMAL,
val navigationAction: ListItemInteraction? = null,
val longClickAction: ((View) -> Boolean)? = null,
val contentDescription: String,
@ColorRes val tint: Int? = null
) : BlockListItem(LIST_ITEM_WITH_ICON) {
override val itemId: Int
get() = (icon ?: 0) + (iconUrl?.hashCode() ?: 0) + (textResource ?: 0) + (text?.hashCode() ?: 0)
enum class IconStyle {
NORMAL, AVATAR, EMPTY_SPACE
}
enum class TextStyle {
NORMAL, LIGHT
}
}
data class ListItemWithImage(
val title: String? = null,
val subTitle: String? = null,
val imageUrl: String? = null
) : BlockListItem(LIST_ITEM_WITH_IMAGE)
data class QuickScanItem(
val startColumn: Column,
val endColumn: Column,
val thirdColumn: Column? = null
) : BlockListItem(QUICK_SCAN_ITEM) {
data class Column(
@StringRes val label: Int,
val value: String,
val highest: String? = null,
val tooltip: String? = null
)
}
data class Information(val text: String) : BlockListItem(INFO)
data class Text(
val text: String? = null,
val textResource: Int? = null,
val links: List<Clickable>? = null,
val bolds: List<String>? = null,
val color: Map<Int, String>? = null,
val isLast: Boolean = false
) : BlockListItem(TEXT) {
data class Clickable(
val link: String? = null,
@DrawableRes val icon: Int? = null,
val navigationAction: ListItemInteraction
)
}
data class Columns(
val columns: List<Column>,
val selectedColumn: Int? = null,
val onColumnSelected: ((position: Int) -> Unit)? = null
) : BlockListItem(COLUMNS) {
override val itemId: Int
get() = columns.hashCode()
data class Column(val header: Int, val value: String, val contentDescription: String)
}
data class Chips(
val chips: List<Chip>,
val selectedColumn: Int? = null,
val onColumnSelected: ((position: Int) -> Unit)? = null
) : BlockListItem(CHIPS) {
override val itemId: Int
get() = chips.hashCode()
data class Chip(val header: Int, val contentDescription: String)
}
data class Link(
@DrawableRes val icon: Int? = null,
@StringRes val text: Int,
val navigateAction: ListItemInteraction
) : BlockListItem(LINK)
data class DialogButtons(
@StringRes val positiveButtonText: Int,
val positiveAction: ListItemInteraction,
@StringRes val negativeButtonText: Int,
val negativeAction: ListItemInteraction
) : BlockListItem(DIALOG_BUTTONS)
data class BarChartItem(
val entries: List<Bar>,
val overlappingEntries: List<Bar>? = null,
val selectedItem: String? = null,
val onBarSelected: ((period: String?) -> Unit)? = null,
val onBarChartDrawn: ((visibleBarCount: Int) -> Unit)? = null,
val entryContentDescriptions: List<String>
) : BlockListItem(BAR_CHART) {
data class Bar(val label: String, val id: String, val value: Int)
override val itemId: Int
get() = entries.hashCode()
}
data class PieChartItem(
val entries: List<Pie>,
val totalLabel: String,
val total: String,
val colors: List<Int>,
val contentDescription: String
) : BlockListItem(PIE_CHART) {
data class Pie(val label: String, val value: Int)
override val itemId: Int
get() = entries.hashCode()
}
data class ValueWithChartItem(
val value: String,
val chartValues: List<Long>? = null,
val positive: Boolean? = null,
val extraBottomMargin: Boolean = false
) : BlockListItem(VALUE_WITH_CHART_ITEM)
data class LineChartItem(
val selectedType: Int,
val entries: List<Line>,
val selectedItemPeriod: String? = null,
val onLineSelected: ((period: String?) -> Unit)? = null,
val onLineChartDrawn: ((visibleLineCount: Int) -> Unit)? = null,
val entryContentDescriptions: List<String>
) : BlockListItem(LINE_CHART) {
data class Line(val label: String, val id: String, val value: Int)
override val itemId: Int
get() = entries.hashCode()
}
data class ChartLegend(@StringRes val text: Int) : BlockListItem(CHART_LEGEND)
data class ChartLegendsBlue(
@StringRes val legend1: Int,
@StringRes val legend2: Int
) : BlockListItem(CHART_LEGENDS_BLUE)
data class ChartLegendsPurple(
@StringRes val legend1: Int,
@StringRes val legend2: Int
) : BlockListItem(CHART_LEGENDS_PURPLE)
data class TabsItem(val tabs: List<Int>, val selectedTabPosition: Int, val onTabSelected: (position: Int) -> Unit) :
BlockListItem(TABS) {
override val itemId: Int
get() = tabs.hashCode()
}
data class Header(
@StringRes val startLabel: Int,
@StringRes val endLabel: Int,
val bolds: List<String>? = null
) : BlockListItem(HEADER)
data class ExpandableItem(
val header: ListItemWithIcon,
val isExpanded: Boolean,
val onExpandClicked: (isExpanded: Boolean) -> Unit
) : BlockListItem(
EXPANDABLE_ITEM
) {
override val itemId: Int
get() = header.itemId
}
data class Empty(@StringRes val textResource: Int? = null, val text: String? = null) : BlockListItem(EMPTY)
data class MapItem(val mapData: String, @StringRes val label: Int) : BlockListItem(MAP)
data class MapLegend(val startLegend: String, val endLegend: String) : BlockListItem(MAP_LEGEND)
object Divider : BlockListItem(DIVIDER)
data class LoadingItem(val loadMore: () -> Unit, val isLoading: Boolean = false) : BlockListItem(LOADING_ITEM)
data class ActivityItem(val blocks: List<Block>) : BlockListItem(ACTIVITY_ITEM) {
data class Block(
val label: String,
val boxes: List<Box>,
val contentDescription: String,
val activityContentDescriptions: List<String>
)
enum class Box {
INVISIBLE, VERY_LOW, LOW, MEDIUM, HIGH, VERY_HIGH
}
override val itemId: Int
get() = blocks.fold(0) { acc, block -> acc + block.label.hashCode() }
}
data class ListItemActionCard(
@StringRes val titleResource: Int,
@StringRes val text: Int,
@StringRes val positiveButtonText: Int,
val positiveAction: ListItemInteraction,
@StringRes val negativeButtonText: Int,
val negativeAction: ListItemInteraction
) : BlockListItem(ACTION_CARD)
data class ListItemGuideCard(
val text: String,
val links: List<Clickable>? = null,
val bolds: List<String>? = null
) : BlockListItem(GUIDE_CARD)
}
| gpl-2.0 | 0ded27f61996883060e3d1872f18c4cb | 36.381963 | 120 | 0.669623 | 4.142563 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/pages/PageListFragment.kt | 1 | 5676 | package org.wordpress.android.ui.pages
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.PagesListFragmentBinding
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.ui.ViewPagerFragment
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.DisplayUtils
import org.wordpress.android.util.QuickStartUtilsWrapper
import org.wordpress.android.util.SnackbarSequencer
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.viewmodel.pages.PageListViewModel
import org.wordpress.android.viewmodel.pages.PageListViewModel.PageListType
import org.wordpress.android.viewmodel.pages.PagesViewModel
import org.wordpress.android.widgets.RecyclerItemDecoration
import javax.inject.Inject
class PageListFragment : ViewPagerFragment(R.layout.pages_list_fragment) {
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject internal lateinit var imageManager: ImageManager
@Inject internal lateinit var uiHelper: UiHelpers
@Inject lateinit var dispatcher: Dispatcher
@Inject lateinit var quickStartUtilsWrapper: QuickStartUtilsWrapper
@Inject lateinit var snackbarSequencer: SnackbarSequencer
private lateinit var viewModel: PageListViewModel
private var linearLayoutManager: LinearLayoutManager? = null
private var binding: PagesListFragmentBinding? = null
private val listStateKey = "list_state"
companion object {
private const val typeKey = "type_key"
fun newInstance(listType: PageListType): PageListFragment {
val fragment = PageListFragment()
val bundle = Bundle()
bundle.putSerializable(typeKey, listType)
fragment.arguments = bundle
return fragment
}
}
override fun getScrollableViewForUniqueIdProvision(): View? {
return binding?.recyclerView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val nonNullActivity = requireActivity()
(nonNullActivity.application as? WordPress)?.component()?.inject(this)
with(PagesListFragmentBinding.bind(view)) {
initializeViews(savedInstanceState)
initializeViewModels(nonNullActivity)
}
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
override fun onSaveInstanceState(outState: Bundle) {
linearLayoutManager?.let {
outState.putParcelable(listStateKey, it.onSaveInstanceState())
}
super.onSaveInstanceState(outState)
}
private fun PagesListFragmentBinding.initializeViewModels(activity: FragmentActivity) {
val pagesViewModel = ViewModelProvider(activity, viewModelFactory).get(PagesViewModel::class.java)
val listType = arguments?.getSerializable(typeKey) as PageListType
viewModel = ViewModelProvider(this@PageListFragment, viewModelFactory)
.get(listType.name, PageListViewModel::class.java)
viewModel.start(listType, pagesViewModel)
setupObservers()
}
private fun PagesListFragmentBinding.initializeViews(savedInstanceState: Bundle?) {
val layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false)
savedInstanceState?.getParcelable<Parcelable>(listStateKey)?.let {
layoutManager.onRestoreInstanceState(it)
}
linearLayoutManager = layoutManager
recyclerView.layoutManager = linearLayoutManager
recyclerView.addItemDecoration(RecyclerItemDecoration(0, DisplayUtils.dpToPx(activity, 1)))
}
private fun PagesListFragmentBinding.setupObservers() {
viewModel.pages.observe(viewLifecycleOwner, { data ->
data?.let { setPages(data.first, data.second, data.third) }
})
viewModel.scrollToPosition.observe(viewLifecycleOwner, { position ->
position?.let {
val smoothScroller = object : LinearSmoothScroller(context) {
override fun getVerticalSnapPreference(): Int {
return SNAP_TO_START
}
}.apply { targetPosition = position }
recyclerView.layoutManager?.startSmoothScroll(smoothScroller)
}
})
}
private fun PagesListFragmentBinding.setPages(
pages: List<PageItem>,
isSitePhotonCapable: Boolean,
isSitePrivateAt: Boolean
) {
val adapter: PageListAdapter
if (recyclerView.adapter == null) {
adapter = PageListAdapter(
{ action, page -> viewModel.onMenuAction(action, page, requireContext()) },
{ page -> viewModel.onItemTapped(page) },
{ viewModel.onEmptyListNewPageButtonTapped() },
isSitePhotonCapable,
isSitePrivateAt,
imageManager,
uiHelper
)
recyclerView.adapter = adapter
} else {
adapter = recyclerView.adapter as PageListAdapter
}
adapter.update(pages)
}
fun scrollToPage(localPageId: Int) {
viewModel.onScrollToPageRequested(localPageId)
}
}
| gpl-2.0 | 72caaf59fc265590d2c9883da44960ba | 38.144828 | 106 | 0.703488 | 5.421203 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/utils/AuthenticationUtils.kt | 1 | 2021 | package org.wordpress.android.ui.utils
import android.util.Base64
import org.wordpress.android.fluxc.network.HTTPAuthManager
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken
import org.wordpress.android.fluxc.network.rest.wpcom.site.PrivateAtomicCookie
import org.wordpress.android.util.WPUrlUtils
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class AuthenticationUtils
@Inject constructor(
private val accessToken: AccessToken,
private val httpAuthManager: HTTPAuthManager,
private val userAgent: UserAgent,
private val privateAtomicCookie: PrivateAtomicCookie
) {
@Suppress("ImplicitDefaultLocale")
fun getAuthHeaders(url: String): Map<String, String> {
val headers = mutableMapOf<String, String>()
headers["User-Agent"] = userAgent.userAgent
// add cookie header to Aztec media requests on private Atomic sites
if (privateAtomicCookie.exists() && WPUrlUtils.safeToAddPrivateAtCookie(url, privateAtomicCookie.getDomain())) {
headers[COOKIE_HEADER_NAME] = privateAtomicCookie.getCookieContent()
}
if (WPUrlUtils.safeToAddWordPressComAuthToken(url)) {
if (accessToken.exists()) {
headers[AUTHORIZATION_HEADER_NAME] = "Bearer " + accessToken.get()
}
} else {
// Check if we had HTTP Auth credentials for the root url
val httpAuthModel = httpAuthManager.getHTTPAuthModel(url)
if (httpAuthModel != null) {
val creds = String.format("%s:%s", httpAuthModel.username, httpAuthModel.password)
val auth = "Basic " + Base64.encodeToString(creds.toByteArray(), Base64.NO_WRAP)
headers[AUTHORIZATION_HEADER_NAME] = auth
}
}
return headers
}
companion object {
const val AUTHORIZATION_HEADER_NAME = "Authorization"
const val COOKIE_HEADER_NAME = "Cookie"
}
}
| gpl-2.0 | cde313992fec78c4317aaeb6475c73d2 | 39.42 | 120 | 0.694706 | 4.461369 | false | false | false | false |
MER-GROUP/intellij-community | plugins/settings-repository/src/settings/IcsSettings.kt | 4 | 3483 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.ObjectWriter
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import com.intellij.util.Time
import java.io.File
private val DEFAULT_COMMIT_DELAY = 10 * Time.MINUTE
class MyPrettyPrinter : DefaultPrettyPrinter() {
init {
_arrayIndenter = DefaultPrettyPrinter.NopIndenter.instance
}
override fun createInstance() = MyPrettyPrinter()
override fun writeObjectFieldValueSeparator(jg: JsonGenerator) {
jg.writeRaw(": ")
}
override fun writeEndObject(jg: JsonGenerator, nrOfEntries: Int) {
if (!_objectIndenter.isInline) {
--_nesting
}
if (nrOfEntries > 0) {
_objectIndenter.writeIndentation(jg, _nesting)
}
jg.writeRaw('}')
}
override fun writeEndArray(jg: JsonGenerator, nrOfValues: Int) {
if (!_arrayIndenter.isInline) {
--_nesting
}
jg.writeRaw(']')
}
}
fun saveSettings(settings: IcsSettings, settingsFile: File) {
val serialized = ObjectMapper().writer<ObjectWriter>(MyPrettyPrinter()).writeValueAsBytes(settings)
if (serialized.size() <= 2) {
FileUtil.delete(settingsFile)
}
else {
FileUtil.writeToFile(settingsFile, serialized)
}
}
fun loadSettings(settingsFile: File): IcsSettings {
if (!settingsFile.exists()) {
return IcsSettings()
}
val settings = ObjectMapper().readValue(settingsFile, IcsSettings::class.java)
if (settings.commitDelay <= 0) {
settings.commitDelay = DEFAULT_COMMIT_DELAY
}
return settings
}
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
class IcsSettings {
var shareProjectWorkspace = false
var commitDelay = DEFAULT_COMMIT_DELAY
var doNoAskMapProject = false
var readOnlySources: List<ReadonlySource> = SmartList()
var autoSync = true
}
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
class ReadonlySource(var url: String? = null, var active: Boolean = true) {
@JsonIgnore
val path: String?
get() {
if (url == null) {
return null
}
else {
var fileName = PathUtilRt.getFileName(url!!)
val suffix = ".git"
if (fileName.endsWith(suffix)) {
fileName = fileName.substring(0, fileName.length - suffix.length)
}
// the convention is that the .git extension should be used for bare repositories
return "${FileUtil.sanitizeFileName(fileName, false)}.${Integer.toHexString(url!!.hashCode())}.git"
}
}
} | apache-2.0 | 620115b5a7cd74d6d6dfb3e99e2f789d | 29.831858 | 107 | 0.725237 | 4.221818 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/DefaultValueEntity.kt | 1 | 1804 | // 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.storage.entities.test.api
import com.intellij.workspaceModel.deft.api.annotations.Default
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.WorkspaceEntity
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.storage.MutableEntityStorage
interface DefaultValueEntity: WorkspaceEntity {
val name: String
val isGenerated: Boolean
@Default get() = true
val anotherName: String
@Default get() = "Another Text"
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: DefaultValueEntity, ModifiableWorkspaceEntity<DefaultValueEntity>, ObjBuilder<DefaultValueEntity> {
override var name: String
override var entitySource: EntitySource
override var isGenerated: Boolean
override var anotherName: String
}
companion object: Type<DefaultValueEntity, Builder>() {
operator fun invoke(name: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): DefaultValueEntity {
val builder = builder()
builder.name = name
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: DefaultValueEntity, modification: DefaultValueEntity.Builder.() -> Unit) = modifyEntity(DefaultValueEntity.Builder::class.java, entity, modification)
//endregion | apache-2.0 | 47458f89e8a0f2e2874bcf1a4bcbfad7 | 39.111111 | 195 | 0.768847 | 4.942466 | false | false | false | false |
micolous/metrodroid | src/jvmCommonMain/kotlin/au/id/micolous/metrodroid/serializers/XmlPullParserIterator.kt | 1 | 5776 | package au.id.micolous.metrodroid.serializers
import au.id.micolous.metrodroid.card.Card
import kotlinx.io.IOException
import kotlinx.io.InputStream
import kotlinx.io.StringWriter
import kotlinx.io.charsets.Charsets
import org.jetbrains.annotations.NonNls
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import org.xmlpull.v1.XmlPullParserFactory
import org.xmlpull.v1.XmlSerializer
import java.util.NoSuchElementException
private object XmlPullFactory {
private val factory: XmlPullParserFactory = XmlPullParserFactory.newInstance()
init {
factory.isNamespaceAware = true
}
fun newPullParser(): XmlPullParser = factory.newPullParser()
fun newSerializer(): XmlSerializer = factory.newSerializer()
}
internal fun iterateXmlCards(stream: InputStream, iter: (String) -> Card?): Iterator<Card> {
val xpp = XmlPullFactory.newPullParser()
val reader = stream.reader(Charsets.UTF_8)
xpp.setInput(reader)
return IteratorTransformerNotNull(XmlPullParserIterator(xpp), iter)
}
private class XmlPullParserIterator(
//private static final String FEATURE_XML_ROUNDTRIP = "http://xmlpull.org/v1/doc/features.html#xml-roundtrip";
private val mxpp: XmlPullParser)// Not on Android :(
//xpp.setFeature(FEATURE_XML_ROUNDTRIP, true);
: Iterator<String> {
@NonNls
private var mRootTag: String? = null
private var mSerializer: XmlSerializer? = null
private var mCurrentCard: StringWriter? = null
private var mCardDepth = 0
override fun next(): String {
try {
if (mSerializer != null || prepareMore()) {
if (mSerializer == null) {
throw NoSuchElementException()
}
val o = mCurrentCard!!.toString()
mCurrentCard = null
mSerializer = null
return o
} else {
throw NoSuchElementException()
}
} catch (e: IOException) {
throw RuntimeException(e)
} catch (e: XmlPullParserException) {
throw RuntimeException(e)
}
}
override fun hasNext(): Boolean {
try {
return prepareMore()
} catch (e: IOException) {
throw RuntimeException(e)
} catch (e: XmlPullParserException) {
throw RuntimeException(e)
}
}
private fun newCard() {
mCurrentCard = StringWriter()
mSerializer = XmlPullFactory.newSerializer().also {
it.setOutput(mCurrentCard)
it.startDocument(null, false)
}
copyStartTag()
}
private fun copyStartTag() {
mSerializer!!.startTag(mxpp.namespace, mxpp.name)
for (i in 0 until mxpp.attributeCount) {
mSerializer!!.attribute(mxpp.getAttributeNamespace(i),
mxpp.getAttributeName(i),
filterBadXMLChars(mxpp.getAttributeValue(i)))
}
}
private fun copyEndTag() {
mSerializer!!.endTag(mxpp.namespace, mxpp.name)
}
private fun copyText() {
mSerializer!!.text(filterBadXMLChars(mxpp.text))
}
private fun isCard(s: String) = s.toLowerCase() == "card"
@SuppressWarnings("CallToSuspiciousStringMethod")
private fun prepareMore(): Boolean {
var eventType = mxpp.eventType
while (eventType != XmlPullParser.END_DOCUMENT) {
if (mRootTag == null) {
if (eventType == XmlPullParser.START_TAG) {
// We have an root tag!
mRootTag = mxpp.name
when (mRootTag?.toLowerCase()) {
"card" -> newCard()
"cards" -> {}
else -> {
// Unexpected content
throw XmlPullParserException("Unexpected document root: ${mxpp.name}")
}
}
// Handled
}
// Ignore other events.
} else if (mSerializer == null) {
when (eventType) {
XmlPullParser.START_TAG -> if (isCard(mxpp.getName())) {
newCard()
} else {
// Unexpected start tag
throw XmlPullParserException("Unexpected start tag: " + mxpp.getName())
}
XmlPullParser.END_TAG -> {
}
}// We got to the end!
} else {
// There is a card currently processing.
when (eventType) {
XmlPullParser.END_TAG -> {
copyEndTag()
if (isCard(mxpp.name)) {
if (mCardDepth > 0) {
mCardDepth--
} else {
// End tag for card
mSerializer!!.endDocument()
mxpp.next()
return true
}
}
}
XmlPullParser.START_TAG -> {
copyStartTag()
if (isCard(mxpp.name)) {
mCardDepth++
}
}
XmlPullParser.TEXT -> copyText()
}
}
eventType = mxpp.next()
}
// End of document
if (mCardDepth > 0 || mCurrentCard != null) {
throw XmlPullParserException("unexpected document end")
}
return false
}
}
| gpl-3.0 | df94dbd482a36e7f0be018b7678b68dc | 30.911602 | 118 | 0.519044 | 5.175627 | false | false | false | false |
rtugores/zanahoria | app/src/main/java/huitca1212/cuantotemide/SplashActivity.kt | 1 | 1345 | package huitca1212.cuantotemide
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import com.google.android.gms.ads.MobileAds
class SplashActivity : Activity() {
private var active = true
private var splashTime = 2000
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
MobileAds.initialize(this)
val splashTread: Thread = object : Thread() {
override fun run() {
try {
var waited = 0
while (active && waited < splashTime) {
sleep(100)
if (active) {
waited += 100
}
}
} catch (e: InterruptedException) {
// do nothing
} finally {
startActivity(Intent(this@SplashActivity, MainActivity::class.java))
finish()
}
}
}
splashTread.start()
}
override fun onTouchEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_DOWN) {
active = false
}
return true
}
}
| gpl-3.0 | 36c692efb91a7517a16f1ce4028ee941 | 27.617021 | 88 | 0.526394 | 5.233463 | false | false | false | false |
zaren678/android-HomeTeachingHelper | app/src/main/kotlin/com/zaren/hometeachinghelper/homeTeaching/HomeTeachingAssignmentList.kt | 1 | 1565 | package com.zaren.hometeachinghelper.homeTeaching
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.view.View
import com.zaren.hometeachinghelper.R
import android.support.v7.widget.RecyclerView
import com.zaren.hometeachinghelper.widget.CursorRecyclerViewAdapter
import android.content.Context
import android.database.Cursor
/**
* Created by John on 3/15/2015.
*/
public class HomeTeachingAssignmentList : Fragment()
{
var mRecyclerView: View? = null;
override fun onCreateView(aInflater: LayoutInflater?, aContainer: ViewGroup?, aSavedInstanceState: Bundle?): View?
{
if( aInflater != null )
{
var theView = aInflater.inflate( R.layout.fragment_home_teaching_assignments, aContainer, false );
mRecyclerView = theView.findViewById( R.id.recycler_view );
//mAdapter = HomeTeachingAssignmentAdapter()
return theView;
}
return null;
}
}
class HomeTeachingAssignmentAdapter( aContext: Context, aCursor: Cursor ) : CursorRecyclerViewAdapter< HomeTeachingAssignmentAdapter.ViewHolder >( aContext, aCursor )
{
override fun onBindViewHolder(viewHolder: ViewHolder?, cursor: Cursor?)
{
throw UnsupportedOperationException()
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder?
{
throw UnsupportedOperationException()
}
class ViewHolder( aView: View ) : RecyclerView.ViewHolder( aView )
{
}
}
| apache-2.0 | 974a4b4889357cd4f9682341ece95139 | 29.096154 | 166 | 0.726518 | 4.323204 | false | false | false | false |
WeAreFrancis/auth-service | src/main/kotlin/com/wearefrancis/auth/service/LoginService.kt | 1 | 1041 | package com.wearefrancis.auth.service
import com.wearefrancis.auth.dto.JwtDTO
import com.wearefrancis.auth.exception.BadCredentialsException
import com.wearefrancis.auth.repository.UserRepository
import com.wearefrancis.auth.security.JwtUtils
import org.slf4j.LoggerFactory
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Service
@Service
class LoginService(
val jwtUtils: JwtUtils,
val passwordEncoder: BCryptPasswordEncoder,
val userRepository: UserRepository
) {
companion object {
val logger = LoggerFactory.getLogger(LoginService::class.java)!!
}
fun login(username: String, password: String): JwtDTO {
val user = userRepository.findByUsername(username)
if (user == null || !passwordEncoder.matches(password, user.password)) {
throw BadCredentialsException()
}
val jwt = JwtDTO(jwtUtils.generateJwt(user))
logger.info("JWT for $username generated")
return jwt
}
} | apache-2.0 | bd321884a604be21350c8b175a65b5b1 | 33.733333 | 80 | 0.738713 | 4.626667 | false | false | false | false |
florent37/Flutter-AssetsAudioPlayer | android/src/main/kotlin/com/github/florent37/assets_audio_player/AssetsAudioPlayerPlugin.kt | 1 | 25485 | package com.github.florent37.assets_audio_player
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.SystemClock
import android.util.Log
import android.view.KeyEvent
import androidx.annotation.NonNull
import com.github.florent37.assets_audio_player.headset.HeadsetStrategy
import com.github.florent37.assets_audio_player.notification.*
import com.github.florent37.assets_audio_player.playerimplem.PlayerFinder
import com.github.florent37.assets_audio_player.stopwhencall.AudioFocusStrategy
import com.github.florent37.assets_audio_player.stopwhencall.HeadsetManager
import com.github.florent37.assets_audio_player.stopwhencall.StopWhenCall
import com.github.florent37.assets_audio_player.stopwhencall.StopWhenCallAudioFocus
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.PluginRegistry
internal val METHOD_POSITION = "player.position"
internal val METHOD_VOLUME = "player.volume"
internal val METHOD_FORWARD_REWIND_SPEED = "player.forwardRewind"
internal val METHOD_PLAY_SPEED = "player.playSpeed"
internal val METHOD_PITCH = "player.pitch"
internal val METHOD_FINISHED = "player.finished"
internal val METHOD_IS_PLAYING = "player.isPlaying"
internal val METHOD_IS_BUFFERING = "player.isBuffering"
internal val METHOD_CURRENT = "player.current"
internal val METHOD_AUDIO_SESSION_ID = "player.audioSessionId"
internal val METHOD_NEXT = "player.next"
internal val METHOD_PREV = "player.prev"
internal val METHOD_PLAY_OR_PAUSE = "player.playOrPause"
internal val METHOD_NOTIFICATION_STOP = "player.stop"
internal val METHOD_ERROR = "player.error"
class AssetsAudioPlayerPlugin : FlutterPlugin, PluginRegistry.NewIntentListener, ActivityAware {
var myActivity: Activity? = null
var notificationChannel: MethodChannel? = null
companion object {
var instance: AssetsAudioPlayerPlugin? = null
var displayLogs = false
}
var assetsAudioPlayer: AssetsAudioPlayer? = null
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
if(instance != null)return // bug fix
instance = this
notificationChannel = MethodChannel(flutterPluginBinding.binaryMessenger, "assets_audio_player_notification")
assetsAudioPlayer = AssetsAudioPlayer(
flutterAssets = flutterPluginBinding.flutterAssets,
context = flutterPluginBinding.applicationContext,
messenger = flutterPluginBinding.binaryMessenger
)
assetsAudioPlayer!!.register();
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
assetsAudioPlayer?.unregister()
instance = null
}
private fun sendNotificationPayloadMessage(intent: Intent): Boolean? {
if (NotificationAction.ACTION_SELECT == intent.action) {
val trackId = intent.getStringExtra(NotificationService.TRACK_ID)
notificationChannel?.invokeMethod("selectNotification", trackId)
return true
}
return false
}
override fun onNewIntent(intent: Intent): Boolean {
if (intent == null)
return false
if (!intent.getBooleanExtra("isVisited", false)) {
val res = sendNotificationPayloadMessage(intent) ?: false
if (res && myActivity != null) {
myActivity?.intent = intent
intent.putExtra("isVisited", true)
}
return res
}
return false
}
override fun onDetachedFromActivity() {
myActivity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
binding.addOnNewIntentListener(this)
myActivity = binding.activity
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
binding.addOnNewIntentListener(this)
myActivity = binding.activity;
}
override fun onDetachedFromActivityForConfigChanges() {
myActivity = null
}
}
class AssetsAudioPlayer(
private val context: Context,
private val messenger: BinaryMessenger,
private val flutterAssets: FlutterPlugin.FlutterAssets
) : MethodCallHandler {
private var stopWhenCall = StopWhenCallAudioFocus(context)
private var headsetManager = HeadsetManager(context)
private val notificationManager = NotificationManager(context)
private val uriResolver = UriResolver(context)
private var mediaButtonsReceiver: MediaButtonsReceiver? = null
private val stopWhenCallListener = object : StopWhenCall.Listener {
override fun onPhoneStateChanged(audioState: StopWhenCall.AudioState) {
players.values.forEach {
it.updateEnableToPlay(audioState)
}
}
}
private val onHeadsetPluggedListener = { plugged: Boolean ->
players.values.forEach {
it.onHeadsetPlugged(plugged)
}
}
private var lastPlayerIdWithNotificationEnabled: String? = null
fun register() {
stopWhenCall.register(stopWhenCallListener)
headsetManager.onHeadsetPluggedListener = onHeadsetPluggedListener
headsetManager.start()
mediaButtonsReceiver = MediaButtonsReceiver(context,
onAction = {
onMediaButton(it)
},
onNotifSeek = { position ->
onNotifSeekPlayer(position)
}
)
val channel = MethodChannel(messenger, "assets_audio_player")
channel.setMethodCallHandler(this)
//stopWhenCall?.requestAudioFocus()
}
fun unregister() {
stopWhenCall.stop()
notificationManager.hideNotificationService(definitively = true)
stopWhenCall.unregister(stopWhenCallListener)
players.values.forEach {
it.stop()
}
players.clear()
}
private val players = mutableMapOf<String, Player>()
fun getPlayer(id: String): Player? {
return this.players[id]
}
private fun getOrCreatePlayer(id: String): Player {
return players.getOrPut(id) {
val channel = MethodChannel(messenger, "assets_audio_player/$id")
val player = Player(
context = context,
id = id,
notificationManager = notificationManager,
stopWhenCall = stopWhenCall,
flutterAssets = flutterAssets
)
player.apply {
onVolumeChanged = { volume ->
channel.invokeMethod(METHOD_VOLUME, volume)
}
onForwardRewind = { speed ->
channel.invokeMethod(METHOD_FORWARD_REWIND_SPEED, speed)
}
onPlaySpeedChanged = { speed ->
channel.invokeMethod(METHOD_PLAY_SPEED, speed)
}
onPitchChanged = { pitch ->
channel.invokeMethod(METHOD_PITCH, pitch)
}
onPositionMSChanged = { positionMS ->
channel.invokeMethod(METHOD_POSITION, positionMS)
}
onReadyToPlay = { totalDurationMs ->
channel.invokeMethod(METHOD_CURRENT, mapOf(
"totalDurationMs" to totalDurationMs)
)
}
onSessionIdFound = { sessionId ->
channel.invokeMethod(METHOD_AUDIO_SESSION_ID, sessionId)
}
onPlaying = {
channel.invokeMethod(METHOD_IS_PLAYING, it)
}
onBuffering = {
channel.invokeMethod(METHOD_IS_BUFFERING, it)
}
onFinished = {
channel.invokeMethod(METHOD_FINISHED, null)
}
onPrev = {
channel.invokeMethod(METHOD_PREV, null)
}
onNext = {
channel.invokeMethod(METHOD_NEXT, null)
}
onStop = {
channel.invokeMethod(METHOD_CURRENT, null)
}
onNotificationPlayOrPause = {
channel.invokeMethod(METHOD_PLAY_OR_PAUSE, null)
}
onNotificationStop = {
channel.invokeMethod(METHOD_NOTIFICATION_STOP, null)
}
onError = {
channel.invokeMethod(METHOD_ERROR, mapOf(
"type" to it.type,
"message" to it.message
))
}
}
return@getOrPut player
}
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"isPlaying" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
getOrCreatePlayer(id).let { player ->
result.success(player.isPlaying)
}
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"play" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
getOrCreatePlayer(id).play()
result.success(null)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"pause" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
getOrCreatePlayer(id).pause()
result.success(null)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"stop" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
val removeNotification = args["removeNotification"] as? Boolean ?: true
getOrCreatePlayer(id).stop(removeNotification = removeNotification)
result.success(null)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"volume" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
val volume = args["volume"] as? Double ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Double.", null)
return
}
getOrCreatePlayer(id).setVolume(volume)
result.success(null)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"playSpeed" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
val speed = args["playSpeed"] as? Double ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Double.", null)
return
}
getOrCreatePlayer(id).setPlaySpeed(speed)
result.success(null)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"pitch" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
val pitch = args["pitch"] as? Double ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Double.", null)
return
}
getOrCreatePlayer(id).setPitch(pitch)
result.success(null)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"showNotification" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
val show = args["show"] as? Boolean ?: run {
result.error("WRONG_FORMAT", "The specified argument (show) must be an Boolean.", null)
return
}
getOrCreatePlayer(id).showNotification(show)
result.success(null)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"forwardRewind" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
val speed = args["speed"] as? Double ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Double.", null)
return
}
getOrCreatePlayer(id).forwardRewind(speed)
result.success(null)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"seek" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
val to = args["to"] as? Int ?: run {
result.error("WRONG_FORMAT", "The specified argument(to) must be an int.", null)
return
}
getOrCreatePlayer(id).seek(to * 1L)
result.success(null)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"loopSingleAudio" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
val loop = args["loop"] as? Boolean ?: run {
result.error("WRONG_FORMAT", "The specified argument(loop) must be an Boolean.", null)
return
}
getOrCreatePlayer(id).loopSingleAudio(loop)
result.success(null)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"onAudioUpdated" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
val path = args["path"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument(path) must be an String.", null)
return
}
val audioMetas = fetchAudioMetas(args)
getOrCreatePlayer(id).onAudioUpdated(path, audioMetas)
result.success(null)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"forceNotificationForGroup" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String
val isPlaying = args["isPlaying"] as? Boolean ?: run {
result.error("WRONG_FORMAT", "The specified argument(isPlaying) must be an Boolean.", null)
return
}
val display = args["display"] as? Boolean ?: run {
result.error("WRONG_FORMAT", "The specified argument(display) must be an Boolean.", null)
return
}
val audioMetas = fetchAudioMetas(args)
val notificationSettings = fetchNotificationSettings(args)
if (!display) {
notificationManager.stopNotification()
} else if (id != null) {
getOrCreatePlayer(id).forceNotificationForGroup(
audioMetas = audioMetas,
isPlaying = isPlaying,
display = display,
notificationSettings = notificationSettings
)
}
result.success(null)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
"open" -> {
(call.arguments as? Map<*, *>)?.let { args ->
val id = args["id"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument (id) must be an String.", null)
return
}
val path = (args["path"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an String `path`", null)
return
}).let {
uriResolver.audioPath(it)
}
val assetPackage = args["package"] as? String
val audioType = args["audioType"] as? String ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<String, Any> containing a `audioType`", null)
return
}
val volume = args["volume"] as? Double ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<String, Any> containing a `volume`", null)
return
}
val playSpeed = args["playSpeed"] as? Double ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<String, Any> containing a `playSpeed`", null)
return
}
val pitch = args["pitch"] as? Double ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<String, Any> containing a `pitch`", null)
return
}
val autoStart = args["autoStart"] as? Boolean ?: true
val displayNotification = args["displayNotification"] as? Boolean ?: false
val respectSilentMode = args["respectSilentMode"] as? Boolean ?: false
val seek = args["seek"] as? Int?
val networkHeaders = args["networkHeaders"] as? Map<*, *>?
val drmConfiguration = args["drmConfiguration"] as? Map<*, *>?
val notificationSettings = fetchNotificationSettings(args)
val audioMetas = fetchAudioMetas(args).let { meta ->
meta.copy(
image = meta.image?.let { img ->
img.copy(
imagePath = uriResolver.imagePath(img.imagePath)
)
}
)
}
val audioFocusStrategy = AudioFocusStrategy.from(args["audioFocusStrategy"] as? Map<*, *>)
val headsetStrategy = HeadsetStrategy.from(args["headPhoneStrategy"] as? String)
getOrCreatePlayer(id).open(
assetAudioPath = path,
assetAudioPackage = assetPackage,
audioType = audioType,
autoStart = autoStart,
volume = volume,
seek = seek,
respectSilentMode = respectSilentMode,
displayNotification = displayNotification,
notificationSettings = notificationSettings,
result = result,
playSpeed = playSpeed,
pitch = pitch,
audioMetas = audioMetas,
headsetStrategy = headsetStrategy,
audioFocusStrategy = audioFocusStrategy,
networkHeaders = networkHeaders,
context = context,
drmConfiguration = drmConfiguration
)
} ?: run {
result.error("WRONG_FORMAT", "The specified argument must be an Map<*, Any>.", null)
return
}
}
else -> result.notImplemented()
}
}
fun registerLastPlayerWithNotif(playerId: String) {
this.lastPlayerIdWithNotificationEnabled = playerId
}
fun onMediaButton(action: MediaButtonsReceiver.MediaButtonAction) {
lastPlayerIdWithNotificationEnabled
?.let {
getPlayer(it)
}?.let { player ->
when (action) {
MediaButtonsReceiver.MediaButtonAction.play -> player.askPlayOrPause()
MediaButtonsReceiver.MediaButtonAction.pause -> player.askPlayOrPause()
MediaButtonsReceiver.MediaButtonAction.playOrPause -> player.askPlayOrPause()
MediaButtonsReceiver.MediaButtonAction.next -> player.next()
MediaButtonsReceiver.MediaButtonAction.prev -> player.prev()
MediaButtonsReceiver.MediaButtonAction.stop -> player.askStop()
}
}
}
fun onNotifSeekPlayer(toMs: Long) {
lastPlayerIdWithNotificationEnabled
?.let {
getPlayer(it)
}?.seek(toMs)
}
}
| apache-2.0 | d5fc44fdd8f261173b9ce3fdf2735efe | 42.713551 | 137 | 0.504375 | 5.461852 | false | false | false | false |
hzsweers/CatchUp | libraries/smmry/src/main/kotlin/io/sweers/catchup/smmry/model/SmmryDatabase.kt | 1 | 1457 | /*
* Copyright (C) 2019. Zac Sweers
*
* 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 io.sweers.catchup.smmry.model
import androidx.annotation.Keep
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.RoomDatabase
private const val TABLE = "smmryEntries"
@Keep
@Entity(tableName = TABLE)
data class SmmryStorageEntry(
@PrimaryKey val url: String,
val json: String
)
@Dao
interface SmmryDao {
@Query("SELECT * FROM $TABLE WHERE url = :url")
suspend fun getItem(url: String): SmmryStorageEntry?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun putItem(item: SmmryStorageEntry)
}
@Database(
entities = [SmmryStorageEntry::class],
version = 1
)
abstract class SmmryDatabase : RoomDatabase() {
abstract fun dao(): SmmryDao
}
| apache-2.0 | 6986720c4e3e01a1140e1f4a8558b60c | 25.981481 | 75 | 0.75978 | 3.804178 | false | false | false | false |
shogo4405/HaishinKit.java | haishinkit/src/main/java/com/haishinkit/rtmp/message/RtmpMessage.kt | 1 | 1833 | package com.haishinkit.rtmp.message
import androidx.core.util.Pools
import com.haishinkit.rtmp.RtmpConnection
import java.nio.ByteBuffer
internal open class RtmpMessage(val type: Byte, private val pool: Pools.Pool<RtmpMessage>? = null) {
var chunkStreamID: Short = 0
var streamID: Int = 0
var timestamp: Int = 0
open var payload: ByteBuffer = EMPTY_BYTE_BUFFER
get() {
if (field.capacity() < length) {
field = ByteBuffer.allocate(length)
} else {
field.limit(length)
}
return field
}
open var length: Int = -1
open fun encode(buffer: ByteBuffer): RtmpMessage {
TODO("$TAG#encode")
}
open fun decode(buffer: ByteBuffer): RtmpMessage {
TODO("$TAG#decode")
}
open fun execute(connection: RtmpConnection): RtmpMessage {
TODO("$TAG#execute")
}
open fun release(): Boolean {
return pool?.release(this) ?: false
}
companion object {
const val TYPE_CHUNK_SIZE: Byte = 0x01
const val TYPE_ABORT: Byte = 0x02
const val TYPE_ACK: Byte = 0x03
const val TYPE_USER: Byte = 0x04
const val TYPE_WINDOW_ACK: Byte = 0x05
const val TYPE_BANDWIDTH: Byte = 0x06
const val TYPE_AUDIO: Byte = 0x08
const val TYPE_VIDEO: Byte = 0x09
const val TYPE_AMF3_DATA: Byte = 0x0F
const val TYPE_AMF3_SHARED: Byte = 0x10
const val TYPE_AMF3_COMMAND: Byte = 0x11
const val TYPE_AMF0_DATA: Byte = 0x12
const val TYPE_AMF0_SHARED: Byte = 0x13
const val TYPE_AMF0_COMMAND: Byte = 0x14
const val TYPE_AGGREGATE: Byte = 0x16
val EMPTY_BYTE_BUFFER: ByteBuffer = ByteBuffer.allocate(0)
private val TAG = RtmpMessage::class.java.simpleName
}
}
| bsd-3-clause | 23473c0dde0f2eae25ee9e6c45ffc92e | 30.603448 | 100 | 0.613748 | 3.810811 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/interactors/encryption/data/Encryption.kt | 1 | 5221 | package com.onyx.interactors.encryption.data
import javax.crypto.*
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import java.io.UnsupportedEncodingException
import java.security.*
import java.security.spec.InvalidKeySpecException
import java.nio.charset.Charset
import java.security.MessageDigest
class Encryption private constructor(private val mBuilder: Builder) {
private val encryptionCipher: Cipher by lazy {
val secretKey = getSecretKey(hashTheKey(mBuilder.key))
val cipher = Cipher.getInstance(mBuilder.algorithm!!)
cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.ivParameterSpec, mBuilder.secureRandom)
return@lazy cipher
}
private val decryptionCipher: Cipher by lazy {
val secretKey = getSecretKey(hashTheKey(mBuilder.key))
val cipher = Cipher.getInstance(mBuilder.algorithm!!)
cipher.init(Cipher.DECRYPT_MODE, secretKey, mBuilder.ivParameterSpec, mBuilder.secureRandom)
return@lazy cipher
}
@Throws(UnsupportedEncodingException::class, NoSuchAlgorithmException::class, NoSuchPaddingException::class, InvalidAlgorithmParameterException::class, InvalidKeyException::class, InvalidKeySpecException::class, BadPaddingException::class, IllegalBlockSizeException::class)
private fun encrypt(data: String?): String? {
if (data == null) return null
val dataBytes = data.toByteArray(charset(mBuilder.charsetName!!))
return Base64.encodeToString(encryptionCipher.doFinal(dataBytes), mBuilder.base64Mode)
}
@Synchronized
fun encrypt(bytes: ByteArray): ByteArray =
encryptionCipher.doFinal(bytes)
fun encryptOrNull(data: String): String? = try {
encrypt(data)
} catch (e: Exception) {
null
}
@Throws(UnsupportedEncodingException::class, NoSuchAlgorithmException::class, InvalidKeySpecException::class, NoSuchPaddingException::class, InvalidAlgorithmParameterException::class, InvalidKeyException::class, BadPaddingException::class, IllegalBlockSizeException::class)
private fun decrypt(data: String?): String? {
if (data == null) return null
val dataBytes = Base64.decode(data, mBuilder.base64Mode)
val dataBytesDecrypted = decryptionCipher.doFinal(dataBytes)
return String(dataBytesDecrypted, charset(mBuilder.charsetName!!))
}
@Synchronized
@Throws(UnsupportedEncodingException::class, NoSuchAlgorithmException::class, InvalidKeySpecException::class, NoSuchPaddingException::class, InvalidAlgorithmParameterException::class, InvalidKeyException::class, BadPaddingException::class, IllegalBlockSizeException::class)
fun decrypt(data: ByteArray): ByteArray =
decryptionCipher.doFinal(data)
fun decryptOrNull(data: String): String? = try {
decrypt(data)
} catch (e: Exception) {
null
}
@Throws(NoSuchAlgorithmException::class, UnsupportedEncodingException::class, InvalidKeySpecException::class)
private fun getSecretKey(key: CharArray): SecretKey {
var keyBytes:ByteArray = (String(key)).toByteArray(Charset.forName("UTF-8"))
val digest:MessageDigest = MessageDigest.getInstance("SHA-1")
keyBytes = digest.digest(keyBytes)
keyBytes = keyBytes.copyOf(16) // use only first 128 bit
return SecretKeySpec(keyBytes, "AES")
}
@Throws(UnsupportedEncodingException::class, NoSuchAlgorithmException::class)
private fun hashTheKey(key: String?): CharArray {
val messageDigest = MessageDigest.getInstance(mBuilder.digestAlgorithm)
messageDigest.update(key!!.toByteArray(charset(mBuilder.charsetName!!)))
return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray()
}
@Suppress("RedundantVisibilityModifier")
private class Builder(
internal var iv: ByteArray? = null,
internal var base64Mode: Int = 0,
internal var key: String? = null,
internal var algorithm: String? = null,
internal var charsetName: String? = null,
internal var digestAlgorithm: String? = null,
internal var secureRandomAlgorithm: String? = null,
internal var secureRandom: SecureRandom? = null,
internal var ivParameterSpec: IvParameterSpec? = null
) {
@Throws(NoSuchAlgorithmException::class)
fun build(): Encryption {
secureRandom = (SecureRandom.getInstance(secureRandomAlgorithm))
ivParameterSpec = (IvParameterSpec(iv!!))
return Encryption(this)
}
companion object {
internal fun getDefaultBuilder(key: String, iv: ByteArray): Builder =
Builder(iv = iv, key = key, charsetName = "UTF8", digestAlgorithm = "SHA1", base64Mode = Base64.DEFAULT, algorithm = "AES/CBC/PKCS5Padding", secureRandomAlgorithm = "SHA1PRNG")
}
}
companion object {
fun getDefault(key: String, iv: ByteArray): Encryption? {
return try {
Builder.getDefaultBuilder(key, iv).build()
} catch (e: NoSuchAlgorithmException) {
null
}
}
}
} | agpl-3.0 | e8a85804be4484ea26bd22da8abbaeeb | 42.882353 | 277 | 0.702164 | 5.029865 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesStatisticsCollector.kt | 8 | 2300 | // 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.find.findUsages
import com.intellij.ide.util.scopeChooser.ScopeIdMapper
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.eventLog.events.ObjectEventData
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.openapi.project.Project
import com.intellij.usages.impl.ScopeRuleValidator
class FindUsagesStatisticsCollector : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
companion object {
@JvmField
val GROUP = EventLogGroup("find.usages", 3)
const val OPTIONS_EVENT_ID = "options"
private val SEARCHABLE_SCOPE_EVENT_FIELD = EventFields.StringValidatedByCustomRule("searchScope", ScopeRuleValidator::class.java)
private val SEARCH_FOR_TEXT_OCCURRENCES_FIELD = EventFields.Boolean("isSearchForTextOccurrences")
private val IS_USAGES_FIELD = EventFields.Boolean("isUsages")
private val ADDITIONAL = EventFields.createAdditionalDataField(GROUP.id, OPTIONS_EVENT_ID)
private val OPEN_IN_NEW_TAB = EventFields.Boolean("openInNewTab")
private val FIND_USAGES_OPTIONS = GROUP.registerVarargEvent(OPTIONS_EVENT_ID,
SEARCH_FOR_TEXT_OCCURRENCES_FIELD,
IS_USAGES_FIELD,
OPEN_IN_NEW_TAB,
SEARCHABLE_SCOPE_EVENT_FIELD,
ADDITIONAL)
@JvmStatic
fun logOptions(project: Project, options: FindUsagesOptions, openInNewTab: Boolean) {
val data: MutableList<EventPair<*>> = mutableListOf(
SEARCH_FOR_TEXT_OCCURRENCES_FIELD.with(options.isSearchForTextOccurrences),
IS_USAGES_FIELD.with(options.isUsages),
OPEN_IN_NEW_TAB.with(openInNewTab),
SEARCHABLE_SCOPE_EVENT_FIELD.with(ScopeIdMapper.instance.getScopeSerializationId(options.searchScope.displayName)),
)
if (options is FusAwareFindUsagesOptions) {
data.add(ADDITIONAL.with(ObjectEventData(options.additionalUsageData)))
}
FIND_USAGES_OPTIONS.log(project, *data.toTypedArray())
}
}
} | apache-2.0 | c07e3dc73cfdb4908c95cf011dcee557 | 44.117647 | 140 | 0.77087 | 4.414587 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/fileActions/export/MarkdownDocxExportProvider.kt | 8 | 3987 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.fileActions.export
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.ProcessOutput
import com.intellij.execution.util.ExecUtil
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.fileActions.MarkdownFileActionFormat
import org.intellij.plugins.markdown.fileActions.utils.MarkdownImportExportUtils
import org.intellij.plugins.markdown.lang.MarkdownFileType
import org.intellij.plugins.markdown.settings.pandoc.PandocExecutableDetector
import org.intellij.plugins.markdown.ui.MarkdownNotifications
import java.util.*
internal class MarkdownDocxExportProvider : MarkdownExportProvider {
override val formatDescription: MarkdownFileActionFormat
get() = format
override fun exportFile(project: Project, mdFile: VirtualFile, outputFile: String) {
MarkdownExportDocxTask(project, mdFile, outputFile).queue()
}
override fun validate(project: Project, file: VirtualFile): String? {
val detected = PandocExecutableDetector.detect(project)
return when {
detected == null -> MarkdownBundle.message("markdown.settings.pandoc.executable.run.in.safe.mode")
detected.isEmpty() -> MarkdownBundle.message("markdown.export.to.docx.failure.msg")
else -> null
}
}
private inner class MarkdownExportDocxTask(
project: Project,
private val mdFile: VirtualFile,
private val outputFile: String
) : Task.Modal(project, MarkdownBundle.message("markdown.export.task", formatDescription.formatName), true) {
private lateinit var output: ProcessOutput
override fun run(indicator: ProgressIndicator) {
//Note: if the reference document is not found for some reason, then all styles in the created docx document will be default.
val refDocx = FileUtil.join(mdFile.parent.path, "${mdFile.nameWithoutExtension}.${formatDescription.extension}")
val cmd = getConvertMdToDocxCommandLine(mdFile, outputFile, refDocx)
output = ExecUtil.execAndGetOutput(cmd)
}
override fun onThrowable(error: Throwable) {
MarkdownNotifications.showError(
project,
id = MarkdownExportProvider.Companion.NotificationIds.exportFailed,
message = "[${mdFile.name}] ${error.localizedMessage}"
)
}
override fun onSuccess() {
if (output.stderrLines.isEmpty()) {
MarkdownImportExportUtils.refreshProjectDirectory(project, mdFile.parent.path)
MarkdownNotifications.showInfo(
project,
id = MarkdownExportProvider.Companion.NotificationIds.exportSuccess,
message = MarkdownBundle.message("markdown.export.success.msg", mdFile.name)
)
} else {
MarkdownNotifications.showError(
project,
id = MarkdownExportProvider.Companion.NotificationIds.exportFailed,
message = "[${mdFile.name}] ${output.stderrLines.joinToString("\n")}"
)
}
}
private fun getConvertMdToDocxCommandLine(srcFile: VirtualFile, targetFile: String, refFile: String): GeneralCommandLine {
val commandLine = mutableListOf(
"pandoc",
srcFile.path,
"-f",
MarkdownFileType.INSTANCE.name.lowercase(Locale.getDefault()),
"-t",
formatDescription.extension,
"-o",
targetFile
)
if (FileUtil.exists(refFile)) {
commandLine.add("--reference-doc=$refFile")
}
return GeneralCommandLine(commandLine)
}
}
companion object {
@JvmStatic
val format = MarkdownFileActionFormat("Microsoft Word", "docx")
}
}
| apache-2.0 | b7773fff1c1639e270357861b5efb432 | 38.87 | 140 | 0.734638 | 4.685076 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/internal/donor/DonorErrorConfigurationViewModel.kt | 1 | 5822 | package org.thoughtcrime.securesms.components.settings.app.internal.donor
import androidx.lifecycle.ViewModel
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import io.reactivex.rxjava3.schedulers.Schedulers
import org.signal.donations.StripeDeclineCode
import org.thoughtcrime.securesms.badges.Badges
import org.thoughtcrime.securesms.badges.models.Badge
import org.thoughtcrime.securesms.components.settings.app.subscription.errors.UnexpectedSubscriptionCancellation
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.jobs.SubscriptionReceiptRequestResponseJob
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.util.rx.RxStore
import org.whispersystems.signalservice.api.subscriptions.ActiveSubscription
import java.util.Locale
class DonorErrorConfigurationViewModel : ViewModel() {
private val store = RxStore(DonorErrorConfigurationState())
private val disposables = CompositeDisposable()
val state: Flowable<DonorErrorConfigurationState> = store.stateFlowable
init {
val giftBadges: Single<List<Badge>> = ApplicationDependencies.getDonationsService()
.getGiftBadges(Locale.getDefault())
.flatMap { it.flattenResult() }
.map { results -> results.values.map { Badges.fromServiceBadge(it) } }
.subscribeOn(Schedulers.io())
val boostBadges: Single<List<Badge>> = ApplicationDependencies.getDonationsService()
.getBoostBadge(Locale.getDefault())
.flatMap { it.flattenResult() }
.map { listOf(Badges.fromServiceBadge(it)) }
.subscribeOn(Schedulers.io())
val subscriptionBadges: Single<List<Badge>> = ApplicationDependencies.getDonationsService()
.getSubscriptionLevels(Locale.getDefault())
.flatMap { it.flattenResult() }
.map { levels -> levels.levels.values.map { Badges.fromServiceBadge(it.badge) } }
.subscribeOn(Schedulers.io())
disposables += Single.zip(giftBadges, boostBadges, subscriptionBadges) { g, b, s ->
g + b + s
}.subscribe { badges ->
store.update { it.copy(badges = badges) }
}
}
override fun onCleared() {
disposables.clear()
}
fun setSelectedBadge(badgeIndex: Int) {
store.update {
it.copy(selectedBadge = if (badgeIndex in it.badges.indices) it.badges[badgeIndex] else null)
}
}
fun setSelectedUnexpectedSubscriptionCancellation(unexpectedSubscriptionCancellationIndex: Int) {
store.update {
it.copy(
selectedUnexpectedSubscriptionCancellation = if (unexpectedSubscriptionCancellationIndex in UnexpectedSubscriptionCancellation.values().indices) {
UnexpectedSubscriptionCancellation.values()[unexpectedSubscriptionCancellationIndex]
} else {
null
}
)
}
}
fun setStripeDeclineCode(stripeDeclineCodeIndex: Int) {
store.update {
it.copy(
selectedStripeDeclineCode = if (stripeDeclineCodeIndex in StripeDeclineCode.Code.values().indices) {
StripeDeclineCode.Code.values()[stripeDeclineCodeIndex]
} else {
null
}
)
}
}
fun save(): Completable {
val snapshot = store.state
val saveState = Completable.fromAction {
synchronized(SubscriptionReceiptRequestResponseJob.MUTEX) {
when {
snapshot.selectedBadge?.isGift() == true -> handleGiftExpiration(snapshot)
snapshot.selectedBadge?.isBoost() == true -> handleBoostExpiration(snapshot)
snapshot.selectedBadge?.isSubscription() == true -> handleSubscriptionExpiration(snapshot)
else -> handleSubscriptionPaymentFailure(snapshot)
}
}
}.subscribeOn(Schedulers.io())
return clear().andThen(saveState)
}
fun clear(): Completable {
return Completable.fromAction {
synchronized(SubscriptionReceiptRequestResponseJob.MUTEX) {
SignalStore.donationsValues().setExpiredBadge(null)
SignalStore.donationsValues().setExpiredGiftBadge(null)
SignalStore.donationsValues().unexpectedSubscriptionCancelationReason = null
SignalStore.donationsValues().unexpectedSubscriptionCancelationTimestamp = 0L
SignalStore.donationsValues().setUnexpectedSubscriptionCancelationChargeFailure(null)
}
store.update {
it.copy(
selectedStripeDeclineCode = null,
selectedUnexpectedSubscriptionCancellation = null,
selectedBadge = null
)
}
}
}
private fun handleBoostExpiration(state: DonorErrorConfigurationState) {
SignalStore.donationsValues().setExpiredBadge(state.selectedBadge)
}
private fun handleGiftExpiration(state: DonorErrorConfigurationState) {
SignalStore.donationsValues().setExpiredGiftBadge(state.selectedBadge)
}
private fun handleSubscriptionExpiration(state: DonorErrorConfigurationState) {
SignalStore.donationsValues().setExpiredBadge(state.selectedBadge)
handleSubscriptionPaymentFailure(state)
}
private fun handleSubscriptionPaymentFailure(state: DonorErrorConfigurationState) {
SignalStore.donationsValues().unexpectedSubscriptionCancelationReason = state.selectedUnexpectedSubscriptionCancellation?.status
SignalStore.donationsValues().unexpectedSubscriptionCancelationTimestamp = System.currentTimeMillis()
SignalStore.donationsValues().setUnexpectedSubscriptionCancelationChargeFailure(
state.selectedStripeDeclineCode?.let {
ActiveSubscription.ChargeFailure(
it.code,
"Test Charge Failure",
"Test Network Status",
"Test Network Reason",
"Test"
)
}
)
}
}
| gpl-3.0 | 079324a2f5514267378d706b71c2f3b0 | 37.302632 | 154 | 0.742528 | 4.884228 | false | false | false | false |
armcha/Ribble | app/src/main/kotlin/io/armcha/ribble/presentation/screen/shot_detail/ShotDetailFragment.kt | 1 | 4790 | package io.armcha.ribble.presentation.screen.shot_detail
import android.animation.StateListAnimator
import android.annotation.SuppressLint
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.v7.widget.LinearLayoutManager
import android.text.method.LinkMovementMethod
import android.view.View
import io.armcha.ribble.R
import io.armcha.ribble.domain.entity.Comment
import io.armcha.ribble.domain.entity.Shot
import io.armcha.ribble.presentation.adapter.RibbleAdapter
import io.armcha.ribble.presentation.base_mvp.base.BaseFragment
import io.armcha.ribble.presentation.utils.C
import io.armcha.ribble.presentation.utils.L
import io.armcha.ribble.presentation.utils.S
import io.armcha.ribble.presentation.utils.delegates.bundle
import io.armcha.ribble.presentation.utils.delegates.bundleWith
import io.armcha.ribble.presentation.utils.extensions.*
import io.armcha.ribble.presentation.utils.glide.TransformationType
import io.armcha.ribble.presentation.utils.glide.load
import io.armcha.ribble.presentation.widget.TextImageLayout
import io.armcha.ribble.presentation.widget.navigation_view.NavigationId
import kotlinx.android.synthetic.main.comment_item.view.*
import kotlinx.android.synthetic.main.fragment_shot_detail.*
import javax.inject.Inject
class ShotDetailFragment : BaseFragment<ShotDetailContract.View, ShotDetailContract.Presenter>(), ShotDetailContract.View {
companion object {
fun getBundle(shot: Shot?) = "shot" bundleWith shot
}
private val items = intArrayOf(R.drawable.heart_full, R.drawable.eye, R.drawable.bucket)
@Inject
protected lateinit var shotDetailPresenter: ShotDetailPresenter
private var recyclerAdapter: RibbleAdapter<Comment>? = null
val shot: Shot by bundle()
override fun injectDependencies() {
activityComponent.inject(this)
}
override val layoutResId = L.fragment_shot_detail
override fun initPresenter() = shotDetailPresenter
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpViews()
}
private fun setUpViews() {
with(shot) {
shotDetailImage.load(image.normal)
shotAuthor.text = user.name
authorLocation.text = user.location
authorImage.load(user.avatarUrl, TransformationType.CIRCLE)
}
progressBar.backgroundCircleColor = takeColor(C.colorPrimary)
//TODO move to attributes
(0 until linearLayout.childCount)
.map { linearLayout[it] }
.map { it as TextImageLayout }
.forEachIndexed { index, child ->
child.imageResId = items[index]
}
likeLayout.layoutText = shot.likesCount
viewCountLayout.layoutText = shot.viewsCount
bucketLayout.layoutText = shot.bucketCount
}
override fun onDataReceive(commentList: List<Comment>) {
updateAdapter(commentList)
}
override fun getShotId() = shot.id
override fun showNoComments() {
lockAppBar()
noCommentsText.setAnimatedText(getString(S.no_comments_text))
}
@SuppressLint("NewApi")
private fun lockAppBar() {
if (isPortrait()) {
val params = scrollingView.layoutParams as AppBarLayout.LayoutParams
params.scrollFlags = 0
LorAbove {
appBarLayout.stateListAnimator = StateListAnimator()
}
}
}
override fun showLoading() {
progressBar.start()
}
override fun hideLoading() {
progressBar.stop()
}
override fun showError(message: String?) {
showErrorDialog(message)
}
private fun updateAdapter(commentList: List<Comment>) {
recyclerAdapter?.update(commentList) ?: this setUpRecyclerView commentList
}
private infix fun setUpRecyclerView(commentList: List<Comment>) {
recyclerView.apply {
adapter = RibbleAdapter(commentList, L.comment_item) {
commentDate.text = it.commentDate
comment.text = it.commentText
comment.movementMethod = LinkMovementMethod.getInstance()
commentAuthor.text = it.user?.username
userImage.load(it.user?.avatarUrl, TransformationType.CIRCLE)
if (it.likeCount.isZero()) {
userCommentLikeCount.invisible()
} else {
userCommentLikeCount.show()
userCommentLikeCount.text = it.likeCount.toString()
}
}
layoutManager = LinearLayoutManager(activity)
}
}
override fun getTitle() = shot.title ?: NavigationId.SHOT_DETAIL.name
}
| apache-2.0 | 8968017d1bcf0d554793bcbf665824c3 | 33.963504 | 123 | 0.688935 | 4.733202 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/network/ProgressResponseBody.kt | 2 | 1388 | package eu.kanade.tachiyomi.network
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.Buffer
import okio.BufferedSource
import okio.ForwardingSource
import okio.Source
import okio.buffer
import java.io.IOException
class ProgressResponseBody(private val responseBody: ResponseBody, private val progressListener: ProgressListener) : ResponseBody() {
private val bufferedSource: BufferedSource by lazy {
source(responseBody.source()).buffer()
}
override fun contentType(): MediaType {
return responseBody.contentType()!!
}
override fun contentLength(): Long {
return responseBody.contentLength()
}
override fun source(): BufferedSource {
return bufferedSource
}
private fun source(source: Source): Source {
return object : ForwardingSource(source) {
var totalBytesRead = 0L
@Throws(IOException::class)
override fun read(sink: Buffer, byteCount: Long): Long {
val bytesRead = super.read(sink, byteCount)
// read() returns the number of bytes read, or -1 if this source is exhausted.
totalBytesRead += if (bytesRead != -1L) bytesRead else 0
progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1L)
return bytesRead
}
}
}
}
| apache-2.0 | bcf10e47754ac18786f962323e2bb2a1 | 30.545455 | 133 | 0.667147 | 5.318008 | false | false | false | false |
reinterpretcat/utynote | app/src/main/java/com/utynote/components/search/data/geojson/entities/Geocoding.kt | 1 | 550 | package com.utynote.components.search.data.geojson.entities
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class Geocoding {
@SerializedName("version")
@Expose
var version: String? = null
@SerializedName("attribution")
@Expose
var attribution: String? = null
@SerializedName("query")
@Expose
var query: Query? = null
@SerializedName("engine")
@Expose
var engine: Engine? = null
@SerializedName("timestamp")
@Expose
var timestamp: Long = 0
}
| agpl-3.0 | 486aec6c0498be22f312291c49d480f4 | 21.916667 | 59 | 0.692727 | 4.135338 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ToRawStringLiteralIntention.kt | 2 | 3711 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.psi.KtEscapeStringTemplateEntry
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtStringTemplateEntry
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class ToRawStringLiteralIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>(
KtStringTemplateExpression::class.java,
KotlinBundle.lazyMessage("to.raw.string.literal")
), LowPriorityAction {
override fun isApplicableTo(element: KtStringTemplateExpression): Boolean {
if (PsiTreeUtil.nextLeaf(element) is PsiErrorElement) {
// Parse error right after the literal
// the replacement may make things even worse, suppress the action
return false
}
val text = element.text
if (text.startsWith("\"\"\"")) return false // already raw
val escapeEntries = element.entries.filterIsInstance<KtEscapeStringTemplateEntry>()
for (entry in escapeEntries) {
val c = entry.unescapedValue.singleOrNull() ?: return false
if (Character.isISOControl(c) && c != '\n' && c != '\r') return false
}
val converted = convertContent(element)
return !converted.contains("\"\"\"") && !hasTrailingSpaces(converted)
}
override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) {
val startOffset = element.startOffset
val endOffset = element.endOffset
val currentOffset = editor?.caretModel?.currentCaret?.offset ?: startOffset
val text = convertContent(element)
val replaced = element.replaced(KtPsiFactory(element).createExpression("\"\"\"" + text + "\"\"\""))
val offset = when {
startOffset == currentOffset -> startOffset
endOffset == currentOffset -> replaced.endOffset
else -> minOf(currentOffset + 2, replaced.endOffset)
}
editor?.caretModel?.moveToOffset(offset)
}
private fun convertContent(element: KtStringTemplateExpression): String {
val text = buildString {
val entries = element.entries
for ((index, entry) in entries.withIndex()) {
val value = entry.value()
if (value.endsWith("$") && index < entries.size - 1) {
val nextChar = entries[index + 1].value().first()
if (nextChar.isJavaIdentifierStart() || nextChar == '{') {
append("\${\"$\"}")
continue
}
}
append(value)
}
}
return StringUtilRt.convertLineSeparators(text, "\n")
}
private fun hasTrailingSpaces(text: String): Boolean {
var afterSpace = false
for (c in text) {
if ((c == '\n' || c == '\r') && afterSpace) return true
afterSpace = c == ' ' || c == '\t'
}
return false
}
private fun KtStringTemplateEntry.value() = if (this is KtEscapeStringTemplateEntry) this.unescapedValue else text
} | apache-2.0 | 345ba166623043db1677f1b50af656a9 | 39.791209 | 158 | 0.654271 | 5.069672 | false | false | false | false |
fwcd/kotlin-language-server | server/src/main/kotlin/org/javacs/kt/overridemembers/OverrideMembers.kt | 1 | 12335 | package org.javacs.kt.overridemembers
import org.eclipse.lsp4j.CodeAction
import org.eclipse.lsp4j.Position
import org.eclipse.lsp4j.Range
import org.eclipse.lsp4j.TextEdit
import org.eclipse.lsp4j.WorkspaceEdit
import org.javacs.kt.CompiledFile
import org.javacs.kt.util.toPath
import org.javacs.kt.position.position
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtTypeArgumentList
import org.jetbrains.kotlin.psi.KtSuperTypeListEntry
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.isInterface
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.MemberDescriptor
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.isAbstract
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.psi.psiUtil.unwrapNullability
import org.jetbrains.kotlin.types.TypeProjection
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
// TODO: see where this should ideally be placed
private const val DEFAULT_TAB_SIZE = 4
fun listOverridableMembers(file: CompiledFile, cursor: Int): List<CodeAction> {
val kotlinClass = file.parseAtPoint(cursor)
if (kotlinClass is KtClass) {
return createOverrideAlternatives(file, kotlinClass)
}
return emptyList()
}
private fun createOverrideAlternatives(file: CompiledFile, kotlinClass: KtClass): List<CodeAction> {
// Get the functions that need to be implemented
val membersToImplement = getUnimplementedMembersStubs(file, kotlinClass)
val uri = file.parse.toPath().toUri().toString()
// Get the padding to be introduced before the member declarations
val padding = getDeclarationPadding(file, kotlinClass)
// Get the location where the new code will be placed
val newMembersStartPosition = getNewMembersStartPosition(file, kotlinClass)
// loop through the memberstoimplement and create code actions
return membersToImplement.map { member ->
val newText = System.lineSeparator() + System.lineSeparator() + padding + member
val textEdit = TextEdit(Range(newMembersStartPosition, newMembersStartPosition), newText)
val codeAction = CodeAction()
codeAction.edit = WorkspaceEdit(mapOf(uri to listOf(textEdit)))
codeAction.title = member
codeAction
}
}
// TODO: any way can repeat less code between this and the getAbstractMembersStubs in the ImplementAbstractMembersQuickfix?
private fun getUnimplementedMembersStubs(file: CompiledFile, kotlinClass: KtClass): List<String> =
// For each of the super types used by this class
// TODO: does not seem to handle the implicit Any and Object super types that well. Need to find out if that is easily solvable. Finds the methods from them if any super class or interface is present
kotlinClass
.superTypeListEntries
.mapNotNull {
// Find the definition of this super type
val referenceAtPoint = file.referenceExpressionAtPoint(it.startOffset)
val descriptor = referenceAtPoint?.second
val classDescriptor = getClassDescriptor(descriptor)
// If the super class is abstract, interface or just plain open
if (null != classDescriptor && classDescriptor.canBeExtended()) {
val superClassTypeArguments = getSuperClassTypeProjections(file, it)
classDescriptor
.getMemberScope(superClassTypeArguments)
.getContributedDescriptors()
.filter { classMember ->
classMember is MemberDescriptor &&
classMember.canBeOverriden() &&
!overridesDeclaration(kotlinClass, classMember)
}
.mapNotNull { member ->
when (member) {
is FunctionDescriptor -> createFunctionStub(member)
is PropertyDescriptor -> createVariableStub(member)
else -> null
}
}
} else {
null
}
}
.flatten()
private fun ClassDescriptor.canBeExtended() = this.kind.isInterface ||
this.modality == Modality.ABSTRACT ||
this.modality == Modality.OPEN
private fun MemberDescriptor.canBeOverriden() = (Modality.ABSTRACT == this.modality || Modality.OPEN == this.modality) && Modality.FINAL != this.modality && this.visibility != DescriptorVisibilities.PRIVATE && this.visibility != DescriptorVisibilities.PROTECTED
// interfaces are ClassDescriptors by default. When calling AbstractClass super methods, we get a ClassConstructorDescriptor
fun getClassDescriptor(descriptor: DeclarationDescriptor?): ClassDescriptor? =
if (descriptor is ClassDescriptor) {
descriptor
} else if (descriptor is ClassConstructorDescriptor) {
descriptor.containingDeclaration
} else {
null
}
fun getSuperClassTypeProjections(
file: CompiledFile,
superType: KtSuperTypeListEntry
): List<TypeProjection> =
superType
.typeReference
?.typeElement
?.children
?.filter { it is KtTypeArgumentList }
?.flatMap { (it as KtTypeArgumentList).arguments }
?.mapNotNull {
(file.referenceExpressionAtPoint(it?.startOffset ?: 0)?.second as?
ClassDescriptor)
?.defaultType?.asTypeProjection()
}
?: emptyList()
// Checks if the class overrides the given declaration
fun overridesDeclaration(kotlinClass: KtClass, descriptor: MemberDescriptor): Boolean =
when (descriptor) {
is FunctionDescriptor -> kotlinClass.declarations.any {
it.name == descriptor.name.asString()
&& it.hasModifier(KtTokens.OVERRIDE_KEYWORD)
&& ((it as? KtNamedFunction)?.let { parametersMatch(it, descriptor) } ?: true)
}
is PropertyDescriptor -> kotlinClass.declarations.any {
it.name == descriptor.name.asString() && it.hasModifier(KtTokens.OVERRIDE_KEYWORD)
}
else -> false
}
// Checks if two functions have matching parameters
private fun parametersMatch(
function: KtNamedFunction,
functionDescriptor: FunctionDescriptor
): Boolean {
if (function.valueParameters.size == functionDescriptor.valueParameters.size) {
for (index in 0 until function.valueParameters.size) {
if (function.valueParameters[index].name !=
functionDescriptor.valueParameters[index].name.asString()
) {
return false
} else if (function.valueParameters[index].typeReference?.typeName() !=
functionDescriptor.valueParameters[index]
.type
.unwrappedType()
.toString() && function.valueParameters[index].typeReference?.typeName() != null
) {
// Any and Any? seems to be null for Kt* psi objects for some reason? At least for equals
// TODO: look further into this
// Note: Since we treat Java overrides as non nullable by default, the above test
// will fail when the user has made the type nullable.
// TODO: look into this
return false
}
}
if (function.typeParameters.size == functionDescriptor.typeParameters.size) {
for (index in 0 until function.typeParameters.size) {
if (function.typeParameters[index].variance !=
functionDescriptor.typeParameters[index].variance
) {
return false
}
}
}
return true
}
return false
}
private fun KtTypeReference.typeName(): String? =
this.name
?: this.typeElement
?.children
?.filter { it is KtSimpleNameExpression }
?.map { (it as KtSimpleNameExpression).getReferencedName() }
?.firstOrNull()
fun createFunctionStub(function: FunctionDescriptor): String {
val name = function.name
val arguments =
function.valueParameters
.map { argument ->
val argumentName = argument.name
val argumentType = argument.type.unwrappedType()
"$argumentName: $argumentType"
}
.joinToString(", ")
val returnType = function.returnType?.unwrappedType()?.toString()?.takeIf { "Unit" != it }
return "override fun $name($arguments)${returnType?.let { ": $it" } ?: ""} { }"
}
fun createVariableStub(variable: PropertyDescriptor): String {
val variableType = variable.returnType?.unwrappedType()?.toString()?.takeIf { "Unit" != it }
return "override val ${variable.name}${variableType?.let { ": $it" } ?: ""} = TODO(\"SET VALUE\")"
}
// about types: regular Kotlin types are marked T or T?, but types from Java are (T..T?) because
// nullability cannot be decided.
// Therefore we have to unpack in case we have the Java type. Fortunately, the Java types are not
// marked nullable, so we default to non nullable types. Let the user decide if they want nullable
// types instead. With this implementation Kotlin types also keeps their nullability
private fun KotlinType.unwrappedType(): KotlinType =
this.unwrap().makeNullableAsSpecified(this.isMarkedNullable)
fun getDeclarationPadding(file: CompiledFile, kotlinClass: KtClass): String {
// If the class is not empty, the amount of padding is the same as the one in the last
// declaration of the class
val paddingSize =
if (kotlinClass.declarations.isNotEmpty()) {
val lastFunctionStartOffset = kotlinClass.declarations.last().startOffset
position(file.content, lastFunctionStartOffset).character
} else {
// Otherwise, we just use a default tab size in addition to any existing padding
// on the class itself (note that the class could be inside another class, for
// example)
position(file.content, kotlinClass.startOffset).character + DEFAULT_TAB_SIZE
}
return " ".repeat(paddingSize)
}
fun getNewMembersStartPosition(file: CompiledFile, kotlinClass: KtClass): Position? =
// If the class is not empty, the new member will be put right after the last declaration
if (kotlinClass.declarations.isNotEmpty()) {
val lastFunctionEndOffset = kotlinClass.declarations.last().endOffset
position(file.content, lastFunctionEndOffset)
} else { // Otherwise, the member is put at the beginning of the class
val body = kotlinClass.body
if (body != null) {
position(file.content, body.startOffset + 1)
} else {
// function has no body. We have to create one. New position is right after entire
// kotlin class text (with space)
val newPosCorrectLine = position(file.content, kotlinClass.startOffset + 1)
newPosCorrectLine.character = (kotlinClass.text.length + 2)
newPosCorrectLine
}
}
fun KtClass.hasNoBody() = null == this.body
| mit | f104d21ff8ae920333a75e60e17a206f | 44.349265 | 261 | 0.651317 | 5.344454 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/cloudwatch/src/main/kotlin/com/kotlin/cloudwatch/EnableAlarmActions.kt | 1 | 1679 | // snippet-sourcedescription:[EnableAlarmActions.kt demonstrates how to enable actions on a CloudWatch alarm.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon CloudWatch]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.cloudwatch
// snippet-start:[cloudwatch.kotlin.enable_alarm_actions.import]
import aws.sdk.kotlin.services.cloudwatch.CloudWatchClient
import aws.sdk.kotlin.services.cloudwatch.model.EnableAlarmActionsRequest
import kotlin.system.exitProcess
// snippet-end:[cloudwatch.kotlin.enable_alarm_actions.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:
<alarmName>
Where:
alarmName - An alarm name to enable.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val alarmName = args[0]
enableActions(alarmName)
}
// snippet-start:[cloudwatch.kotlin.enable_alarm_actions.main]
suspend fun enableActions(alarm: String) {
val request = EnableAlarmActionsRequest {
alarmNames = listOf(alarm)
}
CloudWatchClient { region = "us-east-1" }.use { cwClient ->
cwClient.enableAlarmActions(request)
println("Successfully enabled actions on alarm $alarm")
}
}
// snippet-end:[cloudwatch.kotlin.enable_alarm_actions.main]
| apache-2.0 | 3121026551614936517d52642fa1d072 | 27.45614 | 110 | 0.699226 | 3.922897 | false | false | false | false |
github/codeql | java/ql/test/kotlin/library-tests/generics/generics.kt | 1 | 1190 | package foo.bar
fun <S> Int.f0(s: S): S {
return s
}
fun <S> Int.f1(s: S): C0<S>? {
return null
}
open class C0<V> {}
class C1<T, W>(val t: T) : C0<W>() {
fun f1(t: T) {}
fun <U> f2(u: U): C1<U, U> {
return C1<U, U>(u)
}
}
class C2() {
fun <P> f4(p: P) {}
}
fun m() {
val c1 = C1<Int, Int>(1)
c1.f1(2)
val x1 = c1.f2("")
val c2 = C1<String, Int>("")
c2.f1("a")
val x2 = c2.f2(3)
val c3 = C2()
c3.f4(5)
val c4: C0<*> = C0<Int>()
}
class BoundedTest<T : CharSequence, S : T> {
fun m(s: S, t: T) { }
}
class Outer<T1, T2> {
inner class Inner1<T3, T4> {
fun fn1(t1: T1, t2: T2, t3: T3, t4: T4) {
val c = Inner1<Int, String>()
}
}
class Nested1<T3, T4> {
fun fn2(t3: T3, t4: T4) {
val c = Nested1<Int, String>()
}
}
}
class Class1<T1> {
fun <T2> fn1(t: T2) {
class Local<T3> {
fun <T4> fn2(t2: T2, t4: T4) {}
}
Local<Int>().fn2(t, "")
}
}
// Diagnostic Matches: % Found more type arguments than parameters: foo.bar.Class1 ...while extracting a enclosing class (fn1) at %generics.kt:57:5:62:5%
| mit | b52df5d019afd573cba39dfc6d929961 | 17.307692 | 154 | 0.471429 | 2.266667 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/common/MethodControllerCommon.kt | 1 | 8569 | package top.zbeboy.isy.web.common
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.ui.ModelMap
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.multipart.MultipartHttpServletRequest
import top.zbeboy.isy.config.ISYProperties
import top.zbeboy.isy.config.Workbook
import top.zbeboy.isy.domain.tables.pojos.SystemAlert
import top.zbeboy.isy.domain.tables.pojos.SystemMessage
import top.zbeboy.isy.domain.tables.pojos.Users
import top.zbeboy.isy.service.cache.CacheManageService
import top.zbeboy.isy.service.common.DesService
import top.zbeboy.isy.service.common.FilesService
import top.zbeboy.isy.service.common.UploadService
import top.zbeboy.isy.service.platform.RoleService
import top.zbeboy.isy.service.platform.UsersService
import top.zbeboy.isy.service.system.MailService
import top.zbeboy.isy.service.system.SystemAlertService
import top.zbeboy.isy.service.system.SystemMessageService
import top.zbeboy.isy.service.util.FilesUtils
import top.zbeboy.isy.service.util.RequestUtils
import top.zbeboy.isy.service.util.UUIDUtils
import top.zbeboy.isy.web.bean.file.FileBean
import top.zbeboy.isy.web.util.AjaxUtils
import java.io.IOException
import java.sql.Timestamp
import java.time.Clock
import java.util.*
import javax.annotation.Resource
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* Created by zbeboy 2017-12-07 .
**/
@Component
open class MethodControllerCommon {
private val log = LoggerFactory.getLogger(MethodControllerCommon::class.java)
@Resource
open lateinit var usersService: UsersService
@Resource
open lateinit var roleService: RoleService
@Autowired
open lateinit var isyProperties: ISYProperties
@Resource
open lateinit var mailService: MailService
@Resource
open lateinit var systemAlertService: SystemAlertService
@Resource
open lateinit var systemMessageService: SystemMessageService
@Resource
open lateinit var cacheManageService: CacheManageService
@Resource
open lateinit var uploadService: UploadService
@Resource
open lateinit var filesService: FilesService
@Resource
open lateinit var desService: DesService
/**
* 组装提示信息
*
* @param modelMap 页面对象
* @param tip 提示内容
*/
fun showTip(modelMap: ModelMap, tip: String): String {
modelMap.addAttribute("showTip", true)
modelMap.addAttribute("tip", tip)
modelMap.addAttribute("showButton", true)
modelMap.addAttribute("buttonText", "返回上一页")
return Workbook.TIP_PAGE
}
/**
* 如果是管理员则获取院id,如果是教职工角色则获取系id,如果是普通学生就获取系id,专业id,年级
*
* @return 根据角色返回相应数据
*/
fun adminOrNormalData(): Map<String, Int> {
val map = HashMap<String, Int>()
if (roleService.isCurrentUserInRole(Workbook.ADMIN_AUTHORITIES)) {
val users = usersService.getUserFromSession()
val collegeId = cacheManageService.getRoleCollegeId(users!!)
map.put("collegeId", collegeId)
} else if (!roleService.isCurrentUserInRole(Workbook.SYSTEM_AUTHORITIES)) {
val users = usersService.getUserFromSession()
val userTypeId = users!!.usersTypeId!!
val usersType = cacheManageService.findByUsersTypeId(userTypeId)
if (usersType.usersTypeName == Workbook.STUDENT_USERS_TYPE) {// 学生
val organizeBean = cacheManageService.getRoleOrganizeInfo(users)
map.put("departmentId", organizeBean!!.departmentId)
map.put("scienceId", organizeBean.scienceId)
map.put("grade", organizeBean.grade.toInt())
} else if (usersType.usersTypeName == Workbook.STAFF_USERS_TYPE) {// 教职工
val departmentId = cacheManageService.getRoleDepartmentId(users)
map.put("departmentId", departmentId)
}
}
return map
}
/**
* 发送邮件通知
*
* @param users 接收者
* @param curUsers 发送者
* @param messageTitle 消息标题
* @param notify 通知内容
*/
fun sendNotify(users: Users, curUsers: Users, messageTitle: String, notify: String, request: HttpServletRequest) {
//发送验证邮件
if (isyProperties.getMail().isOpen) {
mailService.sendNotifyMail(users, RequestUtils.getBaseUrl(request), notify)
}
// 保存消息
val systemMessage = SystemMessage()
val messageId = UUIDUtils.getUUID()
val isSee: Byte = 0
val now = Timestamp(Clock.systemDefaultZone().millis())
systemMessage.systemMessageId = messageId
systemMessage.acceptUsers = users.username
systemMessage.isSee = isSee
systemMessage.sendUsers = curUsers.username
systemMessage.messageTitle = messageTitle
systemMessage.messageContent = notify
systemMessage.messageDate = now
systemMessageService.save(systemMessage)
// 保存提醒
val systemAlert = SystemAlert()
val systemAlertType = cacheManageService.findBySystemAlertTypeName(Workbook.ALERT_MESSAGE_TYPE)
systemAlert.systemAlertId = UUIDUtils.getUUID()
systemAlert.isSee = isSee
systemAlert.alertContent = "新消息"
systemAlert.linkId = messageId
systemAlert.systemAlertTypeId = systemAlertType.systemAlertTypeId
systemAlert.username = users.username
systemAlert.alertDate = now
systemAlertService.save(systemAlert)
}
/**
* 上传附件
*
* @param schoolId 学校id
* @param collegeId 院id
* @param departmentId 系id
* @param multipartHttpServletRequest 文件请求
* @return 文件信息
*/
fun uploadFile(schoolId: Int?, collegeId: Int?, @RequestParam("departmentId") departmentId: Int,
multipartHttpServletRequest: MultipartHttpServletRequest): AjaxUtils<FileBean> {
val data = AjaxUtils.of<FileBean>()
try {
val path = Workbook.graduateDesignPath(cacheManageService.schoolInfoPath(schoolId, collegeId, departmentId))
val fileBeen = uploadService.upload(multipartHttpServletRequest,
RequestUtils.getRealPath(multipartHttpServletRequest) + path, multipartHttpServletRequest.remoteAddr)
data.success().listData(fileBeen).obj(path)
} catch (e: Exception) {
log.error("Upload file exception,is {}", e)
}
return data
}
/**
* 删除文件
*
* @param filePath 文件路径
* @param request 请求
* @return true or false
*/
fun deleteFile(filePath: String, request: HttpServletRequest): Boolean {
return try {
FilesUtils.deleteFile(RequestUtils.getRealPath(request) + filePath)
} catch (e: IOException) {
log.error(" delete file is exception.", e)
false
}
}
/**
* 文件下载
*
* @param fileId 文件id
* @param request 请求
* @param response 响应
*/
fun downloadFile(fileId: String, request: HttpServletRequest, response: HttpServletResponse) {
val files = filesService.findById(fileId)
if (!ObjectUtils.isEmpty(files)) {
uploadService.download(files.originalFileName, files.relativePath, response, request)
}
}
/**
* 加密个人数据
*
* @param param 待加密数据
* @param usersKey 用户KEY
*/
fun encryptPersonalData(param: String?, usersKey: String): String? {
var data = param
if (StringUtils.hasLength(data)) {
data = desService.encrypt(data!!, usersKey)
}
return data
}
/**
* 解密个人数据
*
* @param param 待加密数据
* @param usersKey 用户KEY
*/
fun decryptPersonalData(param: String?, usersKey: String): String? {
var data = param
if (StringUtils.hasLength(data)) {
data = desService.decrypt(data, usersKey)
}
return data
}
} | mit | fb7abaab222d693b196ed27548b525a7 | 33.426778 | 121 | 0.672299 | 4.498086 | false | false | false | false |
paplorinc/intellij-community | plugins/stats-collector/features/src/com/jetbrains/completion/feature/impl/CompletionFactors.kt | 3 | 1185 | /*
* 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.jetbrains.completion.feature.impl
class CompletionFactors(allFactors: Set<String>) {
private val knownFactors: Set<String> = HashSet(allFactors)
fun unknownFactors(factors: Set<String>): List<String> {
var result: MutableList<String>? = null
for (factor in factors) {
val normalized = factor.substringBefore('@')
if (normalized !in knownFactors) {
result = (result ?: mutableListOf()).apply { add(normalized) }
}
}
return if (result != null) result else emptyList()
}
}
| apache-2.0 | 0b3d79f963f0ef9b3a8c64d3dcfbd296 | 32.857143 | 78 | 0.679325 | 4.293478 | false | false | false | false |
nick-rakoczy/Conductor | aws-plugin/src/main/java/urn/conductor/aws/CredentialHandler.kt | 1 | 1067 | package urn.conductor.aws
import com.amazonaws.auth.AWSStaticCredentialsProvider
import com.amazonaws.auth.BasicAWSCredentials
import urn.conductor.Engine
import urn.conductor.StandardComplexElementHandler
import urn.conductor.aws.xml.Credentials
class CredentialHandler : StandardComplexElementHandler<Credentials> {
override val handles: Class<Credentials>
get() = Credentials::class.java
override fun process(element: Credentials, engine: Engine, processChild: (Any) -> Unit) {
val vaultRecordName = element.vaultRef?.let(engine::interpolate) ?: error("vault-ref undefined")
val vaultEntry = engine.eval(vaultRecordName) as? Map<*, *> ?: error("Invalid vault reference")
val accessKey = vaultEntry["username"] as? String ?: error("Invalid entry defined")
val secretKey = vaultEntry["password"] as? String ?: error("Invalid entry defined")
val credentials = BasicAWSCredentials(accessKey, secretKey)
val credentialProvider = AWSStaticCredentialsProvider(credentials)
val targetName = element.id
engine.put(targetName, credentialProvider)
}
} | gpl-3.0 | ff18aa6b6db14a5e1e167a2a2392da38 | 45.434783 | 98 | 0.790066 | 4.302419 | false | false | false | false |
chrislo27/Tickompiler | src/main/kotlin/rhmodding/tickompiler/decompiler/Decompiler.kt | 2 | 7835 | package rhmodding.tickompiler.decompiler
import rhmodding.tickompiler.BytesFunction
import rhmodding.tickompiler.Function
import rhmodding.tickompiler.Functions
import rhmodding.tickompiler.Tickompiler.GITHUB
import rhmodding.tickompiler.Tickompiler.VERSION
import rhmodding.tickompiler.util.escape
import java.io.ByteArrayInputStream
import java.nio.ByteOrder
import java.util.*
import kotlin.math.max
class Decompiler(val array: ByteArray, val order: ByteOrder, val functions: Functions) {
var input = ByteArrayInputStream(array)
private fun read(): Long {
val r = input.read()
if (r == -1)
throw IllegalStateException("End of stream reached")
return r.toLong()
}
private fun readInt(): Long {
return if (order == ByteOrder.LITTLE_ENDIAN) {
read() or (read() shl 8) or (read() shl 16) or (read() shl 24)
} else {
(read() shl 24) or (read() shl 16) or (read() shl 8) or read()
}
}
private fun readStringAuto(): Pair<String, Int> {
var result = ""
var i = 2
var r = read()
if (r == 0L) {
return "" to 1
}
var u = false
result += r.toChar()
r = read()
if (r == 0L) {
u = true
r = read()
read()
i += 2
}
while (r != 0L) {
result += r.toChar()
r = read()
i++
if (u) {
read()
i++
}
}
while (i % 4 != 0) {
read()
i++
}
return Pair(result, i)
}
fun decompile(addComments: CommentType, useMetadata: Boolean, indent: String = "\t", macros: Map<Int, Int> = mapOf()): Pair<Double, String> {
val nanoTime = System.nanoTime()
val builder = StringBuilder()
val state = DecompilerState()
run decompilerInfo@ {
builder.append("// Decompiled using Tickompiler $VERSION\n// $GITHUB\n")
}
val markers = mutableMapOf<Long, String>()
if (useMetadata) {
builder.append("#index 0x${readInt().toString(16).toUpperCase()}\n")
markers[readInt()] = "start"
markers[readInt()] = "assets"
}
for ((key, value) in macros) {
markers[key.toLong()] = "sub${value.toString(16).toUpperCase()}"
}
var markerC = 0
val strings = mutableMapOf<Long, String>()
var counter = 0L
// first pass is to construct a list of markers:
while (input.available() > 0) {
val anns = mutableListOf<Long>()
var opint: Long = readInt()
if (opint == 0xFFFFFFFE) {
break
}
if (opint == 0xFFFFFFFF) {
val amount = readInt()
for (i in 1..amount) {
anns.add(readInt())
}
opint = readInt()
}
val opcode: Long = opint and 0b1111111111
val special: Long = (opint ushr 14)
val argCount: Long = (opint ushr 10) and 0b1111
val args: MutableList<Long> = mutableListOf()
if (argCount > 0) {
for (i in 1..argCount) {
args.add(readInt())
}
}
anns.forEach {
val anncode = it and 0xFF
val annArg = (it ushr 8).toInt()
if (anncode == 0L) {
if (!markers.contains(args[annArg])) {
markers[args[annArg]] = "loc${markerC++}"
}
}
}
counter += 4 * (1 + argCount)
}
// and also strings
while (input.available() > 0) {
val p = readStringAuto()
strings[counter] = p.first.escape()
counter += p.second
}
// reset input stream for the second pass:
input = ByteArrayInputStream(array)
if (useMetadata) {
input.skip(12)
}
counter = 0L
while (input.available() > 0) {
if (markers.contains(counter)) {
builder.append("${markers[counter]}:\n")
}
val specialArgStrings: MutableMap<Int, String> = mutableMapOf()
val anns = mutableListOf<Long>()
var opint: Long = readInt()
if (opint == 0xFFFFFFFE) {
break
}
if (opint == 0xFFFFFFFF) {
val amount = readInt()
for (i in 1..amount) {
anns.add(readInt())
}
}
var bytes = 0
anns.forEach {
if ((it and 0xFF) == 3L) {
bytes = (it ushr 8).toInt()
}
}
if (bytes > 0) {
val padding = 4 - (bytes % 4) - (if (bytes % 4 == 0) 4 else 0)
counter += bytes + padding
val byteList = mutableListOf<Long>()
for (i in 1..bytes) {
byteList.add(read())
}
for (i in 1..padding) {
read()
}
val function: Function = BytesFunction()
val tickflow = function.produceTickflow(state, 0, 0, byteList.toLongArray(), addComments, specialArgStrings)
for (i in 1..state.nextIndentLevel) {
builder.append(indent)
}
builder.append(tickflow + "\n")
continue
}
if (opint == 0xFFFFFFFF) {
opint = readInt()
}
val opcode: Long = opint and 0b1111111111
val special: Long = (opint ushr 14)
val argCount: Long = (opint ushr 10) and 0b1111
val function: Function = functions[opint]
val args: MutableList<Long> = mutableListOf()
if (argCount > 0) {
for (i in 1..argCount) {
args.add(readInt())
}
}
anns.forEach {
val anncode = it and 0b11111111
val annArg = (it ushr 8).toInt()
when(anncode) {
0L -> specialArgStrings[annArg] = markers[args[annArg]] ?: args[annArg].toString()
1L -> specialArgStrings[annArg] = "u\"" + (strings[args[annArg]] ?: "") + '"'
2L -> specialArgStrings[annArg] = '"' + (strings[args[annArg]] ?: "") + '"'
}
}
val oldIndent = state.nextIndentLevel
val tickFlow = function.produceTickflow(state, opcode, special, args.toLongArray(), addComments,
specialArgStrings)
for (i in 1..(oldIndent + state.currentAdjust)) {
builder.append(indent)
}
builder.append(tickFlow)
if (addComments == CommentType.BYTECODE) {
fun Int.toLittleEndianHex(): String {
return toString(16).padStart(8, '0').toUpperCase(Locale.ROOT)
}
builder.append(" // bytecode: ${opint.toInt().toLittleEndianHex()} ${args.joinToString(" "){it.toInt().toLittleEndianHex()}}")
}
builder.append('\n')
state.currentAdjust = 0
state.nextIndentLevel = max(state.nextIndentLevel, 0)
counter += 4 * (1 + argCount)
}
return ((System.nanoTime() - nanoTime) / 1_000_000.0) to builder.toString()
}
}
data class DecompilerState(var nextIndentLevel: Int = 0, var currentAdjust: Int = 0)
enum class CommentType {
NONE, NORMAL, BYTECODE
}
| mit | eba43fb35389b25139b7b6b8735e35a8 | 31.510373 | 145 | 0.479898 | 4.508055 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/facet/impl/FacetEventsPublisher.kt | 3 | 6349 | // 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.facet.impl
import com.intellij.ProjectTopics
import com.intellij.facet.*
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.impl.ModuleEx
import com.intellij.openapi.project.ModuleListener
import com.intellij.openapi.project.Project
import com.intellij.util.containers.ContainerUtil
import java.util.*
@Service
internal class FacetEventsPublisher(private val project: Project) {
private val facetsByType: MutableMap<FacetTypeId<*>, MutableMap<Facet<*>, Boolean>> = HashMap()
private val manuallyRegisteredListeners = ContainerUtil.createConcurrentList<Pair<FacetTypeId<*>?, ProjectFacetListener<*>>>()
init {
val connection = project.messageBus.connect()
connection.subscribe(ProjectTopics.MODULES, object : ModuleListener {
override fun modulesAdded(project: Project, modules: MutableList<Module>) {
for (module in modules) {
onModuleAdded(module)
}
}
override fun moduleRemoved(project: Project, module: Module) {
onModuleRemoved(module)
}
})
for (module in ModuleManager.getInstance(project).modules) {
onModuleAdded(module)
}
}
companion object {
@JvmStatic
fun getInstance(project: Project): FacetEventsPublisher = project.service()
@JvmField
internal val LISTENER_EP = ExtensionPointName<ProjectFacetListenerEP>("com.intellij.projectFacetListener")
private val LISTENER_EP_CACHE_KEY = java.util.function.Function<ProjectFacetListenerEP, String> { it.facetTypeId }
private const val ANY_TYPE = "any"
}
fun <F : Facet<*>> registerListener(type: FacetTypeId<F>?, listener: ProjectFacetListener<out F>) {
manuallyRegisteredListeners += Pair(type, listener)
}
fun <F : Facet<*>> unregisterListener(type: FacetTypeId<F>?, listener: ProjectFacetListener<out F>) {
manuallyRegisteredListeners -= Pair(type, listener)
}
fun fireBeforeFacetAdded(facet: Facet<*>) {
getPublisher(facet.module).beforeFacetAdded(facet)
}
fun fireBeforeFacetRemoved(facet: Facet<*>) {
getPublisher(facet.module).beforeFacetRemoved(facet)
onFacetRemoved(facet, true)
}
fun fireBeforeFacetRenamed(facet: Facet<*>) {
getPublisher(facet.module).beforeFacetRenamed(facet)
}
fun fireFacetAdded(facet: Facet<*>) {
getPublisher(facet.module).facetAdded(facet)
onFacetAdded(facet)
}
fun fireFacetRemoved(module: Module, facet: Facet<*>) {
getPublisher(module).facetRemoved(facet)
onFacetRemoved(facet, false)
}
fun fireFacetRenamed(facet: Facet<*>, newName: String) {
getPublisher(facet.module).facetRenamed(facet, newName)
}
fun fireFacetConfigurationChanged(facet: Facet<*>) {
getPublisher(facet.module).facetConfigurationChanged(facet)
onFacetChanged(facet)
}
private fun onModuleRemoved(module: Module) {
for (facet in FacetManager.getInstance(module).allFacets) {
onFacetRemoved(facet, false)
}
}
private fun onModuleAdded(module: Module) {
for (facet in FacetManager.getInstance(module).allFacets) {
onFacetAdded(facet)
}
}
private fun <F : Facet<*>> onFacetRemoved(facet: F, before: Boolean) {
val typeId = facet.typeId
val facets = facetsByType[typeId]
val lastFacet: Boolean
if (facets != null) {
facets.remove(facet)
lastFacet = facets.isEmpty()
if (lastFacet) {
facetsByType.remove(typeId)
}
}
else {
lastFacet = true
}
processListeners(facet.type) {
if (before) {
it.beforeFacetRemoved(facet)
}
else {
it.facetRemoved(facet, project)
if (lastFacet) {
it.allFacetsRemoved(project)
}
}
}
processListeners {
if (before) {
it.beforeFacetRemoved(facet)
}
else {
it.facetRemoved(facet, project)
if (facetsByType.isEmpty()) {
it.allFacetsRemoved(project)
}
}
}
}
private fun <F : Facet<*>> onFacetAdded(facet: F) {
val firstFacet = facetsByType.isEmpty()
val typeId = facet.typeId
var facets = facetsByType[typeId]
if (facets == null) {
facets = WeakHashMap()
facetsByType[typeId] = facets
}
val firstFacetOfType = facets.isEmpty()
facets[facet] = true
processListeners {
if (firstFacet) {
it.firstFacetAdded(project)
}
it.facetAdded(facet)
}
processListeners(facet.type) {
if (firstFacetOfType) {
it.firstFacetAdded(project)
}
it.facetAdded(facet)
}
}
private fun <F : Facet<*>> onFacetChanged(facet: F) {
processListeners(facet.type) {
it.facetConfigurationChanged(facet)
}
processListeners {
it.facetConfigurationChanged(facet)
}
}
@Suppress("UNCHECKED_CAST")
private inline fun <F : Facet<*>> processListeners(facetType: FacetType<F, *>, action: (ProjectFacetListener<F>) -> Unit) {
for (listenerEP in LISTENER_EP.getByGroupingKey<String>(facetType.stringId, LISTENER_EP_CACHE_KEY::class.java, LISTENER_EP_CACHE_KEY)) {
action(listenerEP.listenerInstance as ProjectFacetListener<F>)
}
manuallyRegisteredListeners.filter { it.first == facetType.id }.forEach {
action(it.second as ProjectFacetListener<F>)
}
}
@Suppress("UNCHECKED_CAST")
private inline fun processListeners(action: (ProjectFacetListener<Facet<*>>) -> Unit) {
for (listenerEP in LISTENER_EP.getByGroupingKey<String>(ANY_TYPE, LISTENER_EP_CACHE_KEY::class.java, LISTENER_EP_CACHE_KEY)) {
action(listenerEP.listenerInstance as ProjectFacetListener<Facet<*>>)
}
manuallyRegisteredListeners.asSequence()
.filter { it.first == null }
.forEach {
action(it.second as ProjectFacetListener<Facet<*>>)
}
}
private fun getPublisher(module: Module): FacetManagerListener {
@Suppress("DEPRECATION")
return ((module as? ModuleEx)?.deprecatedModuleLevelMessageBus ?: module.messageBus).syncPublisher(FacetManager.FACETS_TOPIC)
}
}
| apache-2.0 | 173959c60c6d18f4a1c1d561617632ce | 30.904523 | 140 | 0.694283 | 4.464838 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Username.kt | 1 | 2019 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.common.startsWith
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type.*
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
class Username : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.interfaces.contains(Comparable::class.type) }
.and { it.instanceFields.count() == 2 }
.and { it.instanceFields.count { it.type == String::class.type } == 2 }
class name0 : OrderMapper.InConstructor.Field(Username::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type }
}
class cleanName : OrderMapper.InConstructor.Field(Username::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type }
}
@MethodParameters()
class name : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == String::class.type }
.and { it.name != "toString" }
}
@MethodParameters("other")
class compareTo0 : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE }
.and { it.arguments.startsWith(type<Username>()) }
}
@MethodParameters()
class hasCleanName : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
.and { it.name != "equals" }
}
} | mit | 2e95d092b308e111947f39dc9aa26afd | 42.913043 | 122 | 0.710748 | 4.20625 | false | false | false | false |
Kotlin/kotlinx.coroutines | reactive/kotlinx-coroutines-rx3/src/RxCompletable.kt | 1 | 2280 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.rx3
import io.reactivex.rxjava3.core.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
/**
* Creates cold [Completable] that runs a given [block] in a coroutine and emits its result.
* Every time the returned completable is subscribed, it starts a new coroutine.
* Unsubscribing cancels running coroutine.
* Coroutine context can be specified with [context] argument.
* If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used.
* Method throws [IllegalArgumentException] if provided [context] contains a [Job] instance.
*/
public fun rxCompletable(
context: CoroutineContext = EmptyCoroutineContext,
block: suspend CoroutineScope.() -> Unit
): Completable {
require(context[Job] === null) { "Completable context cannot contain job in it." +
"Its lifecycle should be managed via Disposable handle. Had $context" }
return rxCompletableInternal(GlobalScope, context, block)
}
private fun rxCompletableInternal(
scope: CoroutineScope, // support for legacy rxCompletable in scope
context: CoroutineContext,
block: suspend CoroutineScope.() -> Unit
): Completable = Completable.create { subscriber ->
val newContext = scope.newCoroutineContext(context)
val coroutine = RxCompletableCoroutine(newContext, subscriber)
subscriber.setCancellable(RxCancellable(coroutine))
coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
}
private class RxCompletableCoroutine(
parentContext: CoroutineContext,
private val subscriber: CompletableEmitter
) : AbstractCoroutine<Unit>(parentContext, false, true) {
override fun onCompleted(value: Unit) {
try {
subscriber.onComplete()
} catch (e: Throwable) {
handleUndeliverableException(e, context)
}
}
override fun onCancelled(cause: Throwable, handled: Boolean) {
try {
if (subscriber.tryOnError(cause)) {
return
}
} catch (e: Throwable) {
cause.addSuppressed(e)
}
handleUndeliverableException(cause, context)
}
}
| apache-2.0 | cd633286939b8d7a7f93a77cabe0e8e9 | 36.377049 | 123 | 0.710088 | 4.701031 | false | false | false | false |
leafclick/intellij-community | plugins/stats-collector/src/com/intellij/stats/completion/ItemsDiffCustomizingContributor.kt | 1 | 2779 | // 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.stats.completion
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementDecorator
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.completion.settings.CompletionMLRankingSettings
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.intellij.stats.storage.factors.LookupStorage
import com.intellij.ui.JBColor
import java.awt.Color
import java.util.concurrent.atomic.AtomicInteger
class ItemsDiffCustomizingContributor : CompletionContributor() {
companion object {
val DIFF_KEY = Key.create<AtomicInteger>("ItemsDiffCustomizerContributor.DIFF_KEY")
}
override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) {
if (shouldShowDiff(parameters)) {
result.runRemainingContributors(parameters) {
result.passResult(it.withLookupElement(MovedLookupElement(it.lookupElement)))
}
}
else {
super.fillCompletionVariants(parameters, result)
}
}
private fun shouldShowDiff(parameters: CompletionParameters): Boolean {
val mlRankingSettings = CompletionMLRankingSettings.getInstance()
if (!mlRankingSettings.isShowDiffEnabled) return false
if (!mlRankingSettings.isRankingEnabled) return false
val lookup = LookupManager.getActiveLookup(parameters.editor) as? LookupImpl ?: return false
return LookupStorage.get(lookup)?.model != null
}
private class MovedLookupElement(delegate: LookupElement) : LookupElementDecorator<LookupElement>(delegate) {
private companion object {
val ML_RANK_DIFF_GREEN_COLOR = JBColor(JBColor.GREEN.darker(), JBColor.GREEN.brighter())
}
override fun renderElement(presentation: LookupElementPresentation) {
super.renderElement(presentation)
val diff = getUserData(DIFF_KEY)?.get()
if (diff == null || diff == 0 || !presentation.isReal) return
val text = if (diff < 0) " ↑${-diff} " else " ↓$diff "
val color: Color = if (diff < 0) ML_RANK_DIFF_GREEN_COLOR else JBColor.RED
val fragments = presentation.tailFragments
presentation.setTailText(text, color)
for (fragment in fragments) {
presentation.appendTailText(fragment.text, fragment.isGrayed)
}
}
}
} | apache-2.0 | 748ca13b9402a8ffab5dbb0021c0147a | 42.375 | 140 | 0.773694 | 4.564145 | false | false | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/GithubAuthenticationManager.kt | 1 | 6202 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import git4idea.DialogManager
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.annotations.TestOnly
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager
import org.jetbrains.plugins.github.authentication.accounts.GithubProjectDefaultAccountHolder
import org.jetbrains.plugins.github.authentication.ui.GithubLoginDialog
import java.awt.Component
/**
* Entry point for interactions with Github authentication subsystem
*/
class GithubAuthenticationManager internal constructor() {
private val accountManager: GithubAccountManager
get() = service()
@CalledInAny
fun hasAccounts() = accountManager.accounts.isNotEmpty()
@CalledInAny
fun getAccounts(): Set<GithubAccount> = accountManager.accounts
@CalledInAny
internal fun getTokenForAccount(account: GithubAccount): String? = accountManager.getTokenForAccount(account)
@CalledInAwt
@JvmOverloads
internal fun requestNewToken(account: GithubAccount, project: Project?, parentComponent: Component? = null): String? {
val dialog = GithubLoginDialog(GithubApiRequestExecutor.Factory.getInstance(), project, parentComponent, message = "Missing access token for $account")
.withServer(account.server.toString(), false)
.withCredentials(account.name)
.withToken()
DialogManager.show(dialog)
if (!dialog.isOK) return null
val token = dialog.getToken()
account.name = dialog.getLogin()
accountManager.updateAccountToken(account, token)
return token
}
@CalledInAwt
@JvmOverloads
fun requestNewAccount(project: Project?, parentComponent: Component? = null): GithubAccount? {
val dialog = GithubLoginDialog(GithubApiRequestExecutor.Factory.getInstance(), project, parentComponent, ::isAccountUnique)
DialogManager.show(dialog)
if (!dialog.isOK) return null
return registerAccount(dialog.getLogin(), dialog.getServer(), dialog.getToken())
}
@CalledInAwt
@JvmOverloads
fun requestNewAccountForServer(server: GithubServerPath, project: Project?, parentComponent: Component? = null): GithubAccount? {
val dialog = GithubLoginDialog(GithubApiRequestExecutor.Factory.getInstance(), project, parentComponent, ::isAccountUnique).withServer(server.toUrl(), false)
DialogManager.show(dialog)
if (!dialog.isOK) return null
return registerAccount(dialog.getLogin(), dialog.getServer(), dialog.getToken())
}
@CalledInAwt
@JvmOverloads
fun requestNewAccountForServer(server: GithubServerPath,
login: String,
project: Project?,
parentComponent: Component? = null): GithubAccount? {
val dialog = GithubLoginDialog(GithubApiRequestExecutor.Factory.getInstance(), project, parentComponent, ::isAccountUnique)
.withServer(server.toUrl(), false)
.withCredentials(login, editableLogin = false)
DialogManager.show(dialog)
if (!dialog.isOK) return null
return registerAccount(dialog.getLogin(), dialog.getServer(), dialog.getToken())
}
internal fun isAccountUnique(name: String,
server: GithubServerPath) = accountManager.accounts.none { it.name == name && it.server == server }
@CalledInAwt
@JvmOverloads
fun requestReLogin(account: GithubAccount, project: Project?, parentComponent: Component? = null): Boolean {
val dialog = GithubLoginDialog(GithubApiRequestExecutor.Factory.getInstance(), project, parentComponent)
.withServer(account.server.toString(), false)
.withCredentials(account.name)
DialogManager.show(dialog)
if (!dialog.isOK) return false
val token = dialog.getToken()
account.name = dialog.getLogin()
accountManager.updateAccountToken(account, token)
return true
}
@CalledInAwt
internal fun removeAccount(githubAccount: GithubAccount) {
accountManager.accounts -= githubAccount
}
@CalledInAwt
internal fun updateAccountToken(account: GithubAccount, newToken: String) {
accountManager.updateAccountToken(account, newToken)
}
private fun registerAccount(name: String, server: GithubServerPath, token: String): GithubAccount {
val account = GithubAccountManager.createAccount(name, server)
accountManager.accounts += account
accountManager.updateAccountToken(account, token)
return account
}
@CalledInAwt
internal fun registerAccount(name: String, host: String, token: String): GithubAccount {
return registerAccount(name, GithubServerPath.from(host), token)
}
@TestOnly
fun clearAccounts() {
for (account in accountManager.accounts) accountManager.updateAccountToken(account, null)
accountManager.accounts = emptySet()
}
fun getDefaultAccount(project: Project): GithubAccount? {
return project.service<GithubProjectDefaultAccountHolder>().account
}
@TestOnly
fun setDefaultAccount(project: Project, account: GithubAccount?) {
project.service<GithubProjectDefaultAccountHolder>().account = account
}
@CalledInAwt
@JvmOverloads
fun ensureHasAccounts(project: Project?, parentComponent: Component? = null): Boolean {
if (!hasAccounts()) {
if (requestNewAccount(project, parentComponent) == null) {
return false
}
}
return true
}
fun getSingleOrDefaultAccount(project: Project): GithubAccount? {
project.service<GithubProjectDefaultAccountHolder>().account?.let { return it }
val accounts = accountManager.accounts
if (accounts.size == 1) return accounts.first()
return null
}
companion object {
@JvmStatic
fun getInstance(): GithubAuthenticationManager {
return service()
}
}
}
| apache-2.0 | 9d33e2645c49ab7ddffca3efcd2b1904 | 36.361446 | 161 | 0.747823 | 5.021862 | false | false | false | false |
aconsuegra/algorithms-playground | src/main/kotlin/me/consuegra/algorithms/KRemoveElement.kt | 1 | 785 | package me.consuegra.algorithms
/**
* Given an array and a value, remove all instances of that value in place and return the new length.
* <p>
* Do not allocate extra space for another array, you must do this in place with constant memory.
* <p>
* The order of elements can be changed. It doesn't matter what you leave beyond the new length.
* <p>
* Example:
* Given input array nums = [3,2,2,3], val = 3
* <p>
* Your function should return length = 2, with the first two elements of nums being 2.
*/
class KRemoveElement {
fun removeElement(input: IntArray, element: Int): Int {
var i = 0
for (value in input) {
if (value != element) {
input[i] = value
i++
}
}
return i
}
}
| mit | c313f8001e8e33cc26af081a5e9e0381 | 27.035714 | 101 | 0.603822 | 3.829268 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/extensionProperties/accessorForPrivateSetter.kt | 5 | 351 | class A {
var result = "Fail"
private var Int.foo: String
get() = result
private set(value) {
result = value
}
fun run(): String {
class O {
fun run() {
42.foo = "OK"
}
}
O().run()
return (-42).foo
}
}
fun box() = A().run()
| apache-2.0 | 8651f6719998c0b826bb018b1e541070 | 15.714286 | 31 | 0.376068 | 3.94382 | false | false | false | false |
AndroidX/androidx | room/room-runtime/src/test/java/androidx/room/InvalidationLiveDataContainerTest.kt | 3 | 3524 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room
import androidx.lifecycle.LiveData
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mockito
import java.util.concurrent.Callable
@RunWith(JUnit4::class)
class InvalidationLiveDataContainerTest {
private lateinit var container: InvalidationLiveDataContainer
@Before
fun init() {
container = InvalidationLiveDataContainer(
Mockito.mock(RoomDatabase::class.java)
)
}
@Test
fun add() {
val liveData = createLiveData()
assertThat(container.liveDataSet, `is`(emptySet()))
container.onActive(liveData)
assertThat(container.liveDataSet, `is`(setOf(liveData)))
}
@Test
fun add_twice() {
val liveData = createLiveData()
container.onActive(liveData)
container.onActive(liveData)
assertThat(container.liveDataSet, `is`(setOf(liveData)))
}
@Test
fun remove() {
val liveData = createLiveData()
container.onActive(liveData)
container.onInactive(liveData)
assertThat(container.liveDataSet, `is`(emptySet()))
}
@Test
fun remove_twice() {
val liveData = createLiveData()
container.onActive(liveData)
container.onInactive(liveData)
container.onInactive(liveData)
assertThat(container.liveDataSet, `is`(emptySet()))
}
@Test
fun addRemoveMultiple() {
val ld1 = createLiveData()
val ld2 = createLiveData()
assertThat(container.liveDataSet, `is`(emptySet()))
container.onActive(ld1)
container.onActive(ld2)
assertThat(container.liveDataSet, `is`(setOf(ld1, ld2)))
container.onInactive(ld1)
assertThat(container.liveDataSet, `is`(setOf(ld2)))
container.onInactive(ld1) // intentional
assertThat(container.liveDataSet, `is`(setOf(ld2)))
container.onActive(ld1)
assertThat(container.liveDataSet, `is`(setOf(ld1, ld2)))
container.onActive(ld1) // intentional
assertThat(container.liveDataSet, `is`(setOf(ld1, ld2)))
container.onInactive(ld2)
assertThat(container.liveDataSet, `is`(setOf(ld1)))
container.onInactive(ld1)
assertThat(container.liveDataSet, `is`(emptySet()))
container.onActive(ld1)
assertThat(container.liveDataSet, `is`(setOf(ld1)))
container.onActive(ld2)
assertThat(container.liveDataSet, `is`(setOf(ld1, ld2)))
}
private fun createLiveData(): LiveData<Any> {
return container.create(
arrayOf("a", "b"),
false,
createComputeFunction<Any>()
)
}
private fun <T> createComputeFunction(): Callable<T> {
return Callable<T> { null }
}
} | apache-2.0 | 60bfa6c64eee0c2c3ea5e48e85285617 | 31.045455 | 75 | 0.66714 | 4.287105 | false | true | false | false |
smmribeiro/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/settings/MarkdownSettingsUtil.kt | 1 | 2978 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.settings
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.project.Project
import com.intellij.util.application
import com.intellij.util.download.DownloadableFileService
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.extensions.MarkdownExtensionWithDownloadableFiles
import org.intellij.plugins.markdown.extensions.ExtensionsExternalFilesPathManager
import org.intellij.plugins.markdown.extensions.ExtensionsExternalFilesPathManager.Companion.obtainExternalFilesDirectoryPath
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
import kotlin.io.path.absolutePathString
@ApiStatus.Internal
object MarkdownSettingsUtil {
fun downloadExtensionFiles(
extension: MarkdownExtensionWithDownloadableFiles,
project: Project? = null,
parentComponent: JComponent? = null
): Boolean {
val downloader = DownloadableFileService.getInstance()
val descriptions = extension.filesToDownload.mapNotNull { entry ->
entry.link.get()?.let { downloader.createFileDescription(it, entry.filePath) }
}
ExtensionsExternalFilesPathManager.getInstance().cleanupExternalFiles(extension)
val directory = extension.obtainExternalFilesDirectoryPath()
val actualDownloader = downloader.createDownloader(descriptions, "Downloading Extension Files")
val files = actualDownloader.downloadFilesWithProgress(directory.absolutePathString(), project, parentComponent)
return files != null
}
fun downloadExtension(
extension: MarkdownExtensionWithDownloadableFiles,
project: Project? = null,
enableAfterDownload: Boolean = false
): Boolean {
if (extension.downloadFiles(project)) {
if (enableAfterDownload) {
MarkdownExtensionsSettings.getInstance().extensionsEnabledState[extension.id] = true
application.messageBus.syncPublisher(MarkdownExtensionsSettings.ChangeListener.TOPIC).extensionsSettingsChanged(fromSettingsDialog = false)
}
Notifications.Bus.notify(
Notification(
"Markdown",
MarkdownBundle.message("markdown.settings.download.extension.notification.title"),
MarkdownBundle.message("markdown.settings.download.extension.notification.success.content"),
NotificationType.INFORMATION
)
)
return true
} else {
Notifications.Bus.notify(
Notification(
"Markdown",
MarkdownBundle.message("markdown.settings.download.extension.notification.title"),
MarkdownBundle.message("markdown.settings.download.extension.notification.failure.content"),
NotificationType.ERROR
)
)
return false
}
}
}
| apache-2.0 | 6f67b59e0bb2d9903b643a96a7d4f150 | 43.447761 | 147 | 0.774345 | 5.197208 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-api/src/com/intellij/openapi/vcs/changes/ChangeListChange.kt | 8 | 952 | // 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.openapi.vcs.changes
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.containers.HashingStrategy
import org.jetbrains.annotations.NonNls
class ChangeListChange(
val change: Change,
val changeListName: @NlsSafe String,
val changeListId: @NonNls String
) : Change(change) {
companion object {
@JvmField
val HASHING_STRATEGY: HashingStrategy<Any> = object : HashingStrategy<Any> {
override fun hashCode(o: Any?): Int = o?.hashCode() ?: 0
override fun equals(o1: Any?, o2: Any?): Boolean {
return when {
o1 is ChangeListChange && o2 is ChangeListChange -> o1 == o2 && o1.changeListId == o2.changeListId
o1 is ChangeListChange || o2 is ChangeListChange -> false
else -> o1 == o2
}
}
}
}
}
| apache-2.0 | d0c36145eeaa9016d13ce132127f6b5b | 33 | 140 | 0.684874 | 4 | false | false | false | false |
Flank/flank | flank-scripts/src/main/kotlin/flank/scripts/cli/github/DeleteOldTagCommand.kt | 1 | 632 | package flank.scripts.cli.github
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
import flank.scripts.ops.github.tryDeleteOldTag
object DeleteOldTagCommand : CliktCommand(
name = "delete_old_tag",
help = "Delete old tag on GitHub"
) {
private val gitTag by option(help = "Git Tag").required()
private val username by option(help = "Git User").required()
private val token by option(help = "Git Token").required()
override fun run() {
tryDeleteOldTag(gitTag, username, token)
}
}
| apache-2.0 | 631dd8dfa122954f1bb6081a65fb10c3 | 32.263158 | 64 | 0.734177 | 3.761905 | false | false | false | false |
AdamMc331/RecyclerViewUtils | lib/src/main/java/com/adammcneilly/CoreDividerItemDecoration.kt | 1 | 3848 | package com.adammcneilly
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
/**
* DividerItemDecoration to show between RecyclerView items.
*
* Created by adam.mcneilly on 7/26/16.
*/
class CoreDividerItemDecoration @JvmOverloads constructor(context: Context, orientation: Int = CoreDividerItemDecoration.VERTICAL_LIST) : RecyclerView.ItemDecoration() {
/**
* The orientation of the list.
*/
private var orientation: Int = 0
/**
* The actual divider that is displayed.
*/
private val divider: Drawable
init {
val a = context.obtainStyledAttributes(ATTRS)
divider = a.getDrawable(DIVIDER_POSITION)
a.recycle()
setOrientation(orientation)
}
/**
* Sets the orientation of this item decoration. An exception is thrown if it is not one of
* the two given orientations.
*/
private fun setOrientation(orientation: Int) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw IllegalArgumentException(INVALID_ORIENTATION)
}
this.orientation = orientation
}
/**
* Draws the divider depending on the orientation of the RecyclerView.
*/
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) {
when (orientation) {
VERTICAL_LIST -> drawVertical(c, parent)
HORIZONTAL_LIST -> drawHorizontal(c, parent)
}
}
/**
* Draws a divider for a vertical RecyclerView list.
*/
private fun drawVertical(c: Canvas, parent: RecyclerView) {
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
val childCount = parent.childCount
for (i in 0..childCount - 1) {
val child = parent.getChildAt(i)
val params = child
.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + divider.intrinsicHeight
divider.setBounds(left, top, right, bottom)
divider.draw(c)
}
}
/**
* Draws a divider for a horizontal RecyclerView list.
*/
private fun drawHorizontal(c: Canvas, parent: RecyclerView) {
val top = parent.paddingTop
val bottom = parent.height - parent.paddingBottom
val childCount = parent.childCount
for (i in 0..childCount - 1) {
val child = parent.getChildAt(i)
val params = child
.layoutParams as RecyclerView.LayoutParams
val left = child.right + params.rightMargin
val right = left + divider.intrinsicHeight
divider.setBounds(left, top, right, bottom)
divider.draw(c)
}
}
/**
* Determines the offset of the divider based on the orientation of the list.
*/
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
when (orientation) {
VERTICAL_LIST -> outRect.set(0, 0, 0, divider.intrinsicHeight)
HORIZONTAL_LIST -> outRect.set(0, 0, divider.intrinsicWidth, 0)
}
}
companion object {
// Attributes for the divider
private val ATTRS = intArrayOf(android.R.attr.listDivider)
private val DIVIDER_POSITION = 0
// List orientations
val HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL
val VERTICAL_LIST = LinearLayoutManager.VERTICAL
// Error message
val INVALID_ORIENTATION = "Please supply a valid CoreDividerItemDecoration orientation."
}
} | mit | b43826f44e7fdf8c4c083eac85d7bde9 | 32.181034 | 169 | 0.643711 | 4.870886 | false | false | false | false |
mbrlabs/Mundus | editor/src/main/com/mbrlabs/mundus/editor/input/KeyboardLayoutInputAdapter.kt | 1 | 1436 | /*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.input
import com.badlogic.gdx.Input
import com.badlogic.gdx.InputAdapter
import com.mbrlabs.mundus.editor.core.registry.KeyboardLayout
import com.mbrlabs.mundus.editor.core.registry.Registry
/**
* Workaround for LWJGL3's (or GLFW's) key codes and different keyboard layouts.
*
* @author Marcus Brummer
* @version 07-02-2016
*/
open class KeyboardLayoutInputAdapter(private val registry: Registry) : InputAdapter() {
protected fun convertKeycode(code: Int): Int {
if (registry.settings.keyboardLayout == KeyboardLayout.QWERTZ) {
if (code == Input.Keys.Z) {
return Input.Keys.Y
} else if (code == Input.Keys.Y) {
return Input.Keys.Z
}
}
// return default QWERTY
return code
}
}
| apache-2.0 | f3cba2ddffb36490a9c6d6c750c7049f | 30.911111 | 88 | 0.690111 | 4 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/configuration/KotlinTargetDataService.kt | 1 | 3295 | // 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.configuration
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.packaging.artifacts.ModifiableArtifactModel
import com.intellij.packaging.impl.artifacts.JarArtifactType
import com.intellij.packaging.impl.elements.ProductionModuleOutputPackagingElement
import org.jetbrains.kotlin.idea.util.createPointer
class KotlinTargetDataService : AbstractProjectDataService<KotlinTargetData, Void>() {
override fun getTargetDataKey() = KotlinTargetData.KEY
override fun importData(
toImport: MutableCollection<out DataNode<KotlinTargetData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
for (nodeToImport in toImport) {
val targetData = nodeToImport.data
val archiveFile = targetData.archiveFile ?: continue
//TODO(auskov) should be replaced with direct invocation of the method after migration to new API in IDEA 192
val artifactModel = try {
val oldMethod = modelsProvider.javaClass.getMethod("getModifiableArtifactModel")
oldMethod.invoke(modelsProvider) as ModifiableArtifactModel
} catch (_: Exception) {
val newMethod = modelsProvider.javaClass.getMethod("getModifiableModel", Class::class.java)
val packagingModifiableModel = newMethod.invoke(
modelsProvider,
Class.forName("com.intellij.openapi.externalSystem.project.PackagingModifiableModel")
)
packagingModifiableModel.javaClass
.getMethod("getModifiableArtifactModel")
.invoke(packagingModifiableModel) as ModifiableArtifactModel
}
val artifactName = FileUtil.getNameWithoutExtension(archiveFile)
artifactModel.findArtifact(artifactName)?.let { artifactModel.removeArtifact(it) }
artifactModel.addArtifact(artifactName, JarArtifactType.getInstance()).also {
it.outputPath = archiveFile.parent
for (moduleId in targetData.moduleIds) {
val compilationModuleDataNode = nodeToImport.parent?.findChildModuleById(moduleId) ?: continue
val compilationData = compilationModuleDataNode.data
val kotlinSourceSet = compilationModuleDataNode.kotlinSourceSet ?: continue
if (kotlinSourceSet.isTestModule) continue
val moduleToPackage = modelsProvider.findIdeModule(compilationData) ?: continue
it.rootElement.addOrFindChild(ProductionModuleOutputPackagingElement(project, moduleToPackage.createPointer()))
}
}
}
}
} | apache-2.0 | e77319e09d3607991d4c4956e27bdcb7 | 54.864407 | 158 | 0.711077 | 5.801056 | false | false | false | false |
JetBrains/xodus | environment/src/main/kotlin/jetbrains/exodus/gc/CleanEntireLogJob.kt | 1 | 1768 | /**
* Copyright 2010 - 2022 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
*
* 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 jetbrains.exodus.gc
import jetbrains.exodus.core.execution.LatchJob
import mu.KLogging
internal class CleanEntireLogJob(private val gc: GarbageCollector) : LatchJob() {
override fun execute() {
logger.info { "CleanEntireLogJob started" }
try {
val log = gc.log
var lastNumberOfFiles = java.lang.Long.MAX_VALUE
// repeat cleaning until number of files stops decreasing
while (true) {
val numberOfFiles = log.numberOfFiles
if (numberOfFiles == 1L || numberOfFiles >= lastNumberOfFiles) break
lastNumberOfFiles = numberOfFiles
val highFileAddress = log.highFileAddress
var fileAddress = log.lowAddress
while (fileAddress != highFileAddress) {
gc.doCleanFile(fileAddress)
fileAddress = log.getNextFileAddress(fileAddress)
}
gc.testDeletePendingFiles()
}
} finally {
release()
logger.info { "CleanEntireLogJob finished" }
}
}
companion object : KLogging()
}
| apache-2.0 | f6fb3d766a1f666047e6866b27fd9259 | 34.36 | 84 | 0.637443 | 4.702128 | false | false | false | false |