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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
orgzly/orgzly-android
|
app/src/main/java/com/orgzly/android/ui/dialogs/WhatsNewDialog.kt
|
1
|
1279
|
package com.orgzly.android.ui.dialogs
import android.content.Context
import android.text.method.LinkMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.orgzly.R
import com.orgzly.android.ui.util.getLayoutInflater
import com.orgzly.android.util.MiscUtils
object WhatsNewDialog {
/**
* Display dialog with changes.
*/
fun create(context: Context): AlertDialog {
val layoutView = context.getLayoutInflater().inflate(R.layout.dialog_whats_new, null, false)
layoutView.findViewById<TextView>(R.id.dialog_whats_new_intro).apply {
text = MiscUtils.fromHtml(context.getString(R.string.whats_new_intro))
movementMethod = LinkMovementMethod.getInstance()
}
layoutView.findViewById<TextView>(R.id.dialog_whats_new_outro).apply {
text = MiscUtils.fromHtml(context.getString(R.string.whats_new_outro))
movementMethod = LinkMovementMethod.getInstance()
}
return MaterialAlertDialogBuilder(context)
.setTitle(R.string.whats_new_title)
.setPositiveButton(R.string.ok, null)
.setView(layoutView)
.create()
}
}
|
gpl-3.0
|
3b3aca3e7137d9f4b9be0a95fe429837
| 35.571429 | 100 | 0.70993 | 4.365188 | false | false | false | false |
seventhroot/elysium
|
bukkit/rpk-skills-bukkit/src/main/kotlin/com/rpkit/skills/bukkit/command/SkillCommand.kt
|
1
|
5000
|
package com.rpkit.skills.bukkit.command
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import com.rpkit.skills.bukkit.RPKSkillsBukkit
import com.rpkit.skills.bukkit.skills.RPKSkillProvider
import com.rpkit.skills.bukkit.skills.canUse
import com.rpkit.skills.bukkit.skills.use
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
class SkillCommand(private val plugin: RPKSkillsBukkit): CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (sender.hasPermission("rpkit.skills.command.skill")) {
if (sender is Player) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val skillProvider = plugin.core.serviceManager.getServiceProvider(RPKSkillProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender)
if (minecraftProfile != null) {
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character != null) {
if (args.isNotEmpty()) {
val skill = skillProvider.getSkill(args[0])
if (skill != null) {
if (character.canUse(skill)) {
if (character.mana >= skill.manaCost) {
if (skillProvider.getSkillCooldown(character, skill) <= 0) {
character.use(skill)
skillProvider.setSkillCooldown(character, skill, skill.cooldown)
character.mana -= skill.manaCost
characterProvider.updateCharacter(character)
sender.sendMessage(plugin.messages["skill-valid", mapOf(
Pair("skill", skill.name)
)])
} else {
sender.sendMessage(plugin.messages["skill-invalid-on-cooldown", mapOf(
Pair("skill", skill.name),
Pair("cooldown", skillProvider.getSkillCooldown(character, skill).toString())
)])
}
} else {
sender.sendMessage(plugin.messages["skill-invalid-not-enough-mana", mapOf(
Pair("skill", skill.name),
Pair("mana-cost", skill.manaCost.toString()),
Pair("mana", character.mana.toString()),
Pair("max-mana", character.maxMana.toString())
)])
}
} else {
sender.sendMessage(plugin.messages["skill-invalid-unmet-prerequisites", mapOf(
Pair("skill", skill.name)
)])
}
} else {
sender.sendMessage(plugin.messages["skill-invalid-skill"])
}
} else {
sender.sendMessage(plugin.messages["skill-list-title"])
skillProvider.skills
.filter { skill -> character.canUse(skill) }
.forEach { skill ->
sender.sendMessage(plugin.messages["skill-list-item", mapOf(
Pair("skill", skill.name)
)])
}
}
} else {
sender.sendMessage(plugin.messages["no-character"])
}
} else {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
}
} else {
sender.sendMessage(plugin.messages["not-from-console"])
}
} else {
sender.sendMessage(plugin.messages["no-permission-skill"])
}
return true
}
}
|
apache-2.0
|
ab1e4d9e9773e85dce84136975ee5802
| 56.482759 | 129 | 0.4606 | 6.518905 | false | false | false | false |
like5188/Common
|
common/src/main/java/com/like/common/view/chart/horizontalScrollTwoLineChartView/core/WrapHorizontalScrollTwoLineChartView.kt
|
1
|
2226
|
package com.like.common.view.chart.horizontalScrollTwoLineChartView.core
import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.HorizontalScrollView
import com.like.common.view.chart.horizontalScrollTwoLineChartView.entity.TwoLineData
/**
* 可水平滑动的图表视图,只需要在xml文件中写上此视图即可用,必须调用init()方法
*/
class WrapHorizontalScrollTwoLineChartView(context: Context, attrs: AttributeSet) : HorizontalScrollView(context, attrs) {
val twoLineChartView = TwoLineChartView(context)
init {
isVerticalScrollBarEnabled = false
isHorizontalScrollBarEnabled = false
val layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)
twoLineChartView.layoutParams = layoutParams
addView(twoLineChartView)
}
/**
* 设置数据
*
* @param twoLineDataList 数据
* @param touchPosition 初始触摸位置
* @param showPointCount 一屏幕显示的数据个数
* @param listener 点击监听
*/
fun setData(twoLineDataList: List<TwoLineData>, touchPosition: Int = -1, showPointCount: Int = 3, listener: com.like.common.view.chart.horizontalScrollTwoLineChartView.core.OnClickListener? = null) {
if (showPointCount <= 0) {
throw IllegalArgumentException("showPointCount 参数必须大于0")
}
if (touchPosition >= twoLineDataList.size) {
throw IllegalArgumentException("touchPosition 参数必须小于dataList中的数据个数")
}
twoLineChartView.setData(twoLineDataList, touchPosition, showPointCount, listener)
if (touchPosition != -1) {// 如果有初始值,就使这个值处于屏幕中间
val currentTouchPositionX = (twoLineChartView.mConfig.pointList1[touchPosition].x.toInt()
- twoLineChartView.mConfig.screenWidthPixels / 2).toInt()
// 这里必须用post,因为必须在HorizontalScrollView绘制完成后scrollTo()方法才会有效
this.post({ this.scrollTo(currentTouchPositionX, 0) })
}
}
}
|
apache-2.0
|
4f44825accc6ba7983ee147567cbc9c2
| 41.382979 | 203 | 0.717871 | 4.184874 | false | false | false | false |
timakden/advent-of-code
|
src/main/kotlin/ru/timakden/aoc/year2015/day20/Puzzle.kt
|
1
|
871
|
package ru.timakden.aoc.year2015.day20
import ru.timakden.aoc.util.Constants
import ru.timakden.aoc.util.Constants.Part.PART_ONE
import ru.timakden.aoc.util.Constants.Part.PART_TWO
import ru.timakden.aoc.util.measure
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
measure {
println("Part One: ${solve(input, PART_ONE)}")
println("Part Two: ${solve(input, PART_TWO)}")
}
}
fun solve(input: Int, part: Constants.Part): Int {
val presentsPerElf = if (part == PART_TWO) 11 else 10
val houses = IntArray(1000000)
(1..houses.lastIndex).forEach {
var count = 0
var i = it
while (i <= houses.lastIndex) {
houses[i] += presentsPerElf * it
if (part == PART_TWO && ++count == 50) break
i += it
}
}
return houses.indexOfFirst { it >= input }
}
|
apache-2.0
|
9aabcb037c0621d65cca1b35874f59eb
| 24.617647 | 57 | 0.624569 | 3.584362 | false | false | false | false |
oversecio/oversec_crypto
|
crypto/src/main/java/io/oversec/one/crypto/ui/util/TooltipBackgroundDrawable.kt
|
1
|
5975
|
package io.oversec.one.crypto.ui.util
import android.content.Context
import android.content.res.Resources
import android.graphics.*
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.util.TypedValue
import io.oversec.one.crypto.R
class TooltipBackgroundDrawable(context: Context) : Drawable() {
private val mStroke: Paint
private val mPaint: Paint
private val mRect: RectF
private val mPath: Path
private val mArrowRatio: Float
private val mCornerRoundness: Float
private var mPadding = 0
private var mArrowWeight = 0
private var mArrowSide: ARROW_SIDE? = null
private var mArrowPos: Int = 0
enum class ARROW_SIDE {
LEFT, RIGHT, TOP, BOTTOM, NONE
}
init {
val backgroundColor = ContextCompat.getColor(context, R.color.colorTooltipBG)
val borderColor = ContextCompat.getColor(context, R.color.colorTooltipBorder)
this.mCornerRoundness = dipToPixels(context, CORNER_RADIUS_DEFAULT_DP).toFloat()
this.mArrowRatio = ARROW_RATIO_DEFAULT
this.mRect = RectF()
mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
mPaint.color = backgroundColor
mPaint.style = Paint.Style.FILL
mStroke = Paint(Paint.ANTI_ALIAS_FLAG)
mStroke.color = borderColor
mStroke.style = Paint.Style.STROKE
mStroke.strokeWidth = dipToPixels(context, STROKE_WIDTH_DEFAULT_DP).toFloat()
mPath = Path()
}
fun dipToPixels(ctx: Context, dip: Int): Int {
val r = ctx.resources
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dip.toFloat(),
r.displayMetrics
).toInt()
}
override fun draw(canvas: Canvas) {
canvas.drawPath(mPath, mPaint)
canvas.drawPath(mPath, mStroke)
}
fun setAnchor(ARROWSIDE: ARROW_SIDE, padding: Int, position: Int) {
if (ARROWSIDE != this.mArrowSide || padding != this.mPadding || position != this.mArrowPos) {
this.mArrowSide = ARROWSIDE
this.mPadding = padding
this.mArrowPos = position
this.mArrowWeight = (padding.toFloat() / mArrowRatio).toInt()
val bounds = bounds
if (!bounds.isEmpty) {
calculatePath(getBounds())
invalidateSelf()
}
}
}
internal fun calculatePath(outBounds: Rect) {
val left = outBounds.left + mPadding
val top = outBounds.top + mPadding
val right = outBounds.right - mPadding
val bottom = outBounds.bottom - mPadding
if (null != mArrowSide) {
calculatePathWithGravity(outBounds, left, top, right, bottom)
} else {
mRect.set(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat())
mPath.addRoundRect(mRect, mCornerRoundness, mCornerRoundness, Path.Direction.CW)
}
}
private fun calculatePathWithGravity(
outBounds: Rect, left: Int, top: Int, right: Int, bottom: Int
) {
mPath.reset()
mPath.moveTo(left + mCornerRoundness, top.toFloat())
if (mArrowSide == ARROW_SIDE.TOP) {
val arrowPointX = (outBounds.left + outBounds.width() * mArrowPos / 100).toFloat()
mPath.lineTo(left + arrowPointX - mArrowWeight, top.toFloat())
mPath.lineTo(left + arrowPointX, outBounds.top.toFloat())
mPath.lineTo(left.toFloat() + arrowPointX + mArrowWeight.toFloat(), top.toFloat())
}
mPath.lineTo(right - mCornerRoundness, top.toFloat())
mPath.quadTo(right.toFloat(), top.toFloat(), right.toFloat(), top + mCornerRoundness)
if (mArrowSide == ARROW_SIDE.RIGHT) {
val arrowPointY = (outBounds.top + outBounds.height() * mArrowPos / 100).toFloat()
mPath.lineTo(right.toFloat(), top + arrowPointY - mArrowWeight)
mPath.lineTo(outBounds.right.toFloat(), top + arrowPointY)
mPath.lineTo(right.toFloat(), top.toFloat() + arrowPointY + mArrowWeight.toFloat())
}
mPath.lineTo(right.toFloat(), bottom - mCornerRoundness)
mPath.quadTo(right.toFloat(), bottom.toFloat(), right - mCornerRoundness, bottom.toFloat())
if (mArrowSide == ARROW_SIDE.BOTTOM) {
val arrowPointX = (outBounds.left + outBounds.width() * mArrowPos / 100).toFloat()
mPath.lineTo(left.toFloat() + arrowPointX + mArrowWeight.toFloat(), bottom.toFloat())
mPath.lineTo(left + arrowPointX, outBounds.bottom.toFloat())
mPath.lineTo(left + arrowPointX - mArrowWeight, bottom.toFloat())
}
mPath.lineTo(left + mCornerRoundness, bottom.toFloat())
mPath.quadTo(left.toFloat(), bottom.toFloat(), left.toFloat(), bottom - mCornerRoundness)
if (mArrowSide == ARROW_SIDE.LEFT) {
val arrowPointY = (outBounds.top + outBounds.height() * mArrowPos / 100).toFloat()
mPath.lineTo(left.toFloat(), top.toFloat() + arrowPointY + mArrowWeight.toFloat())
mPath.lineTo(outBounds.left.toFloat(), top + arrowPointY)
mPath.lineTo(left.toFloat(), top + arrowPointY - mArrowWeight)
}
mPath.lineTo(left.toFloat(), top + mCornerRoundness)
mPath.quadTo(left.toFloat(), top.toFloat(), left + mCornerRoundness, top.toFloat())
}
override fun onBoundsChange(bounds: Rect) {
super.onBoundsChange(bounds)
calculatePath(bounds)
}
override fun getAlpha(): Int {
return mPaint.alpha
}
override fun setAlpha(alpha: Int) {
mPaint.alpha = alpha
}
override fun setColorFilter(cf: ColorFilter?) {}
override fun getOpacity(): Int {
return PixelFormat.OPAQUE
}
companion object {
const val ARROW_RATIO_DEFAULT = 1.5f
private const val CORNER_RADIUS_DEFAULT_DP = 5
private const val STROKE_WIDTH_DEFAULT_DP = 3
}
}
|
gpl-3.0
|
5deee7443ad3acc882df2a6146817c71
| 33.142857 | 101 | 0.636151 | 4.123533 | false | false | false | false |
EMResearch/EvoMaster
|
core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/sql/SqlUUIDGeneImpact.kt
|
1
|
4616
|
package org.evomaster.core.search.impact.impactinfocollection.sql
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.UUIDGene
import org.evomaster.core.search.impact.impactinfocollection.*
import org.evomaster.core.search.impact.impactinfocollection.value.numeric.LongGeneImpact
/**
* created by manzh on 2019-09-29
*/
class SqlUUIDGeneImpact (sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo,
val mostSigBitsImpact: LongGeneImpact,
val leastSigBitsImpact : LongGeneImpact) : GeneImpact(sharedImpactInfo, specificImpactInfo){
constructor(
id : String,
degree: Double = 0.0,
timesToManipulate : Int = 0,
timesOfNoImpacts : Int = 0,
timesOfNoImpactWithTargets : MutableMap<Int, Double> = mutableMapOf(),
timesOfImpact : MutableMap<Int, Double> = mutableMapOf(),
noImpactFromImpact : MutableMap<Int, Double> = mutableMapOf(),
noImprovement : MutableMap<Int, Double> = mutableMapOf(),
mostSigBitsImpact: LongGeneImpact,
leastSigBitsImpact : LongGeneImpact
) : this(
SharedImpactInfo(id, degree, timesToManipulate, timesOfNoImpacts, timesOfNoImpactWithTargets, timesOfImpact),
SpecificImpactInfo(noImpactFromImpact, noImprovement),
mostSigBitsImpact,
leastSigBitsImpact
)
constructor(id : String, UUIDGene: UUIDGene) : this(
id,
mostSigBitsImpact = ImpactUtils.createGeneImpact(UUIDGene.mostSigBits, id) as? LongGeneImpact
?: throw IllegalStateException("mostSigBitsImpact should be LongGeneImpact"),
leastSigBitsImpact = ImpactUtils.createGeneImpact(UUIDGene.leastSigBits, id) as? LongGeneImpact
?: throw IllegalStateException("leastSigBitsImpact should be LongGeneImpact")
)
override fun copy(): SqlUUIDGeneImpact {
return SqlUUIDGeneImpact(
shared.copy(),
specific.copy(),
mostSigBitsImpact = mostSigBitsImpact.copy(),
leastSigBitsImpact = leastSigBitsImpact.copy())
}
override fun clone(): SqlUUIDGeneImpact {
return SqlUUIDGeneImpact(
shared.clone(),
specific.clone(),
mostSigBitsImpact = mostSigBitsImpact.clone(),
leastSigBitsImpact = leastSigBitsImpact.clone()
)
}
override fun countImpactWithMutatedGeneWithContext(gc: MutatedGeneWithContext,noImpactTargets :Set<Int>, impactTargets: Set<Int>, improvedTargets: Set<Int>, onlyManipulation: Boolean) {
countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = gc.numOfMutatedGene)
if (gc.previous == null && impactTargets.isNotEmpty()) return
if (gc.previous != null && gc.previous !is UUIDGene){
throw IllegalStateException("gc.previous (${gc.previous::class.java.simpleName}) should be SqlNullable")
}
if (gc.current !is UUIDGene){
throw IllegalStateException("gc.current (${gc.current::class.java.simpleName}) should be SqlNullable")
}
val mutatedMost = gc.previous == null || !gc.current.mostSigBits.containsSameValueAs((gc.previous as UUIDGene).mostSigBits)
val mutatedLeast = gc.previous == null || !gc.current.leastSigBits.containsSameValueAs((gc.previous as UUIDGene).leastSigBits)
val num = (if (mutatedLeast) 1 else 0) + (if (mutatedMost) 1 else 0)
if (mutatedMost){
mostSigBitsImpact.countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = num)
}
if (mutatedLeast){
leastSigBitsImpact.countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = num)
}
}
override fun validate(gene: Gene): Boolean = gene is UUIDGene
override fun flatViewInnerImpact(): Map<String, Impact> {
return mutableMapOf(
"${getId()}-${mostSigBitsImpact.getId()}" to mostSigBitsImpact,
"${getId()}-${leastSigBitsImpact.getId()}" to leastSigBitsImpact
)
}
override fun innerImpacts(): List<Impact> {
return listOf(mostSigBitsImpact, leastSigBitsImpact)
}
}
|
lgpl-3.0
|
5f6d32dff88a1c536cb5255201a9f59e
| 49.736264 | 206 | 0.679809 | 5.257403 | false | false | false | false |
thomasnield/RxKotlinFX
|
src/main/kotlin/com/github/thomasnield/rxkotlinfx/Observables.kt
|
1
|
17089
|
package com.github.thomasnield.rxkotlinfx
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.rxjavafx.observables.JavaFxObservable
import io.reactivex.rxjavafx.observers.JavaFxObserver
import io.reactivex.rxjavafx.observers.JavaFxSubscriber
import io.reactivex.rxjavafx.sources.SetChange
import javafx.beans.binding.Binding
import javafx.beans.value.ObservableValue
import javafx.collections.ObservableList
import javafx.collections.ObservableMap
import javafx.collections.ObservableSet
import javafx.event.Event
import javafx.event.EventType
import javafx.scene.Node
import javafx.scene.Scene
import javafx.scene.control.ContextMenu
import javafx.scene.control.Dialog
import javafx.scene.control.MenuItem
import javafx.stage.Window
import javafx.stage.WindowEvent
import java.util.*
/**
* Turns an Observable into a JavaFX Binding. Calling the Binding's dispose() method will handle the disposal.
*/
fun <T> Observable<T>.toBinding(actionOp: (ObservableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = ObservableBindingSideEffects<T>()
it.invoke(sideEffects)
sideEffects.transformer
}
return JavaFxObserver.toBinding((transformer?.let { this.compose(it) }?:this))
}
/**
* Turns an Flowable into a JavaFX Binding. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Flowable<T>.toBinding(actionOp: (FlowableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = FlowableBindingSideEffects<T>()
it.invoke(sideEffects)
sideEffects.transformer
}
return JavaFxSubscriber.toBinding((transformer?.let { this.compose(it) }?:this))
}
/**
* Turns an Observable into a JavaFX Binding with a nullSentinel `T` acting as a placeholder for null values. Calling the Binding's dispose() method will handle the disposal.
*/
fun <T> Observable<T>.toNullBinding(nullSentinel: T, actionOp: (ObservableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = ObservableBindingSideEffects<T>()
it.invoke(sideEffects)
sideEffects.transformer
}
return JavaFxObserver.toNullBinding((transformer?.let { this.compose(it) }?:this), nullSentinel)
}
/**
* Turns an Flowable into a JavaFX Binding with a nullSentinel `T` acting as a placeholder for null values. Calling the Binding's dispose() method will handle the disposal.
*/
fun <T> Flowable<T>.toNullBinding(nullSentinel: T, actionOp: (FlowableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = FlowableBindingSideEffects<T>()
it.invoke(sideEffects)
sideEffects.transformer
}
return JavaFxSubscriber.toNullBinding((transformer?.let { this.compose(it) }?:this), nullSentinel)
}
/**
* Turns an Observable into a JavaFX Binding that automatically unwraps the Optional to a nullable value. Calling the Binding's dispose() method will handle the disposal.
*/
fun <T> Observable<Optional<T>>.toNullableBinding(actionOp: (ObservableBindingSideEffects<Optional<T>>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = ObservableBindingSideEffects<Optional<T>>()
it.invoke(sideEffects)
sideEffects.transformer
}
return JavaFxObserver.toNullableBinding((transformer?.let { this.compose(it) }?:this))
}
/**
* Turns an `Flowable<Optional<T>>` into a JavaFX Binding that automatically unwraps the Optional to a nullable value. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Flowable<Optional<T>>.toNullableBinding(actionOp: (FlowableBindingSideEffects<Optional<T>>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = FlowableBindingSideEffects<Optional<T>>()
it.invoke(sideEffects)
sideEffects.transformer
}
return JavaFxSubscriber.toNullableBinding((transformer?.let { this.compose(it) }?:this))
}
/**
* Turns an Observable into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Observable<T>.toLazyBinding() = JavaFxObserver.toLazyBinding(this)
/**
* Turns a Flowable into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Flowable<T>.toLazyBinding() = JavaFxSubscriber.toLazyBinding(this)
/**
* Turns an `Observable<Optional<T>>` into a lazy JavaFX Binding that automatically unwraps the Optional to a nullable value, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Observable<Optional<T>>.toLazyNullableBinding() = JavaFxObserver.toLazyNullableBinding(this)
/**
* Turns a `Flowable<Optional<T>>` into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Flowable<Optional<T>>.toLazyNullableBinding() = JavaFxSubscriber.toLazyNullableBinding(this)
/**
* Turns a Single into a JavaFX Binding. Calling the Binding's dispose() method will handle the disposal.
*/
fun <T> Single<T>.toBinding(actionOp: (ObservableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = ObservableBindingSideEffects<T>()
it.invoke(sideEffects)
sideEffects.transformer
}
return JavaFxObserver.toBinding((transformer?.let { this.toObservable().compose(it) }?:this.toObservable()))
}
/**
* Turns a Single into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Single<T>.toLazyBinding() = JavaFxObserver.toLazyBinding(this.toObservable())
/**
* Turns a `Single<Optional<T>>` into a lazy JavaFX Binding that automatically unwraps the Optional to a nullable value, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Single<Optional<T>>.toLazyNullableBinding() = JavaFxObserver.toLazyNullableBinding(this.toObservable())
/**
* Turns a Maybe into a JavaFX Binding. Calling the Binding's dispose() method will handle the disposal.
*/
fun <T> Maybe<T>.toBinding(actionOp: (ObservableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = ObservableBindingSideEffects<T>()
it.invoke(sideEffects)
sideEffects.transformer
}
return JavaFxObserver.toBinding((transformer?.let { this.toObservable().compose(it) }?:this.toObservable()))
}
/**
* Turns a Maybe into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Maybe<T>.toLazyBinding() = JavaFxObserver.toLazyBinding(this.toObservable())
/**
* Turns a `Maybe<Optional<T>>` into a lazy JavaFX Binding that automatically unwraps the Optional to a nullable value, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Maybe<Optional<T>>.toLazyNullableBinding() = JavaFxObserver.toLazyNullableBinding(this.toObservable())
/**
* Turns an Observable into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Observable<T>.toLazyBinding(errorHandler: (Throwable) -> Unit) = JavaFxObserver.toLazyBinding(this,errorHandler)
/**
* Turns a Flowable into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Flowable<T>.toLazyBinding(errorHandler: (Throwable) -> Unit) = JavaFxSubscriber.toLazyBinding(this,errorHandler)
/**
* Create an rx Observable from a javafx ObservableValue
* @param <T> the type of the observed value
* @return an Observable emitting values as the wrapped ObservableValue changes
*/
fun <T> ObservableValue<T>.toObservable() = JavaFxObservable.valuesOf(this)
/**
* Create an rx Observable from a javafx ObservableValue
* @param <T> the type of the observed value
* @param nullSentinel the default sentinel value emitted when the observable is null
* @return an Observable emitting values as the wrapped ObservableValue changes
*/
fun <T> ObservableValue<T>.toObservable(nullSentinel: T) = JavaFxObservable.valuesOf(this, nullSentinel)
/**
* Create an rx Observable from a javafx ObservableValue, emitting nullable values as Java 8 `Optional` types
* @param <T> the type of the observed value
* @return an Observable emitting `Optional<T>` values as the wrapped ObservableValue changes
*/
fun <T> ObservableValue<T>.toNullableObservable() = JavaFxObservable.nullableValuesOf(this)
/**
* Create an rx Observable from a javafx Observable, emitting it when an invalidation occursk
* @return an rx Observable emitting the JavaFX Observable every time it is invalidated
*/
fun javafx.beans.Observable.invalidations() = JavaFxObservable.invalidationsOf(this)
/**
* Create an rx Observable from a javafx ObservableValue, and emits changes with old and new value pairs
* @param <T> the type of the observed value
* @return an Observable emitting values as the wrapped ObservableValue changes
*/
fun <T> ObservableValue<T>.toObservableChanges() = JavaFxObservable.changesOf(this)
/**
* Create an rx Observable from a javafx ObservableValue, and emits changes with old and new non-null value pairs
* @param <T> the type of the observed value
* @return an Observable emitting non-null values as the wrapped ObservableValue changes
*/
fun <T> ObservableValue<T>.toObservableChangesNonNull() = JavaFxObservable.nonNullChangesOf(this)
/**
* Creates an observable corresponding to javafx ContextMenu action events.
* @return An Observable of UI ActionEvents
*/
fun ContextMenu.actionEvents() = JavaFxObservable.actionEventsOf(this)
/**
* Creates an observable corresponding to javafx MenuItem action events.
*
* @param menuItem The target of the ActionEvents
* @return An Observable of UI ActionEvents
*/
fun MenuItem.actionEvents() = JavaFxObservable.actionEventsOf(this)
/**
* Creates an observable corresponding to javafx Node action events.
* @return An Observable of UI ActionEvents
*/
fun Node.actionEvents() = JavaFxObservable.actionEventsOf(this)
/**
* Creates an observable corresponding to javafx Node events.
* @param eventType The type of the observed UI events
* @return An Observable of UI events, appropriately typed
*/
fun <T : Event> Node.events(eventType: EventType<T>) = JavaFxObservable.eventsOf(this, eventType)
/**
* Create an rx Observable from a javafx ObservableValue
* @param <T> the type of the observed value
* @return an Observable emitting values as the wrapped ObservableValue changes
*/
fun <T: Event> Scene.events(eventType: EventType<T>) = JavaFxObservable.eventsOf(this,eventType)
/**
* Create an rx Observable from a javafx ObservableValue, and emits changes with old and new value pairs
* @param <T> the type of the observed value
* @return an Observable emitting values as the wrapped ObservableValue changes
*/
fun <T: WindowEvent> Window.events(eventType: EventType<T>) = JavaFxObservable.eventsOf(this,eventType)
/**
* Creates an observable that emits an ObservableList every time it is modified
* @return An Observable emitting the ObservableList each time it changes
*/
fun <T> ObservableList<T>.onChangedObservable() = JavaFxObservable.emitOnChanged(this)
/**
* Creates an observable that emits all removal items from an ObservableList
* @return An Observable emitting items removed from the ObservableList
*/
fun <T> ObservableList<T>.removals() = JavaFxObservable.removalsOf(this)
/**
* Creates an observable that emits all additions to an ObservableList
* @return An Observable emitting items added to the ObservableList
*/
fun <T> ObservableList<T>.additions() = JavaFxObservable.additionsOf(this)
/**
* Creates an observable that emits all updated items from an ObservableList.
* If you declare an ObservableList that listens to one or more properties of each element,
* you can emit the changed items every time these properties are modified
* <pre>ObservableList<Person> sourceList = FXCollections.observableArrayList(user -> new javafx.beans.Observable[]{user.age} );</pre>
* @return An Observable emitting items updated in the ObservableList
*/
fun <T> ObservableList<T>.updates() = JavaFxObservable.updatesOf(this)
/**
* Emits all added, removed, and updated items from an ObservableList
* @return An Observable emitting changed items with an ADDED, REMOVED, or UPDATED flags
*/
fun <T> ObservableList<T>.changes() = JavaFxObservable.changesOf(this)
/**
* Emits distinctly added and removed items from an ObservableList.
* If dupe items with identical hashcode/equals evaluations are added to an ObservableList, only the first one will fire an ADDED item.
* When the last dupe is removed, only then will it fire a REMOVED item.
* @return An Observable emitting changed items with an ADDED, REMOVED, or UPDATED flags
*/
fun <T> ObservableList<T>.distinctChanges() = JavaFxObservable.distinctChangesOf(this)
/**
* Emits distinctly added and removed items item from an ObservableList.
* If dupe mapped R items with identical hashcode/equals evaluations are added to an ObservableList, only the first one will fire an ADDED T item.
* When the last dupe is removed, only then will it fire a REMOVED T item.
* @return An Observable emitting changed mapped items with an ADDED, REMOVED, or UPDATED flags
*/
fun <T,R> ObservableList<T>.distinctChanges(mapper: ((T) -> R)) = JavaFxObservable.distinctChangesOf(this,mapper)
/**
* Emits distinctly added and removed mappings to each R item from an ObservableList.
* If dupe mapped R items with identical hashcode/equals evaluations are added to an ObservableList, only the first one will fire an ADDED R item.
* When the last dupe is removed, only then will it fire a REMOVED R item.
* @return An Observable emitting changed mapped items with an ADDED, REMOVED, or UPDATED flags
*/
fun <T,R> ObservableList<T>.distinctMappingChanges(mapper: ((T) -> R)) = JavaFxObservable.distinctMappingsOf(this,mapper)
/**
* Creates an observable that emits an ObservableMap every time it is modified
* @return An Observable emitting the ObservableMap each time it changes
*/
fun <K,T> ObservableMap<K, T>.onChangedObservable() = JavaFxObservable.emitOnChanged(this)
/**
* Creates an observable that emits all removal items from an ObservableMap
* @return An Observable emitting items removed from the ObservableMap
*/
fun <K,T> ObservableMap<K, T>.removals() = JavaFxObservable.removalsOf(this)
/**
* Creates an observable that emits all additions to an ObservableMap
* @return An Observable emitting items added to the ObservableMap
*/
fun <K,T> ObservableMap<K, T>.additions() = JavaFxObservable.additionsOf(this)
/**
* Emits all added, removed, and updated items from an ObservableMap
* @return An Observable emitting changed items with an ADDED, REMOVED, or UPDATED flags
*/
fun <K,T> ObservableMap<K, T>.changes() = JavaFxObservable.changesOf(this)
/**
* Creates an observable that emits an ObservableSet every time it is modified
* @return An Observable emitting the ObservableSet each time it changes
*/
fun <T> ObservableSet<T>.onChangedObservable() = JavaFxObservable.emitOnChanged(this)
/**
* Creates an observable that emits all removal items from an ObservableSet
* @return An Observable emitting items removed from the ObservableSet
*/
fun <T> ObservableSet<T>.removals() = JavaFxObservable.removalsOf(this)
/**
* Creates an observable that emits all additions to an ObservableSet
* @return An Observable emitting items added to the ObservableSet
*/
fun <T> ObservableSet<T>.additions() = JavaFxObservable.additionsOf(this)
/**
* Emits all added, removed, and updated items from an ObservableSet
* @return An Observable emitting changed items with an ADDED, REMOVED, or UPDATED flags
*/
fun <T> ObservableSet<SetChange<T>>.changes() = JavaFxObservable.changesOf(this)
/**
* Emits the response `T` for a given `Dialog<T>`. If no response is provided the Maybe will be empty.
*/
fun <T> Dialog<T>.toMaybe() = JavaFxObservable.fromDialog(this)!!
|
apache-2.0
|
4a282e69a547633e067f39befc619e2d
| 45.189189 | 272 | 0.754403 | 4.318676 | false | false | false | false |
jayrave/falkon
|
falkon-engine-test-common/src/main/kotlin/com/jayrave/falkon/engine/test/TestSourceGetFieldValueCalls.kt
|
1
|
3923
|
package com.jayrave.falkon.engine.test
import com.jayrave.falkon.engine.Engine
import com.jayrave.falkon.engine.Source
import com.jayrave.falkon.engine.Type
import com.jayrave.falkon.engine.safeCloseAfterExecution
import org.assertj.core.api.Assertions.assertThat
class TestSourceGetFieldValueCalls(engine: Engine) :
BaseClassForTestingSourceImplementation(engine) {
fun `#getColumnIndex throws for column name not in the result set`() {
insertRecord(seed = 5)
queryForAll { source ->
assertThat(source.moveToNext()).isTrue()
failIfOpDoesNotThrow { source.getColumnIndex("this is a crazy column name") }
}
}
fun `test #getColumnIndex & #get* Calls`() {
val insertSql = "INSERT INTO $TABLE_NAME (" +
"$SHORT_COLUMN_NAME, " +
"$INT_COLUMN_NAME, " +
"$LONG_COLUMN_NAME, " +
"$FLOAT_COLUMN_NAME, " +
"$DOUBLE_COLUMN_NAME, " +
"$STRING_COLUMN_NAME, " +
"$BLOB_COLUMN_NAME) VALUES (?, ?, ?, ?, ?, ?, ?)"
engine
.compileInsert(TABLE_NAME, insertSql)
.bindShort(1, 5)
.bindInt(2, 6)
.bindLong(3, 7L)
.bindFloat(4, 8F)
.bindDouble(5, 9.0)
.bindString(6, "test 10")
.bindBlob(7, byteArrayOf(11))
.safeCloseAfterExecution()
queryForAll { s ->
assertThat(s.moveToNext()).isTrue()
assertThat(s.getShort(s.getColumnIndex(SHORT_COLUMN_NAME))).isEqualTo(5)
assertThat(s.getInt(s.getColumnIndex(INT_COLUMN_NAME))).isEqualTo(6)
assertThat(s.getLong(s.getColumnIndex(LONG_COLUMN_NAME))).isEqualTo(7L)
assertThat(s.getFloat(s.getColumnIndex(FLOAT_COLUMN_NAME))).isEqualTo(8F)
assertThat(s.getDouble(s.getColumnIndex(DOUBLE_COLUMN_NAME))).isEqualTo(9.0)
assertThat(s.getString(s.getColumnIndex(STRING_COLUMN_NAME))).isEqualTo("test 10")
assertThat(s.getBlob(s.getColumnIndex(BLOB_COLUMN_NAME))).isEqualTo(byteArrayOf(11))
}
}
fun `test #getColumnIndex & #isNull Calls`() {
val insertSql = "INSERT INTO $TABLE_NAME (" +
"$SHORT_COLUMN_NAME, " +
"$INT_COLUMN_NAME, " +
"$LONG_COLUMN_NAME, " +
"$FLOAT_COLUMN_NAME, " +
"$DOUBLE_COLUMN_NAME, " +
"$STRING_COLUMN_NAME, " +
"$BLOB_COLUMN_NAME) VALUES (?, ?, ?, ?, ?, ?, ?)"
engine
.compileInsert(TABLE_NAME, insertSql)
.bindNull(1, Type.SHORT)
.bindNull(2, Type.INT)
.bindNull(3, Type.LONG)
.bindNull(4, Type.FLOAT)
.bindNull(5, Type.DOUBLE)
.bindNull(6, Type.STRING)
.bindNull(7, Type.BLOB)
.safeCloseAfterExecution()
queryForAll { s ->
assertThat(s.moveToNext()).isTrue()
assertThat(s.isNull(s.getColumnIndex(SHORT_COLUMN_NAME))).isTrue()
assertThat(s.isNull(s.getColumnIndex(INT_COLUMN_NAME))).isTrue()
assertThat(s.isNull(s.getColumnIndex(LONG_COLUMN_NAME))).isTrue()
assertThat(s.isNull(s.getColumnIndex(FLOAT_COLUMN_NAME))).isTrue()
assertThat(s.isNull(s.getColumnIndex(DOUBLE_COLUMN_NAME))).isTrue()
assertThat(s.isNull(s.getColumnIndex(STRING_COLUMN_NAME))).isTrue()
assertThat(s.isNull(s.getColumnIndex(BLOB_COLUMN_NAME))).isTrue()
}
}
private fun queryForAll(test: (Source) -> Any?) {
val cs = engine.compileQuery(listOf(TABLE_NAME), SELECT_ALL_SQL)
val source = cs.execute()
try {
test.invoke(source)
} finally {
source.close()
cs.close()
}
}
}
|
apache-2.0
|
f1f948a94b2c59e7bbae5662b3370fd9
| 38.636364 | 96 | 0.560795 | 4.182303 | false | true | false | false |
slimaku/kondorcet
|
src/main/kotlin/kondorcet/method/CondorcetMethod.kt
|
1
|
2675
|
package kondorcet.method
import kondorcet.Ballot
import kondorcet.model.ballot
import kondorcet.graph.Graph
import kondorcet.graph.emptyGraph
import kondorcet.graph.minus
import kondorcet.method.CondorcetMethod.resultOf
/**
* Standard condorcet method poll. It does not ensure to get a single winner, but if it does this guaranteed to be a condorcet winner.
*
* The [resultOf] method complexity is *O(n^2 + b)* for *n* candidates and *b* ballots
*/
object CondorcetMethod : GraphBasedMethod() {
override fun <T : Any> ballotOf(graph: Graph<T, Int>) =
graph.toBallot()
/** Returns a ballots representing the graph (as a victory graph) */
internal fun <T : Any> Graph<T, Any>.toBallot(): Ballot<T> {
// Extract winners
val (graph, winners) = extractCandidates(
vertices,
{ getDegreeTo(it) == 0 && getDegreeFrom(it) > 0 },
{ list, set -> list + listOf(set) }
)
// Extract losers
val (_, losers) = graph.extractCandidates(
vertices - winners.flatten(),
{ getDegreeFrom(it) == 0 && getDegreeTo(it) > 0 },
{ list, set -> listOf(set) + list }
)
// Get candidates that are no winners or losers
val others = (vertices - winners.flatten() - losers.flatten())
.filter { getDegreeOf(it) > 0 }
.let { if (it.isEmpty()) emptyList() else listOf(it.toSet()) }
return ballot(winners + others + losers)
}
/**
* Extract candidates from the graph
*
* @param candidates Candidates to try to extract
* @param selectCandidate Method to select extractable candidates
* @return a pair with : the graph without the extracted candidates and the extracted candidates
*/
internal fun <T : Any, W : Any> Graph<T, W>.extractCandidates(
candidates: Collection<T>,
selectCandidate: Graph<T, Any>.(candidate: T) -> Boolean,
merge: (List<Set<T>>, Set<T>) -> List<Set<T>>
): Pair<Graph<T, W>, List<Set<T>>> {
var candidatesPool = candidates
var graph = this
var result = emptyList<Set<T>>()
var nextCandidates = candidatesPool.filter { graph.selectCandidate(it) }
while (candidatesPool.isNotEmpty() && nextCandidates.isNotEmpty()) {
for (candidate in nextCandidates)
graph -= candidate
result = merge(result, nextCandidates.toSet())
candidatesPool -= nextCandidates
nextCandidates = candidatesPool.filter { graph.selectCandidate(it) }
}
return graph to result
}
}
|
lgpl-3.0
|
a01ac37523009679d470143d5fc5e6cb
| 34.68 | 134 | 0.608224 | 4.090214 | false | false | false | false |
VerifAPS/verifaps-lib
|
geteta/src/main/kotlin/edu/kit/iti/formal/automation/testtables/apps/coverage.kt
|
1
|
4861
|
package edu.kit.iti.formal.automation.testtables.apps
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.groups.provideDelegate
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
import edu.kit.iti.formal.automation.CommonArguments
import edu.kit.iti.formal.automation.ProgramOptions
import edu.kit.iti.formal.automation.SymbExFacade
import edu.kit.iti.formal.automation.smt.*
import edu.kit.iti.formal.automation.testtables.GetetaFacade
import edu.kit.iti.formal.smt.SList
import edu.kit.iti.formal.smv.ExpressionReplacer
import edu.kit.iti.formal.smv.SMVAstVisitor
import edu.kit.iti.formal.smv.ast.*
import edu.kit.iti.formal.smv.conjunction
import edu.kit.iti.formal.util.info
import java.io.File
/**
*
* @author Alexander Weigl
* @version 1 (2/11/20)
*/
object Coverage {
@JvmStatic
fun main(args: Array<String>) {
CoverageApp().main(args)
}
}
class CoverageApp : CliktCommand(
epilog = "ttcov -- Program Coverage with Test Tables.",
name = "ttcov") {
val common by CommonArguments()
val tableArguments by TableArguments()
val runSmt by option().flag()
val outputFile by option("-o", "--output", help = "Output directory")
val programOptions by ProgramOptions()
val library = programOptions.library
val program =programOptions.program
override fun run() {
common()
val gtts = tableArguments.readTables()
val code = programOptions.readProgram()
val (lineMap, modCode) = SymbExFacade.evaluateProgramWithLineMap(code, programOptions.disableSimplify)
info("Program evaluation")
val superEnumType = GetetaFacade.createSuperEnum(listOf(code.scope))
info("Super enum built")
val definitions = modCode.definitions.map { it.target.name to it.expr }.toMap()
//val r = ExpressionReplacer(definitions)
modCode.unfold()
val dtTranslator: S2SDataTypeTranslator = DefaultS2STranslator()
val fnTranslator: S2SFunctionTranslator = DefaultS2SFunctionTranslator()
val toSmt = Smv2SmtVisitor(fnTranslator, dtTranslator, "")
val toSmtState = Smv2SmtVisitor(fnTranslator, dtTranslator, "old")
val program = SmvSmtFacade.translate(modCode)
gtts.forEach { gtt ->
val varRename = hashMapOf<SMVExpr,SMVExpr>()
gtt.programVariables.forEach {
val internalVariable = it.internalVariable(gtt.programRuns)
varRename[internalVariable] =
SVariable(if(it.isAssumption) "old${it.name}" else "new${it.name}", internalVariable.dataType!!)
}
var renamer = ExpressionReplacer(varRename)
File(outputFile, "${gtt.name}.smt2").bufferedWriter().use { out ->
out.write(";;Preamble\n${program.preamble}\n;;--\n")
out.write(program.getStepDefinition(true, "old"))
out.newLine()
out.write(program.getStepDefinition(false, "new"))
out.newLine()
out.write(SList("assert", program.nextBody).toString())
out.newLine()
//println(program.getAssertNext("_cur", "_new"))
gtt.region.flat().forEach {
val assume = it.inputExpr.values.conjunction(SLiteral.TRUE).accept(renamer).accept(toSmt)
val assert = it.outputExpr.values.conjunction(SLiteral.TRUE).accept(renamer).accept(toSmt)
out.write("""
(push) ;; Table row ${it.id}
(assert $assume) ;; pre-condition
(assert $assert) ;; post-condition
""".trimIndent())
lineMap.branchMap.forEach { (t, _) ->
val e = definitions[t]?.accept(toSmtState)
out.write("\t(push) (assert ${e}) (check-sat) (pop);; check for $t")
out.newLine()
}
out.write("(pop)\n")
}
}
}
}
}
private fun SMVModule.unfold() {
val defs = definitions.map { it.target to it.expr }.toMap()
var m = defs.toMap()
val r = ExpressionReplacer(defs)
while (true) {
r.changed = false
val updated = m.map { (t, u) ->
t to u.accept(r as SMVAstVisitor<SMVAst>) as SMVExpr
}.toMap()
m = updated
if (!r.changed) break
}
definitions.clear()
initAssignments.forEach { it.expr = it.expr.accept(r) as SMVExpr }
nextAssignments.forEach { it.expr = it.expr.accept(r) as SMVExpr }
transExpr = transExpr.map { it.accept(r) as SMVExpr }.toMutableList()
initExpr = initExpr.map { it.accept(r) as SMVExpr }.toMutableList()
}
|
gpl-3.0
|
5cbecab19664db44993e159499560c80
| 37.888 | 124 | 0.621683 | 3.977905 | false | false | false | false |
SimpleMobileTools/Simple-Flashlight
|
app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/LollipopCameraFlash.kt
|
1
|
1170
|
@file:Suppress("DEPRECATION")
package com.simplemobiletools.flashlight.helpers
import android.graphics.SurfaceTexture
import android.hardware.Camera
class LollipopCameraFlash : CameraFlash {
private var camera: Camera? = null
private var params: Camera.Parameters? = null
override fun toggleFlashlight(enable: Boolean) {
try {
if (camera == null || params == null || camera!!.parameters == null) {
return
}
} catch (e: Exception) {
return
}
val flashMode = if (enable) Camera.Parameters.FLASH_MODE_ON else Camera.Parameters.FLASH_MODE_OFF
params!!.flashMode = flashMode
camera!!.parameters = params
if (enable) {
val dummy = SurfaceTexture(1)
camera!!.setPreviewTexture(dummy)
camera!!.startPreview()
}
}
override fun initialize() {
camera = Camera.open()
params = camera!!.parameters
params!!.flashMode = Camera.Parameters.FLASH_MODE_OFF
camera!!.parameters = params
}
override fun release() {
camera?.release()
camera = null
}
}
|
gpl-3.0
|
6fd57d18e916608b4bbc5826829edbb8
| 26.857143 | 105 | 0.602564 | 4.756098 | false | false | false | false |
googlecodelabs/android-compose-codelabs
|
AdvancedStateAndSideEffectsCodelab/app/src/main/java/androidx/compose/samples/crane/base/CraneTabs.kt
|
1
|
3861
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.samples.crane.base
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Tab
import androidx.compose.material.TabRow
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.samples.crane.R
import androidx.compose.samples.crane.home.CraneScreen
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.os.ConfigurationCompat
@Composable
fun CraneTabBar(
modifier: Modifier = Modifier,
onMenuClicked: () -> Unit,
children: @Composable (Modifier) -> Unit
) {
Row(modifier) {
// Separate Row as the children shouldn't have the padding
Row(Modifier.padding(top = 8.dp)) {
Image(
modifier = Modifier
.padding(top = 8.dp)
.clickable(onClick = onMenuClicked),
painter = painterResource(id = R.drawable.ic_menu),
contentDescription = stringResource(id = R.string.cd_menu)
)
Spacer(Modifier.width(8.dp))
Image(
painter = painterResource(id = R.drawable.ic_crane_logo),
contentDescription = null
)
}
children(
Modifier
.weight(1f)
.align(Alignment.CenterVertically)
)
}
}
@Composable
fun CraneTabs(
modifier: Modifier = Modifier,
titles: List<String>,
tabSelected: CraneScreen,
onTabSelected: (CraneScreen) -> Unit
) {
TabRow(
selectedTabIndex = tabSelected.ordinal,
modifier = modifier,
contentColor = MaterialTheme.colors.onSurface,
indicator = { },
divider = { }
) {
titles.forEachIndexed { index, title ->
val selected = index == tabSelected.ordinal
var textModifier = Modifier.padding(vertical = 8.dp, horizontal = 16.dp)
if (selected) {
textModifier =
Modifier
.border(BorderStroke(2.dp, Color.White), RoundedCornerShape(16.dp))
.then(textModifier)
}
Tab(
selected = selected,
onClick = { onTabSelected(CraneScreen.values()[index]) }
) {
Text(
modifier = textModifier,
text = title.uppercase(
ConfigurationCompat.getLocales(LocalConfiguration.current)[0]!!
)
)
}
}
}
}
|
apache-2.0
|
b871478a429052131d0da495da68944f
| 33.473214 | 91 | 0.648796 | 4.702801 | false | false | false | false |
arcao/Geocaching4Locus
|
app/src/main/java/com/arcao/geocaching4locus/base/util/ColorUtil.kt
|
1
|
4512
|
package com.arcao.geocaching4locus.base.util
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.util.TypedValue
import androidx.appcompat.R
import androidx.core.graphics.ColorUtils
import kotlin.math.roundToInt
object ColorUtil {
private val TL_TYPED_VALUE = ThreadLocal<TypedValue>()
private val DISABLED_STATE_SET = intArrayOf(-android.R.attr.state_enabled)
private val FOCUSED_STATE_SET = intArrayOf(android.R.attr.state_focused)
private val ACTIVATED_STATE_SET = intArrayOf(android.R.attr.state_activated)
private val PRESSED_STATE_SET = intArrayOf(android.R.attr.state_pressed)
private val CHECKED_STATE_SET = intArrayOf(android.R.attr.state_checked)
private val SELECTED_STATE_SET = intArrayOf(android.R.attr.state_selected)
private val EMPTY_STATE_SET = IntArray(0)
private val TEMP_ARRAY = IntArray(1)
private var defaultColorStateList: ColorStateList? = null
private val typedValue: TypedValue
get() {
var typedValue: TypedValue? = TL_TYPED_VALUE.get()
if (typedValue == null) {
typedValue = TypedValue()
TL_TYPED_VALUE.set(typedValue)
}
return typedValue
}
fun getDefaultColorStateList(context: Context): ColorStateList {
if (defaultColorStateList == null) {
/*
Generate the default color state list which uses the colorControl attributes.
Order is important here. The default enabled state needs to go at the bottom.
*/
val colorControlNormal = getThemeAttrColor(context, R.attr.colorControlNormal)
val colorControlActivated = getThemeAttrColor(
context,
R.attr.colorControlActivated
)
val states = arrayOfNulls<IntArray>(7)
val colors = IntArray(7)
var i = 0
// Disabled state
states[i] = DISABLED_STATE_SET
colors[i] = getDisabledThemeAttrColor(context, R.attr.colorControlNormal)
i++
states[i] = FOCUSED_STATE_SET
colors[i] = colorControlActivated
i++
states[i] = ACTIVATED_STATE_SET
colors[i] = colorControlActivated
i++
states[i] = PRESSED_STATE_SET
colors[i] = colorControlActivated
i++
states[i] = CHECKED_STATE_SET
colors[i] = colorControlActivated
i++
states[i] = SELECTED_STATE_SET
colors[i] = colorControlActivated
i++
// Default enabled state
states[i] = EMPTY_STATE_SET
colors[i] = colorControlNormal
defaultColorStateList = ColorStateList(states, colors)
}
return defaultColorStateList!!
}
private fun getDisabledThemeAttrColor(context: Context, attr: Int): Int {
val csl = getThemeAttrColorStateList(context, attr)
return if (csl != null && csl.isStateful) {
// If the CSL is stateful, we'll assume it has a disabled state and use it
csl.getColorForState(DISABLED_STATE_SET, csl.defaultColor)
} else {
// Else, we'll generate the color using disabledAlpha from the theme
val tv = typedValue
// Now retrieve the disabledAlpha value from the theme
context.theme.resolveAttribute(android.R.attr.disabledAlpha, tv, true)
val disabledAlpha = tv.float
getThemeAttrColor(context, attr, disabledAlpha)
}
}
private fun getThemeAttrColorStateList(context: Context, attr: Int): ColorStateList? {
TEMP_ARRAY[0] = attr
val a = context.obtainStyledAttributes(null, TEMP_ARRAY)
try {
return a.getColorStateList(0)
} finally {
a.recycle()
}
}
private fun getThemeAttrColor(context: Context, attr: Int, alpha: Float): Int {
val color = getThemeAttrColor(context, attr)
val originalAlpha = Color.alpha(color)
return ColorUtils.setAlphaComponent(color, (originalAlpha * alpha).roundToInt())
}
private fun getThemeAttrColor(context: Context, attr: Int): Int {
TEMP_ARRAY[0] = attr
val a = context.obtainStyledAttributes(null, TEMP_ARRAY)
try {
return a.getColor(0, 0)
} finally {
a.recycle()
}
}
}
|
gpl-3.0
|
bf575233b4ab19e831eceacb87abe160
| 33.707692 | 91 | 0.622119 | 4.594705 | false | false | false | false |
nickthecoder/tickle
|
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/resources/FontResource.kt
|
1
|
4467
|
/*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.resources
import uk.co.nickthecoder.tickle.graphics.FontTexture
import uk.co.nickthecoder.tickle.graphics.FontTextureFactoryViaAWT
import uk.co.nickthecoder.tickle.graphics.Texture
import uk.co.nickthecoder.tickle.util.Deletable
import uk.co.nickthecoder.tickle.util.Dependable
import uk.co.nickthecoder.tickle.util.JsonResources
import uk.co.nickthecoder.tickle.util.Renamable
import java.awt.Font
import java.io.File
class FontResource(var xPadding: Int = 1, var yPadding: Int = 1)
: Deletable, Renamable {
constructor(fontName: String, style: FontStyle, size: Double, xPadding: Int = 1, yPadding: Int = 1) : this(xPadding, yPadding) {
this.fontName = fontName
this.style = style
this.size = size
}
constructor(file: File, size: Double, xPadding: Int = 1, yPadding: Int = 1) : this(xPadding, yPadding) {
this.file = file
this.size = size
}
private var cached: FontTexture? = null
var file: File? = null
set(v) {
if (field != v) {
field = v
cached = null
}
}
var fontName: String = java.awt.Font.SANS_SERIF
set(v) {
if (field != v) {
field = v
cached = null
}
}
var style: FontStyle = FontStyle.PLAIN
set(v) {
if (field != v) {
field = v
cached = null
}
}
var size: Double = 22.0
set(v) {
if (field != v) {
field = v
cached = null
}
}
var pngFile: File? = null
set(v) {
field = v
}
var fontTexture: FontTexture
get() {
cached?.let { return it }
val c = createFontTexture()
cached = c
return c
}
set(v) {
cached = v
}
var outlineFontTexture: FontTexture? = null
fun reload() {
pngFile?.let { pngFile ->
loadFromFile(pngFile)
}
}
fun clearCache() {
cached = null
}
fun loadFromFile(pngFile: File) {
val texture = Texture.create(pngFile)
val metricsFile = File(pngFile.parentFile, pngFile.nameWithoutExtension + ".metrics")
fontTexture = JsonResources.loadFontMetrics(metricsFile, texture)
this.pngFile = pngFile
val outlineFile = File(pngFile.parentFile, pngFile.nameWithoutExtension + "-outline.png")
if (outlineFile.exists()) {
val outlineTexture = Texture.create(outlineFile)
outlineFontTexture = FontTexture(JsonResources.copyGlyphs(outlineTexture, fontTexture.glyphs), fontTexture.lineHeight,
leading = fontTexture.leading, ascent = fontTexture.ascent, descent = fontTexture.descent)
}
}
private fun createFontTexture(): FontTexture {
val font: Font
if (file == null) {
font = Font(fontName, style.ordinal, size.toInt())
} else {
val loadedFont = Font.createFont(java.awt.Font.TRUETYPE_FONT, file)
font = loadedFont.deriveFont(size.toFloat())
}
return FontTextureFactoryViaAWT(font, xPadding = xPadding, yPadding = yPadding).create()
}
override fun dependables(): List<Dependable> {
return Resources.instance.costumes.items().values.filter { it.dependsOn(this) }
}
override fun delete() {
Resources.instance.fontResources.remove(this)
}
fun destroy() {
fontTexture.destroy()
}
override fun rename(newName: String) {
Resources.instance.fontResources.rename(this, newName)
}
enum class FontStyle { PLAIN, BOLD, ITALIC, BOLD_ITALIC }
}
|
gpl-3.0
|
7fd1f906347b33587f6a8f568287c318
| 28.582781 | 132 | 0.615178 | 4.222117 | false | false | false | false |
nickthecoder/tickle
|
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/tabs/GameInfoTab.kt
|
1
|
6009
|
/*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.editor.tabs
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.parameters.*
import uk.co.nickthecoder.tickle.GameInfo
import uk.co.nickthecoder.tickle.NoProducer
import uk.co.nickthecoder.tickle.Producer
import uk.co.nickthecoder.tickle.editor.util.ClassLister
import uk.co.nickthecoder.tickle.editor.util.ClassParameter
import uk.co.nickthecoder.tickle.editor.util.Vector2dParameter
import uk.co.nickthecoder.tickle.editor.util.XYiParameter
import uk.co.nickthecoder.tickle.physics.FilterBits
import uk.co.nickthecoder.tickle.physics.FilterGroups
import uk.co.nickthecoder.tickle.physics.NoFilterBits
import uk.co.nickthecoder.tickle.physics.NoFilterGroups
import uk.co.nickthecoder.tickle.resources.Resources
import uk.co.nickthecoder.tickle.scripts.ScriptManager
class GameInfoTab
: EditTaskTab(
GameInfoTask(Resources.instance.gameInfo),
dataName = "Game Info",
data = Resources.instance.gameInfo,
graphicName = "gameInfo.png") {
}
class GameInfoTask(val gameInfo: GameInfo) : AbstractTask() {
val titleP = StringParameter("title", value = gameInfo.title)
val idP = StringParameter("ID", value = gameInfo.id)
val windowSizeP = XYiParameter("windowSize")
val fullScreenP = BooleanParameter("fullScreen", value = gameInfo.fullScreen)
val resizableP = BooleanParameter("resizable", value = gameInfo.resizable)
val initialSceneP = StringParameter("initialScene", value = Resources.instance.sceneFileToPath(gameInfo.initialScenePath))
val testSceneP = StringParameter("testScene", value = Resources.instance.sceneFileToPath(gameInfo.testScenePath))
val producerP = ClassParameter("producer", Producer::class.java, value = NoProducer::class.java)
val physicsEngineP = BooleanParameter("physicsEngine", value = gameInfo.physicsEngine)
val gravityP = Vector2dParameter("gravity", value = gameInfo.physicsInfo.gravity).asHorizontal()
val scaleP = DoubleParameter("scale", value = gameInfo.physicsInfo.scale)
val framesPerSecondP = IntParameter("framesPerSecond", value = gameInfo.physicsInfo.framesPerSecond)
val velocityIterationsP = IntParameter("velocityIterations", value = gameInfo.physicsInfo.velocityIterations)
val positionIterationsP = IntParameter("positionIterations", value = gameInfo.physicsInfo.positionIterations)
val filterGroupsP = GroupedChoiceParameter<Class<*>>("filterGroups", value = NoFilterGroups::class.java, allowSingleItemSubMenus = true)
val filterBitsP = GroupedChoiceParameter<Class<*>>("filterBits", value = NoFilterBits::class.java, allowSingleItemSubMenus = true)
val physicsDetailsP = SimpleGroupParameter("physicsDetails")
.addParameters(gravityP, scaleP, framesPerSecondP, velocityIterationsP, positionIterationsP, filterGroupsP, filterBitsP)
.asBox()
override val taskD = TaskDescription("editGameInfo")
.addParameters(titleP, idP, windowSizeP, resizableP, fullScreenP, initialSceneP, testSceneP, producerP, physicsEngineP, physicsDetailsP)
init {
windowSizeP.x = gameInfo.width
windowSizeP.y = gameInfo.height
ClassLister.setChoices(filterGroupsP, FilterGroups::class.java)
ClassLister.setChoices(filterBitsP, FilterBits::class.java)
try {
producerP.classValue = ScriptManager.classForName(gameInfo.producerString)
} catch (e: Exception) {
System.err.println("Couldn't find class ${gameInfo.producerString}, defaulting to NoProducer")
}
try {
filterGroupsP.value = ScriptManager.classForName(gameInfo.physicsInfo.filterGroupsString)
} catch (e: Exception) {
System.err.println("Couldn't find class ${gameInfo.physicsInfo.filterGroupsString}, defaulting to NoFilterGroups")
}
try {
filterBitsP.value = ScriptManager.classForName(gameInfo.physicsInfo.filterBitsString)
} catch (e: Exception) {
System.err.println("Couldn't find class ${gameInfo.physicsInfo.filterBitsString}, defaulting to NoFilterBits")
}
physicsDetailsP.hidden = physicsEngineP.value != true
physicsEngineP.listen { physicsDetailsP.hidden = physicsEngineP.value != true }
}
override fun run() {
with(gameInfo) {
title = titleP.value
id = idP.value
width = windowSizeP.x!!
height = windowSizeP.y!!
fullScreen = fullScreenP.value == true
initialScenePath = Resources.instance.scenePathToFile(initialSceneP.value)
testScenePath = Resources.instance.scenePathToFile(testSceneP.value)
resizable = resizableP.value!!
producerString = producerP.classValue!!.name
physicsEngine = physicsEngineP.value == true
}
with(gameInfo.physicsInfo) {
gravity = gravityP.value
scale = scaleP.value!!
framesPerSecond = framesPerSecondP.value!!
velocityIterations = velocityIterationsP.value!!
positionIterations = positionIterationsP.value!!
filterGroupsString = filterGroupsP.value!!.name
filterBitsString = filterBitsP.value!!.name
}
}
}
|
gpl-3.0
|
829b2de4ce5d724b4a81e488132e0608
| 43.183824 | 148 | 0.731569 | 4.289079 | false | false | false | false |
MoonCheesez/sstannouncer
|
sstannouncer/app/src/main/java/sst/com/anouncements/feed/data/parser/w3dom/XMLParser.kt
|
1
|
1779
|
package sst.com.anouncements.feed.data.parser.w3dom
import org.w3c.dom.Document
import org.w3c.dom.Node
import org.w3c.dom.NodeList
import org.xml.sax.InputSource
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPathConstants
import javax.xml.xpath.XPathExpression
import javax.xml.xpath.XPathFactory
// Create XML from String
fun createXMLDocument(XML: String): Document {
val dbFactory = DocumentBuilderFactory.newInstance()
val dBuilder = dbFactory.newDocumentBuilder()
return dBuilder.parse(InputSource(XML.byteInputStream()))
}
// Create XPathExpression object from XPath
fun createXPath(XPath: String): XPathExpression {
val xPathfactory = XPathFactory.newInstance()
val xpath = xPathfactory.newXPath()
return xpath.compile(XPath)
}
// General XPath functions (with different return types)
private fun xpathAnyString(o: Any, XPath: String): String {
val xpathExpression = createXPath(XPath)
return xpathExpression.evaluate(o, XPathConstants.STRING) as String
}
private fun xpathAnyNodeList(o: Any, XPath: String): NodeList {
val xpathExpression = createXPath(XPath)
return xpathExpression.evaluate(o, XPathConstants.NODESET) as NodeList
}
private fun xpathAnyDate(o: Any, XPath: String) = parseDate(xpathAnyString(o, XPath))
// Use extension functions for Document and Node
fun Document.xpathString(XPath: String): String = xpathAnyString(this, XPath)
fun Document.xpathNodeList(XPath: String) = xpathAnyNodeList(this, XPath)
fun Document.xpathDate(XPath: String) = xpathAnyDate(this, XPath)
fun Node.xpathString(XPath: String): String = xpathAnyString(this, XPath)
fun Node.xpathNodeList(XPath: String) = xpathAnyNodeList(this, XPath)
fun Node.xpathDate(XPath: String) = xpathAnyDate(this, XPath)
|
mit
|
3f79ef8c45ac5cf09faf3ea9ae360746
| 34.58 | 85 | 0.784148 | 3.867391 | false | false | false | false |
etesync/android
|
app/src/main/java/com/etesync/syncadapter/ui/etebase/NewAccountWizardActivity.kt
|
1
|
7065
|
package com.etesync.syncadapter.ui.etebase
import android.accounts.Account
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ProgressBar
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.commit
import androidx.fragment.app.viewModels
import com.etebase.client.Collection
import com.etebase.client.FetchOptions
import com.etebase.client.ItemMetadata
import com.etebase.client.exceptions.EtebaseException
import com.etesync.syncadapter.Constants.*
import com.etesync.syncadapter.R
import com.etesync.syncadapter.syncadapter.requestSync
import com.etesync.syncadapter.ui.BaseActivity
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
class NewAccountWizardActivity : BaseActivity() {
private lateinit var account: Account
private val model: AccountViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
account = intent.extras!!.getParcelable(EXTRA_ACCOUNT)!!
setContentView(R.layout.etebase_fragment_activity)
if (savedInstanceState == null) {
setTitle(R.string.account_wizard_collections_title)
model.loadAccount(this, account)
supportFragmentManager.commit {
replace(R.id.fragment_container, WizardCheckFragment())
}
}
}
companion object {
private val EXTRA_ACCOUNT = "account"
fun newIntent(context: Context, account: Account): Intent {
val intent = Intent(context, NewAccountWizardActivity::class.java)
intent.putExtra(EXTRA_ACCOUNT, account)
return intent
}
}
}
fun reportErrorHelper(context: Context, e: Throwable) {
AlertDialog.Builder(context)
.setIcon(R.drawable.ic_info_dark)
.setTitle(R.string.exception)
.setMessage(e.localizedMessage)
.setPositiveButton(android.R.string.yes) { _, _ -> }.show()
}
class WizardCheckFragment : Fragment() {
private val model: AccountViewModel by activityViewModels()
private val loadingModel: LoadingViewModel by viewModels()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val ret = inflater.inflate(R.layout.account_wizard_check, container, false)
if (savedInstanceState == null) {
if (container != null) {
initUi(inflater, ret)
model.observe(this, {
checkAccountInit()
})
}
}
return ret
}
private fun initUi(inflater: LayoutInflater, v: View) {
val button = v.findViewById<Button>(R.id.button_retry)
val progress = v.findViewById<ProgressBar>(R.id.loading)
button.setOnClickListener {
checkAccountInit()
}
loadingModel.observe(this, {
if (it) {
progress.visibility = View.VISIBLE
button.visibility = View.GONE
} else {
progress.visibility = View.GONE
button.visibility = View.VISIBLE
}
})
}
private fun checkAccountInit() {
val colMgr = model.value?.colMgr ?: return
loadingModel.setLoading(true)
doAsync {
try {
val collections = colMgr.list(COLLECTION_TYPES, FetchOptions().limit(1))
uiThread {
if (collections.data.size > 0) {
activity?.finish()
} else {
parentFragmentManager.commit {
replace(R.id.fragment_container, WizardFragment())
}
}
}
} catch (e: Exception) {
uiThread {
reportErrorHelper(requireContext(), e)
loadingModel.setLoading(false)
}
}
}
}
}
class WizardFragment : Fragment() {
private val model: AccountViewModel by activityViewModels()
private val loadingModel: LoadingViewModel by viewModels()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val ret = inflater.inflate(R.layout.account_wizard_collections, container, false)
if (savedInstanceState == null) {
if (container != null) {
initUi(inflater, ret)
}
}
return ret
}
private fun initUi(inflater: LayoutInflater, v: View) {
v.findViewById<Button>(R.id.button_create).setOnClickListener {
createCollections()
}
v.findViewById<Button>(R.id.button_skip).setOnClickListener {
activity?.finish()
}
val buttons = v.findViewById<View>(R.id.buttons_holder)
val progress = v.findViewById<ProgressBar>(R.id.loading)
loadingModel.observe(this, {
if (it) {
progress.visibility = View.VISIBLE
buttons.visibility = View.GONE
} else {
progress.visibility = View.GONE
buttons.visibility = View.VISIBLE
}
})
}
private fun createCollections() {
val accountHolder = model.value ?: return
val colMgr = accountHolder.colMgr
loadingModel.setLoading(true)
doAsync {
try {
val baseMeta = listOf(
Pair(ETEBASE_TYPE_ADDRESS_BOOK, "My Contacts"),
Pair(ETEBASE_TYPE_CALENDAR, "My Calendar"),
Pair(ETEBASE_TYPE_TASKS, "My Tasks"),
)
baseMeta.forEach {
val meta = ItemMetadata()
meta.name = it.second
meta.mtime = System.currentTimeMillis()
val col = colMgr.create(it.first, meta, "")
uploadCollection(accountHolder, col)
}
requestSync(requireContext(), accountHolder.account)
activity?.finish()
} catch (e: EtebaseException) {
uiThread {
reportErrorHelper(requireContext(), e)
}
} finally {
uiThread {
loadingModel.setLoading(false)
}
}
}
}
private fun uploadCollection(accountHolder: AccountHolder, col: Collection) {
val etebaseLocalCache = accountHolder.etebaseLocalCache
val colMgr = accountHolder.colMgr
colMgr.upload(col)
synchronized(etebaseLocalCache) {
etebaseLocalCache.collectionSet(colMgr, col)
}
}
}
|
gpl-3.0
|
8af871a6bc55e2ae5232e52d202ef157
| 32.488152 | 116 | 0.597594 | 5.032051 | false | false | false | false |
NoodleMage/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/data/notification/NotificationReceiver.kt
|
2
|
11920
|
package eu.kanade.tachiyomi.data.notification
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Handler
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.download.DownloadService
import eu.kanade.tachiyomi.data.library.LibraryUpdateService
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.util.DiskUtil
import eu.kanade.tachiyomi.util.getUriCompat
import eu.kanade.tachiyomi.util.notificationManager
import eu.kanade.tachiyomi.util.toast
import uy.kohesive.injekt.injectLazy
import java.io.File
import eu.kanade.tachiyomi.BuildConfig.APPLICATION_ID as ID
/**
* Global [BroadcastReceiver] that runs on UI thread
* Pending Broadcasts should be made from here.
* NOTE: Use local broadcasts if possible.
*/
class NotificationReceiver : BroadcastReceiver() {
/**
* Download manager.
*/
private val downloadManager: DownloadManager by injectLazy()
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
// Dismiss notification
ACTION_DISMISS_NOTIFICATION -> dismissNotification(context, intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1))
// Resume the download service
ACTION_RESUME_DOWNLOADS -> DownloadService.start(context)
// Clear the download queue
ACTION_CLEAR_DOWNLOADS -> downloadManager.clearQueue(true)
// Show message notification created
ACTION_SHORTCUT_CREATED -> context.toast(R.string.shortcut_created)
// Launch share activity and dismiss notification
ACTION_SHARE_IMAGE -> shareImage(context, intent.getStringExtra(EXTRA_FILE_LOCATION),
intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1))
// Delete image from path and dismiss notification
ACTION_DELETE_IMAGE -> deleteImage(context, intent.getStringExtra(EXTRA_FILE_LOCATION),
intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1))
// Cancel library update and dismiss notification
ACTION_CANCEL_LIBRARY_UPDATE -> cancelLibraryUpdate(context, Notifications.ID_LIBRARY_PROGRESS)
// Open reader activity
ACTION_OPEN_CHAPTER -> {
openChapter(context, intent.getLongExtra(EXTRA_MANGA_ID, -1),
intent.getLongExtra(EXTRA_CHAPTER_ID, -1))
}
}
}
/**
* Dismiss the notification
*
* @param notificationId the id of the notification
*/
private fun dismissNotification(context: Context, notificationId: Int) {
context.notificationManager.cancel(notificationId)
}
/**
* Called to start share intent to share image
*
* @param context context of application
* @param path path of file
* @param notificationId id of notification
*/
private fun shareImage(context: Context, path: String, notificationId: Int) {
// Create intent
val intent = Intent(Intent.ACTION_SEND).apply {
val uri = File(path).getUriCompat(context)
putExtra(Intent.EXTRA_STREAM, uri)
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
type = "image/*"
}
// Dismiss notification
dismissNotification(context, notificationId)
// Launch share activity
context.startActivity(intent)
}
/**
* Starts reader activity
*
* @param context context of application
* @param mangaId id of manga
* @param chapterId id of chapter
*/
internal fun openChapter(context: Context, mangaId: Long, chapterId: Long) {
val db = DatabaseHelper(context)
val manga = db.getManga(mangaId).executeAsBlocking()
val chapter = db.getChapter(chapterId).executeAsBlocking()
if (manga != null && chapter != null) {
val intent = ReaderActivity.newIntent(context, manga, chapter).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
}
context.startActivity(intent)
} else {
context.toast(context.getString(R.string.chapter_error))
}
}
/**
* Called to delete image
*
* @param path path of file
* @param notificationId id of notification
*/
private fun deleteImage(context: Context, path: String, notificationId: Int) {
// Dismiss notification
dismissNotification(context, notificationId)
// Delete file
val file = File(path)
file.delete()
DiskUtil.scanMedia(context, file)
}
/**
* Method called when user wants to stop a library update
*
* @param context context of application
* @param notificationId id of notification
*/
private fun cancelLibraryUpdate(context: Context, notificationId: Int) {
LibraryUpdateService.stop(context)
Handler().post { dismissNotification(context, notificationId) }
}
companion object {
private const val NAME = "NotificationReceiver"
// Called to launch share intent.
private const val ACTION_SHARE_IMAGE = "$ID.$NAME.SHARE_IMAGE"
// Called to delete image.
private const val ACTION_DELETE_IMAGE = "$ID.$NAME.DELETE_IMAGE"
// Called to cancel library update.
private const val ACTION_CANCEL_LIBRARY_UPDATE = "$ID.$NAME.CANCEL_LIBRARY_UPDATE"
// Called to open chapter
private const val ACTION_OPEN_CHAPTER = "$ID.$NAME.ACTION_OPEN_CHAPTER"
// Value containing file location.
private const val EXTRA_FILE_LOCATION = "$ID.$NAME.FILE_LOCATION"
// Called to resume downloads.
private const val ACTION_RESUME_DOWNLOADS = "$ID.$NAME.ACTION_RESUME_DOWNLOADS"
// Called to clear downloads.
private const val ACTION_CLEAR_DOWNLOADS = "$ID.$NAME.ACTION_CLEAR_DOWNLOADS"
// Called to notify user shortcut is created.
private const val ACTION_SHORTCUT_CREATED = "$ID.$NAME.ACTION_SHORTCUT_CREATED"
// Called to dismiss notification.
private const val ACTION_DISMISS_NOTIFICATION = "$ID.$NAME.ACTION_DISMISS_NOTIFICATION"
// Value containing notification id.
private const val EXTRA_NOTIFICATION_ID = "$ID.$NAME.NOTIFICATION_ID"
// Value containing manga id.
private const val EXTRA_MANGA_ID = "$ID.$NAME.EXTRA_MANGA_ID"
// Value containing chapter id.
private const val EXTRA_CHAPTER_ID = "$ID.$NAME.EXTRA_CHAPTER_ID"
/**
* Returns a [PendingIntent] that resumes the download of a chapter
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun resumeDownloadsPendingBroadcast(context: Context): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_RESUME_DOWNLOADS
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns a [PendingIntent] that clears the download queue
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun clearDownloadsPendingBroadcast(context: Context): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_CLEAR_DOWNLOADS
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
internal fun shortcutCreatedBroadcast(context: Context) : PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_SHORTCUT_CREATED
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a service which dismissed the notification
*
* @param context context of application
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun dismissNotificationPendingBroadcast(context: Context, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_DISMISS_NOTIFICATION
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a service which cancels the notification and starts a share activity
*
* @param context context of application
* @param path location path of file
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun shareImagePendingBroadcast(context: Context, path: String, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_SHARE_IMAGE
putExtra(EXTRA_FILE_LOCATION, path)
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a service which removes an image from disk
*
* @param context context of application
* @param path location path of file
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun deleteImagePendingBroadcast(context: Context, path: String, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_DELETE_IMAGE
putExtra(EXTRA_FILE_LOCATION, path)
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that start a reader activity containing chapter.
*
* @param context context of application
* @param manga manga of chapter
* @param chapter chapter that needs to be opened
*/
internal fun openChapterPendingBroadcast(context: Context, manga: Manga, chapter: Chapter): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_OPEN_CHAPTER
putExtra(EXTRA_MANGA_ID, manga.id)
putExtra(EXTRA_CHAPTER_ID, chapter.id)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a service which stops the library update
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun cancelLibraryUpdatePendingBroadcast(context: Context): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_CANCEL_LIBRARY_UPDATE
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
}
}
|
apache-2.0
|
1137c0e1ccf9754012e13cb52db19094
| 39.962199 | 118 | 0.649832 | 5.070183 | false | false | false | false |
christophpickl/gadsu
|
src/test/kotlin/at/cpickl/gadsu/client/controller.kt
|
1
|
1973
|
package at.cpickl.gadsu.client
import at.cpickl.gadsu.testinfra.savedValidInstance
import at.cpickl.gadsu.view.components.MyListModel
import at.cpickl.gadsu.view.logic.calculateInsertIndex
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.testng.annotations.BeforeMethod
import org.testng.annotations.Test
@Test class ClientViewControllerTest {
private val prototype = Client.savedValidInstance().copy(lastName = "BBB")
private var model = MyListModel<Client>()
@BeforeMethod
fun resetState() {
model = MyListModel<Client>()
}
fun calculateIndex_emptyModel_returns0() {
assertThat(calculateIndex(prototype), equalTo(0))
}
fun calculateIndex_oneBeingLess_returns1() {
model.addElement(prototype.copy(lastName = "AAA"))
assertThat(calculateIndex(prototype), equalTo(1))
}
fun calculateIndex_oneBeingBigger_returns0() {
model.addElement(prototype.copy(lastName = "CCC"))
assertThat(calculateIndex(prototype), equalTo(0))
}
fun calculateIndex_inBetween_returns1() {
model.addElement(prototype.copy(lastName = "AAA"))
model.addElement(prototype.copy(lastName = "CCC"))
assertThat(calculateIndex(prototype), equalTo(1))
}
fun calculateIndex_twoLessOneBigger_returns2() {
model.addElement(prototype.copy(lastName = "AAA1"))
model.addElement(prototype.copy(lastName = "AAA2"))
model.addElement(prototype.copy(lastName = "CCC"))
assertThat(calculateIndex(prototype), equalTo(2))
}
fun calculateIndex_oneLessTwoBigger_returns1() {
model.addElement(prototype.copy(lastName = "AAA"))
model.addElement(prototype.copy(lastName = "CCC1"))
model.addElement(prototype.copy(lastName = "CCC2"))
assertThat(calculateIndex(prototype), equalTo(1))
}
private fun calculateIndex(client: Client) = model.calculateInsertIndex(client)
}
|
apache-2.0
|
39ecc0ec9a9c8c800e87cbeb616d6e6b
| 33.614035 | 83 | 0.713634 | 4.127615 | false | true | false | false |
kotlintest/kotlintest
|
kotest-assertions/src/jvmMain/kotlin/io/kotest/properties/ExtensionFunctionAssertAll.kt
|
1
|
956
|
package io.kotest.properties
import kotlin.reflect.KFunction1
import kotlin.reflect.KFunction2
inline fun <reified A, R> KFunction1<A, R>.assertAll(crossinline test: PropertyContext.(A, R) -> Unit) {
val gena = Gen.default<A>()
val fn: PropertyContext.(A) -> Unit = { a ->
val r = [email protected](a)
this.test(a, r)
}
_assertAll(1000, gena.constants().asSequence() + gena.random(), gena.shrinker(), fn)
}
inline fun <reified A, reified B, R> KFunction2<A, B, R>.assertAll(crossinline test: PropertyContext.(A, B, R) -> Unit) {
val gena = Gen.default<A>()
val genb = Gen.default<B>()
val fn: PropertyContext.(A, B) -> Unit = { a, b ->
val r = [email protected](a, b)
this.test(a, b, r)
}
val values = gena.constants().flatMap { a ->
genb.constants().map { b ->
Pair(a, b)
}
}.asSequence() + gena.random().zip(genb.random())
_assertAll(1000, values, gena.shrinker(), genb.shrinker(), fn)
}
|
apache-2.0
|
983b6c199e91077edd0e912bc8a8dd87
| 28.90625 | 121 | 0.640167 | 3.034921 | false | true | false | false |
Magneticraft-Team/Magneticraft
|
src/main/kotlin/com/cout970/magneticraft/systems/manual/MdRenderer.kt
|
2
|
4826
|
package com.cout970.magneticraft.systems.manual
import com.cout970.magneticraft.IVector2
import com.cout970.magneticraft.misc.vector.vec2Of
import net.minecraft.util.text.TextFormatting
object MdRenderer {
fun render(doc: MarkdownDocument, pageSize: IVector2, fontHeight: Int, fontWidth: (String) -> Int): List<Page> {
val ctx = Context(pageSize, fontHeight, fontWidth, location = doc.location)
val txt = doc.root.flatMap { renderTag(ctx, it) }
return txt.groupBy { it.page }.map {
Page(
text = it.value.filterIsInstance<NormalTextBox>(),
links = it.value.filterIsInstance<LinkTextBox>(),
index = it.key
)
}
}
fun renderTag(ctx: Context, tag: MdTag): List<TextBox> = tag.run {
when (this) {
is MdBr -> renderText(ctx, "\n")
is MdText -> {
if (txt.isEmpty()) {
emptyList()
} else {
renderText(ctx, txt)
}
}
is MdLink -> {
val (linkSection, page) = parseUrl(ctx.location, url)
listOf(LinkTextBox(childs.flatMap { renderTag(ctx, it) }, linkSection, page))
}
is MdItalic -> {
ctx.prefix += TextFormatting.ITALIC
val ret = childs.flatMap { renderTag(ctx, it) }
ctx.prefix = ctx.prefix.substring(0, ctx.prefix.length - 2)
ret
}
is MdBold -> {
ctx.prefix += TextFormatting.BOLD
val ret = childs.flatMap { renderTag(ctx, it) }
ctx.prefix = ctx.prefix.substring(0, ctx.prefix.length - 2)
ret
}
is MdHeader -> {
ctx.prefix += TextFormatting.BOLD
val ret = childs.flatMap { renderTag(ctx, it) }
ctx.prefix = ctx.prefix.substring(0, ctx.prefix.length - 2)
ret
}
is MdNewLine -> {
ctx.newLine()
emptyList()
}
is MdListItem -> {
val children = childs.flatMap { renderTag(ctx, it) }
ctx.newLine()
children
}
is MdUnsortedList -> {
ctx.newLine()
childs.flatMap { renderText(ctx, "* ") + renderTag(ctx, it) }
}
else -> emptyList()
}
}
private fun renderText(ctx: Context, txt: String): List<TextBox> {
val list = mutableListOf<TextBox>()
if (txt.length != 1 || txt != "\n") {
txt.split(" ", "\n").filter { it.isNotEmpty() }.forEach {
val size = ctx.fontWidth(ctx.prefix + it + " ")
if (ctx.lastPosX + size > ctx.pageSize.xi) {
ctx.newLine()
}
list += NormalTextBox(ctx.prefix + it, vec2Of(ctx.lastPosX, ctx.lastPosY), ctx.page)
ctx.lastPosX += size
}
}
if (txt.endsWith("\n")) {
ctx.newLine()
}
return list
}
fun parseUrl(location: String, url: String): Pair<String, Int> {
val separator = url.indexOfLast { it == '#' }
val page = if (separator != -1) {
url.substringAfterLast('#').toIntOrNull() ?: 0
} else 0
var urlWithoutPage = if (separator != -1) url.substringBeforeLast('#') else url
var baseLoc = location
while (urlWithoutPage.startsWith("../")) {
val parentIndex = baseLoc.lastIndexOf('/')
val index = urlWithoutPage.lastIndexOf("../")
baseLoc = if (parentIndex == -1) "" else baseLoc.substring(0, parentIndex)
urlWithoutPage = urlWithoutPage.replaceRange(index, index + 3, "")
}
if (baseLoc.isNotEmpty()) {
baseLoc += '/'
}
// we remove the ".md" suffix of the page Url because
// with .md suffix, in github we can follow the links in the formatted Markdown
// in game we register resources without ".md" suffixes (see removeSuffix(...) call in Chapters#loadBook)
val section = baseLoc + urlWithoutPage.removeSuffix(".md")
return section to page
}
data class Context(
val pageSize: IVector2,
val fontHeight: Int,
val fontWidth: (String) -> Int,
var lastPosX: Int = 0,
var lastPosY: Int = 0,
var prefix: String = "",
var page: Int = 0,
var location: String = ""
) {
fun newLine() {
lastPosY += fontHeight + 2
lastPosX = 0
if (lastPosY > pageSize.yi) {
lastPosY = 0
page++
}
}
}
}
|
gpl-2.0
|
c88662820d40830461786fc98b263bde
| 32.282759 | 116 | 0.503523 | 4.480966 | false | false | false | false |
f-droid/fdroidclient
|
libs/index/src/androidMain/kotlin/org/fdroid/index/v2/IndexV2DiffStreamProcessor.kt
|
1
|
5561
|
package org.fdroid.index.v2
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.encoding.CompositeDecoder
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.decodeFromStream
import kotlinx.serialization.json.jsonObject
import org.fdroid.index.IndexParser
import java.io.InputStream
@OptIn(ExperimentalSerializationApi::class)
public class IndexV2DiffStreamProcessor(
private val indexStreamReceiver: IndexV2DiffStreamReceiver,
private val json: Json = IndexParser.json,
) : IndexV2StreamProcessor {
public override fun process(
version: Long,
inputStream: InputStream,
onAppProcessed: (Int) -> Unit,
) {
json.decodeFromStream(IndexStreamSerializer(version, onAppProcessed), inputStream)
}
private inner class IndexStreamSerializer(
private val version: Long,
private val onAppProcessed: (Int) -> Unit,
) : KSerializer<IndexV2?> {
override val descriptor = IndexV2.serializer().descriptor
private var appsProcessed: Int = 0
override fun deserialize(decoder: Decoder): IndexV2? {
decoder as? JsonDecoder ?: error("Can be deserialized only by JSON")
decoder.beginStructure(descriptor)
val repoIndex = descriptor.getElementIndex("repo")
val packagesIndex = descriptor.getElementIndex("packages")
when (val startIndex = decoder.decodeElementIndex(descriptor)) {
repoIndex -> {
diffRepo(version, decoder, startIndex)
val index = decoder.decodeElementIndex(descriptor)
if (index == packagesIndex) diffPackages(decoder, index)
}
packagesIndex -> {
diffPackages(decoder, startIndex)
val index = decoder.decodeElementIndex(descriptor)
if (index == repoIndex) diffRepo(version, decoder, index)
}
else -> error("Unexpected startIndex: $startIndex")
}
var currentIndex = 0
while (currentIndex != CompositeDecoder.DECODE_DONE) {
currentIndex = decoder.decodeElementIndex(descriptor)
}
decoder.endStructure(descriptor)
indexStreamReceiver.onStreamEnded()
return null
}
private fun diffRepo(version: Long, decoder: JsonDecoder, index: Int) {
require(index == descriptor.getElementIndex("repo"))
val repo = decoder.decodeJsonElement().jsonObject
indexStreamReceiver.receiveRepoDiff(version, repo)
}
private fun diffPackages(decoder: JsonDecoder, index: Int) {
require(index == descriptor.getElementIndex("packages"))
val mapDescriptor = descriptor.getElementDescriptor(index)
val compositeDecoder = decoder.beginStructure(mapDescriptor)
while (true) {
val packageIndex = compositeDecoder.decodeElementIndex(descriptor)
if (packageIndex == CompositeDecoder.DECODE_DONE) break
readMapEntry(compositeDecoder, packageIndex)
appsProcessed += 1
onAppProcessed(appsProcessed)
}
compositeDecoder.endStructure(mapDescriptor)
}
private fun readMapEntry(decoder: CompositeDecoder, index: Int) {
val packageName = decoder.decodeStringElement(descriptor, index)
decoder.decodeElementIndex(descriptor)
val packageV2 = decoder.decodeSerializableElement(
descriptor, index + 1, JsonElement.serializer()
)
if (packageV2 is JsonNull) {
// delete app and existing metadata
indexStreamReceiver.receivePackageMetadataDiff(packageName, null)
return
}
// diff package metadata
val metadata = packageV2.jsonObject["metadata"]
if (metadata is JsonNull) {
// delete app and existing metadata
indexStreamReceiver.receivePackageMetadataDiff(packageName, null)
} else if (metadata is JsonObject) {
// if it is null, the diff doesn't change it, so only call receiver if not null
indexStreamReceiver.receivePackageMetadataDiff(packageName, metadata)
}
// diff package versions
if (packageV2.jsonObject["versions"] is JsonNull) {
// delete all versions of this app
indexStreamReceiver.receiveVersionsDiff(packageName, null)
} else {
val versions = packageV2.jsonObject["versions"]?.jsonObject?.mapValues {
if (it.value is JsonNull) null else it.value.jsonObject
}
if (versions != null) {
// if it is null, the diff doesn't change it, so only call receiver if not null
indexStreamReceiver.receiveVersionsDiff(packageName, versions)
}
}
}
override fun serialize(encoder: Encoder, value: IndexV2?) {
error("Not implemented")
}
}
}
|
gpl-3.0
|
3bd547c55d21d6fa51c49fb2e97463de
| 42.445313 | 99 | 0.636576 | 5.4148 | false | false | false | false |
jdinkla/groovy-java-ray-tracer
|
src/main/kotlin/net/dinkla/raytracer/objects/mesh/Mesh.kt
|
1
|
2100
|
package net.dinkla.raytracer.objects.mesh
import net.dinkla.raytracer.materials.IMaterial
import net.dinkla.raytracer.math.Normal
import net.dinkla.raytracer.math.Point3D
import java.util.*
class Mesh {
var vertices: ArrayList<Point3D> = ArrayList()
// public List<Integer> indices;
var normals: ArrayList<Normal> = ArrayList()
// public List<Float> us;
// public List<Float> vs;
var vertexFaces: ArrayList<List<Int>> = ArrayList()
// public int numVertices;
// public int numTriangles;
var material: IMaterial? = null
fun computeMeshNormals(objects: ArrayList<MeshTriangle>) {
normals.ensureCapacity(vertices.size)
for (index in vertices.indices) {
var normal = Normal.ZERO
// for (int j = 0; j < vertexFaces.get(index).size(); j++) {
// normal = new Normal(normal.plus(objects.get(vertexFaces.get(index).get(j)).getNormal()));
// }
for (i in vertexFaces[index]) {
val n = objects[i].normal
if (null != n) {
normal = Normal(normal.plus(n))
}
}
// The following code attempts to avoid (nan, nan, nan) normalised normals when all components = 0
if (normal.x == 0.0 && normal.y == 0.0 && normal.z == 0.0) {
normal = Normal(normal.x, 1.0, normal.z)
} else {
normal = normal.normalize()
}
normals.add(index, normal)
}
// erase the vertex_faces arrays because we have now finished with them
/*
for (int index = 0; index < vertices.size(); index++)
for (int j = 0; j < vertexFaces.get(index).size(); j++)
mesh_ptr->vertex_faces[index].erase (mesh_ptr->vertex_faces[index].begin(), mesh_ptr->vertex_faces[index].end());
mesh_ptr->vertex_faces.erase (mesh_ptr->vertex_faces.begin(), mesh_ptr->vertex_faces.end());
cout << "finished constructing normals" << endl;
*/
}
}
|
apache-2.0
|
83f4af734188a38d80ef1f0fd449cd70
| 34 | 129 | 0.56381 | 4 | false | false | false | false |
google/horologist
|
media-ui/src/test/java/com/google/android/horologist/media/ui/screens/entity/CreatePlaylistDownloadScreenStateLoadedTest.kt
|
1
|
9316
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistMediaUiApi::class)
package com.google.android.horologist.media.ui.screens.entity
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import com.google.android.horologist.media.ui.state.model.DownloadMediaUiModel
import com.google.android.horologist.media.ui.state.model.PlaylistUiModel
import com.google.common.truth.Truth.assertThat
import org.junit.Test
class CreatePlaylistDownloadScreenStateLoadedTest {
@Test
fun givenNoDownloaded_thenDownloadMediaListStateIsNone() {
// given
val downloads = listOf(
DownloadMediaUiModel.NotDownloaded(
id = "id",
title = "Song name",
artist = "Artist name",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.NotDownloaded(
id = "id 2",
title = "Song name 2",
artist = "Artist name 2",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.Downloading(
id = "id 3",
title = "Song name 3",
artworkUri = "artworkUri",
progress = DownloadMediaUiModel.Progress.InProgress(60f),
size = DownloadMediaUiModel.Size.Known(sizeInBytes = 1280049)
)
)
// when
val result = createPlaylistDownloadScreenStateLoaded(
playlistModel = PlaylistUiModel(
id = "id",
title = "title"
),
downloadMediaList = downloads
).downloadMediaListState
// then
assertThat(result).isEqualTo(PlaylistDownloadScreenState.Loaded.DownloadMediaListState.None)
}
@Test
fun givenMixed_thenDownloadMediaListStateIsPartially() {
// given
val downloads = listOf(
DownloadMediaUiModel.Downloaded(
id = "id",
title = "Song name",
artist = "Artist name",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.NotDownloaded(
id = "id 2",
title = "Song name 2",
artist = "Artist name 2",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.Downloading(
id = "id 3",
title = "Song name 3",
artworkUri = "artworkUri",
progress = DownloadMediaUiModel.Progress.InProgress(60f),
size = DownloadMediaUiModel.Size.Known(sizeInBytes = 1280049)
)
)
// when
val result = createPlaylistDownloadScreenStateLoaded(
playlistModel = PlaylistUiModel(
id = "id",
title = "title"
),
downloadMediaList = downloads
).downloadMediaListState
// then
assertThat(result).isEqualTo(PlaylistDownloadScreenState.Loaded.DownloadMediaListState.Partially)
}
@Test
fun givenDownloadedAndDownloading_thenDownloadMediaListStateIsPartially() {
// given
val downloads = listOf(
DownloadMediaUiModel.Downloaded(
id = "id",
title = "Song name",
artist = "Artist name",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.Downloading(
id = "id 2",
title = "Song name 2",
artworkUri = "artworkUri",
progress = DownloadMediaUiModel.Progress.InProgress(60f),
size = DownloadMediaUiModel.Size.Known(sizeInBytes = 1280049)
)
)
// when
val result = createPlaylistDownloadScreenStateLoaded(
playlistModel = PlaylistUiModel(
id = "id",
title = "title"
),
downloadMediaList = downloads
).downloadMediaListState
// then
assertThat(result).isEqualTo(PlaylistDownloadScreenState.Loaded.DownloadMediaListState.Partially)
}
@Test
fun givenDownloaded_thenDownloadMediaListStateIsFully() {
// given
val downloads = listOf(
DownloadMediaUiModel.Downloaded(
id = "id",
title = "Song name",
artist = "Artist name",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.Downloaded(
id = "id 2",
title = "Song name 2",
artist = "Artist name 2",
artworkUri = "artworkUri"
)
)
// when
val result = createPlaylistDownloadScreenStateLoaded(
playlistModel = PlaylistUiModel(
id = "id",
title = "title"
),
downloadMediaList = downloads
).downloadMediaListState
// then
assertThat(result).isEqualTo(PlaylistDownloadScreenState.Loaded.DownloadMediaListState.Fully)
}
@Test
fun givenEmptyDownloads_thenDownloadMediaListStateIsFully() {
// given
val downloads = emptyList<DownloadMediaUiModel>()
// when
val result = createPlaylistDownloadScreenStateLoaded(
playlistModel = PlaylistUiModel(
id = "id",
title = "title"
),
downloadMediaList = downloads
).downloadMediaListState
// then
assertThat(result).isEqualTo(PlaylistDownloadScreenState.Loaded.DownloadMediaListState.Fully)
}
@Test
fun givenNoDownloading_thenDownloadsProgressIsIdle() {
// given
val downloads = listOf(
DownloadMediaUiModel.Downloaded(
id = "id",
title = "Song name",
artist = "Artist name",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.NotDownloaded(
id = "id 2",
title = "Song name 2",
artist = "Artist name 2",
artworkUri = "artworkUri"
)
)
// when
val result = createPlaylistDownloadScreenStateLoaded(
playlistModel = PlaylistUiModel(
id = "id",
title = "title"
),
downloadMediaList = downloads
).downloadsProgress
// then
assertThat(result).isEqualTo(PlaylistDownloadScreenState.Loaded.DownloadsProgress.Idle)
}
@Test
fun givenDownloading_thenDownloadsProgressIsInProgress() {
// given
val downloads = listOf(
DownloadMediaUiModel.Downloaded(
id = "id",
title = "Song name",
artist = "Artist name",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.NotDownloaded(
id = "id 2",
title = "Song name 2",
artist = "Artist name 2",
artworkUri = "artworkUri"
),
DownloadMediaUiModel.Downloading(
id = "id 3",
title = "Song name 3",
artworkUri = "artworkUri",
progress = DownloadMediaUiModel.Progress.InProgress(60f),
size = DownloadMediaUiModel.Size.Known(sizeInBytes = 1280049)
),
DownloadMediaUiModel.Downloading(
id = "id 4",
title = "Song name 4",
artworkUri = "artworkUri",
progress = DownloadMediaUiModel.Progress.InProgress(60f),
size = DownloadMediaUiModel.Size.Known(sizeInBytes = 1280049)
)
)
// when
val result = createPlaylistDownloadScreenStateLoaded(
playlistModel = PlaylistUiModel(
id = "id",
title = "title"
),
downloadMediaList = downloads
).downloadsProgress
// then
assertThat(result).isEqualTo(
PlaylistDownloadScreenState.Loaded.DownloadsProgress.InProgress(0.25F)
)
}
@Test
fun givenEmptyDownloads_thenDownloadsProgressIsIdle() {
// given
val downloads = emptyList<DownloadMediaUiModel>()
// when
val result = createPlaylistDownloadScreenStateLoaded(
playlistModel = PlaylistUiModel(
id = "id",
title = "title"
),
downloadMediaList = downloads
).downloadsProgress
// then
assertThat(result).isEqualTo(PlaylistDownloadScreenState.Loaded.DownloadsProgress.Idle)
}
}
|
apache-2.0
|
61f1b433f02f6526588aaf702c651ec7
| 32.153025 | 105 | 0.556033 | 5.761286 | false | false | false | false |
sharaquss/todo
|
app/src/main/java/com/android/szparag/todoist/utils/ReactiveMutableList.kt
|
1
|
4913
|
package com.android.szparag.todoist.utils
import com.android.szparag.todoist.utils.ReactiveList.ReactiveChangeType.DELETED
import com.android.szparag.todoist.utils.ReactiveList.ReactiveChangeType.INSERTED
import com.android.szparag.todoist.utils.ReactiveList.ReactiveChangeType.UPDATED
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
class ReactiveMutableList<E : Any>(private val initialCapacity: Int = 64, private val debuggable: Boolean = false) :
ArrayList<E>(initialCapacity), MutableList<E>, ReactiveList<E> {
private val logger: Logger = if (debuggable) Logger.create(this::class.java, hashCode()) else Logger.createInfunctionalStub()
private var listEventsSubject = PublishSubject.create<ReactiveListEvent<E>>()
private var listDataSubject = PublishSubject.create<ReactiveList<E>>()
override val size: Int
get() = super.size
override fun subscribeForListEvents(): Observable<ReactiveListEvent<E>> {
logger.debug("subscribeForListEvents")
return listEventsSubject
}
override fun subscribeForListData(): Observable<ReactiveList<E>> {
logger.debug("subscribeForListData")
return listDataSubject
}
//todo: fix -1's where they occur
override fun insert(element: E) {
logger.debug("insert, element: $element")
add(element)
.also { listEventsSubject.onNext(ReactiveListEvent(INSERTED, element, lastIndex())) }
.also { listDataSubject.onNext(this) }
}
override fun insert(index: Int, element: E) {
logger.debug("insert, index: $index, element: $element")
add(index, element)
.also { listEventsSubject.onNext(ReactiveListEvent(INSERTED, element, index)) }
.also { listDataSubject.onNext(this) }
}
override fun insert(elements: Collection<E>) {
logger.debug("insert, elements: $elements")
addAll(elements)
.also { listEventsSubject.onNext(ReactiveListEvent(INSERTED, elements, lastIndex() - (elements.size-1))) }
.also { listDataSubject.onNext(this) }
}
override fun insert(index: Int, elements: Collection<E>) {
logger.debug("insert, index: $index, elements: $elements")
addAll(index, elements)
.also { listEventsSubject.onNext(ReactiveListEvent(INSERTED, elements, index)) }
.also { listDataSubject.onNext(this) }
}
override fun delete(element: E) {
logger.debug("delete, element: $element")
super.indexOf(element).let { index ->
remove(element)
.also { listEventsSubject.onNext(ReactiveListEvent(DELETED, element, index)) }
.also { listDataSubject.onNext(this) }
}
}
override fun delete(index: Int) {
logger.debug("delete, index: $index")
removeAt(index)
.also { listEventsSubject.onNext(ReactiveListEvent(DELETED, it, index)) }
.also { listDataSubject.onNext(this) }
}
override fun delete(elements: Collection<E>) {
logger.debug("remove, elements: $elements")
removeAll(elements)
.also { listEventsSubject.onNext(ReactiveListEvent(DELETED, elements, -1)) } //todo -1
.also { listDataSubject.onNext(this) }
}
// override fun delete(indexes: Pair<Int, Int>) {
// logger.debug("remove, indexes: $indexes")
// removeRange(indexes.first, indexes.second)
// .also { listEventsSubject.onNext(ReactiveListEvent(DELETED, )) }
// .also { listDataSubject.onNext(this) }
// }
override fun update(index: Int, element: E) {
logger.debug("update, index: $index, element: $element")
set(index, element)
.also { listEventsSubject.onNext(ReactiveListEvent(UPDATED, element, index)) }
.also { listDataSubject.onNext(this) }
}
override fun update(originalElement: E, updatedElement: E) {
logger.debug("update, originalElement: $originalElement. updatedElement: $")
indexOf(originalElement).let { index ->
set(index, updatedElement)
.also { listEventsSubject.onNext(ReactiveListEvent(DELETED, updatedElement, index)) }
.also { listDataSubject.onNext(this) }
}
}
//todo: figure out rangeListOf indexing - if those should be indexes indeed, then 0..size-1 below:
override fun clear() {
logger.debug("clear")
size.let { size ->
super.clear()
.also { listEventsSubject.onNext(ReactiveListEvent(DELETED, this, 0)) } //todo: event CLEARED
.also { listDataSubject.onNext(this) }
}
}
override fun get(index: Int): E {
logger.debug("get, index: $index")
return super.get(index)
}
//todo: test - check if when 0-indexed element is deleted, list shrinks and fills the space of this element
override fun first() = get(0)
override fun last() = get(size - 1)
//todo: this produces ArrayIndexOutOfBoundsException if list is empty
override fun boundary(forward: Boolean) = if (forward) last() else first()
override fun toString() = asString()
fun lastIndex() = Math.max(0, size-1)
}
|
mit
|
a5a1b366beccbf4eb18741fb11f2b73f
| 36.227273 | 127 | 0.69713 | 3.981361 | false | false | false | false |
gravidence/gravifon
|
gravifon/src/main/kotlin/org/gravidence/gravifon/playlist/StaticPlaylist.kt
|
1
|
1101
|
package org.gravidence.gravifon.playlist
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.gravidence.gravifon.playlist.behavior.PlaybackOrder
import org.gravidence.gravifon.playlist.behavior.PlaylistStructure
import org.gravidence.gravifon.playlist.item.PlaylistItem
import org.gravidence.gravifon.playlist.layout.PlaylistLayout
import org.gravidence.gravifon.playlist.layout.ScrollPosition
import java.util.*
@Serializable
@SerialName("static")
class StaticPlaylist(
override val id: String = UUID.randomUUID().toString(),
override val ownerName: String = "Owner Name",
override var displayName: String = "Display Name",
override val items: MutableList<PlaylistItem> = ArrayList(),
override var position: Int = DEFAULT_POSITION,
override var playbackOrder: PlaybackOrder = PlaybackOrder.SEQUENTIAL,
override var playlistStructure: PlaylistStructure = PlaylistStructure.TRACK,
override var layout: PlaylistLayout = PlaylistLayout(),
override var verticalScrollPosition: ScrollPosition = ScrollPosition(),
) : Playlist()
|
mit
|
48486a71d98863f651815894888f702f
| 44.916667 | 80 | 0.807448 | 4.85022 | false | false | false | false |
inv3rse/ProxerTv
|
app/src/test/java/com/inverse/unofficial/proxertv/model/typeAdapter/CommentRatingsTypeAdapterTest.kt
|
1
|
1319
|
package com.inverse.unofficial.proxertv.model.typeAdapter
import com.google.gson.stream.JsonReader
import com.inverse.unofficial.proxertv.model.CommentRatings
import org.junit.Assert.assertEquals
import org.junit.Test
import java.io.StringReader
/**
* Test cases for the [CommentRatingsTypeAdapter]
*/
class CommentRatingsTypeAdapterTest {
private val adapter = CommentRatingsTypeAdapter()
@Test
fun testEmptyString() {
val ratings = readString("\"\"")
assertEquals(EMPTY_RATINGS, ratings)
}
@Test
fun testEmptyArray() {
val ratings = readString("\"[]\"")
assertEquals(EMPTY_RATINGS, ratings)
}
@Test
fun testEmptyObject() {
val ratings = readString("\"{}\"")
assertEquals(EMPTY_RATINGS, ratings)
}
@Test
fun testCompleteObject() {
// triple " to keep the escape characters
val ratings = readString(""""{\"genre\":\"1\",\"story\":\"1\",\"animation\":\"2\",\"characters\":\"1\",\"music\":\"1\"}"""")
assertEquals(CommentRatings(1, 1, 2, 1, 1), ratings)
}
private fun readString(input: String): CommentRatings {
return adapter.read(JsonReader(StringReader(input)))
}
companion object {
val EMPTY_RATINGS = CommentRatings(null, null, null, null, null)
}
}
|
mit
|
1b9a688d57b96a824cdc187dfeb6c751
| 26.5 | 132 | 0.646702 | 4.338816 | false | true | false | false |
vsch/idea-multimarkdown
|
src/main/java/com/vladsch/md/nav/language/CodeStyleBundle.kt
|
1
|
1670
|
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.language
import com.intellij.AbstractBundle
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import java.lang.ref.Reference
import java.lang.ref.SoftReference
import java.util.*
class CodeStyleBundle {
companion object {
@JvmStatic
fun getString(@PropertyKey(resourceBundle = BUNDLE_NAME) key: String, vararg params: Any): String {
return AbstractBundle.message(bundle, key, *params)
}
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE_NAME) key: String, vararg params: Any): String {
return AbstractBundle.message(bundle, key, *params)
}
@JvmStatic
fun messageOrBlank(@PropertyKey(resourceBundle = BUNDLE_NAME) key: String, vararg params: Any): String {
return AbstractBundle.messageOrDefault(bundle, key, "", *params)
}
private var ourBundle: Reference<ResourceBundle>? = null
@NonNls
internal const val BUNDLE_NAME = "com.vladsch.md.nav.localization.codestyle"
@JvmStatic
val bundle: ResourceBundle
get() {
var bundle = com.intellij.reference.SoftReference.dereference(ourBundle)
if (bundle == null) {
bundle = ResourceBundle.getBundle(BUNDLE_NAME)
ourBundle = SoftReference(bundle)
}
return bundle as ResourceBundle
}
}
}
|
apache-2.0
|
4d20e15a0b2fafd6edef69462293c41d
| 35.304348 | 177 | 0.65509 | 4.798851 | false | false | false | false |
chrisbanes/tivi
|
data-android/src/test/java/app/tivi/utils/FakeTiviShowFts.kt
|
1
|
1268
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.utils
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* A fake version of TiviShowFts to model the same entity
* table, but without actually using FTS. This is because
* Robolectric's SQL implementation does not support everything
* needed for Room's FTS support.
*/
@Entity(tableName = "shows_fts")
internal data class FakeTiviShowFts(
@PrimaryKey
@ColumnInfo(name = "id")
val id: Long? = null,
@ColumnInfo(name = "title") val title: String? = null,
@ColumnInfo(name = "original_title") val originalTitle: String? = null,
@ColumnInfo(name = "docid") val docId: Long? = null
)
|
apache-2.0
|
267077d6108512af7b46d765986c6989
| 33.27027 | 75 | 0.727129 | 3.987421 | false | false | false | false |
JimSeker/ui
|
Basic/FragFormExample_kt/app/src/main/java/edu/cs4730/fragformexample_kt/FormFragment.kt
|
1
|
3115
|
package edu.cs4730.fragformexample_kt
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
/**
* The meat of the example is here, instead of the mainActivity. OnCreateView has the setup
* and then all the listeners.
*/
class FormFragment : Fragment(), RadioGroup.OnCheckedChangeListener,
TextWatcher, View.OnClickListener {
//variables for the widgets
lateinit var myRadioGroup: RadioGroup
lateinit var et: EditText
lateinit var btnalert: Button
lateinit var label: TextView
//variable for the log
var TAG = "FormFragment"
//OnCreateView is where everything is inflated and any listeners are setup at.
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle? ): View {
// Inflate the layout for this fragment
val myView = inflater.inflate(R.layout.fragment_form, container, false)
//EditText view setup and listner
et = myView.findViewById(R.id.ETname)
et.addTextChangedListener(this)
//the top label in the xml doc.
label = myView.findViewById(R.id.Label01)
//setup the radio group with a listener.
myRadioGroup = myView.findViewById(R.id.SndGroup)
myRadioGroup.setOnCheckedChangeListener(this)
//setup the button with a listener as well.
btnalert = myView.findViewById(R.id.Button01)
btnalert.setOnClickListener(this)
return myView
}
/* Radio group listener for OnCheckedChangeListener */
override fun onCheckedChanged(group: RadioGroup, CheckedId: Int) {
if (group === myRadioGroup) { //if not myRadioGroup, we are in trouble!
if (CheckedId == R.id.RB01) {
// information radio button clicked
Log.d(TAG, "RB01 was pushed.")
} else if (CheckedId == R.id.RB02) {
// Confirmation radio button clicked
Log.d(TAG, "RB02 was pushed.")
} else if (CheckedId == R.id.RB03) {
// Warning radio button clicked
Toast.makeText(activity, "Warning!", Toast.LENGTH_LONG).show()
}
}
}
/* EditView listeners */
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (et.length() > 10) {
Toast.makeText(activity, "Long Word!", Toast.LENGTH_SHORT).show()
Log.d(TAG, "Long Word!")
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
//left blank
}
override fun afterTextChanged(s: Editable?) {
//left blank
}
/* button listener */
override fun onClick(v: View) {
if (v === btnalert) {
Toast.makeText(activity, "The button was pressed", Toast.LENGTH_SHORT).show()
Log.d(TAG, "The button was pressed.")
}
}
}
|
apache-2.0
|
d380c0667a6beeb721abc06b30b64269
| 32.494624 | 92 | 0.64077 | 4.362745 | false | false | false | false |
pnemonic78/RemoveDuplicates
|
duplicates-android/app/src/main/java/com/github/duplicates/DuplicateViewHolder.kt
|
1
|
3276
|
/*
* Copyright 2016, Moshe Waisberg
*
* 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.duplicates
import android.content.Context
import android.graphics.Color
import android.view.View
import androidx.annotation.ColorInt
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.RecyclerView
import com.github.android.removeduplicates.R
import java.text.NumberFormat
/**
* View holder for a duplicate item.
*
* @author moshe.w
*/
abstract class DuplicateViewHolder<T : DuplicateItem>(
itemView: View,
protected val onCheckedChangeListener: OnItemCheckedChangeListener<T>? = null
) : RecyclerView.ViewHolder(itemView) {
private val context: Context
@ColorInt
protected val colorDifferent: Int
@ColorInt
protected val colorError: Int
protected val percentFormatter = NumberFormat.getPercentInstance()
protected lateinit var item1: T
protected lateinit var item2: T
init {
val context = itemView.context
val res = context.resources
this.context = context
this.colorDifferent = ResourcesCompat.getColor(res, R.color.different, null)
this.colorError = ResourcesCompat.getColor(res, R.color.error, null)
}
/**
* Bind the pair to the view.
*
* @param pair the pair of items.
*/
fun bind(pair: DuplicateItemPair<T>) {
val item1 = pair.item1
val item2 = pair.item2
this.item1 = pair.item1
this.item2 = pair.item2
bindHeader(context, pair)
bindItem1(context, item1)
bindItem2(context, item2)
bindDifference(context, pair)
if (item1.isError || item2.isError) {
itemView.setBackgroundColor(colorError)
} else {
itemView.background = null
}
}
protected abstract fun bindHeader(context: Context, pair: DuplicateItemPair<T>)
protected abstract fun bindItem1(context: Context, item: T)
protected abstract fun bindItem2(context: Context, item: T)
protected abstract fun bindDifference(context: Context, pair: DuplicateItemPair<T>)
protected fun bindDifference(view1: View, view2: View, different: Boolean) {
if (different) {
view1.setBackgroundColor(colorDifferent)
view2.setBackgroundColor(colorDifferent)
} else {
view1.setBackgroundColor(Color.TRANSPARENT)
view2.setBackgroundColor(Color.TRANSPARENT)
}
}
interface OnItemCheckedChangeListener<T> {
/**
* Notification that the item was clicked.
*
* @param item the item.
* @param checked is checked?
*/
fun onItemCheckedChangeListener(item: T, checked: Boolean)
}
}
|
apache-2.0
|
596145dcdbb3b507b1cd3e4fe0d82398
| 29.915094 | 87 | 0.684982 | 4.439024 | false | false | false | false |
laurencegw/jenjin
|
jenjin-demo/src/com/binarymonks/jj/demo/demos/D18_physics_debug.kt
|
1
|
2948
|
package com.binarymonks.jj.demo.demos
import com.badlogic.gdx.physics.box2d.BodyDef
import com.binarymonks.jj.core.JJ
import com.binarymonks.jj.core.JJConfig
import com.binarymonks.jj.core.JJGame
import com.binarymonks.jj.core.physics.collisions.SoundCollision
import com.binarymonks.jj.core.specs.Circle
import com.binarymonks.jj.core.specs.SceneSpec
import com.binarymonks.jj.core.specs.params
class D18_physics_debug : JJGame(JJConfig {
b2d.debugRender = true
debugStep = true
val width = 30f
gameView.worldBoxWidth = width
gameView.cameraPosX = 0f
gameView.cameraPosY = 0f
}) {
public override fun gameOn() {
JJ.scenes.addSceneSpec("ball", ball())
JJ.scenes.addSceneSpec("terrain", floor())
JJ.scenes.loadAssetsNow()
//Set up our collision groups
JJ.physics.collisionGroups.buildGroups {
group("layer1").collidesWith("layer1")
group("layer2").collidesWith("layer2")
}
val initialSceneSpec = SceneSpec {
//Set up some balls and a terrain on 'layer1' collision group
node("ball"){ x = -8f; y = 8f; prop("collisionGroup", "layer1") }
node("ball"){ x = -2f; y = 9f; scaleX = 2f; scaleY = 2f;prop("collisionGroup", "layer1") }
node("terrain"){ x = 0f; y = 0f; scaleX = 20f;prop("collisionGroup", "layer1") }
//Set up some balls and a terrain on 'layer2' collision group
node("ball"){ x = 2f; y = 10f;prop("collisionGroup", "layer2") }
node("ball"){ x = +8f; y = 11f; scaleX = 2f; scaleY = 2f;prop("collisionGroup", "layer2") }
node("terrain"){ x = 0f; y = -10f; scaleX = 20f;prop("collisionGroup", "layer2") }
}
JJ.scenes.instantiate(initialSceneSpec)
}
private fun ball(): SceneSpec {
return SceneSpec {
sounds.sound("bounce", "sounds/pong.mp3", volume = 0.6f)
physics {
fixture {
bodyType = BodyDef.BodyType.DynamicBody
shape = Circle()
restitution = 0.7f
// We bind the collision group to a property key
collisionGroupProperty("collisionGroup")
// We can add collisions to the fixture (called first)
collisions.begin(SoundCollision(soundName = "bounce"))
}
//And we can add collisions to the root (called after fixture collision handlers)
collisions.begin(SoundCollision(soundName = "bounce"))
}
}
}
private fun floor(): SceneSpec {
return SceneSpec {
physics {
bodyType = BodyDef.BodyType.StaticBody
fixture {
// We bind the collision group to a property key
collisionGroupProperty("collisionGroup")
}
}
}
}
}
|
apache-2.0
|
717d36dcd63745e0d814df5ba6fc13bb
| 36.316456 | 103 | 0.582768 | 4.117318 | false | false | false | false |
googlearchive/android-RecyclerView
|
kotlinApp/app/src/main/java/com/example/android/common/logger/LogView.kt
|
3
|
4123
|
/*
* 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.example.android.common.logger
import android.app.Activity
import android.content.Context
import android.util.*
import android.widget.TextView
/** Simple TextView which is used to output log data received through the LogNode interface.
*/
class LogView : TextView, LogNode {
// The next LogNode in the chain.
private var next: LogNode? = null
@JvmOverloads
constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) :
super(context, attrs, defStyle)
/**
* Formats the log data and prints it out to the LogView.
* @param priority Log level of the data being logged. Verbose, Error, etc.
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged. The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
override fun println(priority: Int, tag: String?, msg: String?, tr: Throwable?) {
// For the purposes of this View, we want to print the priority as readable text.
val priorityStr = when (priority) {
android.util.Log.VERBOSE -> "VERBOSE"
android.util.Log.DEBUG -> "DEBUG"
android.util.Log.INFO -> "INFO"
android.util.Log.WARN -> "WARN"
android.util.Log.ERROR -> "ERROR"
android.util.Log.ASSERT -> "ASSERT"
else -> null
}
// Handily, the Log class has a facility for converting a stack trace into a usable string.
val exceptionStr = tr?.let{ android.util.Log.getStackTraceString(it) }
// Take the priority, tag, message, and exception, and concatenate as necessary
// into one usable line of text.
val outputBuilder = StringBuilder()
val delimiter = "\t"
appendIfNotNull(outputBuilder, priorityStr, delimiter)
appendIfNotNull(outputBuilder, tag, delimiter)
appendIfNotNull(outputBuilder, msg, delimiter)
appendIfNotNull(outputBuilder, exceptionStr, delimiter)
// In case this was originally called from an AsyncTask or some other off-UI thread,
// make sure the update occurs within the UI thread.
(context as Activity).runOnUiThread( {
// Display the text we just generated within the LogView.
appendToLog(outputBuilder.toString())
})
next?.println(priority, tag, msg, tr)
}
/** Takes a string and adds to it, with a separator, if the bit to be added isn't null. Since
* the logger takes so many arguments that might be null, this method helps cut out some of the
* agonizing tedium of writing the same 3 lines over and over.
* @param source StringBuilder containing the text to append to.
* @param addStr The String to append
* @param delimiter The String to separate the source and appended strings. A tab or comma,
* for instance.
* @return The fully concatenated String as a StringBuilder
*/
private fun appendIfNotNull(source: StringBuilder, addStr: String?, delimiter: String): StringBuilder {
if (addStr != null && !addStr.isEmpty()) {
return source.append(addStr).append(delimiter)
}
return source
}
/** Outputs the string as a new line of log data in the LogView. */
private fun appendToLog(s: String) {
append("\n" + s)
}
}
|
apache-2.0
|
0d3f914156aade6dac1c9a8c43552e90
| 38.266667 | 107 | 0.670871 | 4.38617 | false | false | false | false |
rock3r/detekt
|
detekt-gradle-plugin/src/test/kotlin/io/gitlab/arturbosch/detekt/DslGradleRunner.kt
|
1
|
4965
|
package io.gitlab.arturbosch.detekt
import io.gitlab.arturbosch.detekt.test.createTempDirectoryForTest
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.GradleRunner
import java.io.File
import java.util.UUID
class DslGradleRunner @Suppress("LongParameterList") constructor(
val projectLayout: ProjectLayout,
val buildFileName: String,
val mainBuildFileContent: String,
val configFileOrNone: String? = null,
val baselineFileOrNone: String? = null,
val gradleVersionOrNone: String? = null,
val dryRun: Boolean = false
) {
private val rootDir: File = createTempDirectoryForTest(prefix = "applyPlugin").toFile()
private val randomString = UUID.randomUUID().toString()
private val settingsContent = """
|rootProject.name = "rootDir-project"
|include(${projectLayout.submodules.map { "\"${it.name}\"" }.joinToString(",")})
|
""".trimMargin()
private val baselineContent = """
|<some>
| <xml/>
|</some>
""".trimMargin()
private val configFileContent = """
|build:
| maxIssues: 5
|style:
| MagicNumber:
| active: true
""".trimMargin()
/**
* Each generated file is different so the artifacts are not cached in between test runs
*/
private fun ktFileContent(className: String, withCodeSmell: Boolean = false) = """
|internal class $className(
| val randomDefaultValue: String = "$randomString"
|) {
| val smellyConstant: Int = ${if (withCodeSmell) "11" else "0"}
|}
|
""".trimMargin()
fun setupProject() {
writeProjectFile(buildFileName, mainBuildFileContent)
writeProjectFile(SETTINGS_FILENAME, settingsContent)
configFileOrNone?.let { writeProjectFile(configFileOrNone, configFileContent) }
baselineFileOrNone?.let { writeProjectFile(baselineFileOrNone, baselineContent) }
projectLayout.srcDirs.forEachIndexed { srcDirIdx, sourceDir ->
repeat(projectLayout.numberOfSourceFilesInRootPerSourceDir) {
val withCodeSmell =
srcDirIdx * projectLayout.numberOfSourceFilesInRootPerSourceDir + it < projectLayout.numberOfCodeSmellsInRootPerSourceDir
writeKtFile(File(rootDir, sourceDir), "MyRoot${it}Class", withCodeSmell)
}
}
projectLayout.submodules.forEach { submodule ->
val moduleRoot = File(rootDir, submodule.name)
moduleRoot.mkdirs()
File(moduleRoot, buildFileName).writeText(submodule.detektConfig ?: "")
submodule.srcDirs.forEachIndexed { srcDirIdx, moduleSourceDir ->
repeat(submodule.numberOfSourceFilesPerSourceDir) {
val withCodeSmell =
srcDirIdx * submodule.numberOfSourceFilesPerSourceDir + it < submodule.numberOfCodeSmells
writeKtFile(File(moduleRoot, moduleSourceDir), "My${submodule.name}${it}Class", withCodeSmell)
}
}
}
}
fun writeProjectFile(filename: String, content: String) {
File(rootDir, filename).writeText(content)
}
fun writeKtFile(srcDir: String, className: String) {
writeKtFile(File(rootDir, srcDir), className)
}
private fun writeKtFile(dir: File, className: String, withCodeSmell: Boolean = false) {
dir.mkdirs()
File(dir, "$className.kt").writeText(ktFileContent(className, withCodeSmell))
}
private fun buildGradleRunner(tasks: List<String>): GradleRunner {
val args = mutableListOf("--stacktrace", "--info", "--build-cache")
if (dryRun) {
args.add("-Pdetekt-dry-run=true")
}
args.addAll(tasks.toList())
return GradleRunner.create().apply {
withProjectDir(rootDir)
withPluginClasspath()
withArguments(args)
gradleVersionOrNone?.let { withGradleVersion(gradleVersionOrNone) }
}
}
fun runTasksAndCheckResult(vararg tasks: String, doAssert: DslGradleRunner.(BuildResult) -> Unit) {
val result: BuildResult = runTasks(*tasks)
this.doAssert(result)
}
fun runTasks(vararg tasks: String): BuildResult = buildGradleRunner(tasks.toList()).build()
fun runDetektTaskAndCheckResult(doAssert: DslGradleRunner.(BuildResult) -> Unit) {
runTasksAndCheckResult(DETEKT_TASK) { this.doAssert(it) }
}
fun runDetektTask(): BuildResult = runTasks(DETEKT_TASK)
fun runDetektTaskAndExpectFailure(doAssert: DslGradleRunner.(BuildResult) -> Unit = {}) {
val result = buildGradleRunner(listOf(DETEKT_TASK)).buildAndFail()
this.doAssert(result)
}
fun projectFile(path: String): File = File(rootDir, path).canonicalFile
companion object {
const val SETTINGS_FILENAME = "settings.gradle"
private const val DETEKT_TASK = "detekt"
}
}
|
apache-2.0
|
a7c19e39adb9910866386f29a882cfaa
| 36.330827 | 141 | 0.654179 | 4.679548 | false | false | false | false |
ankidroid/Anki-Android
|
AnkiDroid/src/main/java/com/ichi2/anki/BackendImporting.kt
|
1
|
4960
|
/***************************************************************************************
* Copyright (c) 2022 Ankitects Pty Ltd <http://apps.ankiweb.net> *
* *
* 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/>. *
****************************************************************************************/
// BackendFactory.defaultLegacySchema must be false to use this code.
package com.ichi2.anki
import anki.import_export.ExportLimit
import anki.import_export.ImportResponse
import com.afollestad.materialdialogs.MaterialDialog
import com.ichi2.anki.CollectionManager.withCol
import com.ichi2.anki.pages.PagesActivity
import com.ichi2.libanki.CollectionV16
import com.ichi2.libanki.exportAnkiPackage
import com.ichi2.libanki.exportCollectionPackage
import com.ichi2.libanki.importAnkiPackage
import com.ichi2.libanki.importer.importCsvRaw
import com.ichi2.libanki.undoableOp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.ankiweb.rsdroid.Translations
fun DeckPicker.importApkgs(apkgPaths: List<String>) {
launchCatchingTask {
for (apkgPath in apkgPaths) {
val report = withProgress(
extractProgress = {
if (progress.hasImporting()) {
text = progress.importing
}
},
) {
undoableOp {
importAnkiPackage(apkgPath)
}
}
showSimpleMessageDialog(summarizeReport(col.tr, report))
}
}
}
@Suppress("BlockingMethodInNonBlockingContext") // ImportResponse.parseFrom
suspend fun PagesActivity.importCsvRaw(input: ByteArray): ByteArray {
return withContext(Dispatchers.Main) {
val output = withProgress(
extractProgress = {
if (progress.hasImporting()) {
text = progress.importing
}
},
op = { withCol { (this as CollectionV16).importCsvRaw(input) } }
)
val importResponse = ImportResponse.parseFrom(output)
undoableOp { importResponse }
MaterialDialog(this@importCsvRaw).show {
message(text = summarizeReport(col.tr, importResponse))
positiveButton(R.string.dialog_ok) {
[email protected]()
}
}
output
}
}
private fun summarizeReport(tr: Translations, output: ImportResponse): String {
val log = output.log
val total = log.conflictingCount + log.updatedCount + log.newCount + log.duplicateCount
val msgs = mutableListOf(tr.importingNotesFoundInFile(total))
if (log.conflictingCount > 0) {
msgs.add(tr.importingNotesThatCouldNotBeImported(log.conflictingCount))
}
if (log.updatedCount > 0) {
msgs.add(tr.importingNotesUpdatedAsFileHadNewer(log.updatedCount))
}
if (log.newCount > 0) {
msgs.add(tr.importingNotesAddedFromFile(log.newCount))
}
if (log.duplicateCount > 0) {
msgs.add(tr.importingNotesSkippedAsTheyreAlreadyIn(log.duplicateCount))
}
return msgs.joinToString("\n")
}
suspend fun AnkiActivity.exportApkg(
apkgPath: String,
withScheduling: Boolean,
withMedia: Boolean,
limit: ExportLimit
) {
withProgress(
extractProgress = {
if (progress.hasExporting()) {
text = progress.exporting
}
},
) {
withCol {
newBackend.exportAnkiPackage(apkgPath, withScheduling, withMedia, limit)
}
}
}
suspend fun AnkiActivity.exportColpkg(
colpkgPath: String,
withMedia: Boolean,
) {
withProgress(
extractProgress = {
if (progress.hasExporting()) {
text = progress.exporting
}
},
) {
withCol {
newBackend.exportCollectionPackage(colpkgPath, withMedia, true)
}
}
}
|
gpl-3.0
|
0405805997e918ed1383259df836b6e4
| 36.862595 | 91 | 0.571573 | 4.8867 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/registry/LanternAdventureRegistry.kt
|
1
|
2658
|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.registry
import net.kyori.adventure.sound.Sound
import net.kyori.adventure.text.event.ClickEvent
import net.kyori.adventure.text.event.HoverEvent
import net.kyori.adventure.util.Index
import org.lanternpowered.api.boss.BossBarColor
import org.lanternpowered.api.boss.BossBarFlag
import org.lanternpowered.api.boss.BossBarOverlay
import org.lanternpowered.api.text.format.NamedTextColor
import org.lanternpowered.api.text.format.TextDecoration
import org.spongepowered.api.adventure.AdventureRegistry
import java.util.Optional
import org.lanternpowered.api.util.optional.asOptional
object LanternAdventureRegistry : AdventureRegistry {
private val decorations = ForIndex(TextDecoration.NAMES)
private val namedColors = ForIndex(NamedTextColor.NAMES)
private val clickEventActions = ForIndex(ClickEvent.Action.NAMES)
private val hoverEventActions = ForIndex(HoverEvent.Action.NAMES)
private val bossBarColors = ForIndex(BossBarColor.NAMES)
private val bossBarOverlays = ForIndex(BossBarOverlay.NAMES)
private val bossBarFlags = ForIndex(BossBarFlag.NAMES)
private val soundSources = ForIndex(Sound.Source.NAMES)
override fun getBossBarFlags(): AdventureRegistry.OfType<BossBarFlag> = this.bossBarFlags
override fun getBossBarOverlays(): AdventureRegistry.OfType<BossBarOverlay> = this.bossBarOverlays
override fun getBossBarColors(): AdventureRegistry.OfType<BossBarColor> = this.bossBarColors
override fun getSoundSources(): AdventureRegistry.OfType<Sound.Source> = this.soundSources
override fun getNamedColors(): AdventureRegistry.OfType<NamedTextColor> = this.namedColors
override fun getDecorations(): AdventureRegistry.OfType<TextDecoration> = this.decorations
override fun getClickEventActions(): AdventureRegistry.OfType<ClickEvent.Action> = this.clickEventActions
override fun getHoverEventActions(): AdventureRegistry.OfType<HoverEvent.Action<*>> = this.hoverEventActions
private class ForIndex<T : Any>(private val registry: Index<String, T>) : AdventureRegistry.OfType<T> {
override fun getKey(value: T): String = this.registry.key(value)!!
override fun getValue(key: String): Optional<T> = this.registry.value(key).asOptional()
override fun keys(): Set<String> = this.registry.keys()
}
}
|
mit
|
985f7582e3f58e9055923b354dea4640
| 51.117647 | 112 | 0.78781 | 4.185827 | false | false | false | false |
asamm/locus-api
|
locus-api-core/src/main/java/locus/api/objects/styles/LabelStyle.kt
|
1
|
1538
|
/****************************************************************************
*
* Created by menion on 17.08.2019.
* Copyright (c) 2019. All rights reserved.
*
* This file is part of the Asamm team software.
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
* WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
***************************************************************************/
package locus.api.objects.styles
import locus.api.objects.Storable
import locus.api.utils.DataReaderBigEndian
import locus.api.utils.DataWriterBigEndian
import java.io.IOException
/**
* Container for label style.
*/
class LabelStyle : Storable() {
/**
* Color defined for a label.
*/
var color: Int = GeoDataStyle.COLOR_DEFAULT
/**
* Scale defined for a label.
*/
var scale: Float = 1.0f
set(value) {
field = if (value < 0.0f) {
0.0f
} else {
value
}
}
//*************************************************
// STORABLE
//*************************************************
override fun getVersion(): Int {
return 0
}
@Throws(IOException::class)
override fun readObject(version: Int, dr: DataReaderBigEndian) {
color = dr.readInt()
scale = dr.readFloat()
}
@Throws(IOException::class)
override fun writeObject(dw: DataWriterBigEndian) {
dw.writeInt(color)
dw.writeFloat(scale)
}
}
|
mit
|
d96d6f32e464fd228aac1cb27530e63e
| 24.65 | 77 | 0.507152 | 4.660606 | false | false | false | false |
cedardevs/onestop
|
buildSrc/src/main/kotlin/ShellUtility.kt
|
1
|
1095
|
import java.io.File
fun String.runShell(dir: File? = null, quiet: Boolean = true): String? {
val builder: ProcessBuilder = ProcessBuilder("/bin/sh", "-c", this)
.redirectErrorStream(true)
.directory(dir)
val process: Process = builder.start()
val exitCode: Int = process.waitFor()
var output: String? = process.inputStream.readBytes().toString(Charsets.UTF_8).trim()
if(exitCode != 0) {
// print stderr for visibility, since we return `null` on error
println("\nError running: `${this}`\n")
println("${output}\n")
output = null
}
if(!quiet && exitCode == 0) {
// print stdout when `quiet = false` to prevent excessive output by default
println("\nRunning: `${this}`\n")
println("${output}\n")
}
return output
}
fun String.runShellExitCode(dir: File? = null): Int {
val builder: ProcessBuilder = ProcessBuilder("/bin/sh", "-c", this)
.redirectErrorStream(true)
.directory(dir)
val process: Process = builder.start()
return process.waitFor()
}
|
gpl-2.0
|
058ddb3824a89c7c4dca5e7673d5b81a
| 35.533333 | 89 | 0.612785 | 4.085821 | false | false | false | false |
tasks/tasks
|
app/src/main/java/org/tasks/dashclock/DashClockExtension.kt
|
1
|
2920
|
package org.tasks.dashclock
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.google.android.apps.dashclock.api.DashClockExtension
import com.google.android.apps.dashclock.api.ExtensionData
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import org.tasks.LocalBroadcastManager
import org.tasks.R
import org.tasks.data.TaskDao
import org.tasks.intents.TaskIntents
import org.tasks.preferences.DefaultFilterProvider
import org.tasks.preferences.Preferences
import timber.log.Timber
import javax.inject.Inject
@AndroidEntryPoint
class DashClockExtension : DashClockExtension() {
private val job = SupervisorJob()
private val scope = CoroutineScope(Dispatchers.Default + job)
@Inject lateinit var defaultFilterProvider: DefaultFilterProvider
@Inject lateinit var taskDao: TaskDao
@Inject lateinit var preferences: Preferences
@Inject lateinit var localBroadcastManager: LocalBroadcastManager
private val refreshReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
refresh()
}
}
override fun onCreate() {
super.onCreate()
localBroadcastManager.registerRefreshReceiver(refreshReceiver)
}
override fun onDestroy() {
super.onDestroy()
localBroadcastManager.unregisterReceiver(refreshReceiver)
job.cancel()
}
override fun onUpdateData(i: Int) {
refresh()
}
private fun refresh() = scope.launch {
val filterPreference = preferences.getStringValue(R.string.p_dashclock_filter)
val filter = defaultFilterProvider.getFilterFromPreference(filterPreference)
val count = taskDao.count(filter)
if (count == 0) {
publish(null)
} else {
val clickIntent = TaskIntents.getTaskListIntent(this@DashClockExtension, filter)
val extensionData = ExtensionData()
.visible(true)
.icon(R.drawable.ic_check_white_24dp)
.status(count.toString())
.expandedTitle(resources.getQuantityString(R.plurals.task_count, count, count))
.expandedBody(filter.listingTitle)
.clickIntent(clickIntent)
if (count == 1) {
val tasks = taskDao.fetchFiltered(filter)
if (tasks.isNotEmpty()) {
extensionData.expandedTitle(tasks[0].title)
}
}
publish(extensionData)
}
}
private fun publish(data: ExtensionData?) {
try {
publishUpdate(data)
} catch (e: Exception) {
Timber.e(e)
}
}
}
|
gpl-3.0
|
5eef24dc51edc0a2c569e33d22bba8e8
| 33.364706 | 99 | 0.676027 | 4.882943 | false | false | false | false |
AoEiuV020/PaNovel
|
api/src/main/java/cc/aoeiuv020/panovel/api/site/exiaoshuo.kt
|
1
|
2965
|
package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.base.jar.textListSplitWhitespace
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
import cc.aoeiuv020.panovel.api.firstThreeIntPattern
import java.net.URL
/**
* Created by AoEiuV020 on 2018.06.06-12:42:10.
*/
class Exiaoshuo : DslJsoupNovelContext() {init {
hide = true
site {
name = "E小说"
baseUrl = "https://www.exiaoshuo.cc"
logo = "https://www.exiaoshuo.cc/images/logo.gif"
}
search {
// https://www.exiaoshuo.cc/modules/article/search.php?searchkey=%B6%BC%CA%D0&page=1
get {
charset = "GBK"
url = "/modules/article/search.php"
data {
"searchtype" to "articlename"
"searchkey" to it
// 加上&page=1可以避开搜索时间间隔的限制,
// 也可以通过不加载cookies避开搜索时间间隔的限制,
"page" to "1"
}
}
document {
if (URL(root.ownerDocument().location()).path.startsWith("/intro/")) {
single {
name(".r420 > h1:nth-child(1)")
author("span.black:nth-child(1)")
}
} else {
items("ul.clearfix > li") {
name("> div:nth-child(2) > h3:nth-child(1) > a:nth-child(1)")
author("> div:nth-child(2) > div:nth-child(2) > span:nth-child(1)")
}
}
}
}
// https://www.exiaoshuo.cc/intro/397
// https://www.exiaoshuo.cc/xiaoshuo/0/397/index.html
// https://www.exiaoshuo.cc/xiaoshuo/0/397/336169.html
bookIdRegex = "/(intro|xiaoshuo/\\d+)/(\\d+)"
bookIdIndex = 1
detailPageTemplate = "/intro/%s"
detail {
document {
novel {
name(".r420 > h1:nth-child(1)")
author("span.black:nth-child(1)")
}
image(".con_limg > img:nth-child(1)")
update(".green", format = "yyyy-MM-dd")
introduction(".r_cons > p:nth-child(1)") {
it.textListSplitWhitespace().joinToString("\n") {
it.removeSuffix("...[详细介绍]")
}
}
}
}
// https://www.exiaoshuo.cc/xiaoshuo/0/397/index.html
chapterDivision = 1000
chaptersPageTemplate = "/xiaoshuo/%d/%s/index.html"
chapters {
document {
items(".clearfix > ul > li > a:nth-child(1)")
}
}
// https://www.exiaoshuo.cc/xiaoshuo/0/397/336169.html
bookIdWithChapterIdRegex = firstThreeIntPattern
contentPageTemplate = "/xiaoshuo/%s.html"
content {
document {
/*
<center><br><h2>记住E小说永久网址:www.exiaoshuo.cc | 手机站:m.exiaoshuo.cc</h2><br></center>
*/
items(".chapter_content", block = ownLines())
}
}
}
}
|
gpl-3.0
|
b51a9841865c2291732cb434bf6d730f
| 31.816092 | 96 | 0.519089 | 3.573217 | false | false | false | false |
SpineEventEngine/core-java
|
server/src/main/kotlin/io/spine/server/query/QueryingClient.kt
|
1
|
4869
|
/*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.query
import io.grpc.stub.StreamObserver
import io.spine.base.EntityState
import io.spine.base.Identifier
import io.spine.client.ActorRequestFactory
import io.spine.client.Query
import io.spine.client.QueryResponse
import io.spine.core.userId
import io.spine.protobuf.AnyPacker
import io.spine.server.BoundedContext
import io.spine.util.theOnly
import java.util.*
/**
* A builder for queries to the states of entities.
*
* @param T the type of entity states to query.
*/
public class QueryingClient<T : EntityState<*>>
constructor(
private val context: BoundedContext,
private val type: Class<T>,
actorName: String
) {
private val actor = userId { value = actorName }
private val factory = ActorRequestFactory.newBuilder()
.setActor(actor)
.build()
/**
* Obtains a state of an entity by its ID.
*
* The value of the ID must be one of the [supported types][io.spine.base.Identifier].
*
* @return the state of the entity or empty `Optional` if the entity with the given ID
* was not found
* @throws IllegalArgumentException
* if the given ID is not of one of the supported types
*/
public fun find(id: Any): Optional<T> {
Identifier.checkSupported(id.javaClass)
val query = buildQuery(id)
val results = execute(query)
return if (results.isEmpty()) {
Optional.empty()
} else {
val value = results.theOnly()
Optional.of(value)
}
}
/**
* Obtains a state of an entity by its ID.
*
* The value of the ID must be one of the [supported types][io.spine.base.Identifier].
*
* Does the same as [find] and provided for fluent calls when called after [Querying.select]
*
* @return the state of the entity or empty `Optional` if the entity with the given ID
* was not found
* @throws IllegalArgumentException
* if the given ID is not of one of the supported types
* @see [find]
*/
public fun withId(id: Any): Optional<T> = find(id)
/**
* Selects all entities of the given type.
*/
public fun all(): Set<T> {
val query = buildQuery()
return execute(query)
}
private fun buildQuery(id: Any? = null): Query {
val queries = factory.query()
return if (id == null) {
queries.all(type)
} else {
queries.byIds(type, setOf(id))
}
}
/**
* Executes the given [query] upon the given [context].
*/
private fun execute(query: Query): Set<T> {
val observer = Observer(type)
context.stand().execute(query, observer)
return observer.foundResult().toSet()
}
}
/**
* A [StreamObserver] which listens to a single [QueryResponse].
*
* The observer persists the [found result][foundResult] as a list of messages.
*/
private class Observer<T : EntityState<*>>(
private val type: Class<T>
) : StreamObserver<QueryResponse> {
private var result: List<T>? = null
override fun onNext(response: QueryResponse) {
result = response.messageList.map {
AnyPacker.unpack(it.state, type)
}
}
override fun onError(e: Throwable) {
throw e
}
override fun onCompleted() {
// Do nothing.
}
/**
* Obtains the found result or throws an `IllegalStateException` if
* the result has not been received.
*/
fun foundResult(): List<T> {
return result ?: error("Query has not yielded any result yet.")
}
}
|
apache-2.0
|
3086458e30d7041f5413603fcb31b3e2
| 30.616883 | 96 | 0.657014 | 4.179399 | false | false | false | false |
cloose/luftbild4p3d
|
src/main/kotlin/org/luftbild4p3d/app/Area.kt
|
1
|
536
|
package org.luftbild4p3d.app
import org.luftbild4p3d.bing.LevelOfDetail
import org.luftbild4p3d.bing.Wgs84Coordinates
data class Area(val latitude: Int, val longitude: Int, val levelOfDetail: LevelOfDetail) {
val startTile = Wgs84Coordinates(latitude.toDouble(), longitude.toDouble()).toPixelCoordinates(levelOfDetail).toTile()
companion object {
val BGL_FILES_PER_ROW = 4
val BGL_FILES_PER_COLUMN = 6
val IMAGES_PER_BGL_FILE_ROW_AND_COLUMN = 3
val TILES_PER_IMAGE_ROW_AND_COLUMN = 16
}
}
|
gpl-3.0
|
cd67f1fb9e56b14d2b1f4859aee3c8e4
| 32.5625 | 122 | 0.725746 | 3.209581 | false | false | false | false |
material-components/material-components-android-examples
|
Owl/app/src/main/java/com/materialstudies/owl/ui/learn/LearnFragment.kt
|
1
|
3265
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.owl.ui.learn
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.materialstudies.owl.R
import com.materialstudies.owl.databinding.FragmentLearnBinding
import com.materialstudies.owl.model.CourseRepo
import com.materialstudies.owl.model.courses
import com.materialstudies.owl.ui.lessons.LessonsSheetFragment
import com.materialstudies.owl.util.transition.DiagonalSlide
import com.materialstudies.owl.util.transition.MaterialContainerTransition
import com.materialstudies.owl.util.loadListener
import java.util.concurrent.TimeUnit
/**
* A [Fragment] displaying the learn screen.
*/
class LearnFragment : Fragment() {
private val args: LearnFragmentArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val course = CourseRepo.getCourse(args.courseId)
val binding = FragmentLearnBinding.inflate(inflater, container, false).apply {
this.course = course
imageLoadListener = loadListener {
startPostponedEnterTransition()
}
toolbar.setNavigationOnClickListener {
findNavController().navigateUp()
}
alsoLikeList.adapter = RelatedAdapter().apply {
submitList(courses)
}
}
(childFragmentManager.findFragmentById(R.id.lessons_sheet) as? LessonsSheetFragment)?.let {
it.course = course
}
postponeEnterTransition(1000L, TimeUnit.MILLISECONDS)
val interp = AnimationUtils.loadInterpolator(
context,
android.R.interpolator.fast_out_slow_in
)
sharedElementEnterTransition = MaterialContainerTransition(R.id.scroll).apply {
duration = 400L
interpolator = interp
}
enterTransition = DiagonalSlide().apply {
addTarget(R.id.lessons_sheet)
startDelay = 200L
duration = 200L
interpolator = interp
}
sharedElementReturnTransition = MaterialContainerTransition().apply {
duration = 300L
interpolator = interp
}
returnTransition = DiagonalSlide().apply {
addTarget(R.id.lessons_sheet)
duration = 100L
interpolator = interp
}
return binding.root
}
}
|
apache-2.0
|
e319d3289228835da3e385a9d6c97cf5
| 34.879121 | 99 | 0.68974 | 4.887725 | false | false | false | false |
apixandru/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.kt
|
3
|
6804
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.keymap.impl
import com.intellij.configurationStore.LazySchemeProcessor
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.ide.WelcomeWizardUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.keymap.ex.KeymapManagerEx
import com.intellij.openapi.options.SchemeManager
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.Conditions
import com.intellij.openapi.util.Disposer
import com.intellij.ui.AppUIUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.SmartHashSet
import gnu.trove.THashMap
import org.jdom.Element
import java.util.function.Function
internal const val KEYMAPS_DIR_PATH = "keymaps"
private const val ACTIVE_KEYMAP = "active_keymap"
private const val NAME_ATTRIBUTE = "name"
@State(name = "KeymapManager", storages = arrayOf(Storage(value = "keymap.xml", roamingType = RoamingType.PER_OS)), additionalExportFile = KEYMAPS_DIR_PATH)
class KeymapManagerImpl(defaultKeymap: DefaultKeymap, factory: SchemeManagerFactory) : KeymapManagerEx(), PersistentStateComponent<Element> {
private val listeners = ContainerUtil.createLockFreeCopyOnWriteList<KeymapManagerListener>()
private val boundShortcuts = THashMap<String, String>()
private val schemeManager: SchemeManager<Keymap>
init {
schemeManager = factory.create(KEYMAPS_DIR_PATH, object : LazySchemeProcessor<Keymap, KeymapImpl>() {
override fun createScheme(dataHolder: SchemeDataHolder<KeymapImpl>,
name: String,
attributeProvider: Function<String, String?>,
isBundled: Boolean) = KeymapImpl(name, dataHolder)
override fun onCurrentSchemeSwitched(oldScheme: Keymap?, newScheme: Keymap?) {
for (listener in listeners) {
listener.activeKeymapChanged(newScheme)
}
}
override fun reloaded(schemeManager: SchemeManager<Keymap>, schemes: Collection<Keymap>) {
if (schemeManager.currentScheme == null) {
// listeners expect that event will be fired in EDT
AppUIUtil.invokeOnEdt {
schemeManager.setCurrentSchemeName(defaultKeymap.defaultKeymapName, true)
}
}
}
})
val systemDefaultKeymap = if (WelcomeWizardUtil.getWizardMacKeymap() == null) defaultKeymap.defaultKeymapName else WelcomeWizardUtil.getWizardMacKeymap()
for (keymap in defaultKeymap.keymaps) {
schemeManager.addScheme(keymap)
if (keymap.name == systemDefaultKeymap) {
activeKeymap = keymap
}
}
schemeManager.loadSchemes()
ourKeymapManagerInitialized = true
}
companion object {
@JvmField
var ourKeymapManagerInitialized: Boolean = false
}
override fun getAllKeymaps() = getKeymaps(Conditions.alwaysTrue<Keymap>()).toTypedArray()
fun getKeymaps(additionalFilter: Condition<Keymap>) = schemeManager.allSchemes.filter { !it.presentableName.startsWith("$") && additionalFilter.value(it) }
override fun getKeymap(name: String) = schemeManager.findSchemeByName(name)
override fun getActiveKeymap() = schemeManager.currentScheme
override fun setActiveKeymap(keymap: Keymap?) = schemeManager.setCurrent(keymap)
override fun bindShortcuts(sourceActionId: String, targetActionId: String) {
boundShortcuts.put(targetActionId, sourceActionId)
}
override fun unbindShortcuts(targetActionId: String) {
boundShortcuts.remove(targetActionId)
}
override fun getBoundActions() = boundShortcuts.keys
override fun getActionBinding(actionId: String): String? {
var visited: MutableSet<String>? = null
var id = actionId
while (true) {
val next = boundShortcuts.get(id) ?: break
if (visited == null) {
visited = SmartHashSet()
}
id = next
if (!visited.add(id)) {
break
}
}
return if (id == actionId) null else id
}
override fun getSchemeManager() = schemeManager
fun setKeymaps(keymaps: List<Keymap>, active: Keymap?, removeCondition: Condition<Keymap>?) {
schemeManager.setSchemes(keymaps, active, removeCondition)
}
override fun getState(): Element {
val result = Element("state")
schemeManager.currentScheme?.let {
if (it.name != DefaultKeymap.instance.defaultKeymapName) {
val e = Element(ACTIVE_KEYMAP)
e.setAttribute(NAME_ATTRIBUTE, it.name)
result.addContent(e)
}
}
return result
}
override fun loadState(state: Element) {
val child = state.getChild(ACTIVE_KEYMAP)
val activeKeymapName = child?.getAttributeValue(NAME_ATTRIBUTE)
if (!activeKeymapName.isNullOrBlank()) {
schemeManager.currentSchemeName = activeKeymapName
}
}
@Suppress("OverridingDeprecatedMember")
override fun addKeymapManagerListener(listener: KeymapManagerListener) {
pollQueue()
listeners.add(listener)
}
@Suppress("DEPRECATION")
override fun addKeymapManagerListener(listener: KeymapManagerListener, parentDisposable: Disposable) {
pollQueue()
listeners.add(listener)
Disposer.register(parentDisposable, Disposable { removeKeymapManagerListener(listener) })
}
private fun pollQueue() {
listeners.removeAll { it is WeakKeymapManagerListener && it.isDead }
}
@Suppress("OverridingDeprecatedMember")
override fun removeKeymapManagerListener(listener: KeymapManagerListener) {
pollQueue()
listeners.remove(listener)
}
@Suppress("DEPRECATION")
override fun addWeakListener(listener: KeymapManagerListener) {
addKeymapManagerListener(WeakKeymapManagerListener(this, listener))
}
override fun removeWeakListener(listenerToRemove: KeymapManagerListener) {
listeners.removeAll { it is WeakKeymapManagerListener && it.isWrapped(listenerToRemove) }
}
}
|
apache-2.0
|
a9977c3dd7df1cb1f4528a147ef95303
| 35.778378 | 158 | 0.741035 | 4.842705 | false | false | false | false |
rarspace01/airportticketvalidator
|
app/src/main/java/org/rarspace01/airportticketvalidator/MainActivity.kt
|
1
|
9608
|
package org.rarspace01.airportticketvalidator
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.VolleyLog
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.zxing.integration.android.IntentIntegrator
import org.rarspace01.airportticketvalidator.bcbp.Parser
import java.util.*
import kotlin.collections.ArrayList
class MainActivity : AppCompatActivity() {
val cachedFlightList: ArrayList<Flight> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnScan = findViewById<Button>(R.id.btn_Scan)
val btnResult = findViewById<Button>(R.id.btn_result)
val textAirport = findViewById<EditText>(R.id.txtAirport)
setProgressBar(0)
btnScan.setOnClickListener({
IntentIntegrator(this).setBeepEnabled(false).setOrientationLocked(false).initiateScan()
})
btnScan.setOnLongClickListener {
showCode()
true
}
btnResult.setOnLongClickListener {
resetBackgroundSuccess()
getDepartingFlights(textAirport.text.toString());
true
}
}
private fun showCode() {
val txtAirport = findViewById<EditText>(R.id.txtAirport)
var flightList: Array<String>?
var flightListString: ArrayList<String> = ArrayList()
AirportTicketValidatorApplication.getInstance().flightCache.sort()
for (flight: Flight in AirportTicketValidatorApplication.getInstance().flightCache) {
flightListString.add(flight.toString());
}
flightList = flightListString.toArray(arrayOfNulls<String>(0))
if (flightList != null) {
AlertDialog.Builder(this).setTitle("Choose flight")
.setItems(flightList, DialogInterface.OnClickListener { dialog, which ->
val flightFromString = getFlightFromString(flightList[which])
// TODO: set the date according to flight
var dayOfTheYear = "000" + Calendar.getInstance().get(Calendar.DAY_OF_YEAR)
dayOfTheYear = dayOfTheYear.substring(dayOfTheYear.length - 3, dayOfTheYear.length)
var defaultString = "M1FOUNDTHE/EASTEREGG"
if (txtAirport != null && txtAirport.text != null) {
val emptyString = " "
defaultString = (txtAirport.text.toString() + emptyString).substring(0, 20)
}
val bcbpRawData = defaultString + " AAAAAH " + flightFromString.fromAirport + flightFromString.toAirport +
flightFromString.unifiedFlightNameBCBP + " " +
dayOfTheYear + "Y001A0018 147>1181 7250BEW 0000000000000291040000000000 0 LH 992003667193035 Y"
val context = this
val intent = Intent("com.google.zxing.client.android.ENCODE")
intent.putExtra("ENCODE_TYPE", "Text")
intent.putExtra("ENCODE_DATA", bcbpRawData)
intent.putExtra("ENCODE_FORMAT", "AZTEC")
startActivity(intent)
})
.create()
.show()
}
}
private fun getFlightFromString(listString: String): Flight {
var returnFlight = Flight()
for (flight: Flight in AirportTicketValidatorApplication.getInstance().flightCache) {
if (listString.contains(flight.unifiedFlightName)) {
returnFlight = flight
break;
}
}
return returnFlight
}
private fun setProgressBar(progress: Int) {
val progressbar = findViewById<ProgressBar>(R.id.databasePogressBar)
progressbar.progress = progress
}
private fun setBackgroundSuccess(isSuccessfull: Boolean) {
val resultButton = findViewById<Button>(R.id.btn_result)
if (isSuccessfull) {
resultButton.setBackgroundColor(Color.GREEN)
} else {
resultButton.setBackgroundColor(Color.RED)
}
}
private fun resetBackgroundSuccess() {
val resultButton = findViewById<Button>(R.id.btn_result)
resultButton.setBackgroundColor(Color.GRAY)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
if (result != null) {
if (result.contents == null) {
Log.d("MainActivity", "Cancelled scan")
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show()
} else {
Log.d("MainActivity", "Scanned")
Log.d("MainActivity", result.contents)
//Toast.makeText(this, "Scanned: " + result.contents, Toast.LENGTH_LONG).show()
val bcbpParser = Parser()
val readTicket = bcbpParser.parse(result.contents)
Log.d("City from: ", readTicket.firstFlightSegment.fromCity)
var airportText = findViewById<EditText>(R.id.txtAirport)
//getDepartingFlights(airportText.text.toString())
// wait till Flights are requested
val bcbpFlight = FlightFactory.createFlightFromBCBP(readTicket)
if (FlightUtil.isFlightInList(bcbpFlight, AirportTicketValidatorApplication.getInstance().flightCache)) {
Toast.makeText(this, "Valid Ticket!", Toast.LENGTH_LONG).show()
setBackgroundSuccess(true)
//postOnSlack(readTicket.passengerName + " had an valid Ticket!\uE312")
} else {
Toast.makeText(this, bcbpFlight.toString(), Toast.LENGTH_LONG).show()
setBackgroundSuccess(false)
//postOnSlack(readTicket.passengerName + " had an invalid Ticket")
}
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data)
}
}
fun getDepartingFlights(airportCode: String): List<Flight> {
cachedFlightList.clear()
var isProccessed = false;
val flights = ArrayList<Flight>()
val currentDate = Calendar.getInstance()
var departedPage = String.format("https://www.flightstats.com/v2/api-next/flight-tracker/dep/%s/%d/%d/%d/0?carrierCode=&numHours=12",airportCode,currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH)+1, currentDate.get(Calendar.DAY_OF_MONTH))
val queue = Volley.newRequestQueue(this)
val req = object : StringRequest(Request.Method.GET, departedPage,
Response.Listener<String> { response ->
//Log.d("Response", response)
// parse Flights to Array of Flights
cachedFlightList.addAll(FlightFactory.createFlightsFromJSONSource(response,airportCode))
AirportTicketValidatorApplication.getInstance().addToFlightCache(cachedFlightList);
val btnScan = findViewById<Button>(R.id.btn_Scan)
btnScan.setText(resources.getString(R.string.scan) + String.format("[%d]",cachedFlightList.size))
isProccessed = true;
setProgressBar(100)
}, Response.ErrorListener { error ->
VolleyLog.d("Error", "Error: " + error.message)
isProccessed = true;
Toast.makeText(this@MainActivity, "" + error.message, Toast.LENGTH_SHORT).show()
}) {}
var departedPage2 = String.format("https://www.flightstats.com/v2/api-next/flight-tracker/dep/%s/%d/%d/%d/12?carrierCode=&numHours=12",airportCode,currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH)+1, currentDate.get(Calendar.DAY_OF_MONTH))
val req2 = object : StringRequest(Request.Method.GET, departedPage2,
Response.Listener<String> { response ->
//Log.d("Response", response)
// parse Flights to Array of Flights
cachedFlightList.addAll(FlightFactory.createFlightsFromJSONSource(response,airportCode))
AirportTicketValidatorApplication.getInstance().addToFlightCache(cachedFlightList);
val btnScan = findViewById<Button>(R.id.btn_Scan)
btnScan.setText(resources.getString(R.string.scan) + String.format("[%d]",cachedFlightList.size))
isProccessed = true;
setProgressBar(100)
}, Response.ErrorListener { error ->
VolleyLog.d("Error", "Error: " + error.message)
isProccessed = true;
Toast.makeText(this@MainActivity, "" + error.message, Toast.LENGTH_SHORT).show()
}) {}
queue.add(req)
queue.add(req2)
return flights
}
}
|
gpl-3.0
|
e525d579b3b8ad9c730f324f2574467c
| 43.481481 | 260 | 0.619692 | 4.594931 | false | false | false | false |
wikimedia/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/usercontrib/UserContribListViewModel.kt
|
1
|
5634
|
package org.wikipedia.usercontrib
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.paging.*
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.wikipedia.Constants
import org.wikipedia.WikipediaApp
import org.wikipedia.dataclient.Service
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.mwapi.UserContribution
import org.wikipedia.settings.Prefs
import org.wikipedia.util.DateUtil
import org.wikipedia.util.Resource
import org.wikipedia.util.log.L
import retrofit2.HttpException
import java.io.IOException
import java.util.*
class UserContribListViewModel(bundle: Bundle) : ViewModel() {
val userContribStatsData = MutableLiveData<Resource<UserContribStats>>()
var userName: String = bundle.getString(UserContribListActivity.INTENT_EXTRA_USER_NAME)!!
var langCode: String = WikipediaApp.instance.appOrSystemLanguageCode
val wikiSite get(): WikiSite {
return when (langCode) {
Constants.WIKI_CODE_COMMONS -> WikiSite(Service.COMMONS_URL)
Constants.WIKI_CODE_WIKIDATA -> WikiSite(Service.WIKIDATA_URL)
else -> WikiSite.forLanguageCode(langCode)
}
}
var currentQuery = ""
var actionModeActive = false
var userContribSource: UserContribPagingSource? = null
private val cachedContribs = mutableListOf<UserContribution>()
private var cachedContinueKey: String? = null
val userContribFlow = Pager(PagingConfig(pageSize = 50), pagingSourceFactory = {
userContribSource = UserContribPagingSource()
userContribSource!!
}).flow.map { pagingData ->
pagingData.filter {
if (currentQuery.isNotEmpty()) {
it.comment.contains(currentQuery, true) ||
it.title.contains(currentQuery, true)
} else true
}.map {
UserContribItem(it)
}.insertSeparators { before, after ->
val dateBefore = if (before != null) DateUtil.getShortDateString(before.item.date()) else ""
val dateAfter = if (after != null) DateUtil.getShortDateString(after.item.date()) else ""
if (dateAfter.isNotEmpty() && dateAfter != dateBefore) {
UserContribSeparator(dateAfter)
} else {
null
}
}
}.cachedIn(viewModelScope)
init {
loadStats()
}
fun excludedFiltersCount(): Int {
val excludedNsFilter = Prefs.userContribFilterExcludedNs
return UserContribFilterActivity.NAMESPACE_LIST.count { excludedNsFilter.contains(it) }
}
fun loadStats() {
viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
L.e(throwable)
}) {
withContext(Dispatchers.IO) {
val messageName = "project-localized-name-${wikiSite.dbName()}"
val query = ServiceFactory.get(wikiSite).userInfoWithMessages(userName, messageName).query
userContribStatsData.postValue(Resource.Success(UserContribStats(query?.users!![0].editCount,
query.users[0].registrationDate, query.allmessages.orEmpty().getOrNull(0)?.content.orEmpty().ifEmpty { wikiSite.dbName() })))
}
}
}
fun clearCache() {
cachedContribs.clear()
}
inner class UserContribPagingSource : PagingSource<String, UserContribution>() {
override suspend fun load(params: LoadParams<String>): LoadResult<String, UserContribution> {
return try {
if (params.key == null && cachedContribs.isNotEmpty()) {
return LoadResult.Page(cachedContribs, null, cachedContinueKey)
}
if (excludedFiltersCount() == UserContribFilterActivity.NAMESPACE_LIST.size) {
return LoadResult.Page(emptyList(), null, null)
}
val nsFilter = UserContribFilterActivity.NAMESPACE_LIST.filter { !Prefs.userContribFilterExcludedNs.contains(it) }.joinToString("|")
val response = ServiceFactory.get(wikiSite).getUserContrib(userName, 500, nsFilter.ifEmpty { null }, null, params.key)
val contribs = response.query?.userContributions!!
cachedContinueKey = response.continuation?.ucContinuation
cachedContribs.addAll(contribs)
LoadResult.Page(contribs, null, cachedContinueKey)
} catch (e: IOException) {
LoadResult.Error(e)
} catch (e: HttpException) {
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<String, UserContribution>): String? {
return null
}
}
open class UserContribItemModel
class UserContribItem(val item: UserContribution) : UserContribItemModel()
class UserContribSeparator(val date: String) : UserContribItemModel()
class UserContribStats(val totalEdits: Int, val registrationDate: Date, val projectName: String) : UserContribItemModel()
class Factory(private val bundle: Bundle) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return UserContribListViewModel(bundle) as T
}
}
}
|
apache-2.0
|
9c5827d36f83cf9842d8d26c7ab91246
| 38.957447 | 149 | 0.672701 | 4.890625 | false | false | false | false |
stripe/stripe-android
|
payments-core/src/main/java/com/stripe/android/model/MandateDataParams.kt
|
1
|
4003
|
package com.stripe.android.model
import android.os.Parcelable
import androidx.annotation.RestrictTo
import kotlinx.parcelize.Parcelize
/**
* Mandate Data parameters for
* [confirming a PaymentIntent](https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-mandate_data)
* or [confirming a SetupIntent](https://stripe.com/docs/api/setup_intents/confirm#confirm_setup_intent-mandate_data)
*/
@Parcelize
data class MandateDataParams constructor(
private val type: Type
) : StripeParamsModel, Parcelable {
override fun toParamMap(): Map<String, Any> {
return mapOf(
PARAM_CUSTOMER_ACCEPTANCE to mapOf(
PARAM_TYPE to type.code,
type.code to type.toParamMap()
)
)
}
sealed class Type(
internal val code: String
) : StripeParamsModel, Parcelable {
/**
* If this is a Mandate accepted online, this hash contains details about the online acceptance.
*
* [mandate_data.customer_acceptance.online](https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-mandate_data-customer_acceptance-online)
*/
@Parcelize
data class Online internal constructor(
/**
* The IP address from which the Mandate was accepted by the customer.
*
* [mandate_data.customer_acceptance.online.ip_address](https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-mandate_data-customer_acceptance-online-ip_address)
*/
private val ipAddress: String? = null,
/**
* The user agent of the browser from which the Mandate was accepted by the customer.
*
* [mandate_data.customer_acceptance.online.user_agent](https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-mandate_data-customer_acceptance-online-user_agent)
*/
private val userAgent: String? = null,
private val inferFromClient: Boolean = false
) : Type("online") {
constructor(
/**
* The IP address from which the Mandate was accepted by the customer.
*
* [mandate_data.customer_acceptance.online.ip_address](https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-mandate_data-customer_acceptance-online-ip_address)
*/
ipAddress: String,
/**
* The user agent of the browser from which the Mandate was accepted by the customer.
*
* [mandate_data.customer_acceptance.online.user_agent](https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-mandate_data-customer_acceptance-online-user_agent)
*/
userAgent: String
) : this(
ipAddress,
userAgent,
inferFromClient = false
)
override fun toParamMap(): Map<String, Any> {
return if (inferFromClient) {
mapOf(PARAM_INFER_FROM_CLIENT to true)
} else {
mapOf(
PARAM_IP_ADDRESS to ipAddress.orEmpty(),
PARAM_USER_AGENT to userAgent.orEmpty()
)
}
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) // For paymentsheet
companion object {
private const val PARAM_IP_ADDRESS = "ip_address"
private const val PARAM_USER_AGENT = "user_agent"
private const val PARAM_INFER_FROM_CLIENT = "infer_from_client"
val DEFAULT = Online(inferFromClient = true)
}
}
}
private companion object {
private const val PARAM_CUSTOMER_ACCEPTANCE = "customer_acceptance"
private const val PARAM_TYPE = "type"
}
}
|
mit
|
32347452e0f6445a9c99367c3ebeeda3
| 39.434343 | 198 | 0.594804 | 4.61707 | false | false | false | false |
exponent/exponent
|
packages/expo-facebook/android/src/main/java/expo/modules/facebook/FacebookModule.kt
|
2
|
11683
|
package expo.modules.facebook
import expo.modules.core.Promise
import expo.modules.core.ExportedModule
import expo.modules.core.ModuleRegistry
import expo.modules.core.interfaces.ExpoMethod
import expo.modules.core.arguments.ReadableArguments
import expo.modules.core.ModuleRegistryDelegate
import expo.modules.core.interfaces.ActivityEventListener
import expo.modules.core.interfaces.ActivityProvider
import expo.modules.core.interfaces.services.UIManager
import com.facebook.CallbackManager
import com.facebook.FacebookSdk
import com.facebook.AccessToken
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.appevents.AppEventsLogger
import com.facebook.internal.AttributionIdentifiers
import com.facebook.login.LoginManager
import com.facebook.login.LoginBehavior
import com.facebook.login.LoginResult
import android.os.Bundle
import android.app.Activity
import android.content.Context
import android.content.Intent
import java.lang.Exception
import java.lang.IllegalStateException
import java.math.BigDecimal
import java.util.*
private const val ERR_FACEBOOK_MISCONFIGURED = "ERR_FACEBOOK_MISCONFIGURED"
private const val ERR_FACEBOOK_LOGIN = "ERR_FACEBOOK_LOGIN"
private const val PUSH_PAYLOAD_KEY = "fb_push_payload"
private const val PUSH_PAYLOAD_CAMPAIGN_KEY = "campaign"
open class FacebookModule(
context: Context,
private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate()
) : ExportedModule(context), ActivityEventListener {
private val callbackManager: CallbackManager = CallbackManager.Factory.create()
private var appEventLogger: AppEventsLogger? = null
private var attributionIdentifiers: AttributionIdentifiers? = null
protected var appId: String? = null
private set
protected var appName: String? = null
private set
private val uIManager: UIManager by moduleRegistry()
private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>()
override fun getName() = "ExponentFacebook"
override fun onCreate(moduleRegistry: ModuleRegistry) {
moduleRegistryDelegate.onCreate(moduleRegistry)
uIManager.registerActivityEventListener(this)
}
override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
callbackManager.onActivityResult(requestCode, resultCode, data)
}
override fun onNewIntent(intent: Intent) = Unit
private fun bundleWithNullValuesAsStrings(parameters: ReadableArguments?): Bundle {
return Bundle().apply {
if (parameters != null) {
for (key in parameters.keys()) {
val value = parameters[key]
when (value) {
null -> putString(key, "null")
is String -> putString(key, value)
is Int -> putInt(key, value)
is Double -> putDouble(key, value)
is Long -> putLong(key, value)
}
}
}
}
}
@ExpoMethod
fun setAutoLogAppEventsEnabledAsync(enabled: Boolean, promise: Promise) {
FacebookSdk.setAutoLogAppEventsEnabled(enabled)
promise.resolve(null)
}
@ExpoMethod
fun setAdvertiserIDCollectionEnabledAsync(enabled: Boolean, promise: Promise) {
FacebookSdk.setAdvertiserIDCollectionEnabled(enabled)
promise.resolve(null)
}
@ExpoMethod
open fun getAuthenticationCredentialAsync(promise: Promise) {
val accessToken = AccessToken.getCurrentAccessToken()
promise.resolve(accessTokenToBundle(accessToken))
}
private fun accessTokenToBundle(accessToken: AccessToken?): Bundle? {
return accessToken?.let {
Bundle().apply {
putString("token", it.token)
putString("userId", it.userId)
putString("appId", it.applicationId)
putStringArrayList("permissions", ArrayList(it.permissions))
putStringArrayList("declinedPermissions", ArrayList(it.declinedPermissions))
putStringArrayList("expiredPermissions", ArrayList(it.expiredPermissions))
putDouble("expirationDate", it.expires.time.toDouble())
putDouble("dataAccessExpirationDate", it.dataAccessExpirationTime.time.toDouble())
putDouble("refreshDate", it.lastRefresh.time.toDouble())
putString("tokenSource", it.source.name)
}
}
}
@ExpoMethod
open fun initializeAsync(options: ReadableArguments, promise: Promise) {
try {
options.getString("appId")?.let {
appId = it
FacebookSdk.setApplicationId(appId)
}
options.getString("appName")?.let {
appName = it
FacebookSdk.setApplicationId(appName)
}
options.getString("version")?.let {
FacebookSdk.setGraphApiVersion(it)
}
options.getString("domain")?.let {
FacebookSdk.setFacebookDomain(it)
}
if (options.containsKey("autoLogAppEvents")) {
FacebookSdk.setAutoLogAppEventsEnabled(options.getBoolean("isDebugEnabled"))
}
if (options.containsKey("isDebugEnabled")) {
FacebookSdk.setAutoLogAppEventsEnabled(options.getBoolean("isDebugEnabled"))
}
FacebookSdk.sdkInitialize(context) {
FacebookSdk.fullyInitialize()
appId = FacebookSdk.getApplicationId()
appName = FacebookSdk.getApplicationName()
appEventLogger = AppEventsLogger.newLogger(context)
attributionIdentifiers = AttributionIdentifiers.getAttributionIdentifiers(context)
promise.resolve(null)
}
} catch (e: Exception) {
promise.reject(ERR_FACEBOOK_MISCONFIGURED, "An error occurred while trying to initialize a FBSDK app", e)
}
}
@ExpoMethod
open fun logOutAsync(promise: Promise) {
AccessToken.setCurrentAccessToken(null)
LoginManager.getInstance().logOut()
promise.resolve(null)
}
@ExpoMethod
open fun logInWithReadPermissionsAsync(config: ReadableArguments, promise: Promise) {
if (FacebookSdk.getApplicationId() == null) {
promise.reject(
ERR_FACEBOOK_MISCONFIGURED,
"No appId configured, required for initialization. " +
"Please ensure that you're either providing `appId` to `initializeAsync` as an argument or inside AndroidManifest.xml."
)
return
}
// Log out
AccessToken.setCurrentAccessToken(null)
LoginManager.getInstance().logOut()
// Convert permissions
val permissions = config.getList("permissions", listOf("public_profile", "email")) as List<String?>
if (config.containsKey("behavior")) {
val behavior = when (config.getString("behavior")) {
"browser" -> LoginBehavior.WEB_ONLY
"web" -> LoginBehavior.WEB_VIEW_ONLY
else -> LoginBehavior.NATIVE_WITH_FALLBACK
}
LoginManager.getInstance().loginBehavior = behavior
}
LoginManager.getInstance().registerCallback(
callbackManager,
object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
LoginManager.getInstance().registerCallback(callbackManager, null)
// This is the only route through which we send an access token back. Make sure the
// application ID is correct.
if (appId != loginResult.accessToken.applicationId) {
promise.reject(IllegalStateException("Logged into wrong app, try again?"))
return
}
val response = accessTokenToBundle(loginResult.accessToken)?.apply {
putString("type", "success")
}
promise.resolve(response)
}
override fun onCancel() {
LoginManager.getInstance().registerCallback(callbackManager, null)
promise.resolve(
Bundle().apply {
putString("type", "cancel")
}
)
}
override fun onError(error: FacebookException) {
LoginManager.getInstance().registerCallback(callbackManager, null)
promise.reject(ERR_FACEBOOK_LOGIN, "An error occurred while trying to log in to Facebook", error)
}
}
)
try {
val activityProvider: ActivityProvider by moduleRegistry()
LoginManager.getInstance().logInWithReadPermissions(activityProvider.currentActivity, permissions)
} catch (e: FacebookException) {
promise.reject(ERR_FACEBOOK_LOGIN, "An error occurred while trying to log in to Facebook", e)
}
}
@ExpoMethod
fun setFlushBehaviorAsync(flushBehavior: String, promise: Promise) {
AppEventsLogger.setFlushBehavior(AppEventsLogger.FlushBehavior.valueOf(flushBehavior.toUpperCase(Locale.ROOT)))
promise.resolve(null)
}
@ExpoMethod
fun logEventAsync(eventName: String?, valueToSum: Double, parameters: ReadableArguments?, promise: Promise) {
appEventLogger?.let {
it.logEvent(eventName, valueToSum, bundleWithNullValuesAsStrings(parameters))
promise.resolve(null)
} ?: run {
promise.reject("ERR_FACEBOOK_APP_EVENT_LOGGER", "appEventLogger is not initialized")
}
}
@ExpoMethod
fun logPurchaseAsync(
purchaseAmount: Double,
currencyCode: String?,
parameters: ReadableArguments?,
promise: Promise
) {
appEventLogger?.let {
it.logPurchase(
BigDecimal.valueOf(purchaseAmount),
Currency.getInstance(currencyCode),
bundleWithNullValuesAsStrings(parameters)
)
promise.resolve(null)
} ?: run {
promise.reject("ERR_FACEBOOK_APP_EVENT_LOGGER", "appEventLogger is not initialized")
}
}
@ExpoMethod
fun logPushNotificationOpenAsync(campaign: String?, promise: Promise) {
// the Android FBSDK expects the fb_push_payload to be a JSON string
val payload = Bundle().apply {
putString(PUSH_PAYLOAD_KEY, String.format("{\"%s\" : \"%s\"}", PUSH_PAYLOAD_CAMPAIGN_KEY, campaign))
}
appEventLogger?.let {
it.logPushNotificationOpen(payload)
promise.resolve(null)
} ?: run {
promise.reject("ERR_FACEBOOK_APP_EVENT_LOGGER", "appEventLogger is not initialized")
}
}
@ExpoMethod
fun setUserIDAsync(userID: String?, promise: Promise) {
AppEventsLogger.setUserID(userID)
promise.resolve(null)
}
@ExpoMethod
fun getUserIDAsync(promise: Promise) {
promise.resolve(AppEventsLogger.getUserID())
}
@ExpoMethod
fun getAnonymousIDAsync(promise: Promise) {
try {
promise.resolve(AppEventsLogger.getAnonymousAppDeviceGUID(context))
} catch (e: Exception) {
promise.reject("ERR_FACEBOOK_ANONYMOUS_ID", "Can not get anonymousID", e)
}
}
@ExpoMethod
fun getAdvertiserIDAsync(promise: Promise) {
attributionIdentifiers?.let {
promise.resolve(it.androidAdvertiserId)
} ?: run {
promise.reject("ERR_FACEBOOK_ADVERTISER_ID", "Can not get advertiserID")
}
}
@ExpoMethod
fun getAttributionIDAsync(promise: Promise) {
attributionIdentifiers?.let {
promise.resolve(it.attributionId)
} ?: run {
promise.reject("ERR_FACEBOOK_ADVERTISER_ID", "Can not get attributionID")
}
}
@ExpoMethod
fun setUserDataAsync(userData: ReadableArguments, promise: Promise) {
with(userData) {
AppEventsLogger.setUserData(
getString("email"),
getString("firstName"),
getString("lastName"),
getString("phone"),
getString("dateOfBirth"),
getString("gender"),
getString("city"),
getString("state"),
getString("zip"),
getString("country")
)
}
promise.resolve(null)
}
@ExpoMethod
fun flushAsync(promise: Promise) {
appEventLogger?.let {
it.flush()
promise.resolve(null)
} ?: kotlin.run {
promise.reject("ERR_FACEBOOK_APP_EVENT_LOGGER", "appEventLogger is not initialized")
}
}
}
|
bsd-3-clause
|
6fa757e608227b435e2a016fd8946e38
| 33.061224 | 129 | 0.700419 | 4.636111 | false | false | false | false |
AndroidX/androidx
|
hilt/hilt-navigation-compose/src/androidTest/java/androidx/hilt/navigation/compose/HiltViewModelComposeTest.kt
|
3
|
6778
|
/*
* 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.hilt.navigation.compose
import android.content.Context
import androidx.activity.ComponentActivity
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navigation
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import javax.inject.Inject
@LargeTest
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class HiltViewModelComposeTest {
@get:Rule
val testRule = HiltAndroidRule(this)
@get:Rule
val composeTestRule = createAndroidComposeRule<TestActivity>()
@Test
fun verifyCurrentNavGraphViewModel() {
lateinit var firstViewModel: SimpleViewModel
lateinit var secondViewModel: SimpleViewModel
composeTestRule.setContent {
val navController = rememberNavController()
NavHost(navController, startDestination = "One") {
composable("One") {
firstViewModel = hiltViewModel()
}
}
secondViewModel = hiltViewModel()
}
composeTestRule.waitForIdle()
assertThat(firstViewModel).isNotNull()
assertThat(firstViewModel.handle).isNotNull()
assertThat(secondViewModel).isNotNull()
assertThat(secondViewModel.handle).isNotNull()
assertThat(firstViewModel).isNotSameInstanceAs(secondViewModel)
}
@Test
fun differentViewModelAcrossRoutes() {
lateinit var firstViewModel: SimpleViewModel
lateinit var secondViewModel: SimpleViewModel
composeTestRule.setContent {
val navController = rememberNavController()
NavHost(navController, startDestination = "One") {
composable("One") {
firstViewModel = hiltViewModel()
NavigateButton("Two") { navController.navigate("Two") }
}
composable("Two") {
secondViewModel = hiltViewModel()
NavigateButton("One") { navController.navigate("One") }
}
}
}
composeTestRule.waitForIdle()
assertThat(firstViewModel).isNotNull()
assertThat(firstViewModel.handle).isNotNull()
composeTestRule.onNodeWithText("Navigate to Two").performClick()
composeTestRule.waitForIdle()
assertThat(firstViewModel).isNotSameInstanceAs(secondViewModel)
}
@Test
fun sameParentViewModelAcrossRoutes() {
lateinit var firstViewModel: SimpleViewModel
lateinit var secondViewModel: SimpleViewModel
composeTestRule.setContent {
val navController = rememberNavController()
NavHost(navController, startDestination = "Main") {
navigation(startDestination = "One", route = "Main") {
composable("One") {
firstViewModel = hiltViewModel(
navController.getBackStackEntry("Main")
)
NavigateButton("Two") { navController.navigate("Two") }
}
composable("Two") {
secondViewModel = hiltViewModel(
navController.getBackStackEntry("Main")
)
NavigateButton("One") { navController.navigate("One") }
}
}
}
}
composeTestRule.waitForIdle()
assertThat(firstViewModel).isNotNull()
assertThat(firstViewModel.handle).isNotNull()
composeTestRule.onNodeWithText("Navigate to Two").performClick()
composeTestRule.waitForIdle()
assertThat(firstViewModel).isSameInstanceAs(secondViewModel)
}
@Test
fun keyedViewModel() {
lateinit var firstViewModel: SimpleViewModel
lateinit var secondViewModel: SimpleViewModel
lateinit var thirdViewModel: SimpleViewModel
composeTestRule.setContent {
val navController = rememberNavController()
NavHost(navController, startDestination = "Main") {
composable("Main") {
firstViewModel = hiltViewModel(key = "One")
secondViewModel = hiltViewModel(key = "One")
thirdViewModel = hiltViewModel(key = "Two")
}
}
}
composeTestRule.waitForIdle()
assertThat(firstViewModel).isNotNull()
assertThat(secondViewModel).isNotNull()
assertThat(thirdViewModel).isNotNull()
assertThat(firstViewModel).isSameInstanceAs(secondViewModel)
assertThat(firstViewModel).isNotSameInstanceAs(thirdViewModel)
}
@Composable
private fun NavigateButton(text: String, listener: () -> Unit = { }) {
Button(onClick = listener) {
Text(text = "Navigate to $text")
}
}
@AndroidEntryPoint
class TestActivity : ComponentActivity()
@HiltViewModel
class SimpleViewModel @Inject constructor(
val handle: SavedStateHandle,
val logger: MyLogger,
// TODO(kuanyingchou) Remove this after https://github.com/google/dagger/issues/3601 is
// resolved.
@ApplicationContext val context: Context
) : ViewModel()
class MyLogger @Inject constructor()
}
|
apache-2.0
|
c93b0e95d80272946182184cbfb27ceb
| 36.038251 | 95 | 0.66288 | 5.524042 | false | true | false | false |
AndroidX/androidx
|
compose/material/material/src/commonMain/kotlin/androidx/compose/material/pullrefresh/PullRefresh.kt
|
3
|
4385
|
/*
* 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.material.pullrefresh
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.NestedScrollSource.Companion.Drag
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.platform.inspectable
import androidx.compose.ui.unit.Velocity
/**
* PullRefresh modifier to be used in conjunction with [PullRefreshState]. Provides a connection
* to the nested scroll system. Based on Android's SwipeRefreshLayout.
*
* @sample androidx.compose.material.samples.PullRefreshSample
*
* @param state The [PullRefreshState] associated with this pull-to-refresh component.
* The state will be updated by this modifier.
* @param enabled If not enabled, all scroll delta and fling velocity will be ignored.
*/
// TODO(b/244423199): Move pullRefresh into its own material library similar to material-ripple.
@ExperimentalMaterialApi
fun Modifier.pullRefresh(
state: PullRefreshState,
enabled: Boolean = true
) = inspectable(inspectorInfo = debugInspectorInfo {
name = "pullRefresh"
properties["state"] = state
properties["enabled"] = enabled
}) {
Modifier.pullRefresh(state::onPull, { state.onRelease() }, enabled)
}
/**
* A modifier for building pull-to-refresh components. Provides a connection to the nested scroll
* system.
*
* @sample androidx.compose.material.samples.CustomPullRefreshSample
*
* @param onPull Callback for dispatching vertical scroll delta, takes float pullDelta as argument.
* Positive delta (pulling down) is dispatched only if the child does not consume it (i.e. pulling
* down despite being at the top of a scrollable component), whereas negative delta (swiping up) is
* dispatched first (in case it is needed to push the indicator back up), and then whatever is not
* consumed is passed on to the child.
* @param onRelease Callback for when drag is released, takes float flingVelocity as argument.
* @param enabled If not enabled, all scroll delta and fling velocity will be ignored and neither
* [onPull] nor [onRelease] will be invoked.
*/
@ExperimentalMaterialApi
fun Modifier.pullRefresh(
onPull: (pullDelta: Float) -> Float,
onRelease: suspend (flingVelocity: Float) -> Unit,
enabled: Boolean = true
) = inspectable(inspectorInfo = debugInspectorInfo {
name = "pullRefresh"
properties["onPull"] = onPull
properties["onRelease"] = onRelease
properties["enabled"] = enabled
}) {
Modifier.nestedScroll(PullRefreshNestedScrollConnection(onPull, onRelease, enabled))
}
private class PullRefreshNestedScrollConnection(
private val onPull: (pullDelta: Float) -> Float,
private val onRelease: suspend (flingVelocity: Float) -> Unit,
private val enabled: Boolean
) : NestedScrollConnection {
override fun onPreScroll(
available: Offset,
source: NestedScrollSource
): Offset = when {
!enabled -> Offset.Zero
source == Drag && available.y < 0 -> Offset(0f, onPull(available.y)) // Swiping up
else -> Offset.Zero
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset = when {
!enabled -> Offset.Zero
source == Drag && available.y > 0 -> Offset(0f, onPull(available.y)) // Pulling down
else -> Offset.Zero
}
override suspend fun onPreFling(available: Velocity): Velocity {
onRelease(available.y)
return Velocity.Zero
}
}
|
apache-2.0
|
36fbbc2b76b92b11444efdc7580f807d
| 38.513514 | 99 | 0.740479 | 4.438259 | false | false | false | false |
AndroidX/androidx
|
room/room-runtime/src/main/java/androidx/room/RoomSQLiteQuery.kt
|
3
|
7712
|
/*
* 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 androidx.room
import androidx.annotation.IntDef
import androidx.annotation.RestrictTo
import androidx.annotation.VisibleForTesting
import androidx.sqlite.db.SupportSQLiteProgram
import androidx.sqlite.db.SupportSQLiteQuery
import java.util.Arrays
import java.util.TreeMap
/**
* This class is used as an intermediate place to keep binding arguments so that we can run
* Cursor queries with correct types rather than passing everything as a string.
*
* Because it is relatively a big object, they are pooled and must be released after each use.
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
class RoomSQLiteQuery private constructor(
@field:VisibleForTesting val capacity: Int
) : SupportSQLiteQuery, SupportSQLiteProgram {
@Volatile
private var query: String? = null
@JvmField
@VisibleForTesting
val longBindings: LongArray
@JvmField
@VisibleForTesting
val doubleBindings: DoubleArray
@JvmField
@VisibleForTesting
val stringBindings: Array<String?>
@JvmField
@VisibleForTesting
val blobBindings: Array<ByteArray?>
@Binding
private val bindingTypes: IntArray
// number of arguments in the query
override var argCount = 0
private set
fun init(query: String, initArgCount: Int) {
this.query = query
argCount = initArgCount
}
init {
// because, 1 based indices... we don't want to offsets everything with 1 all the time.
val limit = capacity + 1
bindingTypes = IntArray(limit)
longBindings = LongArray(limit)
doubleBindings = DoubleArray(limit)
stringBindings = arrayOfNulls(limit)
blobBindings = arrayOfNulls(limit)
}
/**
* Releases the query back to the pool.
*
* After released, the statement might be returned when [.acquire] is called
* so you should never re-use it after releasing.
*/
fun release() {
synchronized(queryPool) {
queryPool[capacity] = this
prunePoolLocked()
}
}
override val sql: String
get() = checkNotNull(this.query)
override fun bindTo(statement: SupportSQLiteProgram) {
for (index in 1..argCount) {
when (bindingTypes[index]) {
NULL -> statement.bindNull(index)
LONG -> statement.bindLong(index, longBindings[index])
DOUBLE -> statement.bindDouble(index, doubleBindings[index])
STRING -> statement.bindString(index, requireNotNull(stringBindings[index]))
BLOB -> statement.bindBlob(index, requireNotNull(blobBindings[index]))
}
}
}
override fun bindNull(index: Int) {
bindingTypes[index] = NULL
}
override fun bindLong(index: Int, value: Long) {
bindingTypes[index] = LONG
longBindings[index] = value
}
override fun bindDouble(index: Int, value: Double) {
bindingTypes[index] = DOUBLE
doubleBindings[index] = value
}
override fun bindString(index: Int, value: String) {
bindingTypes[index] = STRING
stringBindings[index] = value
}
override fun bindBlob(index: Int, value: ByteArray) {
bindingTypes[index] = BLOB
blobBindings[index] = value
}
override fun close() {
// no-op. not calling release because it is internal API.
}
/**
* Copies arguments from another RoomSQLiteQuery into this query.
*
* @param other The other query, which holds the arguments to be copied.
*/
fun copyArgumentsFrom(other: RoomSQLiteQuery) {
val argCount = other.argCount + 1 // +1 for the binding offsets
System.arraycopy(other.bindingTypes, 0, bindingTypes, 0, argCount)
System.arraycopy(other.longBindings, 0, longBindings, 0, argCount)
System.arraycopy(other.stringBindings, 0, stringBindings, 0, argCount)
System.arraycopy(other.blobBindings, 0, blobBindings, 0, argCount)
System.arraycopy(other.doubleBindings, 0, doubleBindings, 0, argCount)
}
override fun clearBindings() {
Arrays.fill(bindingTypes, NULL)
Arrays.fill(stringBindings, null)
Arrays.fill(blobBindings, null)
query = null
// no need to clear others
}
@Retention(AnnotationRetention.SOURCE)
@IntDef(NULL, LONG, DOUBLE, STRING, BLOB)
internal annotation class Binding
companion object {
// Maximum number of queries we'll keep cached.
@VisibleForTesting
const val POOL_LIMIT = 15
// Once we hit POOL_LIMIT, we'll bring the pool size back to the desired number. We always
// clear the bigger queries (# of arguments).
@VisibleForTesting
const val DESIRED_POOL_SIZE = 10
@JvmField
@VisibleForTesting
val queryPool = TreeMap<Int, RoomSQLiteQuery>()
/**
* Copies the given SupportSQLiteQuery and converts it into RoomSQLiteQuery.
*
* @param supportSQLiteQuery The query to copy from
* @return A new query copied from the provided one.
*/
@JvmStatic
fun copyFrom(supportSQLiteQuery: SupportSQLiteQuery): RoomSQLiteQuery {
val query = acquire(
supportSQLiteQuery.sql,
supportSQLiteQuery.argCount
)
supportSQLiteQuery.bindTo(object : SupportSQLiteProgram by query {})
return query
}
/**
* Returns a new RoomSQLiteQuery that can accept the given number of arguments and holds the
* given query.
*
* @param query The query to prepare
* @param argumentCount The number of query arguments
* @return A RoomSQLiteQuery that holds the given query and has space for the given number
* of arguments.
*/
@JvmStatic
fun acquire(query: String, argumentCount: Int): RoomSQLiteQuery {
synchronized(queryPool) {
val entry = queryPool.ceilingEntry(argumentCount)
if (entry != null) {
queryPool.remove(entry.key)
val sqliteQuery = entry.value
sqliteQuery.init(query, argumentCount)
return sqliteQuery
}
}
val sqLiteQuery = RoomSQLiteQuery(argumentCount)
sqLiteQuery.init(query, argumentCount)
return sqLiteQuery
}
internal fun prunePoolLocked() {
if (queryPool.size > POOL_LIMIT) {
var toBeRemoved = queryPool.size - DESIRED_POOL_SIZE
val iterator = queryPool.descendingKeySet().iterator()
while (toBeRemoved-- > 0) {
iterator.next()
iterator.remove()
}
}
}
private const val NULL = 1
private const val LONG = 2
private const val DOUBLE = 3
private const val STRING = 4
private const val BLOB = 5
}
}
|
apache-2.0
|
9cac1c2fc5975900a0b9fbcbd8de6e23
| 31.961538 | 100 | 0.633558 | 4.826033 | false | false | false | false |
Dr-Horv/Advent-of-Code-2017
|
src/main/kotlin/solutions/day09/Day9.kt
|
1
|
1953
|
package solutions.day09
import solutions.Solver
data class Node(val parent: Node?, val children: MutableList<Node>) {
fun addChild(child: Node) {
children.add(child)
}
}
class Day9: Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val first = input.first()
val stream = first.toCharArray().slice(IntRange(1, first.lastIndex - 1)) // Create outmost node before loop
val iterator = stream.toCharArray().iterator()
var curr = Node(null, mutableListOf())
var garbageSum = 0
while(iterator.hasNext()) {
val c = iterator.nextChar()
if(c == '<') {
garbageSum += handleGarbage(iterator)
}
when(c) {
'{' -> curr = goDeeper(curr)
'}' -> curr = goShallower(curr)
}
}
return if(!partTwo) {
sumGroupScore(curr).toString()
} else {
garbageSum.toString()
}
}
private fun goShallower(curr: Node): Node {
if(curr.parent != null) {
return curr.parent
} else {
throw RuntimeException("Unexpected no parent")
}
}
private fun goDeeper(curr: Node): Node {
val deeperNode = Node(parent = curr, children = mutableListOf())
curr.addChild(deeperNode)
return deeperNode
}
private fun handleGarbage(iterator: CharIterator): Int {
var garbageSum = 0
while(iterator.hasNext()) {
val c = iterator.nextChar()
when(c) {
'!' -> iterator.next()
'>' -> return garbageSum
else -> garbageSum++
}
}
throw RuntimeException("Unexpected no end of garbage")
}
private fun sumGroupScore(root: Node, level: Int = 1): Int {
return level + root.children.map { sumGroupScore(it, level+1) }.sum()
}
}
|
mit
|
bbded1a313271fedc43cd3b67b29ab97
| 27.735294 | 115 | 0.541731 | 4.418552 | false | false | false | false |
MeilCli/Twitter4HK
|
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/media/ChunkedUpload.kt
|
1
|
2661
|
package com.twitter.meil_mitu.twitter4hk.api.media
import com.twitter.meil_mitu.twitter4hk.AbsOauth
import com.twitter.meil_mitu.twitter4hk.AbsPost
import com.twitter.meil_mitu.twitter4hk.OauthType
import com.twitter.meil_mitu.twitter4hk.converter.IMediaConverter
import com.twitter.meil_mitu.twitter4hk.data.Media
import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException
import java.io.File
class ChunkedUpload<TMedia>(
oauth: AbsOauth,
protected val json: IMediaConverter<TMedia>,
media: File,
mediaType: String) : AbsPost<TMedia>(oauth) {
var media: File
var mediaType: String
internal val initCommand = "INIT"
internal val appendCommand = "APPEND"
internal val finalizeCommand = "FINALIZE"
internal val maxSeparateByte = 5 * 1024 * 1024
override val url = "https://upload.twitter.com/1.1/media/upload.json"
override val allowOauthType = OauthType.oauth1
override val isAuthorization = true
init {
this.media = media
this.mediaType = mediaType
}
@Throws(Twitter4HKException::class)
override fun call(): TMedia {
paramMap["command"] = initCommand
paramMap["media_type"] = mediaType
paramMap["total_bytes"] = media.length().toString()
val initResult = Media(json.toJSONObject(json.toString(oauth.post(this).body())))
paramMap.remove("command")
paramMap.remove("media_type")
paramMap.remove("total_bytes")
val totalByte = media.length()
val separateCount = totalByte / maxSeparateByte + (if (totalByte % maxSeparateByte > 0) 1 else 0)
paramMap["command"] = appendCommand
paramMap["media_id"] = initResult.mediaId.toString()
fileMap["media"] = media
for (i in 0..separateCount - 1) {
paramMap["segment_index"] = i.toString()
val startByte = i * maxSeparateByte
val size = if ((i + 1) * maxSeparateByte <= totalByte)
maxSeparateByte.toInt() else
(totalByte - startByte).toInt()
separateFileMap["media"] = Pair(startByte, startByte + size)
json.toString(oauth.post(this).body())
}
paramMap.remove("command")
paramMap.remove("media_id")
fileMap.remove("media")
paramMap.remove("segment_index")
separateFileMap.remove("media")
paramMap["command"] = finalizeCommand
paramMap["media_id"] = initResult.mediaId.toString()
val finalizeResult = json.toMedia(oauth.post(this))
paramMap.remove("command")
paramMap.remove("media_id")
return finalizeResult
}
}
|
mit
|
5e0d2e1ae7c6bc38c860606acdb69567
| 37.57971 | 105 | 0.658775 | 4.131988 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/ide/refactoring/extractStructFields/RsExtractStructFieldsAction.kt
|
2
|
2483
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.extractStructFields
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.RsBundle
import org.rust.ide.refactoring.RsBaseEditorRefactoringAction
import org.rust.ide.refactoring.generate.StructMember
import org.rust.ide.refactoring.generate.showStructMemberChooserDialog
import org.rust.lang.core.psi.RsStructItem
import org.rust.lang.core.psi.ext.ancestorOrSelf
import org.rust.lang.core.psi.ext.isTupleStruct
import org.rust.lang.core.types.emptySubstitution
data class RsExtractStructFieldsContext(
val struct: RsStructItem,
val fields: List<StructMember>,
val name: String
)
class RsExtractStructFieldsAction : RsBaseEditorRefactoringAction() {
override fun isAvailableOnElementInEditorAndFile(
element: PsiElement,
editor: Editor,
file: PsiFile,
context: DataContext
): Boolean = findApplicableContext(editor, file) != null
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) {
val struct = findApplicableContext(editor, file) ?: return
val fields = StructMember.fromStruct(struct, emptySubstitution)
val chosenFields = showStructMemberChooserDialog(
project,
struct,
fields,
RsBundle.message("action.Rust.RsExtractStructFields.choose.fields.title"),
allowEmptySelection = false
) ?: return
if (chosenFields.isEmpty()) return
val name = showExtractStructFieldsDialog(project) ?: return
val ctx = RsExtractStructFieldsContext(struct, chosenFields, name)
val processor = RsExtractStructFieldsProcessor(project, editor, ctx)
processor.setPreviewUsages(false)
processor.run()
}
companion object {
private fun findApplicableContext(editor: Editor, file: PsiFile): RsStructItem? {
val offset = editor.caretModel.offset
val struct = file.findElementAt(offset)?.ancestorOrSelf<RsStructItem>() ?: return null
if (struct.isTupleStruct) return null
if (struct.blockFields?.namedFieldDeclList?.isEmpty() != false) return null
return struct
}
}
}
|
mit
|
f40fd516a48f33fdd4633bbb293b5dc9
| 36.621212 | 101 | 0.723319 | 4.581181 | false | false | false | false |
kiruto/debug-bottle
|
components/src/main/kotlin/com/exyui/android/debugbottle/components/fragments/components/switchers.kt
|
1
|
5142
|
package com.exyui.android.debugbottle.components.fragments.components
import android.app.Activity
import android.content.Context
import android.support.annotation.IdRes
import android.support.v7.widget.SwitchCompat
import android.view.View
import android.widget.Toast
import com.exyui.android.debugbottle.components.DTSettings
import com.exyui.android.debugbottle.components.R
import com.exyui.android.debugbottle.components.bubbles.services.__3DViewBubble
import com.exyui.android.debugbottle.components.floating.frame.__FloatFrame
import com.exyui.android.debugbottle.components.isSystemAlertPermissionGranted
import com.exyui.android.debugbottle.components.requestingPermissionDrawOverOtherApps
import com.exyui.android.debugbottle.components.widgets.DTListItemSwitch
import com.exyui.android.debugbottle.ui.BlockCanary
/**
* Created by yuriel on 10/12/16.
*/
internal fun View.networkSwitcher(@IdRes id: Int): DTListItemSwitch {
return (findViewById(id) as DTListItemSwitch).apply {
isChecked = DTSettings.networkSniff
setOnCheckedChangeListener { _, isChecked ->
DTSettings.networkSniff = isChecked
}
}
}
internal fun View.strictSwitcher(@IdRes id: Int): DTListItemSwitch {
return (findViewById(id) as DTListItemSwitch).apply {
isChecked = DTSettings.strictMode
setOnCheckedChangeListener { _, isChecked ->
DTSettings.strictMode = isChecked
hintRestart(context)
}
}
}
internal fun View.view3DSwitcher(@IdRes id: Int): DTListItemSwitch {
return (findViewById(id) as DTListItemSwitch).apply {
val activity = context as Activity
isChecked = __3DViewBubble.isRunning()
setOnCheckedChangeListener { _, isChecked ->
if (!activity.isSystemAlertPermissionGranted()){
this.isChecked = false
activity.requestingPermissionDrawOverOtherApps(null)
} else {
if (isChecked) {
val started = __3DViewBubble.create(activity.applicationContext)
if (!started) {
this.isChecked = false
activity.requestingPermissionDrawOverOtherApps(null)
}
} else {
__3DViewBubble.destroy(activity.applicationContext)
}
}
}
}
}
internal fun View.leakCanarySwitcher(@IdRes id: Int): DTListItemSwitch {
return (findViewById(id) as DTListItemSwitch).apply {
isChecked = DTSettings.leakCanaryEnable
setOnCheckedChangeListener { _, isChecked ->
DTSettings.leakCanaryEnable = isChecked
hintRestart(context)
}
}
}
internal fun View.blockCanarySwitcherCompat(@IdRes id: Int): SwitchCompat {
return (findViewById(id) as SwitchCompat).apply {
isChecked = DTSettings.blockCanaryEnable
setOnCheckedChangeListener(::blockCanarySwitcherListener)
}
}
internal fun View.blockCanarySwitcher(@IdRes id: Int): DTListItemSwitch {
return (findViewById(id) as DTListItemSwitch).apply {
isChecked = DTSettings.blockCanaryEnable
setOnCheckedChangeListener(::blockCanarySwitcherListener)
}
}
internal fun View.bottleSwitch(@IdRes id: Int): DTListItemSwitch {
return (findViewById(id) as DTListItemSwitch).apply {
isChecked = DTSettings.bottleEnable
setOnCheckedChangeListener { _, isChecked ->
DTSettings.bottleEnable = isChecked
hintRestart(context)
}
}
}
internal fun View.frameSwitcher(@IdRes id: Int): DTListItemSwitch {
return (findViewById(id) as DTListItemSwitch).apply {
val activity = context as Activity
isChecked = DTSettings.frameEnable
setOnCheckedChangeListener { _, isChecked ->
DTSettings.frameEnable = isChecked
if (isChecked) {
__FloatFrame.start(activity)
} else {
__FloatFrame.stop(activity)
}
}
}
}
internal fun View.monkeyBlackListSwitcher(@IdRes id: Int): DTListItemSwitch {
return (findViewById(id) as DTListItemSwitch).apply {
isChecked = DTSettings.monkeyBlacklist
setOnCheckedChangeListener { _, isChecked ->
DTSettings.monkeyBlacklist = isChecked
}
}
}
internal fun View.notificationLockSwitcher(@IdRes id: Int): DTListItemSwitch {
return (findViewById(id) as DTListItemSwitch).apply {
isChecked = DTSettings.notificationLock
setOnCheckedChangeListener { _, isChecked ->
DTSettings.notificationLock = isChecked
}
}
}
private fun hintRestart(context: Context) {
Toast.makeText(context, R.string.__dt_need_restart_after_apply, Toast.LENGTH_LONG).show()
}
@Suppress("UNUSED_PARAMETER")
private fun blockCanarySwitcherListener(v: View, isChecked: Boolean) {
DTSettings.blockCanaryEnable = isChecked
try {
if (isChecked) {
BlockCanary.get().start()
} else {
BlockCanary.get().stop()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
|
apache-2.0
|
04df03d23cce4c95f14264936ce536ff
| 34.226027 | 93 | 0.675029 | 4.721763 | false | false | false | false |
ryan652/EasyCrypt
|
appKotlin/src/main/java/com/pvryan/easycryptsample/action/FragmentSymmetricString.kt
|
1
|
3982
|
/*
* Copyright 2018 Priyank Vasa
* 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.pvryan.easycryptsample.action
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pvryan.easycrypt.ECResultListener
import com.pvryan.easycrypt.symmetric.ECSymmetric
import com.pvryan.easycryptsample.Constants
import com.pvryan.easycryptsample.R
import com.pvryan.easycryptsample.extensions.hide
import com.pvryan.easycryptsample.extensions.setOnClickEndDrawableListener
import com.pvryan.easycryptsample.extensions.show
import com.pvryan.easycryptsample.extensions.snackLong
import kotlinx.android.synthetic.main.fragment_symmetric_string.*
import org.jetbrains.anko.support.v4.onUiThread
class FragmentSymmetricString : Fragment(), ECResultListener {
private val eCryptSymmetric = ECSymmetric()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_symmetric_string, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
edInputS.setOnClickEndDrawableListener {
/*val intent = Intent(activity, CameraActivity::class.java)
intent.putExtra(Constants.TITLE, getString(R.string.title_camera))
startActivityForResult(intent, Constants.rCCameraResult)*/
llContentSString.snackLong(getString(R.string.scanComingSoon, "encrypt"))
}
buttonEncryptS.setOnClickListener {
if (edPasswordS.text.toString() != "") {
progressBarS.show()
eCryptSymmetric.encrypt(edInputS.text, edPasswordS.text.toString(), this)
} else view.snackLong("Password cannot be empty!")
}
buttonDecryptS.setOnClickListener {
if (edPasswordS.text.toString() != "") {
progressBarS.show()
eCryptSymmetric.decrypt(edInputS.text, edPasswordS.text.toString(), this)
} else view.snackLong("Password cannot be empty!")
}
val clipboard = activity?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
tvResultS.setOnLongClickListener {
val data = ClipData.newPlainText("result", tvResultS.text)
clipboard.primaryClip = data
view.snackLong("Result copied to clipboard")
true
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
Constants.rCCameraResult -> {
data?.let { edInputS.setText(it.getStringExtra(Constants.INPUT_STRING) ?: "") }
}
}
}
override fun <T> onSuccess(result: T) {
onUiThread {
progressBarS.hide()
tvResultS.text = result as String
}
}
override fun onFailure(message: String, e: Exception) {
e.printStackTrace()
onUiThread {
progressBarS.hide()
llContentSString.snackLong("Error: $message")
}
}
companion object {
fun newInstance(): Fragment = FragmentSymmetricString()
}
}
|
apache-2.0
|
f3645c5d731fc444823c12bff49f4d15
| 36.92381 | 97 | 0.692868 | 4.598152 | false | false | false | false |
androidx/androidx
|
room/room-compiler/src/main/kotlin/androidx/room/solver/types/CompositeAdapter.kt
|
3
|
2117
|
/*
* Copyright (C) 2016 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.solver.types
import androidx.room.compiler.processing.XType
import androidx.room.solver.CodeGenScope
/**
* A column adapter that uses a type converter to do the conversion. The type converter may be
* a composite one.
*/
class CompositeAdapter(
out: XType,
val columnTypeAdapter: ColumnTypeAdapter,
val intoStatementConverter: TypeConverter?,
val fromCursorConverter: TypeConverter?
) : ColumnTypeAdapter(out, columnTypeAdapter.typeAffinity) {
override fun readFromCursor(
outVarName: String,
cursorVarName: String,
indexVarName: String,
scope: CodeGenScope
) {
if (fromCursorConverter == null) {
return
}
scope.builder.apply {
val tmpCursorValue = scope.getTmpVar()
addLocalVariable(tmpCursorValue, columnTypeAdapter.outTypeName)
columnTypeAdapter.readFromCursor(tmpCursorValue, cursorVarName, indexVarName, scope)
fromCursorConverter.convert(tmpCursorValue, outVarName, scope)
}
}
override fun bindToStmt(
stmtName: String,
indexVarName: String,
valueVarName: String,
scope: CodeGenScope
) {
if (intoStatementConverter == null) {
return
}
scope.builder.apply {
val bindVar = intoStatementConverter.convert(valueVarName, scope)
columnTypeAdapter.bindToStmt(stmtName, indexVarName, bindVar, scope)
}
}
}
|
apache-2.0
|
b900be0380a427a73c99f6d5e22e0ccb
| 32.603175 | 96 | 0.687293 | 4.582251 | false | false | false | false |
oleksiyp/mockk
|
mockk/common/src/main/kotlin/io/mockk/impl/recording/PermanentMocker.kt
|
1
|
4469
|
package io.mockk.impl.recording
import io.mockk.EqMatcher
import io.mockk.EquivalentMatcher
import io.mockk.RecordedCall
import io.mockk.impl.InternalPlatform
import io.mockk.impl.log.Logger
import io.mockk.impl.log.SafeToString
import io.mockk.impl.stub.StubRepository
class PermanentMocker(
val stubRepo: StubRepository,
val safeToString: SafeToString
) {
val log = safeToString(Logger<PermanentMocker>())
val permanentMocks = InternalPlatform.identityMap<Any, Any>()
val callRef = InternalPlatform.weakMap<Any, RecordedCall>()
fun mock(calls: List<RecordedCall>): List<RecordedCall> {
val result = mutableListOf<RecordedCall>()
for (call in calls) {
val permanentCall = permamentize(call)
result.add(permanentCall)
}
val callTree = safeToString.exec { describeCallTree(result) }
if (callTree.size == 1) {
log.trace { "Mocked permanently: " + callTree[0] }
} else {
log.trace { "Mocked permanently:\n" + callTree.joinToString(", ") }
}
return result
}
private fun permamentize(call: RecordedCall): RecordedCall {
val newCall = makeCallPermanent(call)
val retValue = call.retValue
if (call.isRetValueMock && retValue != null) {
val equivalentCall = makeEquivalent(newCall)
log.trace { "Child search key: ${equivalentCall.matcher}" }
val childMock = stubRepo.stubFor(newCall.matcher.self)
.childMockK(equivalentCall.matcher, equivalentCall.retType)
val newNewCall = newCall.copy(retValue = childMock)
permanentMocks[retValue] = childMock
callRef[retValue] = newNewCall
return newNewCall
}
return newCall
}
private fun makeEquivalent(newCall: RecordedCall): RecordedCall {
val equivalentArgs = newCall.matcher.args.map {
when (it) {
is EquivalentMatcher -> it.equivalent()
else -> it
}
}
val equivalentIM = newCall.matcher.copy(args = equivalentArgs)
return newCall.copy(matcher = equivalentIM)
}
private fun makeCallPermanent(call: RecordedCall): RecordedCall {
val selfChain = callRef[call.matcher.self]
val argChains = call.matcher.args
.map {
when (it) {
is EqMatcher -> callRef[it.value] ?: it
else -> it
}
}
val newSelf = permanentMocks[call.matcher.self] ?: call.matcher.self
val newArgs = call.matcher.args.map { it.substitute(permanentMocks) }
val newMatcher = call.matcher.copy(self = newSelf, args = newArgs)
return call.copy(
matcher = newMatcher,
selfChain = selfChain,
argChains = argChains
)
}
private fun describeCallTree(calls: MutableList<RecordedCall>): List<String> {
val callTree = linkedMapOf<RecordedCall, String>()
val usedCalls = hashSetOf<RecordedCall>()
for (call in calls) {
callTree[call] = formatCall(
call,
callTree,
usedCalls
)
}
return calls.filter {
it !in usedCalls
}.map {
callTree[it] ?: "<bad call>"
}
}
private fun formatCall(
call: RecordedCall,
tree: Map<RecordedCall, String>,
usedCalls: MutableSet<RecordedCall>
): String {
val methodName = call.matcher.method.name
val args = call.argChains!!.map {
when (it) {
is RecordedCall -> {
usedCalls.add(it)
tree[it] ?: "<bad link>"
}
else -> it.toString()
}
}
val selfChain = call.selfChain
val prefix = if (selfChain != null) {
usedCalls.add(selfChain)
(tree[selfChain] ?: "<bad link>") + "."
} else {
call.matcher.self.toString() + "."
}
if (methodName.startsWith("get") &&
methodName.length > 3 &&
args.isEmpty()
) {
return prefix +
methodName[3].toLowerCase() +
methodName.substring(4)
}
return prefix + methodName + "(" + args.joinToString(", ") + ")"
}
}
|
apache-2.0
|
eb6b1bd70f680b5e428d10e54f22fadb
| 29.202703 | 82 | 0.562318 | 4.527862 | false | false | false | false |
52inc/android-52Kit
|
library/src/main/java/com/ftinc/kit/extensions/ContextExtensions.kt
|
1
|
4716
|
/*
* Copyright (c) 2019 52inc.
*
* 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.ftinc.kit.extensions
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.core.content.ContextCompat
import android.util.TypedValue
import androidx.annotation.*
import androidx.fragment.app.Fragment
import com.ftinc.kit.util.ScreenUtils
fun Context.dp(dp: Float) : Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, this.resources.displayMetrics)
fun Context.pt(pt: Float) : Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, pt, this.resources.displayMetrics)
fun Context.dip(dp: Float) : Int = this.dp(dp).toInt()
fun Context.sp(sp: Float): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, this.resources.displayMetrics)
fun Fragment.dp(dp: Float) : Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, this.resources.displayMetrics)
fun Fragment.pt(pt: Float) : Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, pt, this.resources.displayMetrics)
fun Fragment.dip(dp: Float) : Int = this.dp(dp).toInt()
fun Fragment.sp(sp: Float): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, this.resources.displayMetrics)
fun Context.dp(dp: Int) : Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), this.resources.displayMetrics)
fun Context.pt(pt: Int) : Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, pt.toFloat(), this.resources.displayMetrics)
fun Context.dip(dp: Int) : Int = this.dp(dp).toInt()
fun Context.sp(sp: Int): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp.toFloat(), this.resources.displayMetrics)
fun Fragment.dp(dp: Int) : Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), this.resources.displayMetrics)
fun Fragment.pt(pt: Int) : Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, pt.toFloat(), this.resources.displayMetrics)
fun Fragment.dip(dp: Int) : Int = this.dp(dp).toInt()
fun Fragment.sp(sp: Int): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp.toFloat(), this.resources.displayMetrics)
@ColorInt
fun Context.color(@ColorRes resId: Int) : Int = ContextCompat.getColor(this, resId)
fun Context.drawable(@DrawableRes resId: Int) : Drawable? = ContextCompat.getDrawable(this, resId)
fun Context.dimenPixelSize(@DimenRes resId: Int): Int = resources.getDimensionPixelSize(resId)
fun Context.dimen(@DimenRes resId: Int): Float = resources.getDimension(resId)
fun Context.int(@IntegerRes resId: Int): Int = resources.getInteger(resId)
fun Context.quantity(@PluralsRes resId: Int, count: Int, vararg args: Any): String = resources.getQuantityString(resId, count, *args)
@ColorInt
fun Fragment.color(@ColorRes resId: Int) : Int = ContextCompat.getColor(requireContext(), resId)
fun Fragment.drawable(@DrawableRes resId: Int) : Drawable? = ContextCompat.getDrawable(requireContext(), resId)
fun Fragment.dimenPixelSize(@DimenRes resId: Int): Int = resources.getDimensionPixelSize(resId)
fun Fragment.dimen(@DimenRes resId: Int): Float = resources.getDimension(resId)
fun Fragment.int(@IntegerRes resId: Int): Int = resources.getInteger(resId)
fun Fragment.quantity(@PluralsRes resId: Int, count: Int, vararg args: Any): String = resources.getQuantityString(resId, count, *args)
fun Context.smallestWidth(config: ScreenUtils.Config): Boolean = ScreenUtils.smallestWidth(this.resources, config)
@Suppress("UNCHECKED_CAST")
fun <T> Context.systemService(name: String): Lazy<T> = lazy {
this.getSystemService(name) as T
}
@Suppress("UNCHECKED_CAST")
fun <T> Fragment.systemService(name: String): Lazy<T> = lazy {
requireContext().getSystemService(name) as T
}
fun Context.getMetaData(): Bundle? {
val appInfo = this.packageManager.getApplicationInfo(this.packageName, PackageManager.GET_META_DATA)
return appInfo?.metaData
}
@Suppress("UNCHECKED_CAST")
fun <T> Context.getMetaData(name: String): T? {
val appInfo = this.packageManager.getApplicationInfo(this.packageName, PackageManager.GET_META_DATA)
return appInfo?.metaData?.get(name)?.let { it as? T }
}
|
apache-2.0
|
a4cc394814e917ee8161d77ff2194ad3
| 52.590909 | 134 | 0.773325 | 3.862408 | false | false | false | false |
jsocle/jsocle-html2jsocle
|
src/main/kotlin/com/github/jsocle/html2jsocle/App.kt
|
1
|
1641
|
package com.github.jsocle.html2jsocle
import com.github.jsocle.JSocle
import com.github.jsocle.html.elements.Html
import com.github.jsocle.html.elements.Label
import com.github.jsocle.request
import com.github.jsocle.requests.handlers.RequestHandler0
object App : JSocle() {
val index: RequestHandler0<Html> = route("/") { ->
val html = request.parameter("html")?.trim() ?: ""
var language = request.parameter("language")
if (language == null) language = "kotlin"
val includeBody = request.parameter("includeBody") != null
val kt = if (html.length() == 0) "" else if (language == "kotlin") convert(html, includeBody = includeBody) else convertJava(html, includeBody = includeBody)
return@route Html {
body {
form(method = "post", action = index.url()) {
input(type = "radio", name = "language", value = "kotlin", checked = if (language == "kotlin") "true" else null)
+Label("Kotlin")
input(type = "radio", name = "language", value = "java", checked = if (language == "java") "true" else null)
+Label("Java")
br()
textarea(name = "html", text_ = html, style = "width:500px; height:400px")
input(type = "checkbox", name = "includeBody", value = "includeBody", checked = if (includeBody) "true" else null)
button(text_ = "convert")
pre(text_ = kt)
}
}
}
}
@JvmStatic fun main(args: Array<String>) {
run(Config.port)
}
}
|
mit
|
23fe63643cfa8cfb6f24e3d1d7f83de7
| 39.02439 | 165 | 0.561853 | 3.935252 | false | false | false | false |
anlun/haskell-idea-plugin
|
plugin/src/org/jetbrains/grammar/dumb/Term.kt
|
1
|
860
|
package org.jetbrains.grammar.dumb
import org.jetbrains.haskell.parser.HaskellTokenType
/**
* Created by atsky on 14/11/14.
*/
open class Term {
}
public class Terminal(val tokenType: HaskellTokenType) : Term() {
override fun toString(): String {
return "'" + tokenType.myName + "'"
}
override fun equals(other: Any?): Boolean {
if (other !is Terminal) {
return false
}
return tokenType == other.tokenType
}
override fun hashCode() = tokenType.hashCode()
}
public class NonTerminal(val rule: String) : Term() {
override fun toString(): String {
return rule
}
override fun equals(other: Any?): Boolean {
if (other !is NonTerminal) {
return false
}
return rule == other.rule
}
override fun hashCode() = rule.hashCode()
}
|
apache-2.0
|
392490f4f5b0cd7f1ae2cf7b36ff9356
| 19.023256 | 65 | 0.605814 | 4.278607 | false | false | false | false |
TCA-Team/TumCampusApp
|
app/src/main/java/de/tum/in/tumcampusapp/component/ui/chat/ChatMessagesCard.kt
|
1
|
3645
|
package de.tum.`in`.tumcampusapp.component.ui.chat
import android.content.Context
import android.content.SharedPreferences.Editor
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.other.navigation.NavDestination
import de.tum.`in`.tumcampusapp.component.ui.chat.activity.ChatActivity
import de.tum.`in`.tumcampusapp.component.ui.chat.model.ChatMessage
import de.tum.`in`.tumcampusapp.component.ui.chat.model.ChatRoom
import de.tum.`in`.tumcampusapp.component.ui.chat.model.ChatRoomDbRow
import de.tum.`in`.tumcampusapp.component.ui.overview.CardInteractionListener
import de.tum.`in`.tumcampusapp.component.ui.overview.CardManager.CARD_CHAT
import de.tum.`in`.tumcampusapp.component.ui.overview.card.Card
import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder
import de.tum.`in`.tumcampusapp.database.TcaDb
import de.tum.`in`.tumcampusapp.utils.Const
import java.util.ArrayList
/**
* Card that shows the cafeteria menu
*/
class ChatMessagesCard(
context: Context,
room: ChatRoomDbRow
) : Card(CARD_CHAT, context, "card_chat") {
private var mUnread: List<ChatMessage> = ArrayList()
private var nrUnread = 0
private var mRoomName = ""
private var mRoomId = 0
private var mRoomIdString = ""
private val chatMessageDao: ChatMessageDao
override val optionsMenuResId: Int
get() = R.menu.card_popup_menu
init {
val tcaDb = TcaDb.getInstance(context)
chatMessageDao = tcaDb.chatMessageDao()
setChatRoom(room.name, room.room, "${room.semesterId}:${room.name}")
}
override fun updateViewHolder(viewHolder: RecyclerView.ViewHolder) {
super.updateViewHolder(viewHolder)
val chatMessagesViewHolder = viewHolder as? ChatMessagesCardViewHolder
chatMessagesViewHolder?.bind(mRoomName, mRoomId, mRoomIdString, mUnread)
}
/**
* Sets the information needed to build the card
*
* @param roomName Name of the chat room
* @param roomId Id of the chat room
*/
private fun setChatRoom(roomName: String, roomId: Int, roomIdString: String) {
mRoomName = listOf("[A-Z, 0-9(LV\\.Nr)=]+$", "\\([A-Z]+[0-9]+\\)", "\\[[A-Z]+[0-9]+\\]")
.map { it.toRegex() }
.fold(roomName) { name, regex -> name.replace(regex, "") }
.trim()
chatMessageDao.deleteOldEntries()
nrUnread = chatMessageDao.getNumberUnread(roomId)
mUnread = chatMessageDao.getLastUnread(roomId).asReversed()
mRoomIdString = roomIdString
mRoomId = roomId
}
override fun getNavigationDestination(): NavDestination? {
val bundle = Bundle().apply {
val chatRoom = ChatRoom(mRoomIdString).apply { id = mRoomId }
val value = Gson().toJson(chatRoom)
putString(Const.CURRENT_CHAT_ROOM, value)
}
return NavDestination.Activity(ChatActivity::class.java, bundle)
}
override fun getId() = mRoomId
override fun discard(editor: Editor) = chatMessageDao.markAsRead(mRoomId)
companion object {
@JvmStatic
fun inflateViewHolder(
parent: ViewGroup,
interactionListener: CardInteractionListener
): CardViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.card_chat_messages, parent, false)
return ChatMessagesCardViewHolder(view, interactionListener)
}
}
}
|
gpl-3.0
|
1f37392db0ba2346ad7cbb32b6cb8ea3
| 36.193878 | 96 | 0.69273 | 4.204152 | false | false | false | false |
westnordost/osmagent
|
app/src/main/java/de/westnordost/streetcomplete/quests/note_discussion/NoteDiscussionForm.kt
|
1
|
6768
|
package de.westnordost.streetcomplete.quests.note_discussion
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.format.DateUtils
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import java.io.File
import java.util.Date
import javax.inject.Inject
import de.westnordost.streetcomplete.Injector
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.OsmModule
import de.westnordost.streetcomplete.data.osmnotes.OsmNoteQuestDao
import de.westnordost.streetcomplete.quests.AbstractQuestAnswerFragment
import de.westnordost.osmapi.notes.NoteComment
import de.westnordost.streetcomplete.util.BitmapUtil
import de.westnordost.streetcomplete.util.TextChangedWatcher
import de.westnordost.streetcomplete.view.ListAdapter
import android.text.format.DateUtils.MINUTE_IN_MILLIS
import kotlinx.android.synthetic.main.fragment_quest_answer.*
import kotlinx.android.synthetic.main.quest_buttonpanel_note_discussion.*
import kotlinx.android.synthetic.main.quest_note_discussion_content.*
class NoteDiscussionForm : AbstractQuestAnswerFragment<NoteAnswer>() {
override val contentLayoutResId = R.layout.quest_note_discussion_content
override val buttonsResId = R.layout.quest_buttonpanel_note_discussion
private lateinit var anonAvatar: Bitmap
@Inject internal lateinit var noteDb: OsmNoteQuestDao
private val attachPhotoFragment get() =
childFragmentManager.findFragmentById(R.id.attachPhotoFragment) as? AttachPhotoFragment
private val noteText: String get() = noteInput?.text?.toString().orEmpty().trim()
init {
Injector.instance.applicationComponent.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
doneButton.setOnClickListener { onClickOk() }
noButton.setOnClickListener { skipQuest() }
noteInput.addTextChangedListener(TextChangedWatcher { updateDoneButtonEnablement() })
otherAnswersButton.visibility = View.GONE
updateDoneButtonEnablement()
anonAvatar = BitmapUtil.createBitmapFrom(resources.getDrawable(R.drawable.ic_osm_anon_avatar))
inflateNoteDiscussion(noteDb.get(questId).note.comments)
if (savedInstanceState == null) {
childFragmentManager.beginTransaction()
.add(R.id.attachPhotoFragment, AttachPhotoFragment())
.commit()
}
}
private fun inflateNoteDiscussion(comments: List<NoteComment>) {
val discussionView = layoutInflater.inflate(R.layout.quest_note_discussion_items, scrollViewChild, false) as RecyclerView
discussionView.isNestedScrollingEnabled = false
discussionView.layoutManager = LinearLayoutManager(
context,
RecyclerView.VERTICAL,
false
)
discussionView.adapter = NoteCommentListAdapter(comments)
scrollViewChild.addView(discussionView, 0)
}
private fun onClickOk() {
applyAnswer(NoteAnswer(noteText, attachPhotoFragment?.imagePaths))
}
public override fun onDiscard() {
attachPhotoFragment?.deleteImages()
}
override fun isRejectingClose(): Boolean {
val f = attachPhotoFragment
val hasPhotos = f != null && !f.imagePaths.isEmpty()
return hasPhotos || noteText.isNotEmpty()
}
private fun updateDoneButtonEnablement() {
doneButton.isEnabled = noteText.isNotEmpty()
}
private inner class NoteCommentListAdapter(list: List<NoteComment>) :
ListAdapter<NoteComment>(list) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListAdapter.ViewHolder<NoteComment> {
return NoteCommentViewHolder(
layoutInflater.inflate(R.layout.quest_note_discussion_item, parent, false)
)
}
}
private inner class NoteCommentViewHolder(itemView: View) :
ListAdapter.ViewHolder<NoteComment>(itemView) {
private val commentContainer: ViewGroup = itemView.findViewById(R.id.commentView)
private val commentAvatar: ImageView = itemView.findViewById(R.id.commentAvatarImage)
private val commentText: TextView = itemView.findViewById(R.id.commentText)
private val commentInfo: TextView = itemView.findViewById(R.id.commentInfoText)
private val commentStatusText: TextView = itemView.findViewById(R.id.commentStatusText)
override fun onBind(with: NoteComment) {
val comment = with
val dateDescription = DateUtils.getRelativeTimeSpanString(comment.date.time, Date().time, MINUTE_IN_MILLIS)
val userName = if (comment.user != null) comment.user.displayName else getString(R.string.quest_noteDiscussion_anonymous)
val commentActionResourceId = comment.action.actionResourceId
if (commentActionResourceId != 0) {
commentStatusText.visibility = View.VISIBLE
commentStatusText.text = getString(commentActionResourceId, userName, dateDescription)
} else {
commentStatusText.visibility = View.GONE
}
if (!comment.text.isNullOrEmpty()) {
commentContainer.visibility = View.VISIBLE
commentText.text = comment.text
commentInfo.text = getString(R.string.quest_noteDiscussion_comment2, userName, dateDescription)
var bitmap = anonAvatar
if (comment.user != null) {
val avatarFile = File(OsmModule.getAvatarsCacheDirectory(context!!).toString() + File.separator + comment.user.id)
if (avatarFile.exists()) {
bitmap = BitmapFactory.decodeFile(avatarFile.path)
}
}
val avatarDrawable = RoundedBitmapDrawableFactory.create(resources, bitmap)
avatarDrawable.isCircular = true
commentAvatar.setImageDrawable(avatarDrawable)
} else {
commentContainer.visibility = View.GONE
}
}
private val NoteComment.Action.actionResourceId get() = when (this) {
NoteComment.Action.CLOSED -> R.string.quest_noteDiscussion_closed2
NoteComment.Action.REOPENED -> R.string.quest_noteDiscussion_reopen2
NoteComment.Action.HIDDEN -> R.string.quest_noteDiscussion_hide2
else -> 0
}
}
}
|
gpl-3.0
|
97f665d950717b3e63261e995088b99d
| 39.047337 | 134 | 0.707742 | 4.980132 | false | false | false | false |
westnordost/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/quests/car_wash_type/AddCarWashType.kt
|
1
|
1325
|
package de.westnordost.streetcomplete.quests.car_wash_type
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.car_wash_type.CarWashType.*
class AddCarWashType : OsmFilterQuestType<List<CarWashType>>() {
override val elementFilter = "nodes, ways with amenity = car_wash and !automated and !self_service"
override val commitMessage = "Add car wash type"
override val wikiLink = "Tag:amenity=car_wash"
override val icon = R.drawable.ic_quest_car_wash
override fun getTitle(tags: Map<String, String>) = R.string.quest_carWashType_title
override fun createForm() = AddCarWashTypeForm()
override fun applyAnswerTo(answer: List<CarWashType>, changes: StringMapChangesBuilder) {
val isAutomated = answer.contains(AUTOMATED)
changes.add("automated", isAutomated.toYesNo())
val hasSelfService = answer.contains(SELF_SERVICE)
val selfService = when {
hasSelfService && answer.size == 1 -> "only"
hasSelfService -> "yes"
else -> "no"
}
changes.add("self_service", selfService)
}
}
|
gpl-3.0
|
2a7598ba3cecf9953653f56df3bb85cb
| 40.40625 | 103 | 0.727547 | 4.206349 | false | false | false | false |
HabitRPG/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/utils/NotificationDeserializer.kt
|
1
|
1130
|
package com.habitrpg.android.habitica.utils
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonParseException
import com.habitrpg.common.habitica.models.Notification
import java.lang.reflect.Type
class NotificationDeserializer : JsonDeserializer<Notification> {
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Notification {
val notification = Notification()
val obj = json.asJsonObject
if (obj.has("id")) {
notification.id = obj.get("id").asString
}
if (obj.has("type")) {
notification.type = obj.get("type").asString
}
if (obj.has("seen")) {
notification.seen = obj.get("seen").asBoolean
}
val dataType = notification.getDataType()
if (obj.has("data") && dataType != null) {
notification.data = context.deserialize(obj.getAsJsonObject("data"), dataType)
}
return notification
}
}
|
gpl-3.0
|
1183f4f86ee90848ec70c3e329e9b29f
| 31.285714 | 115 | 0.672566 | 4.650206 | false | false | false | false |
westnordost/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/data/osm/mapdata/NodeTable.kt
|
1
|
609
|
package de.westnordost.streetcomplete.data.osm.mapdata
object NodeTable {
const val NAME = "osm_nodes"
object Columns {
const val ID = "id"
const val LATITUDE = "latitude"
const val LONGITUDE = "longitude"
const val VERSION = "version"
const val TAGS = "tags"
}
const val CREATE = """
CREATE TABLE $NAME (
${Columns.ID} int PRIMARY KEY,
${Columns.VERSION} int NOT NULL,
${Columns.LATITUDE} double NOT NULL,
${Columns.LONGITUDE} double NOT NULL,
${Columns.TAGS} blob
);"""
}
|
gpl-3.0
|
33ec8e8787337de1740c78d01e83ffab
| 26.681818 | 54 | 0.563218 | 4.319149 | false | false | false | false |
jiaminglu/kotlin-native
|
backend.native/tests/lower/tailrec.kt
|
1
|
2044
|
fun main(args: Array<String>) {
println(add(5, 7))
println(add(100000000, 0))
println(fib(6))
println(one(5))
countdown(3)
println(listOf(1, 2, 3).indexOf(3))
println(listOf(1, 2, 3).indexOf(4))
println(Integer(5).isLessOrEqualThan(7))
println(Integer(42).isLessOrEqualThan(1))
println(DefaultArgGetter().foo("non-default"))
println(EitherDelegatedOrNot(NotDelegated()).get42())
}
tailrec fun add(x: Int, y: Int): Int = if (x > 0) add(x - 1, y + 1) else y
fun fib(n: Int): Int {
tailrec fun fibAcc(n: Int, acc: Int): Int = if (n < 2) {
n + acc
} else {
fibAcc(n - 1, fibAcc(n - 2, acc))
}
return fibAcc(n, 0)
}
tailrec fun one(delay: Int, result: Int = delay + 1): Int = if (delay > 0) one(delay - 1) else result
tailrec fun countdown(iterations: Int): Unit {
if (iterations > 0) {
println("$iterations ...")
countdown(iterations - 1)
} else {
println("ready!")
}
}
tailrec fun <T> List<T>.indexOf(x: T, startIndex: Int = 0): Int {
if (startIndex >= this.size) {
return -1
}
if (this[startIndex] != x) {
return this.indexOf(x, startIndex + 1)
}
return startIndex
}
open class Integer(val value: Int) {
open tailrec fun isLessOrEqualThan(value: Int): Boolean {
if (this.value == value) {
return true
} else if (value > 0) {
return this.isLessOrEqualThan(value - 1)
} else {
return false
}
}
}
open class DefaultArgHolder {
open fun foo(s: String = "default") = s
}
class DefaultArgGetter : DefaultArgHolder() {
override tailrec fun foo(s: String): String {
return if (s == "default") s else foo()
}
}
open class EitherDelegatedOrNot(val delegate: EitherDelegatedOrNot?) {
open tailrec fun get42(): Int = if (delegate != null) {
delegate.get42()
} else {
throw Error()
}
}
class NotDelegated : EitherDelegatedOrNot(null) {
override fun get42() = 42
}
|
apache-2.0
|
85308e341eb4234f5d0a08647cfa8bc4
| 21.977528 | 101 | 0.583659 | 3.42953 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android
|
my_library_framework/src/main/java/com/vmenon/mpo/my_library/framework/RoomShowPersistenceDataSource.kt
|
1
|
1908
|
package com.vmenon.mpo.my_library.framework
import com.vmenon.mpo.my_library.data.ShowPersistenceDataSource
import com.vmenon.mpo.my_library.domain.ShowModel
import com.vmenon.mpo.persistence.room.dao.ShowDao
import com.vmenon.mpo.persistence.room.entity.ShowDetailsEntity
import com.vmenon.mpo.persistence.room.entity.ShowEntity
class RoomShowPersistenceDataSource(private val showDao: ShowDao) : ShowPersistenceDataSource {
override suspend fun insertOrUpdate(showModel: ShowModel): ShowModel =
showDao.insertOrUpdate(showModel.toEntity()).toModel()
override suspend fun getByName(name: String): ShowModel? = showDao.getByName(name)?.toModel()
override suspend fun getSubscribed(): List<ShowModel> =
showDao.getSubscribed().map { entity -> entity.toModel() }
override suspend fun getSubscribedAndLastUpdatedBefore(comparisonTime: Long): List<ShowModel> =
showDao.getSubscribedAndLastUpdatedBefore(comparisonTime).map { entity -> entity.toModel() }
private fun ShowEntity.toModel() = ShowModel(
id = showId,
name = details.showName,
artworkUrl = details.showArtworkUrl,
genres = details.genres,
feedUrl = details.feedUrl,
description = details.showDescription,
author = details.author,
isSubscribed = details.isSubscribed,
lastEpisodePublished = details.lastEpisodePublished,
lastUpdate = details.lastUpdate
)
private fun ShowModel.toEntity() = ShowEntity(
details = ShowDetailsEntity(
showName = name,
showDescription = description,
showArtworkUrl = artworkUrl,
lastUpdate = lastUpdate,
lastEpisodePublished = lastEpisodePublished,
isSubscribed = isSubscribed,
author = author,
feedUrl = feedUrl,
genres = genres
),
showId = id
)
}
|
apache-2.0
|
dfe2a8b3d58c53645e58a28c2d39dc71
| 38.770833 | 100 | 0.697589 | 4.653659 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android
|
persistence_room/src/main/java/com/vmenon/mpo/persistence/room/entity/ShowSearchResultsEntity.kt
|
1
|
826
|
package com.vmenon.mpo.persistence.room.entity
import androidx.room.*
@Entity(
indices = [
Index(value = ["showName"]),
Index("showSearchResultsSearchId")
],
tableName = "showSearchResults",
foreignKeys = [ForeignKey(
entity = ShowSearchEntity::class,
parentColumns = arrayOf("showSearchId"),
childColumns = arrayOf("showSearchResultsSearchId")
)]
)
data class ShowSearchResultsEntity(
val showName: String,
val showArtworkUrl: String?,
val genres: List<String>,
val author: String,
val feedUrl: String,
val showDescription: String,
val lastUpdate: Long,
val lastEpisodePublished: Long,
val isSubscribed: Boolean,
@PrimaryKey(autoGenerate = true)
val showSearchResultsId: Long,
val showSearchResultsSearchId: Long
)
|
apache-2.0
|
cf425605f9572c7023f7c71df69dfeb2
| 26.533333 | 59 | 0.684019 | 4.563536 | false | false | false | false |
googlecodelabs/android-people
|
app/src/main/java/com/example/android/people/ui/main/ContactAdapter.kt
|
2
|
2425
|
/*
* Copyright (C) 2020 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.people.ui.main
import android.graphics.drawable.Icon
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.android.people.R
import com.example.android.people.data.Contact
import com.example.android.people.databinding.ChatItemBinding
class ContactAdapter(
private val onChatClicked: (id: Long) -> Unit
) : ListAdapter<Contact, ContactViewHolder>(DIFF_CALLBACK) {
init {
setHasStableIds(true)
}
override fun getItemId(position: Int): Long {
return getItem(position).id
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactViewHolder {
val holder = ContactViewHolder(parent)
holder.itemView.setOnClickListener {
onChatClicked(holder.itemId)
}
return holder
}
override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
val contact: Contact = getItem(position)
holder.binding.icon.setImageIcon(Icon.createWithAdaptiveBitmapContentUri(contact.iconUri))
holder.binding.name.text = contact.name
}
}
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Contact>() {
override fun areItemsTheSame(oldItem: Contact, newItem: Contact): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Contact, newItem: Contact): Boolean {
return oldItem == newItem
}
}
class ContactViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.chat_item, parent, false)
) {
val binding: ChatItemBinding = ChatItemBinding.bind(itemView)
}
|
apache-2.0
|
816a3ee7c2311209ef6a118f83c9d443
| 34.144928 | 98 | 0.739381 | 4.433272 | false | false | false | false |
exponentjs/exponent
|
packages/expo-clipboard/android/src/main/java/expo/modules/clipboard/ClipboardEventEmitter.kt
|
2
|
1531
|
package expo.modules.clipboard
import android.content.Context
import android.content.ClipboardManager
import android.os.Bundle
import android.util.Log
import expo.modules.core.ModuleRegistry
import expo.modules.core.interfaces.LifecycleEventListener
import expo.modules.core.interfaces.services.EventEmitter
import expo.modules.core.interfaces.services.UIManager
class ClipboardEventEmitter(context: Context, moduleRegistry: ModuleRegistry) : LifecycleEventListener {
private val onClipboardEventName = "onClipboardChanged"
private var isListening = true
private var eventEmitter = moduleRegistry.getModule(EventEmitter::class.java)
init {
moduleRegistry.getModule(UIManager::class.java).registerLifecycleEventListener(this)
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
if (clipboard == null) {
Log.e("Clipboard", "CLIPBOARD_SERVICE unavailable. Events wont be received")
} else {
clipboard.addPrimaryClipChangedListener {
if (isListening) {
val clip = clipboard.primaryClip
if (clip != null && clip.itemCount >= 1) {
eventEmitter.emit(
onClipboardEventName,
Bundle().apply {
putString("content", clip.getItemAt(0).text.toString())
}
)
}
}
}
}
}
override fun onHostResume() {
isListening = true
}
override fun onHostPause() {
isListening = false
}
override fun onHostDestroy() = Unit
}
|
bsd-3-clause
|
46e6b2696646511839fd54215817d72b
| 30.244898 | 104 | 0.702809 | 4.875796 | false | false | false | false |
weitjong/Urho3D
|
android/launcher-app/src/main/java/com/github/urho3d/launcher/LauncherActivity.kt
|
2
|
4136
|
//
// Copyright (c) 2008-2020 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
package com.github.urho3d.launcher
import android.app.ExpandableListActivity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ExpandableListView
import android.widget.SimpleExpandableListAdapter
import com.github.urho3d.UrhoActivity
class LauncherActivity : ExpandableListActivity() {
// Filter to only include filename that has an extension
private fun getScriptNames(path: String) = assets.list(path)!!.filter { it.contains('.') }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Only the sample library is selectable, excluding Urho3DPlayer which is handled separately
val regex = Regex("^(?:Urho3D.*|.+_shared)\$")
val libraryNames = UrhoActivity.getLibraryNames(this)
val items = mutableMapOf("C++" to libraryNames.filterNot { regex.matches(it) }.sorted())
if (libraryNames.find { it == "Urho3DPlayer" } != null) {
items.putAll(mapOf(
// FIXME: Should not assume both scripting subsystems are enabled in the build
"AngelScript" to getScriptNames("Data/Scripts"),
"Lua" to getScriptNames("Data/LuaScripts")
))
}
items.filterValues { it.isEmpty() }.forEach { items.remove(it.key) }
setListAdapter(SimpleExpandableListAdapter(this,
items.map {
mapOf("api" to it.key, "info" to "Click to expand/collapse")
},
android.R.layout.simple_expandable_list_item_2,
arrayOf("api", "info"),
intArrayOf(android.R.id.text1, android.R.id.text2),
items.map {
it.value.map { name ->
mapOf("item" to name)
}
},
R.layout.launcher_list_item,
arrayOf("item"),
intArrayOf(android.R.id.text1)
))
setContentView(R.layout.activity_launcher)
// Pass the argument to the main activity, if any
launch(intent.getStringExtra(MainActivity.argument))
}
override fun onChildClick(parent: ExpandableListView?, v: View?, groupPos: Int, childPos: Int,
id: Long): Boolean {
@Suppress("UNCHECKED_CAST")
launch((expandableListAdapter.getChild(groupPos, childPos) as Map<String, String>)["item"])
return true
}
private fun launch(argument: String?) {
if (argument != null) {
startActivity(Intent(this, MainActivity::class.java)
.putExtra(MainActivity.argument,
if (argument.contains('.')) {
if (argument.endsWith(".as")) "Urho3DPlayer:Scripts/$argument"
else "Urho3DPlayer:LuaScripts/$argument"
} else argument
)
)
}
}
}
|
mit
|
e1c8fb9c260cdbccf82f9ad93647345f
| 42.083333 | 100 | 0.630077 | 4.684032 | false | false | false | false |
ThoseGrapefruits/intellij-rust
|
src/main/kotlin/org/rust/lang/colorscheme/RustColors.kt
|
1
|
2320
|
package org.rust.lang.colorscheme
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
object RustColors {
private fun r(id: String, attrKey: TextAttributesKey) =
TextAttributesKey.createTextAttributesKey(id, attrKey)
val IDENTIFIER = r("org.rust.IDENTIFIER", DefaultLanguageHighlighterColors.IDENTIFIER)
val LIFETIME = r("org.rust.LIFETIME", DefaultLanguageHighlighterColors.IDENTIFIER)
val CHAR = r("org.rust.CHAR", DefaultLanguageHighlighterColors.STRING)
val STRING = r("org.rust.STRING", DefaultLanguageHighlighterColors.STRING)
val NUMBER = r("org.rust.NUMBER", DefaultLanguageHighlighterColors.NUMBER)
val KEYWORD = r("org.rust.KEYWORD", DefaultLanguageHighlighterColors.KEYWORD)
val BLOCK_COMMENT = r("org.rust.BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT)
val EOL_COMMENT = r("org.rust.EOL_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT)
val DOC_COMMENT = r("org.rust.DOC_COMMENT", DefaultLanguageHighlighterColors.DOC_COMMENT)
val PARENTHESIS = r("org.rust.PARENTHESIS", DefaultLanguageHighlighterColors.PARENTHESES)
val BRACKETS = r("org.rust.BRACKETS", DefaultLanguageHighlighterColors.BRACKETS)
val BRACES = r("org.rust.BRACES", DefaultLanguageHighlighterColors.BRACES)
val OPERATORS = r("org.rust.OPERATORS", DefaultLanguageHighlighterColors.OPERATION_SIGN)
val SEMICOLON = r("org.rust.SEMICOLON", DefaultLanguageHighlighterColors.SEMICOLON)
val DOT = r("org.rust.DOT", DefaultLanguageHighlighterColors.DOT)
val COMMA = r("org.rust.COMMA", DefaultLanguageHighlighterColors.COMMA)
val ATTRIBUTE = r("org.rust.ATTRIBUTE", DefaultLanguageHighlighterColors.METADATA)
val MACRO = r("org.rust.MACRO", DefaultLanguageHighlighterColors.IDENTIFIER)
val TYPE_PARAMETER = r("org.rust.TYPE_PARAMETER", DefaultLanguageHighlighterColors.IDENTIFIER)
val MUT_BINDING = r("org.rust.MUT_BINDING", DefaultLanguageHighlighterColors.IDENTIFIER)
}
|
mit
|
d22281645d925ae18b1139d977c540f0
| 55.585366 | 104 | 0.69181 | 5.010799 | false | false | false | false |
just-4-fun/holomorph
|
src/test/kotlin/just4fun/holomorph/debug.kt
|
1
|
1116
|
package just4fun.holomorph
fun <T> measureTime(tag: String = "", times: Int = 1, warmup: Boolean = true, antiSurgeRate:Double = .0, code: () -> T): T {
// warm-up
var prevTime = 0L
if (warmup) {
val ratioMax = 5f / 4f
var count = 0
do {
val t0 = System.nanoTime()
code()
val time = System.nanoTime() - t0
val ratio = prevTime / time.toDouble()
// if (ratio < 1) println("Warmup $count; recent= $prevTime; curr= $time; ratio= $ratio")
prevTime = time
} while (count++ < 2 || ratio > ratioMax)
}
//
var result: T
var count = times
var t = 0L
var t1 = 0L
do {
val t0 = System.nanoTime()
result = code()
t1 = System.nanoTime() - t0
if (antiSurgeRate > 0 && prevTime > 0 && t1 >= prevTime*antiSurgeRate) continue // against extreme surges @ by java class newInstance()
t += t1
prevTime = t1
count--
} while (count > 0)
println("$tag :: $times times; ${t / 1000000} ms; $t ns; ${t / times} ns/call")
totalNs += t
totalN++
return result
}
private var totalNs = 0L
private var totalN = 0
val measuredTimeAvg get() = if (totalN == 0) 0 else totalNs / totalN
|
apache-2.0
|
7df54dc9f7a77e8267016043c278573b
| 24.953488 | 137 | 0.616487 | 2.748768 | false | false | false | false |
Hexworks/zircon
|
zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/api/application/AppConfigTest.kt
|
1
|
3007
|
package org.hexworks.zircon.api.application
import org.assertj.core.api.Assertions.assertThat
import org.hexworks.zircon.api.builder.application.AppConfigBuilder
import org.hexworks.zircon.api.color.ANSITileColor
import org.junit.Test
private object TestAppConfigKey : AppConfigKey<String>
private object TestAppConfigKey2 : AppConfigKey<String>
class AppConfigTest {
@Test
fun shouldProperlySetValues() {
val target = AppConfigBuilder.newBuilder()
.withBlinkLengthInMilliSeconds(BLINK_TIME)
.withClipboardAvailable(HAS_CLIPBOARD)
.withCursorBlinking(IS_BLINKING)
.withCursorColor(CURSOR_COLOR)
.withCursorStyle(CURSOR_STYLE)
.build()
assertThat(target.blinkLengthInMilliSeconds)
.isEqualTo(BLINK_TIME)
assertThat(target.cursorStyle)
.isEqualTo(CURSOR_STYLE)
assertThat(target.cursorColor)
.isEqualTo(CURSOR_COLOR)
assertThat(target.isCursorBlinking)
.isEqualTo(IS_BLINKING)
assertThat(target.isClipboardAvailable)
.isEqualTo(HAS_CLIPBOARD)
}
@Test
fun propertyUnset() {
val appConfig = AppConfigBuilder.newBuilder().build()
assertThat(appConfig.getOrNull(TestAppConfigKey))
.isNull()
}
@Test
fun propertySet() {
val appConfig = AppConfigBuilder.newBuilder()
.withProperty(TestAppConfigKey, "foo")
.build()
assertThat(appConfig.getOrNull(TestAppConfigKey))
.isEqualTo("foo")
}
@Test
fun propertyOverwrite() {
val appConfig = AppConfigBuilder.newBuilder()
.withProperty(TestAppConfigKey, "foo")
.withProperty(TestAppConfigKey, "bar")
.build()
assertThat(appConfig.getOrNull(TestAppConfigKey))
.isEqualTo("bar")
}
@Test
fun propertyMultiple() {
val appConfig = AppConfigBuilder.newBuilder()
.withProperty(TestAppConfigKey, "foo")
.withProperty(TestAppConfigKey2, "bar")
.build()
assertThat(appConfig.getOrNull(TestAppConfigKey))
.isEqualTo("foo")
assertThat(appConfig.getOrNull(TestAppConfigKey2))
.isEqualTo("bar")
}
@Test
fun propertyExample() {
// Plugin API
val key = object : AppConfigKey<Int> {} // use a real internal or private `object`, not an anonymous one!
fun AppConfigBuilder.enableCoolFeature() = also { withProperty(key, 42) }
// User code
val appConfig = AppConfigBuilder.newBuilder()
.enableCoolFeature()
.build()
// Plugin internals
assertThat(appConfig.getOrNull(key))
.isEqualTo(42)
}
companion object {
val BLINK_TIME = 5L
val CURSOR_STYLE = CursorStyle.UNDER_BAR
val CURSOR_COLOR = ANSITileColor.GREEN
val IS_BLINKING = true
val HAS_CLIPBOARD = true
}
}
|
apache-2.0
|
4f311652171ee2d48f3c2fb8cf9c0306
| 30.322917 | 113 | 0.633522 | 4.626154 | false | true | false | false |
JetBrains/ideavim
|
src/main/java/com/maddyhome/idea/vim/extension/matchit/Matchit.kt
|
1
|
25786
|
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.extension.matchit
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.elementType
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.getLineEndForOffset
import com.maddyhome.idea.vim.api.getLineEndOffset
import com.maddyhome.idea.vim.api.getLineStartForOffset
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.api.normalizeOffset
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.command.MotionType
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.common.Direction
import com.maddyhome.idea.vim.extension.ExtensionHandler
import com.maddyhome.idea.vim.extension.VimExtension
import com.maddyhome.idea.vim.extension.VimExtensionFacade
import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingIfMissing
import com.maddyhome.idea.vim.handler.Motion
import com.maddyhome.idea.vim.handler.MotionActionHandler
import com.maddyhome.idea.vim.handler.toMotionOrError
import com.maddyhome.idea.vim.helper.EditorHelper
import com.maddyhome.idea.vim.helper.PsiHelper
import com.maddyhome.idea.vim.helper.enumSetOf
import com.maddyhome.idea.vim.helper.vimStateMachine
import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim
import java.util.*
import java.util.regex.Pattern
/**
* Port of matchit.vim (https://github.com/chrisbra/matchit)
* @author Martin Yzeiri (@myzeiri)
*/
class Matchit : VimExtension {
override fun getName(): String = "matchit"
override fun init() {
VimExtensionFacade.putExtensionHandlerMapping(MappingMode.NXO, injector.parser.parseKeys("<Plug>(MatchitMotion)"), owner, MatchitHandler(false), false)
VimExtensionFacade.putExtensionHandlerMapping(MappingMode.NXO, injector.parser.parseKeys("<Plug>(MatchitMotion)"), owner, MatchitHandler(false), false)
putKeyMappingIfMissing(MappingMode.NXO, injector.parser.parseKeys("%"), owner, injector.parser.parseKeys("<Plug>(MatchitMotion)"), true)
VimExtensionFacade.putExtensionHandlerMapping(MappingMode.NXO, injector.parser.parseKeys("<Plug>(ReverseMatchitMotion)"), owner, MatchitHandler(true), false)
VimExtensionFacade.putExtensionHandlerMapping(MappingMode.NXO, injector.parser.parseKeys("<Plug>(ReverseMatchitMotion)"), owner, MatchitHandler(true), false)
putKeyMappingIfMissing(MappingMode.NXO, injector.parser.parseKeys("g%"), owner, injector.parser.parseKeys("<Plug>(ReverseMatchitMotion)"), true)
}
private class MatchitAction : MotionActionHandler.ForEachCaret() {
var reverse = false
var isInOpPending = false
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_SAVE_JUMP)
override fun getOffset(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments,
): Motion {
return getMatchitOffset(editor.ij, caret.ij, operatorArguments.count0, isInOpPending, reverse).toMotionOrError()
}
override fun process(cmd: Command) {
motionType = if (cmd.rawCount != 0) MotionType.LINE_WISE else MotionType.INCLUSIVE
}
override var motionType: MotionType = MotionType.INCLUSIVE
}
private class MatchitHandler(private val reverse: Boolean) : ExtensionHandler {
override fun execute(editor: VimEditor, context: ExecutionContext) {
val commandState = editor.vimStateMachine
val count = commandState.commandBuilder.count
// Reset the command count so it doesn't transfer onto subsequent commands.
editor.vimStateMachine.commandBuilder.resetCount()
// Normally we want to jump to the start of the matching pair. But when moving forward in operator
// pending mode, we want to include the entire match. isInOpPending makes that distinction.
val isInOpPending = commandState.isOperatorPending
if (isInOpPending) {
val matchitAction = MatchitAction()
matchitAction.reverse = reverse
matchitAction.isInOpPending = true
commandState.commandBuilder.completeCommandPart(
Argument(
Command(
count,
matchitAction, Command.Type.MOTION, EnumSet.noneOf(CommandFlags::class.java)
)
)
)
} else {
editor.forEachCaret { caret ->
VimPlugin.getMark().saveJumpLocation(editor)
caret.moveToOffset(getMatchitOffset(editor.ij, caret.ij, count, isInOpPending, reverse))
}
}
}
}
}
/**
* To find a match, we need two patterns that describe what the opening and closing pairs look like, and we need a
* pattern to describe the valid starting points for the jump. A PatternsTable maps valid starting points to the pair of
* patterns needed for the search.
*
* We pass around strings instead of compiled Java Patterns since a pattern may require back references to be added
* before the search can proceed. E.g. for HTML, we use a general pattern to check if the cursor is inside a tag. The
* pattern captures the tag's name as a back reference so we can later search for something more specific like "</div>"
*/
private typealias PatternsTable = Map<String, Pair<String, String>>
/**
* A language can have many different matching pairs. We divide the patterns into four PatternsTables. `openings` and
* `closings` handle the % motion while `reversedOpenings` and `reversedClosings` handle the g% motion.
*/
private data class LanguagePatterns(
val openings: PatternsTable,
val closings: PatternsTable,
val reversedOpenings: PatternsTable,
val reversedClosings: PatternsTable,
) {
// Helper constructor for languages that don't need reversed patterns.
constructor(openings: PatternsTable, closings: PatternsTable) : this(openings, closings, openings, closings)
operator fun plus(newLanguagePatterns: LanguagePatterns): LanguagePatterns {
return LanguagePatterns(
this.openings + newLanguagePatterns.openings,
this.closings + newLanguagePatterns.closings,
this.reversedOpenings + newLanguagePatterns.reversedOpenings,
this.reversedClosings + newLanguagePatterns.reversedClosings
)
}
// Helper constructors for the most common language patterns. More complicated structures, i.e. those that require
// back references, should be built with the default constructor.
companion object {
operator fun invoke(openingPattern: String, closingPattern: String): LanguagePatterns {
val openingPatternsTable = mapOf(openingPattern to Pair(openingPattern, closingPattern))
val closingPatternsTable = mapOf(closingPattern to Pair(openingPattern, closingPattern))
return LanguagePatterns(openingPatternsTable, closingPatternsTable)
}
operator fun invoke(openingPattern: String, middlePattern: String, closingPattern: String): LanguagePatterns {
val openingAndMiddlePatterns = "(?:$openingPattern)|(?:$middlePattern)"
val middleAndClosingPatterns = "(?:$middlePattern)|(?:$closingPattern)"
val openings = mapOf(openingAndMiddlePatterns to Pair(openingAndMiddlePatterns, middleAndClosingPatterns))
val closings = mapOf(closingPattern to Pair(openingPattern, closingPattern))
// Supporting the g% motion is just a matter of rearranging the patterns table.
// This particular arrangement relies on our checking if the cursor is on a closing pattern first.
val reversedOpenings = mapOf(
openingPattern to Pair(openingPattern, closingPattern),
middlePattern to Pair(openingAndMiddlePatterns, middlePattern)
)
val reversedClosings = mapOf(middleAndClosingPatterns to Pair(openingAndMiddlePatterns, middleAndClosingPatterns))
return LanguagePatterns(openings, closings, reversedOpenings, reversedClosings)
}
}
}
/**
* All the information we need to find a match.
*/
private data class MatchitSearchParams(
val initialPatternStart: Int, // Starting offset of the pattern containing the cursor.
val initialPatternEnd: Int,
val targetOpeningPattern: String,
val targetClosingPattern: String,
// If the cursor is not in a comment, then we want to ignore any matches found in comments.
// But if we are in comment, then we only want to match on things in comments. The same goes for quotes.
val skipComments: Boolean,
val skipStrings: Boolean
)
/**
* Patterns for the supported file types are stored in this object.
*/
private object FileTypePatterns {
fun getMatchitPatterns(virtualFile: VirtualFile?): LanguagePatterns? {
// fileType is only populated for files supported by the user's IDE + language plugins.
// Checking the file's name or extension is a simple fallback which also makes unit testing easier.
val fileTypeName = virtualFile?.fileType?.name
val fileName = virtualFile?.nameWithoutExtension
val fileExtension = virtualFile?.extension
return if (fileTypeName in htmlLikeFileTypes) {
this.htmlPatterns
} else if (fileTypeName == "Ruby" || fileExtension == "rb") {
this.rubyPatterns
} else if (fileTypeName == "RHTML" || fileExtension == "erb") {
this.rubyAndHtmlPatterns
} else if (fileTypeName == "C++" || fileTypeName == "C#" || fileTypeName == "ObjectiveC" || fileExtension == "c") {
// "C++" also covers plain C.
this.cPatterns
} else if (fileTypeName == "Makefile" || fileName == "Makefile") {
this.gnuMakePatterns
} else if (fileTypeName == "CMakeLists.txt" || fileName == "CMakeLists") {
this.cMakePatterns
} else {
return null
}
}
private val htmlLikeFileTypes = setOf(
"HTML", "XML", "XHTML", "JSP", "JavaScript", "JSX Harmony", "TypeScript", "TypeScript JSX", "Vue.js", "Handlebars/Mustache"
)
private val htmlPatterns = createHtmlPatterns()
private val rubyPatterns = createRubyPatterns()
private val rubyAndHtmlPatterns = rubyPatterns + htmlPatterns
private val cPatterns = createCPatterns()
private val gnuMakePatterns = createGnuMakePatterns()
private val cMakePatterns = createCMakePatterns()
private fun createHtmlPatterns(): LanguagePatterns {
// A tag name may contain any characters except slashes, whitespace, and angle brackets.
// We surround the tag name in a capture group so that we can use it when searching for a match later.
val tagNamePattern = "([^/\\s><]+)"
// An opening tag consists of "<" followed by a tag name and optionally some additional text after whitespace.
// Note the assertion on "<" to not match on that character. If the cursor is on an angle bracket, then we want to
// match angle brackets, not HTML tags.
val openingTagPattern = String.format("(?<=<)%s(?:\\s[^<>]*(\".*\")?)?", tagNamePattern)
// A closing tag consists of a "<" followed by a slash, the tag name, and a ">".
val closingTagPattern = String.format("(?<=<)/%s(?=>)", tagNamePattern)
// The tag name is left as %s so we can substitute the back reference we captured.
val htmlSearchPair = Pair("(?<=<)%s(?:\\s[^<>]*(\".*\")?)?", "(?<=<)/%s>")
return (
LanguagePatterns("<", ">") +
LanguagePatterns(mapOf(openingTagPattern to htmlSearchPair), mapOf(closingTagPattern to htmlSearchPair))
)
}
private fun createRubyPatterns(): LanguagePatterns {
// Original patterns: https://github.com/vim/vim/blob/master/runtime/ftplugin/ruby.vim
// We use non-capturing groups (?:) since we don't need any back refs. The \\b marker takes care of word boundaries.
// On the class keyword we exclude an equal sign from appearing afterwards since it clashes with the HTML attribute.
val openingKeywords = "(?:\\b(?:do|if|unless|case|def|for|while|until|module|begin)\\b)|(?:\\bclass\\b[^=])"
val endKeyword = "\\bend\\b"
// A "middle" keyword is one that can act as both an opening or a closing pair. E.g. "elsif" can appear any number
// of times between the opening "if" and the closing "end".
val middleKeywords = "(?:\\b(?:else|elsif|break|when|rescue|ensure|redo|next|retry)\\b)"
// The cursor shouldn't jump to the equal sign on a block comment, so we exclude it with a look-behind assertion.
val blockCommentStart = "(?<==)begin\\b"
val blockCommentEnd = "(?<==)end\\b"
return (
LanguagePatterns(blockCommentStart, blockCommentEnd) +
LanguagePatterns(openingKeywords, middleKeywords, endKeyword)
)
}
private fun createCPatterns(): LanguagePatterns {
// Original patterns: https://github.com/vim/vim/blob/master/runtime/ftplugin/c.vim
return LanguagePatterns("#\\s*if(?:def|ndef)?\\b", "#\\s*(?:elif|else)\\b", "#\\s*endif\\b")
}
private fun createGnuMakePatterns(): LanguagePatterns {
// Original patterns: https://github.com/vim/vim/blob/master/runtime/ftplugin/make.vim
return (
LanguagePatterns("\\bdefine\\b", "\\bendef\\b") +
LanguagePatterns("(?<!else )ifn?(?:eq|def)\\b", "\\belse(?:\\s+ifn?(?:eq|def))?\\b", "\\bendif\\b")
)
}
private fun createCMakePatterns(): LanguagePatterns {
// Original patterns: https://github.com/vim/vim/blob/master/runtime/ftplugin/cmake.vim
return (
LanguagePatterns("\\bif\\b", "\\belse(?:if)?\\b", "\\bendif\\b") +
LanguagePatterns("\\b(?:foreach)|(?:while)\\b", "\\bbreak\\b", "\\b(?:endforeach)|(?:endwhile)\\b") +
LanguagePatterns("\\bmacro\\b", "\\bendmacro\\b") +
LanguagePatterns("\\bfunction\\b", "\\bendfunction\\b")
)
}
}
/*
* Helper search functions.
*/
private val DEFAULT_PAIRS = setOf('(', ')', '[', ']', '{', '}')
private fun getMatchitOffset(editor: Editor, caret: Caret, count: Int, isInOpPending: Boolean, reverse: Boolean): Int {
val virtualFile = EditorHelper.getVirtualFile(editor)
var caretOffset = caret.offset
// Handle the case where visual mode has brought the cursor past the end of the line.
val lineEndOffset = editor.vim.getLineEndOffset(caret.logicalPosition.line, true)
if (caretOffset > 0 && caretOffset == lineEndOffset) {
caretOffset--
}
val currentChar = editor.document.charsSequence[caretOffset]
var motion = -1
if (count > 0) {
// Matchit doesn't affect the percent motion, so we fall back to the default behavior.
motion = VimPlugin.getMotion().moveCaretToLinePercent(editor.vim, caret.vim, count)
} else {
// Check the simplest case first.
if (DEFAULT_PAIRS.contains(currentChar)) {
motion = VimPlugin.getMotion().moveCaretToMatchingPair(editor.vim, caret.vim)
} else {
val matchitPatterns = FileTypePatterns.getMatchitPatterns(virtualFile)
if (matchitPatterns != null) {
motion = if (reverse) {
findMatchingPair(editor, caretOffset, isInOpPending, matchitPatterns.reversedOpenings, matchitPatterns.reversedClosings)
} else {
findMatchingPair(editor, caretOffset, isInOpPending, matchitPatterns.openings, matchitPatterns.closings)
}
}
if (motion < 0) {
// Use default motion if the file type isn't supported or we didn't find any extended pairs.
motion = VimPlugin.getMotion().moveCaretToMatchingPair(editor.vim, caret.vim)
}
}
}
if (motion >= 0) {
motion = editor.vim.normalizeOffset(motion, false)
}
return motion
}
private fun findMatchingPair(
editor: Editor,
caretOffset: Int,
isInOpPending: Boolean,
openings: PatternsTable,
closings: PatternsTable
): Int {
// For better performance, we limit our search to the current line. This way we don't have to scan the entire file
// to determine if we're on a pattern or not. The original plugin behaves the same way.
val currentLineStart = IjVimEditor(editor).getLineStartForOffset(caretOffset)
val currentLineEnd = IjVimEditor(editor).getLineEndForOffset(caretOffset)
val currentLineChars = editor.document.charsSequence.subSequence(currentLineStart, currentLineEnd)
val offset = caretOffset - currentLineStart
var closestSearchPair: Pair<String, String>? = null
var closestMatchStart = Int.MAX_VALUE
var closestMatchEnd = Int.MAX_VALUE
var closestBackRef: String? = null
var caretInClosestMatch = false
var direction = Direction.FORWARDS
// Find the closest pattern containing or after the caret offset, if any exist.
var patternIndex = 0
for ((pattern, searchPair) in closings + openings) {
val matcher = Pattern.compile(pattern).matcher(currentLineChars)
while (matcher.find()) {
val matchStart = matcher.start()
val matchEnd = matcher.end()
if (offset >= matchEnd) continue
// We prefer matches containing the cursor over matches after the cursor.
// If the cursor in inside multiple patterns, pick the smaller one.
var foundCloserMatch = false
if (offset in matchStart until matchEnd) {
if (!caretInClosestMatch || (matchEnd - matchStart < closestMatchEnd - closestMatchStart)) {
caretInClosestMatch = true
foundCloserMatch = true
}
} else if (!caretInClosestMatch && matchStart < closestMatchStart &&
!containsDefaultPairs(currentLineChars.subSequence(offset, matchStart))
) {
// A default pair after the cursor is preferred over any extended pairs after the cursor.
foundCloserMatch = true
}
if (foundCloserMatch) {
closestSearchPair = searchPair
closestMatchStart = matchStart
closestMatchEnd = matchEnd
closestBackRef = if (matcher.groupCount() > 0) matcher.group(1) else null
direction = if (closings.isNotEmpty() && patternIndex in 0 until closings.size) Direction.BACKWARDS else Direction.FORWARDS
}
}
patternIndex++
}
if (closestSearchPair != null) {
val targetOpeningPattern: String
val targetClosingPattern: String
// Substitute any captured back references to the search patterns, if necessary.
if (closestBackRef != null) {
targetOpeningPattern = String.format(closestSearchPair.first, closestBackRef)
targetClosingPattern = String.format(closestSearchPair.second, closestBackRef)
} else {
targetOpeningPattern = closestSearchPair.first
targetClosingPattern = closestSearchPair.second
}
// HTML attributes are a special case where the cursor is inside of quotes, but we want to jump as if we were
// anywhere else inside the opening tag.
val currentPsiElement = PsiHelper.getFile(editor)!!.findElementAt(caretOffset)
val skipComments = !isComment(currentPsiElement)
val skipQuotes = !isQuoted(currentPsiElement) || isHtmlAttribute(currentPsiElement)
val initialPatternStart = currentLineStart + closestMatchStart
val initialPatternEnd = currentLineStart + closestMatchEnd
val searchParams = MatchitSearchParams(initialPatternStart, initialPatternEnd, targetOpeningPattern, targetClosingPattern, skipComments, skipQuotes)
val matchingPairOffset = if (direction == Direction.FORWARDS) {
findClosingPair(editor, isInOpPending, searchParams)
} else {
findOpeningPair(editor, searchParams)
}
// If the user is on a valid pattern, but we didn't find a matching pair, then the cursor shouldn't move.
// We return the current caret offset to reflect that case, as opposed to -1 which means the cursor isn't on a
// valid pattern at all.
return if (matchingPairOffset < 0) caretOffset else matchingPairOffset
}
return -1
}
private fun findClosingPair(editor: Editor, isInOpPending: Boolean, searchParams: MatchitSearchParams): Int {
val (_, searchStartOffset, openingPattern, closingPattern, skipComments, skipStrings) = searchParams
val chars = editor.document.charsSequence
val searchSpace = chars.subSequence(searchStartOffset, chars.length)
val compiledClosingPattern = Pattern.compile(closingPattern)
val compiledSearchPattern = Pattern.compile(String.format("(?<opening>%s)|(?<closing>%s)", openingPattern, closingPattern))
val matcher = compiledSearchPattern.matcher(searchSpace)
// We're looking for the first closing pair that isn't already matched by an opening.
// As we find opening patterns, we push their offsets to this stack and pop whenever we find a closing pattern,
// effectively crossing off that item from our search.
val unmatchedOpeningPairs: Deque<Int> = ArrayDeque()
while (matcher.find()) {
val matchOffset = if (isInOpPending) {
searchStartOffset + matcher.end() - 1
} else {
searchStartOffset + matcher.start()
}
if (matchShouldBeSkipped(editor, matchOffset, skipComments, skipStrings)) {
continue
}
val openingGroup = matcher.group("opening")
val foundOpeningPattern = openingGroup != null
val foundMiddlePattern = foundOpeningPattern && compiledClosingPattern.matcher(openingGroup).matches()
if (foundMiddlePattern) {
// Middle patterns e.g. "elsif" can appear any number of times between a strict opening and a strict closing.
if (!unmatchedOpeningPairs.isEmpty()) {
unmatchedOpeningPairs.pop()
unmatchedOpeningPairs.push(matchOffset)
} else {
return matchOffset
}
} else if (foundOpeningPattern) {
unmatchedOpeningPairs.push(matchOffset)
} else {
// Found a closing pattern
if (!unmatchedOpeningPairs.isEmpty()) {
unmatchedOpeningPairs.pop()
} else {
return matchOffset
}
}
}
return -1
}
private fun findOpeningPair(editor: Editor, searchParams: MatchitSearchParams): Int {
val (searchEndOffset, _, openingPattern, closingPattern, skipComments, skipStrings) = searchParams
val chars = editor.document.charsSequence
val searchSpace = chars.subSequence(0, searchEndOffset)
val compiledClosingPattern = Pattern.compile(closingPattern)
val compiledSearchPattern = Pattern.compile(String.format("(?<opening>%s)|(?<closing>%s)", openingPattern, closingPattern))
val matcher = compiledSearchPattern.matcher(searchSpace)
val unmatchedOpeningPairs: Deque<Int> = ArrayDeque()
while (matcher.find()) {
val matchOffset = matcher.start()
if (matchShouldBeSkipped(editor, matchOffset, skipComments, skipStrings)) {
continue
}
val openingGroup = matcher.group("opening")
val foundOpeningPattern = openingGroup != null
val foundMiddlePattern = foundOpeningPattern && compiledClosingPattern.matcher(openingGroup).matches()
if (foundMiddlePattern) {
if (!unmatchedOpeningPairs.isEmpty()) {
unmatchedOpeningPairs.pop()
unmatchedOpeningPairs.push(matchOffset)
} else {
unmatchedOpeningPairs.push(matchOffset)
}
} else if (foundOpeningPattern) {
unmatchedOpeningPairs.push(matchOffset)
} else if (!unmatchedOpeningPairs.isEmpty()) {
// Found a closing pattern. We check the stack isn't empty to handle malformed code.
unmatchedOpeningPairs.pop()
}
}
return if (!unmatchedOpeningPairs.isEmpty()) {
unmatchedOpeningPairs.pop()
} else {
-1
}
}
private fun containsDefaultPairs(chars: CharSequence): Boolean {
for (c in chars) {
if (c in DEFAULT_PAIRS) return true
}
return false
}
private fun matchShouldBeSkipped(editor: Editor, offset: Int, skipComments: Boolean, skipStrings: Boolean): Boolean {
val psiFile = PsiHelper.getFile(editor)
val psiElement = psiFile!!.findElementAt(offset)
// TODO: as we add support for more languages, we should store the ignored keywords for each language in its own
// data structure. The original plugin stores that information in strings called match_skip.
if (isSkippedRubyKeyword(psiElement)) {
return true
}
val insideComment = isComment(psiElement)
val insideQuotes = isQuoted(psiElement)
return (skipComments && insideComment) || (!skipComments && !insideComment) ||
(skipStrings && insideQuotes) || (!skipStrings && !insideQuotes)
}
private fun isSkippedRubyKeyword(psiElement: PsiElement?): Boolean {
// In Ruby code, we want to ignore anything inside of a regular expression like "/ class /" and identifiers like
// "Foo.class". Matchit also ignores any "do" keywords that follow a loop or an if condition, as well as any inline
// "if" and "unless" expressions (a.k.a conditional modifiers).
val elementType = psiElement?.node?.elementType?.debugName
return elementType == "do_cond" || elementType == "if modifier" || elementType == "unless modifier" ||
elementType == "regexp content" || elementType == "identifier"
}
private fun isComment(psiElement: PsiElement?): Boolean {
return PsiTreeUtil.getParentOfType(psiElement, PsiComment::class.java, false) != null
}
private fun isQuoted(psiElement: PsiElement?): Boolean {
val elementType = psiElement?.elementType?.debugName
return elementType == "STRING_LITERAL" || elementType == "XML_ATTRIBUTE_VALUE_TOKEN" ||
elementType == "string content" // Ruby specific.
}
private fun isHtmlAttribute(psiElement: PsiElement?): Boolean {
val elementType = psiElement?.elementType?.debugName
return elementType == "XML_ATTRIBUTE_VALUE_TOKEN"
}
|
mit
|
7542b2b7f1114d869eb8d4e069ccb93c
| 42.048414 | 161 | 0.7252 | 4.276285 | false | false | false | false |
KotlinNLP/SimpleDNN
|
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/merge/affine/AffineLayer.kt
|
1
|
2380
|
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.merge.affine
import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.helpers.RelevanceHelper
import com.kotlinnlp.simplednn.core.layers.models.merge.MergeLayer
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
/**
* The Affine Layer Structure.
*
* @property inputArrays the input arrays of the layer
* @property inputType the input array type (default Dense)
* @property outputArray the output array of the layer
* @property params the parameters which connect the input to the output
* @property activationFunction the activation function of the layer
* @property dropout the probability of dropout
*/
internal class AffineLayer<InputNDArrayType : NDArray<InputNDArrayType>>(
inputArrays: List<AugmentedArray<InputNDArrayType>>,
inputType: LayerType.Input,
outputArray: AugmentedArray<DenseNDArray>,
override val params: AffineLayerParameters,
activationFunction: ActivationFunction? = null,
dropout: Double
) : MergeLayer<InputNDArrayType>(
inputArrays = inputArrays,
inputType = inputType,
outputArray = outputArray,
params = params,
activationFunction = activationFunction,
dropout = dropout
) {
init { this.checkInputSize() }
/**
* The helper which execute the forward.
*/
override val forwardHelper = AffineForwardHelper(layer = this)
/**
* The helper which execute the backward.
*/
override val backwardHelper = AffineBackwardHelper(layer = this)
/**
* The helper which calculates the relevance
*/
override val relevanceHelper: RelevanceHelper? = null
/**
* Initialization: set the activation function of the outputArray.
*/
init {
if (activationFunction != null) {
outputArray.setActivation(activationFunction)
}
}
}
|
mpl-2.0
|
265136dfd8705cce7a7bd4cfdaf3b797
| 33.492754 | 82 | 0.743697 | 4.685039 | false | false | false | false |
michaelkourlas/voipms-sms-client
|
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/database/daos/ArchivedDao.kt
|
1
|
1671
|
/*
* VoIP.ms SMS
* Copyright (C) 2021 Michael Kourlas
*
* 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 net.kourlas.voipms_sms.database.daos
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import net.kourlas.voipms_sms.database.entities.Archived
import net.kourlas.voipms_sms.database.entities.Sms
@Dao
interface ArchivedDao {
@Query("DELETE FROM ${Archived.TABLE_NAME}")
suspend fun deleteAll()
@Query(
"DELETE FROM ${Archived.TABLE_NAME} WHERE ${Sms.COLUMN_DID} = :did AND ${Sms.COLUMN_CONTACT} = :contact"
)
suspend fun deleteConversation(did: String, contact: String)
@Query(
"DELETE FROM ${Archived.TABLE_NAME} WHERE ${Archived.COLUMN_DID} NOT IN(:dids)"
)
suspend fun deleteWithoutDids(dids: Set<String>)
@Query(
"SELECT * FROM ${Archived.TABLE_NAME} WHERE ${Sms.COLUMN_DID} = :did AND ${Sms.COLUMN_CONTACT} = :contact LIMIT 1"
)
suspend fun getConversation(did: String, contact: String): Archived?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun update(archived: Archived)
}
|
apache-2.0
|
367e9e335824ce06fed8cf2b627720b3
| 33.122449 | 122 | 0.721125 | 3.931765 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractClass/ExtractSuperRefactoring.kt
|
1
|
15218
|
// 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.refactoring.introduce.extractClass
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.extractSuperclass.ExtractSuperClassUtil
import com.intellij.refactoring.memberPullUp.PullUpProcessor
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.refactoring.util.DocCommentPolicy
import com.intellij.refactoring.util.MoveRenameUsageInfo
import com.intellij.usageView.UsageInfo
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.actions.NewKotlinFileAction
import org.jetbrains.kotlin.idea.base.psi.copied
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.introduce.insertDeclaration
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.getChildrenToAnalyze
import org.jetbrains.kotlin.idea.refactoring.memberInfo.toJavaMemberInfo
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinMoveTargetForDeferredFile
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinMoveTargetForExistingElement
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveConflictChecker
import org.jetbrains.kotlin.idea.refactoring.pullUp.checkVisibilityInAbstractedMembers
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
data class ExtractSuperInfo(
val originalClass: KtClassOrObject,
val memberInfos: Collection<KotlinMemberInfo>,
val targetParent: PsiElement,
val targetFileName: String,
val newClassName: String,
val isInterface: Boolean,
val docPolicy: DocCommentPolicy<*>
)
class ExtractSuperRefactoring(
private var extractInfo: ExtractSuperInfo
) {
companion object {
private fun getElementsToMove(
memberInfos: Collection<KotlinMemberInfo>,
originalClass: KtClassOrObject,
isExtractInterface: Boolean
): Map<KtElement, KotlinMemberInfo?> {
val project = originalClass.project
val elementsToMove = LinkedHashMap<KtElement, KotlinMemberInfo?>()
runReadAction {
val superInterfacesToMove = ArrayList<KtElement>()
for (memberInfo in memberInfos) {
val member = memberInfo.member ?: continue
if (memberInfo.isSuperClass) {
superInterfacesToMove += member
} else {
elementsToMove[member] = memberInfo
}
}
val superTypeList = originalClass.getSuperTypeList()
if (superTypeList != null) {
for (superTypeListEntry in originalClass.superTypeListEntries) {
val superType =
superTypeListEntry.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, superTypeListEntry.typeReference]
?: continue
val superClassDescriptor = superType.constructor.declarationDescriptor ?: continue
val superClass = DescriptorToSourceUtilsIde.getAnyDeclaration(project, superClassDescriptor) as? KtClass ?: continue
if ((!isExtractInterface && !superClass.isInterface()) || superClass in superInterfacesToMove) {
elementsToMove[superTypeListEntry] = null
}
}
}
}
return elementsToMove
}
fun collectConflicts(
originalClass: KtClassOrObject,
memberInfos: List<KotlinMemberInfo>,
targetParent: PsiElement,
newClassName: String,
isExtractInterface: Boolean
): MultiMap<PsiElement, String> {
val conflicts = MultiMap<PsiElement, String>()
val project = originalClass.project
if (targetParent is KtElement) {
val targetSibling = originalClass.parentsWithSelf.first { it.parent == targetParent } as KtElement
targetSibling.getResolutionScope()
.findClassifier(Name.identifier(newClassName), NoLookupLocation.FROM_IDE)
?.let { DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) }
?.let {
conflicts.putValue(
it,
KotlinBundle.message(
"text.class.0.already.exists.in.the.target.scope",
newClassName
)
)
}
}
val elementsToMove = getElementsToMove(memberInfos, originalClass, isExtractInterface).keys
val moveTarget = if (targetParent is PsiDirectory) {
val targetPackage = targetParent.getPackage() ?: return conflicts
KotlinMoveTargetForDeferredFile(FqName(targetPackage.qualifiedName), targetParent.virtualFile)
} else {
KotlinMoveTargetForExistingElement(targetParent as KtElement)
}
val conflictChecker = MoveConflictChecker(
project,
elementsToMove,
moveTarget,
originalClass,
memberInfos.asSequence().filter { it.isToAbstract }.mapNotNull { it.member }.toList()
)
project.runSynchronouslyWithProgress(RefactoringBundle.message("detecting.possible.conflicts"), true) {
runReadAction {
val usages = LinkedHashSet<UsageInfo>()
for (element in elementsToMove) {
ReferencesSearch.search(element).mapTo(usages) { MoveRenameUsageInfo(it, element) }
if (element is KtCallableDeclaration) {
element.toLightMethods().flatMapTo(usages) {
MethodReferencesSearch.search(it).map { reference -> MoveRenameUsageInfo(reference, element) }
}
}
}
conflictChecker.checkAllConflicts(usages, LinkedHashSet(), conflicts)
if (targetParent is PsiDirectory) {
ExtractSuperClassUtil.checkSuperAccessible(targetParent, conflicts, originalClass.toLightClass())
}
checkVisibilityInAbstractedMembers(memberInfos, originalClass.getResolutionFacade(), conflicts)
}
}
return conflicts
}
}
private val project = extractInfo.originalClass.project
private val psiFactory = KtPsiFactory(project)
private val typeParameters = LinkedHashSet<KtTypeParameter>()
private val bindingContext = extractInfo.originalClass.analyze(BodyResolveMode.PARTIAL)
private fun collectTypeParameters(refTarget: PsiElement?) {
if (refTarget is KtTypeParameter && refTarget.getStrictParentOfType<KtTypeParameterListOwner>() == extractInfo.originalClass) {
typeParameters += refTarget
refTarget.accept(
object : KtTreeVisitorVoid() {
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
(expression.mainReference.resolve() as? KtTypeParameter)?.let { typeParameters += it }
}
}
)
}
}
private fun analyzeContext() {
val visitor = object : KtTreeVisitorVoid() {
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val refTarget = expression.mainReference.resolve()
collectTypeParameters(refTarget)
}
}
getElementsToMove(extractInfo.memberInfos, extractInfo.originalClass, extractInfo.isInterface)
.asSequence()
.flatMap {
val (element, info) = it
info?.getChildrenToAnalyze()?.asSequence() ?: sequenceOf(element)
}
.forEach { it.accept(visitor) }
}
private fun createClass(superClassEntry: KtSuperTypeListEntry?): KtClass? {
val targetParent = extractInfo.targetParent
val newClassName = extractInfo.newClassName.quoteIfNeeded()
val originalClass = extractInfo.originalClass
val kind = if (extractInfo.isInterface) "interface" else "class"
val prototype = psiFactory.createClass("$kind $newClassName")
val newClass = if (targetParent is PsiDirectory) {
val file = targetParent.findFile(extractInfo.targetFileName) ?: run {
val template = FileTemplateManager.getInstance(project).getInternalTemplate("Kotlin File")
NewKotlinFileAction.createFileFromTemplate(extractInfo.targetFileName, template, targetParent) ?: return null
}
file.add(prototype) as KtClass
} else {
val targetSibling = originalClass.parentsWithSelf.first { it.parent == targetParent }
insertDeclaration(prototype, targetSibling)
}
val shouldBeAbstract = extractInfo.memberInfos.any { it.isToAbstract }
if (!extractInfo.isInterface) {
newClass.addModifier(if (shouldBeAbstract) KtTokens.ABSTRACT_KEYWORD else KtTokens.OPEN_KEYWORD)
}
if (typeParameters.isNotEmpty()) {
val typeParameterListText = typeParameters.sortedBy { it.startOffset }.joinToString(prefix = "<", postfix = ">") { it.text }
newClass.addAfter(psiFactory.createTypeParameterList(typeParameterListText), newClass.nameIdentifier)
}
val targetPackageFqName = (targetParent as? PsiDirectory)?.getFqNameWithImplicitPrefix()?.quoteSegmentsIfNeeded()
val superTypeText = buildString {
if (!targetPackageFqName.isNullOrEmpty()) {
append(targetPackageFqName).append('.')
}
append(newClassName)
if (typeParameters.isNotEmpty()) {
append(typeParameters.sortedBy { it.startOffset }.map { it.name }.joinToString(prefix = "<", postfix = ">"))
}
}
val needSuperCall = !extractInfo.isInterface
&& (superClassEntry is KtSuperTypeCallEntry
|| originalClass.hasPrimaryConstructor()
|| originalClass.secondaryConstructors.isEmpty())
val newSuperTypeListEntry = if (needSuperCall) {
psiFactory.createSuperTypeCallEntry("$superTypeText()")
} else {
psiFactory.createSuperTypeEntry(superTypeText)
}
if (superClassEntry != null) {
val qualifiedTypeRefText = bindingContext[BindingContext.TYPE, superClassEntry.typeReference]?.let {
IdeDescriptorRenderers.SOURCE_CODE.renderType(it)
}
val superClassEntryToAdd = if (qualifiedTypeRefText != null) {
superClassEntry.copied().apply { typeReference?.replace(psiFactory.createType(qualifiedTypeRefText)) }
} else superClassEntry
newClass.addSuperTypeListEntry(superClassEntryToAdd)
ShortenReferences.DEFAULT.process(superClassEntry.replaced(newSuperTypeListEntry))
} else {
ShortenReferences.DEFAULT.process(originalClass.addSuperTypeListEntry(newSuperTypeListEntry))
}
ShortenReferences.DEFAULT.process(newClass)
return newClass
}
fun performRefactoring() {
val originalClass = extractInfo.originalClass
val handler = if (extractInfo.isInterface) KotlinExtractInterfaceHandler else KotlinExtractSuperclassHandler
handler.getErrorMessage(originalClass)?.let { throw CommonRefactoringUtil.RefactoringErrorHintException(it) }
val superClassEntry = if (!extractInfo.isInterface) {
val originalClassDescriptor = originalClass.unsafeResolveToDescriptor() as ClassDescriptor
val superClassDescriptor = originalClassDescriptor.getSuperClassNotAny()
originalClass.superTypeListEntries.firstOrNull {
bindingContext[BindingContext.TYPE, it.typeReference]?.constructor?.declarationDescriptor == superClassDescriptor
}
} else null
project.runSynchronouslyWithProgress(RefactoringBundle.message("progress.text"), true) { runReadAction { analyzeContext() } }
project.executeWriteCommand(KotlinExtractSuperclassHandler.REFACTORING_NAME) {
val newClass = createClass(superClassEntry) ?: return@executeWriteCommand
val subClass = extractInfo.originalClass.toLightClass() ?: return@executeWriteCommand
val superClass = newClass.toLightClass() ?: return@executeWriteCommand
PullUpProcessor(
subClass,
superClass,
extractInfo.memberInfos.mapNotNull { it.toJavaMemberInfo() }.toTypedArray(),
extractInfo.docPolicy
).moveMembersToBase()
performDelayedRefactoringRequests(project)
}
}
}
|
apache-2.0
|
3c99ca2159a4640f509bbc9445291c45
| 48.409091 | 158 | 0.675779 | 5.873408 | false | false | false | false |
cqjjjzr/BiliLiveLib
|
BiliLiveOnlineKeeper/src/main/kotlin/charlie/bilionlinekeeper/FreeSilver.kt
|
1
|
3617
|
package charlie.bilionlinekeeper
import charlie.bililivelib.exceptions.BiliLiveException
import charlie.bililivelib.freesilver.FreeSilverProtocol
import charlie.bililivelib.internalutil.MiscUtil
import charlie.bililivelib.user.Session
import charlie.bilionlinekeeper.util.I18n
import charlie.bilionlinekeeper.util.LogUtil
import charlie.bilionlinekeeper.util.TimeUtil
import org.apache.logging.log4j.Level
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
class FreeSilver(session: Session) {
private val LOGGER_NAME = "freeSilver"
private val THREAD_NAME = "FreeSilverGetter"
private val EXCEPTION_WAIT_TIME_MILLIS: Long = 10 * 60 * 1000 // 10 Minutes
private val protocol: FreeSilverProtocol = FreeSilverProtocol(session)
private val logger: Logger = LogManager.getLogger(LOGGER_NAME)
private var thread: Thread = Thread()
fun start() {
thread = Thread(FreeSilverRunnable())
thread.start()
logger.info(I18n.getString("freeSilver.start"))
}
fun stop() {
thread.interrupt()
logger.info(I18n.getString("freeSilver.stop"))
}
fun isStarted(): Boolean = thread.isAlive
private inner class FreeSilverRunnable : Runnable {
override fun run() {
initThreadName()
out@ while (!Thread.currentThread().isInterrupted) {
try {
val currentInfo: FreeSilverProtocol.CurrentSilverTaskInfo = protocol.currentFreeSilverStatus
if (!currentInfo.hasRemaining()) logAndStopToday()
logCurrentTask(currentInfo)
val gotInfo: FreeSilverProtocol.GetSilverInfo
try {
gotInfo = protocol.waitToGetSilver(currentInfo)
} catch(e: InterruptedException) {
break@out
}
when (gotInfo.status()) {
FreeSilverProtocol.GetSilverInfo.Status.NOT_LOGGED_IN -> {
logNotLoggedIn()
break@out
}
else -> logRound(gotInfo)
}
if (gotInfo.isEnd) logAndStopToday()
} catch(e: BiliLiveException) {
logRoundException(e)
MiscUtil.sleepMillis(EXCEPTION_WAIT_TIME_MILLIS)
continue
}
}
}
private fun logCurrentTask(currentInfo: FreeSilverProtocol.CurrentSilverTaskInfo) {
logger.info(I18n.format("freeSilver.currentTask",
currentInfo.data.minute,
currentInfo.data.silverCount))
}
private fun logNotLoggedIn() {
logger.error(I18n.getString("user.logNotLoggedIn"))
}
private fun logRound(gotInfo: FreeSilverProtocol.GetSilverInfo) {
logger.info(I18n.format("freeSilver.gotRound",
gotInfo.data.awardSilverCount))
}
private fun logRoundException(e: BiliLiveException) {
LogUtil.logException(logger, Level.WARN, I18n.getString("freeSilver.roundException")!!, e)
}
private fun logAndStopToday() {
logger.info(I18n.getString("freeSilver.stopToday"))
waitToTomorrow()
}
private fun waitToTomorrow() {
MiscUtil.sleepMillis(TimeUtil.calculateToTomorrowMillis())
}
private fun initThreadName() {
Thread.currentThread().name = THREAD_NAME
}
}
}
|
apache-2.0
|
7104989f7281e8d08a51ea69751cfed6
| 35.535354 | 112 | 0.604645 | 4.438037 | false | false | false | false |
mbrlabs/Mundus
|
editor/src/main/com/mbrlabs/mundus/editor/ui/widgets/AssetSelectionField.kt
|
1
|
2246
|
/*
* 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.ui.widgets
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.kotcrab.vis.ui.widget.VisTable
import com.kotcrab.vis.ui.widget.VisTextButton
import com.kotcrab.vis.ui.widget.VisTextField
import com.mbrlabs.mundus.commons.assets.Asset
import com.mbrlabs.mundus.editor.assets.AssetFilter
import com.mbrlabs.mundus.editor.ui.UI
import com.mbrlabs.mundus.editor.ui.modules.dialogs.assets.AssetPickerDialog
/**
* @author Marcus Brummer
* @version 13-10-2016
*/
class AssetSelectionField : VisTable() {
private val textField: VisTextField
private val btn: VisTextButton
var pickerListener: AssetPickerDialog.AssetPickerListener? = null
var assetFilter: AssetFilter? = null
private val internalListener: AssetPickerDialog.AssetPickerListener
init {
textField = VisTextField()
textField.isDisabled = true
btn = VisTextButton("Select")
add(textField).grow()
add(btn).padLeft(5f).row()
internalListener = object: AssetPickerDialog.AssetPickerListener {
override fun onSelected(asset: Asset?) {
setAsset(asset)
pickerListener?.onSelected(asset)
}
}
btn.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
UI.assetSelectionDialog.show(true, assetFilter, internalListener)
}
})
}
fun setAsset(asset: Asset?) {
textField.text = if (asset == null) "None" else asset.name
}
}
|
apache-2.0
|
f50fdb607a5e34e1e5bdc652098eafa2
| 31.550725 | 81 | 0.702137 | 4.143911 | false | false | false | false |
ChristopherGittner/OSMBugs
|
app/src/main/java/org/gittner/osmbugs/osmnotes/OsmNoteCommentsAdapter.kt
|
1
|
1332
|
package org.gittner.osmbugs.osmnotes
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import org.gittner.osmbugs.R
import org.gittner.osmbugs.databinding.RowOsmNoteCommentBinding
import org.joda.time.DateTimeZone
/**
* Adapter for OsmNote Comments.
* Each row contains the User an the comment
* @param context The current context.
* @param comments The Comments to display. The comments will be added to the Adapter automatically
*/
class OsmNoteCommentsAdapter(context: Context, comments: ArrayList<OsmNote.OsmNoteComment>) :
ArrayAdapter<OsmNote.OsmNoteComment>(context, R.layout.row_osm_note_comment) {
init {
addAll(comments)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val v = convertView ?: LayoutInflater.from(context).inflate(R.layout.row_osm_note_comment, parent, false)
val binding = RowOsmNoteCommentBinding.bind(v)
val item = getItem(position)!!
binding.apply {
txtvUser.text = item.User
txtvText.text = item.Comment
txtvDate.text = item.Date.withZone(DateTimeZone.getDefault()).toString(context.getString(R.string.datetime_format))
}
return v
}
}
|
mit
|
b87a80d02ca5aa11cf95ddf416be7925
| 33.153846 | 127 | 0.728979 | 4.149533 | false | false | false | false |
GunoH/intellij-community
|
platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionToolRegistrar.kt
|
3
|
8383
|
// 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.codeInspection.ex
import com.intellij.analysis.AnalysisBundle
import com.intellij.codeInsight.daemon.HighlightDisplayKey
import com.intellij.codeInspection.*
import com.intellij.diagnostic.PluginException
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.util.SmartList
import com.intellij.util.containers.CollectionFactory
import org.jetbrains.annotations.ApiStatus
private val LOG = logger<InspectionToolRegistrar>()
private val EP_NAME = ExtensionPointName<InspectionToolProvider>("com.intellij.inspectionToolProvider")
private typealias InspectionFactory = () -> InspectionToolWrapper<*, *>?
@Service
class InspectionToolRegistrar : InspectionToolsSupplier() {
companion object {
@JvmStatic
fun getInstance() = service<InspectionToolRegistrar>()
@ApiStatus.Internal
@JvmStatic
fun wrapTool(profileEntry: InspectionProfileEntry): InspectionToolWrapper<*, *> {
return when (profileEntry) {
is LocalInspectionTool -> LocalInspectionToolWrapper(profileEntry)
is GlobalInspectionTool -> GlobalInspectionToolWrapper(profileEntry)
else -> throw RuntimeException("unknown inspection class: " + profileEntry + "; " + profileEntry.javaClass)
}
}
}
private val toolFactories: MutableCollection<MutableList<InspectionFactory>>
init {
val app = ApplicationManager.getApplication()
val result = CollectionFactory.createSmallMemoryFootprintMap<Any, MutableList<InspectionFactory>>()
val shortNames = CollectionFactory.createSmallMemoryFootprintMap<String, InspectionEP>()
registerToolProviders(result)
registerInspections(result, app, shortNames, LocalInspectionEP.LOCAL_INSPECTION)
registerInspections(result, app, shortNames, InspectionEP.GLOBAL_INSPECTION)
toolFactories = result.values
}
private fun unregisterInspectionOrProvider(inspectionOrProvider: Any, factories: MutableMap<Any, MutableList<InspectionFactory>>) {
for (removedTool in (factories.remove(inspectionOrProvider) ?: return)) {
removedTool()?.shortName?.let { shortName -> HighlightDisplayKey.unregister(shortName) }
fireToolRemoved(removedTool)
}
}
private fun <T : InspectionEP> registerInspections(factories: MutableMap<Any, MutableList<InspectionFactory>>,
app: Application,
shortNames: MutableMap<String, InspectionEP>,
extensionPointName: ExtensionPointName<T>) {
val isInternal = app.isInternal
for (extension in extensionPointName.extensionList) {
registerInspection(extension, shortNames, isInternal, factories)
}
extensionPointName.addExtensionPointListener(object : ExtensionPointListener<T> {
override fun extensionAdded(inspection: T, pluginDescriptor: PluginDescriptor) {
fireToolAdded(registerInspection(inspection, shortNames, isInternal, factories) ?: return)
}
override fun extensionRemoved(inspection: T, pluginDescriptor: PluginDescriptor) {
unregisterInspectionOrProvider(inspection, factories)
shortNames.remove(inspection.getShortName())
}
}, null)
}
private fun registerToolProviders(factories: MutableMap<Any, MutableList<InspectionFactory>>) {
EP_NAME.processWithPluginDescriptor { provider, pluginDescriptor ->
registerToolProvider(provider, pluginDescriptor, factories, null)
}
EP_NAME.addExtensionPointListener(object : ExtensionPointListener<InspectionToolProvider> {
override fun extensionAdded(extension: InspectionToolProvider, pluginDescriptor: PluginDescriptor) {
val added = mutableListOf<InspectionFactory>()
registerToolProvider(extension, pluginDescriptor, factories, added)
for (supplier in added) {
fireToolAdded(supplier)
}
}
override fun extensionRemoved(extension: InspectionToolProvider, pluginDescriptor: PluginDescriptor) {
unregisterInspectionOrProvider(extension, factories)
}
}, null)
}
private fun fireToolAdded(factory: InspectionFactory) {
val inspectionToolWrapper = factory() ?: return
for (listener in listeners) {
listener.toolAdded(inspectionToolWrapper)
}
}
private fun fireToolRemoved(factory: InspectionFactory) {
val inspectionToolWrapper = factory() ?: return
for (listener in listeners) {
listener.toolRemoved(inspectionToolWrapper)
}
}
override fun createTools(): List<InspectionToolWrapper<*, *>> {
val tools = ArrayList<InspectionToolWrapper<*, *>>()
for (list in toolFactories) {
tools.ensureCapacity(list.size)
for (factory in list) {
ProgressManager.checkCanceled()
val toolWrapper = factory()
if (toolWrapper != null && checkTool(toolWrapper) == null) {
tools.add(toolWrapper)
}
}
}
return tools
}
}
private fun <T : InspectionEP> registerInspection(inspection: T,
shortNames: MutableMap<String, InspectionEP>,
isInternal: Boolean,
factories: MutableMap<Any, MutableList<InspectionFactory>>): (InspectionFactory)? {
checkForDuplicateShortName(inspection, shortNames)
if (!isInternal && inspection.isInternal) {
return null
}
val factory = {
if (inspection is LocalInspectionEP) LocalInspectionToolWrapper(inspection) else GlobalInspectionToolWrapper(inspection)
}
factories.computeIfAbsent(inspection) { SmartList() }.add(factory)
return factory
}
private fun registerToolProvider(provider: InspectionToolProvider,
pluginDescriptor: PluginDescriptor,
keyToFactories: MutableMap<Any, MutableList<InspectionFactory>>,
added: MutableList<InspectionFactory>?) {
val factories = keyToFactories.computeIfAbsent(provider) { ArrayList() }
for (aClass in provider.inspectionClasses) {
val supplier = {
try {
val constructor = aClass.getDeclaredConstructor()
constructor.isAccessible = true
InspectionToolRegistrar.wrapTool(constructor.newInstance())
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
LOG.error(PluginException(e, pluginDescriptor.pluginId))
null
}
}
factories.add(supplier)
added?.add(supplier)
}
}
private fun checkForDuplicateShortName(ep: InspectionEP, shortNames: MutableMap<String, InspectionEP>) {
val shortName = ep.getShortName()
val duplicate = shortNames.put(shortName, ep) ?: return
val descriptor = ep.pluginDescriptor
LOG.error(PluginException(
"""
Short name '$shortName' is not unique
class '${ep.instantiateTool().javaClass.canonicalName}' in $descriptor
and class '${duplicate.instantiateTool().javaClass.canonicalName}' in ${duplicate.pluginDescriptor}
conflict
""".trimIndent(),
descriptor.pluginId))
}
private fun checkTool(toolWrapper: InspectionToolWrapper<*, *>): String? {
if (toolWrapper !is LocalInspectionToolWrapper) {
return null
}
var message: String? = null
try {
val id = toolWrapper.getID()
if (!LocalInspectionTool.isValidID(id)) {
message = AnalysisBundle.message("inspection.disabled.wrong.id", toolWrapper.getShortName(), id, LocalInspectionTool.VALID_ID_PATTERN)
}
}
catch (t: Throwable) {
message = AnalysisBundle.message("inspection.disabled.error", toolWrapper.getShortName(), t.message)
}
if (message != null) {
LOG.error(message)
}
return message
}
|
apache-2.0
|
33631dacc409e77f406821e17b94403c
| 39.502415 | 140 | 0.712275 | 5.265704 | false | false | false | false |
GunoH/intellij-community
|
platform/platform-impl/src/com/intellij/ide/ui/text/ShortcutsRenderingUtil.kt
|
2
|
6823
|
// 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.ide.ui.text
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.KeyboardShortcut
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.keymap.MacKeymapUtil
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.StringUtil.NON_BREAK_SPACE
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NonNls
import java.awt.event.KeyEvent
import javax.swing.KeyStroke
@ApiStatus.Experimental
@ApiStatus.Internal
object ShortcutsRenderingUtil {
val SHORTCUT_PART_SEPARATOR = NON_BREAK_SPACE.repeat(3)
/**
* @param actionId
* *
* @return null if actionId is null
*/
fun getShortcutByActionId(actionId: String?): KeyboardShortcut? {
actionId ?: return null
val activeKeymap = KeymapManager.getInstance().activeKeymap
findCustomShortcut(activeKeymap, actionId)?.let {
return it
}
val shortcuts = activeKeymap.getShortcuts(actionId)
val bestShortcut: KeyboardShortcut? = shortcuts.filterIsInstance<KeyboardShortcut>().let { kbShortcuts ->
kbShortcuts.find { !it.isNumpadKey } ?: kbShortcuts.firstOrNull()
}
return bestShortcut
}
private fun findCustomShortcut(activeKeymap: Keymap, actionId: String): KeyboardShortcut? {
val currentShortcuts = activeKeymap.getShortcuts(actionId).toList()
if (!activeKeymap.canModify()) return null
val parentShortcuts = activeKeymap.parent?.getShortcuts(actionId)?.toList() ?: return null
val shortcuts = currentShortcuts - parentShortcuts
if (shortcuts.isEmpty()) return null
return shortcuts.reversed().filterIsInstance<KeyboardShortcut>().firstOrNull()
}
private val KeyboardShortcut.isNumpadKey: Boolean
get() = firstKeyStroke.keyCode in KeyEvent.VK_NUMPAD0..KeyEvent.VK_DIVIDE || firstKeyStroke.keyCode == KeyEvent.VK_NUM_LOCK
fun getKeyboardShortcutData(shortcut: KeyboardShortcut?): Pair<@NlsSafe String, List<IntRange>> {
if (shortcut == null) return Pair("", emptyList())
val firstKeyStrokeData = getKeyStrokeData(shortcut.firstKeyStroke)
val secondKeyStroke = shortcut.secondKeyStroke ?: return firstKeyStrokeData
val secondKeyStrokeData = getKeyStrokeData(secondKeyStroke)
val firstPartString = firstKeyStrokeData.first + "$SHORTCUT_PART_SEPARATOR,$SHORTCUT_PART_SEPARATOR"
val firstPartLength = firstPartString.length
val shiftedList = secondKeyStrokeData.second.map { IntRange(it.first + firstPartLength, it.last + firstPartLength) }
return (firstPartString + secondKeyStrokeData.first) to (firstKeyStrokeData.second + shiftedList)
}
fun getKeyStrokeData(keyStroke: KeyStroke?): Pair<@NlsSafe String, List<IntRange>> {
if (keyStroke == null) return Pair("", emptyList())
val modifiers: List<String> = getModifiersText(keyStroke.modifiers)
val keyString = getKeyString(keyStroke.keyCode)
val intervals = mutableListOf<IntRange>()
val builder = StringBuilder()
fun addPart(part: String) {
val start = builder.length
builder.append(part)
intervals.add(IntRange(start, builder.length - 1))
}
for (m in modifiers) {
addPart(m)
builder.append(SHORTCUT_PART_SEPARATOR)
}
addPart(keyString)
return Pair(builder.toString(), intervals)
}
/**
* Converts raw shortcut to presentable form. The parts should be separated by plus sign.
* Example of input: Ctrl + Shift + T
*/
fun getRawShortcutData(shortcut: String): Pair<@NlsSafe String, List<IntRange>> {
val parts = shortcut.split(Regex(""" *\+ *""")).map(this::getPresentableModifier)
val builder = StringBuilder()
val ranges = mutableListOf<IntRange>()
var curInd = 0
for ((ind, part) in parts.withIndex()) {
builder.append(part.replaceSpacesWithNonBreakSpaces())
ranges.add(curInd until builder.length)
if (ind != parts.lastIndex) {
builder.append(SHORTCUT_PART_SEPARATOR)
}
curInd = builder.length
}
return builder.toString() to ranges
}
fun getGotoActionData(@NonNls actionId: String): Pair<String, List<IntRange>> {
val action = ActionManager.getInstance().getAction(actionId)
val actionName = if (action != null) {
action.templatePresentation.text.replaceSpacesWithNonBreakSpaces()
}
else {
thisLogger().error("Failed to find action with id: $actionId")
actionId
}
val gotoActionShortcut = getShortcutByActionId("GotoAction")
val gotoAction = getKeyboardShortcutData(gotoActionShortcut)
val updated = ArrayList<IntRange>(gotoAction.second)
val start = gotoAction.first.length + 5
updated.add(IntRange(start, start + actionName.length - 1))
return Pair(gotoAction.first + " → " + actionName, updated)
}
private fun getModifiersText(modifiers: Int): List<String> {
val modifiersString = if (SystemInfo.isMac) {
// returns glyphs if native shortcuts are enabled, text presentation otherwise
MacKeymapUtil.getModifiersText(modifiers, "+")
}
else KeyEvent.getKeyModifiersText(modifiers)
return modifiersString
.split("[ +]+".toRegex())
.dropLastWhile { it.isEmpty() }
.map(this::getPresentableModifier)
}
private fun getKeyString(code: Int) = when (code) {
KeyEvent.VK_LEFT -> "←"
KeyEvent.VK_RIGHT -> "→"
KeyEvent.VK_UP -> "↑"
KeyEvent.VK_DOWN -> "↓"
else -> if (SystemInfo.isMac) getMacKeyString(code) else getLinuxWinKeyString(code)
}.replaceSpacesWithNonBreakSpaces()
private fun getLinuxWinKeyString(code: Int) = when (code) {
KeyEvent.VK_ENTER -> "↩ Enter"
KeyEvent.VK_BACK_SPACE -> "← Backspace"
else -> KeyEvent.getKeyText(code)
}
private fun getMacKeyString(code: Int) = when (code) {
KeyEvent.VK_ENTER -> "↩ Return"
KeyEvent.VK_BACK_SPACE -> "⌫ Del"
KeyEvent.VK_ESCAPE -> "⎋ Esc"
KeyEvent.VK_TAB -> "⇥ Tab"
else -> KeyEvent.getKeyText(code)
}
private fun getPresentableModifier(rawModifier: String): String {
val modifier = if (KeymapUtil.isSimplifiedMacShortcuts()) getSimplifiedMacModifier(rawModifier) else rawModifier
return modifier.replaceSpacesWithNonBreakSpaces()
}
private fun getSimplifiedMacModifier(modifier: String) = when (modifier) {
"Ctrl" -> "⌃ Ctrl"
"Alt" -> "⌥ Opt"
"Shift" -> "⇧ Shift"
"Cmd" -> "⌘ Cmd"
else -> modifier
}
private fun String.replaceSpacesWithNonBreakSpaces() = this.replace(" ", NON_BREAK_SPACE)
}
|
apache-2.0
|
9fc83d5cf684cfdf636881e596520ff1
| 37.162921 | 127 | 0.721036 | 4.237679 | false | false | false | false |
AsamK/TextSecure
|
app/src/main/java/org/thoughtcrime/securesms/stories/landing/StoriesLandingItem.kt
|
1
|
10998
|
package org.thoughtcrime.securesms.stories.landing
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.avatar.view.AvatarView
import org.thoughtcrime.securesms.badges.BadgeImageView
import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord
import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader
import org.thoughtcrime.securesms.mms.GlideApp
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.stories.StoryTextPostModel
import org.thoughtcrime.securesms.stories.dialogs.StoryContextMenu
import org.thoughtcrime.securesms.util.DateUtils
import org.thoughtcrime.securesms.util.SpanUtil
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
import org.thoughtcrime.securesms.util.visible
import java.util.Locale
/**
* Items displaying a preview and metadata for a story from a user, allowing them to launch into the story viewer.
*/
object StoriesLandingItem {
private const val STATUS_CHANGE = 0
fun register(mappingAdapter: MappingAdapter) {
mappingAdapter.registerFactory(Model::class.java, LayoutFactory(::ViewHolder, R.layout.stories_landing_item))
}
class Model(
val data: StoriesLandingItemData,
val onRowClick: (Model, View) -> Unit,
val onHideStory: (Model) -> Unit,
val onForwardStory: (Model) -> Unit,
val onShareStory: (Model) -> Unit,
val onGoToChat: (Model) -> Unit,
val onSave: (Model) -> Unit,
val onDeleteStory: (Model) -> Unit
) : MappingModel<Model> {
override fun areItemsTheSame(newItem: Model): Boolean {
return data.storyRecipient.id == newItem.data.storyRecipient.id
}
override fun areContentsTheSame(newItem: Model): Boolean {
return data.storyRecipient.hasSameContent(newItem.data.storyRecipient) &&
data == newItem.data &&
!hasStatusChange(newItem) &&
(data.sendingCount == newItem.data.sendingCount && data.failureCount == newItem.data.failureCount) &&
data.storyViewState == newItem.data.storyViewState
}
override fun getChangePayload(newItem: Model): Any? {
return if (isSameRecord(newItem) && hasStatusChange(newItem)) {
STATUS_CHANGE
} else {
null
}
}
private fun isSameRecord(newItem: Model): Boolean {
return data.primaryStory.messageRecord.id == newItem.data.primaryStory.messageRecord.id
}
private fun hasStatusChange(newItem: Model): Boolean {
val oldRecord = data.primaryStory.messageRecord
val newRecord = newItem.data.primaryStory.messageRecord
return oldRecord.isOutgoing &&
newRecord.isOutgoing &&
(oldRecord.isPending != newRecord.isPending || oldRecord.isSent != newRecord.isSent || oldRecord.isFailed != newRecord.isFailed)
}
}
private class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) {
private val avatarView: AvatarView = itemView.findViewById(R.id.avatar)
private val badgeView: BadgeImageView = itemView.findViewById(R.id.badge)
private val storyPreview: ImageView = itemView.findViewById<ImageView>(R.id.story).apply {
isClickable = false
}
private val storyBlur: ImageView = itemView.findViewById<ImageView>(R.id.story_blur).apply {
isClickable = false
}
private val storyOutline: ImageView = itemView.findViewById(R.id.story_outline)
private val storyMulti: ImageView = itemView.findViewById<ImageView>(R.id.story_multi).apply {
isClickable = false
}
private val sender: TextView = itemView.findViewById(R.id.sender)
private val date: TextView = itemView.findViewById(R.id.date)
private val icon: ImageView = itemView.findViewById(R.id.icon)
private val errorIndicator: View = itemView.findViewById(R.id.error_indicator)
override fun bind(model: Model) {
presentDateOrStatus(model)
setUpClickListeners(model)
if (payload.contains(STATUS_CHANGE)) {
return
}
if (model.data.storyRecipient.isMyStory) {
avatarView.displayProfileAvatar(Recipient.self())
badgeView.setBadgeFromRecipient(Recipient.self())
} else {
avatarView.displayProfileAvatar(model.data.storyRecipient)
badgeView.setBadgeFromRecipient(model.data.storyRecipient)
}
val record = model.data.primaryStory.messageRecord as MediaMmsMessageRecord
avatarView.setStoryRingFromState(model.data.storyViewState)
val thumbnail = record.slideDeck.thumbnailSlide?.uri
val blur = record.slideDeck.thumbnailSlide?.placeholderBlur
clearGlide()
storyBlur.visible = blur != null
if (blur != null) {
GlideApp.with(storyBlur).load(blur).into(storyBlur)
}
@Suppress("CascadeIf")
if (record.storyType.isTextStory) {
storyBlur.visible = false
val storyTextPostModel = StoryTextPostModel.parseFrom(record)
GlideApp.with(storyPreview)
.load(storyTextPostModel)
.placeholder(storyTextPostModel.getPlaceholder())
.centerCrop()
.dontAnimate()
.into(storyPreview)
} else if (thumbnail != null) {
storyBlur.visible = blur != null
GlideApp.with(storyPreview)
.load(DecryptableStreamUriLoader.DecryptableUri(thumbnail))
.addListener(HideBlurAfterLoadListener())
.centerCrop()
.dontAnimate()
.into(storyPreview)
}
if (model.data.secondaryStory != null) {
val secondaryRecord = model.data.secondaryStory.messageRecord as MediaMmsMessageRecord
val secondaryThumb = secondaryRecord.slideDeck.thumbnailSlide?.uri
storyOutline.setBackgroundColor(ContextCompat.getColor(context, R.color.signal_background_primary))
@Suppress("CascadeIf")
if (secondaryRecord.storyType.isTextStory) {
val storyTextPostModel = StoryTextPostModel.parseFrom(secondaryRecord)
GlideApp.with(storyMulti)
.load(storyTextPostModel)
.placeholder(storyTextPostModel.getPlaceholder())
.centerCrop()
.dontAnimate()
.into(storyMulti)
storyMulti.visible = true
} else if (secondaryThumb != null) {
GlideApp.with(storyMulti)
.load(DecryptableStreamUriLoader.DecryptableUri(secondaryThumb))
.centerCrop()
.dontAnimate()
.into(storyMulti)
storyMulti.visible = true
} else {
storyOutline.setBackgroundColor(Color.TRANSPARENT)
GlideApp.with(storyMulti).clear(storyMulti)
storyMulti.visible = false
}
} else {
storyOutline.setBackgroundColor(Color.TRANSPARENT)
GlideApp.with(storyMulti).clear(storyMulti)
storyMulti.visible = false
}
sender.text = when {
model.data.storyRecipient.isMyStory -> context.getText(R.string.StoriesLandingFragment__my_stories)
model.data.storyRecipient.isGroup -> getGroupPresentation(model)
else -> model.data.storyRecipient.getDisplayName(context)
}
icon.visible = model.data.hasReplies || model.data.hasRepliesFromSelf
icon.setImageResource(
when {
model.data.hasReplies -> R.drawable.ic_messages_solid_20
else -> R.drawable.ic_reply_24_solid_tinted
}
)
listOf(avatarView, storyPreview, storyMulti, sender, date, icon).forEach {
it.alpha = if (model.data.isHidden) 0.5f else 1f
}
}
private fun presentDateOrStatus(model: Model) {
if (model.data.sendingCount > 0 || (model.data.primaryStory.messageRecord.isOutgoing && (model.data.primaryStory.messageRecord.isPending || model.data.primaryStory.messageRecord.isMediaPending))) {
errorIndicator.visible = model.data.failureCount > 0L
if (model.data.sendingCount > 1) {
date.text = context.getString(R.string.StoriesLandingItem__sending_d, model.data.sendingCount)
} else {
date.setText(R.string.StoriesLandingItem__sending)
}
} else if (model.data.failureCount > 0 || (model.data.primaryStory.messageRecord.isOutgoing && model.data.primaryStory.messageRecord.isFailed)) {
errorIndicator.visible = true
val message = if (model.data.primaryStory.messageRecord.isIdentityMismatchFailure) R.string.StoriesLandingItem__partially_sent else R.string.StoriesLandingItem__send_failed
date.text = SpanUtil.color(ContextCompat.getColor(context, R.color.signal_alert_primary), context.getString(message))
} else {
errorIndicator.visible = false
date.text = DateUtils.getBriefRelativeTimeSpanString(context, Locale.getDefault(), model.data.dateInMilliseconds)
}
}
private fun setUpClickListeners(model: Model) {
itemView.setOnClickListener {
model.onRowClick(model, storyPreview)
}
if (model.data.storyRecipient.isMyStory) {
itemView.setOnLongClickListener(null)
} else {
itemView.setOnLongClickListener {
displayContext(model)
true
}
}
}
private fun getGroupPresentation(model: Model): String {
return context.getString(
R.string.StoryViewerPageFragment__s_to_s,
getIndividualPresentation(model),
model.data.storyRecipient.getDisplayName(context)
)
}
private fun getIndividualPresentation(model: Model): String {
return if (model.data.primaryStory.messageRecord.isOutgoing) {
context.getString(R.string.Recipient_you)
} else {
model.data.individualRecipient.getDisplayName(context)
}
}
private fun displayContext(model: Model) {
itemView.isSelected = true
StoryContextMenu.show(context, itemView, model) { itemView.isSelected = false }
}
private fun clearGlide() {
GlideApp.with(storyPreview).clear(storyPreview)
GlideApp.with(storyBlur).clear(storyBlur)
}
private inner class HideBlurAfterLoadListener : RequestListener<Drawable> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean = false
override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
storyBlur.visible = false
return false
}
}
}
}
|
gpl-3.0
|
4f8e04e9a66f3ee900348dd86f885f1b
| 38.992727 | 203 | 0.707856 | 4.454435 | false | false | false | false |
linkedin/LiTr
|
litr/src/main/java/com/linkedin/android/litr/render/AudioRenderer.kt
|
1
|
7376
|
/*
* Copyright 2022 LinkedIn Corporation
* All Rights Reserved.
*
* Licensed under the BSD 2-Clause License (the "License"). See License in the project root for
* license information.
*/
package com.linkedin.android.litr.render
import android.media.MediaCodec
import android.media.MediaFormat
import android.util.Log
import android.view.Surface
import com.linkedin.android.litr.codec.Encoder
import com.linkedin.android.litr.codec.Frame
import com.linkedin.android.litr.filter.BufferFilter
import com.linkedin.android.litr.utils.ByteBufferPool
import com.linkedin.android.litr.utils.MediaFormatUtils
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.math.ceil
private const val BYTES_PER_SAMPLE = 2
private const val FRAME_WAIT_TIMEOUT: Long = 0L
private const val UNDEFINED_VALUE: Int = -1
private const val TAG = "AudioRenderer"
class AudioRenderer @JvmOverloads constructor(
private val encoder: Encoder,
filters: MutableList<BufferFilter>? = null
) : Renderer {
private val filters: List<BufferFilter> = filters ?: listOf()
private var sourceMediaFormat: MediaFormat? = null
private var targetMediaFormat: MediaFormat? = null
private var targetSampleDurationUs = 0.0
private var sourceChannelCount = UNDEFINED_VALUE
private var targetChannelCount = UNDEFINED_VALUE
private var sourceSampleRate = UNDEFINED_VALUE
private var targetSampleRate = UNDEFINED_VALUE
private var samplingRatio = 1.0
private val bufferPool = ByteBufferPool(true)
private val audioProcessorFactory = AudioProcessorFactory()
private var audioProcessor: AudioProcessor? = null
private var released: AtomicBoolean = AtomicBoolean(false)
private val renderQueue = LinkedBlockingDeque<Frame>()
private val renderThread = RenderThread()
override fun init(outputSurface: Surface?, sourceMediaFormat: MediaFormat?, targetMediaFormat: MediaFormat?) {
onMediaFormatChanged(sourceMediaFormat, targetMediaFormat)
released.set(false)
renderThread.start()
filters.forEach { it.init(targetMediaFormat) }
}
override fun onMediaFormatChanged(sourceMediaFormat: MediaFormat?, targetMediaFormat: MediaFormat?) {
val sourceChannelCount =
sourceMediaFormat?.let { MediaFormatUtils.getChannelCount(it, UNDEFINED_VALUE) } ?: UNDEFINED_VALUE
val targetChannelCount =
targetMediaFormat?.let { MediaFormatUtils.getChannelCount(it, UNDEFINED_VALUE) } ?: UNDEFINED_VALUE
val sourceSampleRate =
sourceMediaFormat?.let { MediaFormatUtils.getSampleRate(it, UNDEFINED_VALUE) } ?: UNDEFINED_VALUE
val targetSampleRate =
targetMediaFormat?.let { MediaFormatUtils.getSampleRate(it, UNDEFINED_VALUE) } ?: UNDEFINED_VALUE
if (this.sourceChannelCount != sourceChannelCount ||
this.targetChannelCount != targetChannelCount ||
this.sourceSampleRate != sourceSampleRate ||
this.targetSampleRate != targetSampleRate) {
audioProcessor?.release()
audioProcessor = audioProcessorFactory.createAudioProcessor(sourceMediaFormat, targetMediaFormat)
this.sourceChannelCount = sourceChannelCount.toInt()
this.targetChannelCount = targetChannelCount.toInt()
this.sourceSampleRate = sourceSampleRate.toInt()
this.targetSampleRate = targetSampleRate.toInt()
targetSampleDurationUs = 1_000_000.0 / targetSampleRate.toDouble()
samplingRatio = targetSampleRate.toDouble() / sourceSampleRate.toDouble()
this.sourceMediaFormat = sourceMediaFormat
this.targetMediaFormat = targetMediaFormat
}
}
override fun getInputSurface(): Surface? {
return null
}
override fun renderFrame(inputFrame: Frame?, presentationTimeNs: Long) {
if (!released.get() && inputFrame != null) {
val sourceSampleCount = inputFrame.bufferInfo.size / (BYTES_PER_SAMPLE * sourceChannelCount)
val estimatedTargetSampleCount = ceil(sourceSampleCount * samplingRatio).toInt()
val targetBufferCapacity = estimatedTargetSampleCount * targetChannelCount * BYTES_PER_SAMPLE
val targetBuffer = bufferPool.get(targetBufferCapacity)
val processedFrame = Frame(inputFrame.tag, targetBuffer, MediaCodec.BufferInfo())
audioProcessor?.processFrame(inputFrame, processedFrame)
filters.forEach { it.apply(processedFrame) }
renderQueue.add(processedFrame)
}
}
override fun release() {
released.set(true)
audioProcessor?.release()
bufferPool.clear()
filters.forEach { it.release() }
}
override fun hasFilters(): Boolean {
return filters.isNotEmpty()
}
private inner class RenderThread : Thread() {
override fun run() {
while (!released.get()) {
renderQueue.peekFirst()?.let { inputFrame ->
val tag = encoder.dequeueInputFrame(FRAME_WAIT_TIMEOUT)
when {
tag >= 0 -> renderFrame(tag, inputFrame)
tag == MediaCodec.INFO_TRY_AGAIN_LATER -> {} // do nothing, will try later
else -> Log.e(TAG, "Unhandled value $tag when receiving decoded input frame")
}
}
}
renderQueue.clear()
}
private fun renderFrame(tag: Int, inputFrame: Frame) {
encoder.getInputFrame(tag)?.let { outputFrame ->
if (outputFrame.buffer != null && inputFrame.buffer != null) {
outputFrame.bufferInfo.offset = 0
outputFrame.bufferInfo.flags = inputFrame.bufferInfo.flags
outputFrame.bufferInfo.presentationTimeUs =
inputFrame.bufferInfo.presentationTimeUs +
((inputFrame.buffer.position() / (targetChannelCount * BYTES_PER_SAMPLE)) * targetSampleDurationUs).toLong()
val inputBufferDepleted = if (outputFrame.buffer.limit() >= inputFrame.buffer.remaining()) {
// if remaining input bytes fit output buffer, use them all
outputFrame.bufferInfo.size = inputFrame.buffer.remaining()
true
} else {
// otherwise, fill the output buffer and clear its EOS flag
outputFrame.bufferInfo.size = outputFrame.buffer.limit()
outputFrame.bufferInfo.flags = outputFrame.bufferInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM.inv()
false
}
repeat(outputFrame.bufferInfo.size) {
outputFrame.buffer.put(inputFrame.buffer.get())
}
if (inputBufferDepleted) {
// all input buffer contents are consumed, remove it from render queue and put it back into buffer pool
renderQueue.removeFirst()
bufferPool.put(inputFrame.buffer)
}
encoder.queueInputFrame(outputFrame)
}
}
}
}
}
|
bsd-2-clause
|
f766de90a46538b4024fef8b4d1aecfa
| 42.134503 | 136 | 0.649132 | 5.031378 | false | false | false | false |
marius-m/wt4
|
components/src/main/java/lt/markmerkk/export/entities/ExportLogResponse.kt
|
1
|
612
|
package lt.markmerkk.export.entities
import lt.markmerkk.entities.Log
data class ExportLogResponse(
val start: Long,
val end: Long,
val duration: Long,
val code: String,
val comment: String
) {
companion object {
fun fromLog(log: Log): ExportLogResponse {
return ExportLogResponse(
start = log.time.startAsRaw,
end = log.time.endAsRaw,
duration = log.time.durationAsRaw,
code = log.code.code,
comment = log.comment
)
}
}
}
|
apache-2.0
|
5c68f8fd2f1e7f80db90da8cde3c914e
| 25.652174 | 54 | 0.527778 | 4.467153 | false | false | false | false |
marius-m/wt4
|
app/src/main/java/lt/markmerkk/dagger/modules/SyncModule.kt
|
1
|
1993
|
package lt.markmerkk.dagger.modules
import dagger.Module
import dagger.Provides
import lt.markmerkk.*
import lt.markmerkk.interactors.*
import lt.markmerkk.worklogs.WorklogApi
import javax.inject.Singleton
@Module
class SyncModule {
@Provides
@Singleton
fun providesClientProvider(
userSettings: UserSettings
): JiraClientProvider {
return if (BuildConfig.oauth) {
JiraClientProviderOauth(userSettings)
} else {
JiraClientProviderBasic(userSettings)
}
}
@Provides
@Singleton
fun providesSyncInteractor(
schedulerProvider: SchedulerProvider,
timeProvider: TimeProvider,
worklogStorage: WorklogStorage,
worklogApi: WorklogApi,
jiraClientProvider: JiraClientProvider,
userSettings: UserSettings,
jiraBasicApi: JiraBasicApi,
activeDisplayRepository: ActiveDisplayRepository
): SyncInteractor {
return SyncInteractorImpl(
ioScheduler = schedulerProvider.io(),
uiScheduler = schedulerProvider.ui(),
timeProvider = timeProvider,
jiraClientProvider = jiraClientProvider,
worklogStorage = worklogStorage,
worklogApi = worklogApi,
userSettings = userSettings,
jiraBasicApi = jiraBasicApi,
activeDisplayRepository = activeDisplayRepository
)
}
@Provides
@Singleton
fun providesJiraBasicApi(
jiraClientProvider: JiraClientProvider
): JiraBasicApi {
return JiraBasicApi(jiraClientProvider)
}
@Provides
@Singleton
fun providesJiraAuthInteractor(
jiraClientProvider: JiraClientProvider,
jiraBasicApi: JiraBasicApi,
userSettings: UserSettings
): AuthService.AuthInteractor {
return AuthInteractorImpl(
jiraClientProvider,
jiraBasicApi,
userSettings
)
}
}
|
apache-2.0
|
e802d12e204dc614d694e5952ca37223
| 26.694444 | 61 | 0.652785 | 5.931548 | false | false | false | false |
marius-m/wt4
|
app/src/main/java/lt/markmerkk/widgets/statistics/StatisticsPresenter.kt
|
1
|
2240
|
package lt.markmerkk.widgets.statistics
import lt.markmerkk.ActiveDisplayRepository
import lt.markmerkk.utils.LogUtils
import lt.markmerkk.utils.hourglass.HourGlass
class StatisticsPresenter(
private val hourGlass: HourGlass,
private val activeDisplayRepository: ActiveDisplayRepository
) : StatisticsContract.Presenter {
private var view: StatisticsContract.View? = null
override fun onAttach(view: StatisticsContract.View) {
this.view = view
}
override fun onDetach() {
this.view = null
}
override fun mapData(): Map<String, Long> {
val ticketDurationMap = activeDisplayRepository.displayLogs
.map { it.code.code to it.time.duration.millis }
val ticketDurationSumMap = mutableMapOf<String, Long>()
ticketDurationMap
.forEach {
if (ticketDurationSumMap.contains(it.first)) {
val oldDuration = ticketDurationSumMap[it.first]
ticketDurationSumMap[it.first] = oldDuration!!.plus(it.second)
} else {
ticketDurationSumMap[it.first] = it.second
}
}
if (ticketDurationSumMap.containsKey("")) {
ticketDurationSumMap.put("Not mapped", ticketDurationSumMap[""]!!)
ticketDurationSumMap.remove("")
}
return ticketDurationSumMap
}
override fun totalAsString(): String {
if (hourGlass.isRunning()) {
val totalLogged: Long = activeDisplayRepository.totalInMillis()
val formatTotalLogged = LogUtils.formatShortDurationMillis(totalLogged)
val totalRunning = hourGlass.duration.millis
val formatTotalRunning = LogUtils.formatShortDurationMillis(totalRunning)
val formatTotal = LogUtils.formatShortDurationMillis(totalLogged + totalRunning)
return "Logged ($formatTotalLogged) + Running ($formatTotalRunning) = $formatTotal"
} else {
val totalLogged = activeDisplayRepository.totalInMillis()
val formatTotalLogged = LogUtils.formatShortDurationMillis(totalLogged)
return "Logged ($formatTotalLogged)"
}
}
}
|
apache-2.0
|
bcc39d6f17bfc0fa900a8d35916cb9fc
| 38.315789 | 95 | 0.649554 | 5.056433 | false | false | false | false |
contentful/contentful-management.java
|
src/test/kotlin/com/contentful/java/cma/LocalesTests.kt
|
1
|
10528
|
package com.contentful.java.cma
import com.contentful.java.cma.lib.TestCallback
import com.contentful.java.cma.lib.TestUtils
import com.contentful.java.cma.model.CMALocale
import com.google.gson.Gson
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.util.logging.LogManager
import kotlin.test.assertEquals
class LocalesTests{
var server: MockWebServer? = null
var client: CMAClient? = null
var gson: Gson? = null
@Before
fun setUp() {
LogManager.getLogManager().reset()
// MockWebServer
server = MockWebServer()
server!!.start()
// Client
client = CMAClient.Builder()
.setAccessToken("token")
.setCoreEndpoint(server!!.url("/").toString())
.setUploadEndpoint(server!!.url("/").toString())
.setSpaceId("configuredSpaceId")
.setEnvironmentId("configuredEnvironmentId")
.build()
gson = CMAClient.createGson()
}
@After
fun tearDown() {
server!!.shutdown()
}
@Test
fun testFetchOne() {
val responseBody = TestUtils.fileToString("locales_get_one.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
val result = assertTestCallback(client!!.locales().async()
.fetchOne("spaceId", "master", "localeId", TestCallback()) as TestCallback)!!
assertEquals("U.S. English", result.name)
assertEquals("en-US", result.code)
assertEquals(null, result.fallbackCode)
assertEquals(true, result.isDefault)
assertEquals(true, result.isContentManagementApi)
assertEquals(true, result.isContentDeliveryApi)
assertEquals(false, result.isOptional)
assertEquals("7lTcrh2SzR626t7fR8rIPD", result.id)
assertEquals("Locale", result.system.type.name)
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/spaces/spaceId/environments/master/locales/localeId", recordedRequest.path)
}
@Test
fun testFetchOneWithConfiguredSpaceAndEnvironment() {
val responseBody = TestUtils.fileToString("locales_get_one.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
assertTestCallback(client!!.locales().async().fetchOne("localeId", TestCallback())
as TestCallback)!!
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/spaces/configuredSpaceId/environments/configuredEnvironmentId"
+ "/locales/localeId",
recordedRequest.path)
}
@Test
fun testFetchAll() {
val responseBody = TestUtils.fileToString("locales_get_all.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
val result = assertTestCallback(client!!.locales().async()
.fetchAll("spaceId", "master", TestCallback()) as TestCallback)!!
assertEquals(2, result.total)
assertEquals(100, result.limit)
assertEquals(0, result.skip)
assertEquals(2, result.items.size)
assertEquals("U.S. English", result.items[0].name)
assertEquals("English (British)", result.items[1].name)
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/spaces/spaceId/environments/master/locales", recordedRequest.path)
}
@Test
fun testFetchAllWithConfiguredSpaceAndEnvironment() {
val responseBody = TestUtils.fileToString("locales_get_all.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
assertTestCallback(client!!.locales().async().fetchAll(TestCallback()) as TestCallback)!!
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/spaces/configuredSpaceId/environments/configuredEnvironmentId/locales",
recordedRequest.path)
}
@Test
fun testCreateNew() {
val responseBody = TestUtils.fileToString("locales_create.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
val locale = CMALocale()
.setName("English (British)")
.setCode("en-UK")
.setFallbackCode("en-US")
.setOptional(false)
val result = assertTestCallback(client!!.locales().async()
.create("spaceId", "master", locale, TestCallback()) as TestCallback)!!
assertEquals("English (British)", result.name)
assertEquals("en-UK", result.code)
assertEquals("en-US", result.fallbackCode)
assertEquals(false, result.isOptional)
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("POST", recordedRequest.method)
assertEquals("/spaces/spaceId/environments/master/locales/", recordedRequest.path)
}
@Test
fun testCreateNewWithConfiguredSpaceAndEnvironment() {
val responseBody = TestUtils.fileToString("locales_create.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
val locale = CMALocale()
.setName("English (British)")
.setCode("en-UK")
.setFallbackCode("en-US")
.setOptional(false)
assertTestCallback(client!!.locales().async().create(locale, TestCallback())
as TestCallback)!!
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("POST", recordedRequest.method)
assertEquals("/spaces/configuredSpaceId/environments/configuredEnvironmentId/locales/",
recordedRequest.path)
}
@Test
fun testUpdate() {
val responseBody = TestUtils.fileToString("locales_update.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
// DO NOT USE IN PRODUCTION: USE A FETCH FIRST!
val locale = CMALocale()
.setId("sampleId")
.setSpaceId("spaceId")
.setVersion(3)
.setName("U.S. English")
.setCode("en-US")
.setFallbackCode(null)
.setOptional(false)
val result = assertTestCallback(client!!.locales().async()
.update(locale, TestCallback()) as TestCallback)!!
assertEquals("U.S. English", result.name)
assertEquals("en-US", result.code)
assertEquals(null, result.fallbackCode)
assertEquals(true, result.isDefault)
assertEquals(true, result.isContentManagementApi)
assertEquals(true, result.isContentDeliveryApi)
assertEquals(false, result.isOptional)
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("PUT", recordedRequest.method)
assertEquals("/spaces/spaceId/environments/master/locales/sampleId", recordedRequest.path)
}
@Test
fun testDeleteOne() {
val responseBody = TestUtils.fileToString("locales_delete.json")
server!!.enqueue(MockResponse().setResponseCode(204).setBody(responseBody))
assertTestCallback(client!!.locales().async()
.delete(
CMALocale().setId("localeId").setSpaceId("spaceId"),
TestCallback()
) as TestCallback)
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("DELETE", recordedRequest.method)
assertEquals("/spaces/spaceId/environments/master/locales/localeId", recordedRequest.path)
}
@Test
fun testFetchAllFromEnvironment() {
val responseBody = TestUtils.fileToString("locales_get_all_form_environment.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
val result = assertTestCallback(client!!.locales().async()
.fetchAll("spaceId", "staging", TestCallback()) as TestCallback)!!
assertEquals(8, result.total)
assertEquals(100, result.limit)
assertEquals(0, result.skip)
assertEquals(8, result.items.size)
assertEquals("U.S. English", result.items[0].name)
assertEquals("English (British)", result.items[1].name)
assertEquals("staging", result.items[0].environmentId)
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/spaces/spaceId/environments/staging/locales", recordedRequest.path)
}
@Test
fun testFetchOneFromEnvironment() {
val responseBody = TestUtils.fileToString("locales_get_one_form_environment.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
val result = assertTestCallback(client!!.locales().async()
.fetchOne("spaceId", "staging", "7lTcrh2SzR626t7fR8rIPD", TestCallback()) as TestCallback)!!
assertEquals("U.S. English", result.name)
assertEquals("staging", result.environmentId)
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/spaces/spaceId/environments/staging/locales/7lTcrh2SzR626t7fR8rIPD", recordedRequest.path)
}
@Test
fun testCreateInEnvironment() {
val responseBody = TestUtils.fileToString("locales_create_in_environment.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
val locale = CMALocale().apply {
name = "Chinese"
code = "cn"
}
val result = assertTestCallback(client!!.locales().async()
.create("spaceId", "staging", locale, TestCallback()) as TestCallback)!!
assertEquals("Chinese", result.name)
assertEquals("cn", result.code)
assertEquals("staging", result.environmentId)
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("POST", recordedRequest.method)
assertEquals("/spaces/spaceId/environments/staging/locales/", recordedRequest.path)
}
}
|
apache-2.0
|
ee8ca0b03443bb047d7a14ed30712527
| 36.603571 | 113 | 0.646657 | 5.010947 | false | true | false | false |
Philip-Trettner/GlmKt
|
GlmKtGen/src/code/Func.kt
|
1
|
2982
|
package code
import SourceGen
import cjoin
import sjoin
import types.AbstractType
import types.BaseType
import java.io.InvalidClassException
import kotlin.coroutines.experimental.buildSequence
open class Func(val name: String,
val returnType: AbstractType,
val funcArgs: Iterable<Argument> = listOf(),
val isInfix: Boolean = false,
val isOperator: Boolean = false,
val isOverride: Boolean = false,
val isInline: Boolean = false,
val isConstructor: Boolean = false,
val isProperty: Boolean = false,
val genericArg: String = "",
val extends: String = "",
val modifier: String = "" // default public is warning in IntelliJ
) : Declaration() {
var hasGetter = false
var hasSetter = false
var implementation: SourceGen.(String) -> Unit = { +"$it = TODO: IMPLEMENT ME!" }
var getterImpl: SourceGen.(String) -> Unit = { +"$it = TODO: IMPLEMENT ME!" }
var setterImpl: SourceGen.(String) -> Unit = { +"$it = TODO: IMPLEMENT ME!" }
override fun generate(gen: SourceGen) = with(gen) {
// comments
comments.forEach { +it }
val fDecl = buildSequence {
if (modifier != "") yield(modifier)
if (isOverride) yield("override")
if (isInline) yield("inline")
if (isInfix) yield("infix")
if (isOperator) yield("operator")
if (isProperty) yield(if (hasSetter) "var" else "val")
else if (isConstructor) yield("constructor")
else yield("fun")
if (genericArg != "") yield("<$genericArg>")
if (!isConstructor)
if (extends != "") yield("$extends.$name")
else yield(name)
}.sjoin()
val fArgs = if (isProperty) "" else "(${funcArgs.cjoin()})"
val fDef = if (isConstructor || returnType === BaseType.Unit) "$fDecl$fArgs" else "$fDecl$fArgs: ${returnType.typeNameWithT}"
if (isProperty) {
when {
hasGetter && hasSetter -> {
+fDef
indent {
getterImpl("get()")
setterImpl("set(value)")
}
}
hasGetter -> getterImpl("$fDef get()")
hasSetter -> setterImpl("$fDef set(value)")
else -> throw Exception("No Getter or Setter")
}
} else {
implementation(fDef)
}
}
infix fun impl(func: SourceGen.(String) -> Unit): Func {
implementation = func
return this
}
infix fun getter(func: SourceGen.(String) -> Unit): Func {
getterImpl = func
hasGetter = true
return this
}
infix fun setter(func: SourceGen.(String) -> Unit): Func {
setterImpl = func
hasSetter = true
return this
}
}
|
mit
|
3c3d8b2a1a2a032a6a6e6a6ac0846519
| 33.686047 | 133 | 0.532529 | 4.696063 | false | false | false | false |
Scavi/BrainSqueeze
|
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day7HandyHaversacks.kt
|
1
|
1656
|
package com.scavi.brainsqueeze.adventofcode
import com.scavi.brainsqueeze.adventofcode.util.GraphAccess
import java.lang.IllegalArgumentException
class Day7HandyHaversacks {
private val bagSplit = """[a-z]*\s[a-z]*(?=\sbag)|((?<=\s)\d+)""".toRegex()
fun solveA(input: List<String>): Int {
val graph = createGraphAccess(input)
return graph.findPossiblePathTo("shiny gold")
}
fun solveB(input: List<String>): Int {
val graph = createGraphAccess(input)
return calc(graph, "shiny gold") - 1
}
private fun calc(graphAccess: GraphAccess<String>, bagName: String): Int {
if (graphAccess.getGraph()[bagName]?.isEmpty() ?: error("Unknown bag: $bagName")) {
return 1
}
var count = 1
for (nextBag in graphAccess.getGraph()[bagName] ?: error("Unknown bag: $bagName")) {
count += nextBag.weight * calc(graphAccess, nextBag.targetNode)
}
return count
}
private fun createGraphAccess(input: List<String>): GraphAccess<String> {
val graphAccess = GraphAccess<String>()
for (rule in input) {
val tokens = split(rule)
if (tokens.size >= 3) {
for (i in 1 until tokens.size step 2) {
graphAccess.addEdge(tokens[0], tokens[i + 1], tokens[i].toInt())
}
} else {
if (tokens.size != 2) {
throw IllegalArgumentException("woot?!")
}
}
}
return graphAccess
}
fun split(input: String) = bagSplit.findAll(input).map { it.groupValues[0] }.toList()
}
|
apache-2.0
|
de64b55ad3542744c685f0ea053de33f
| 32.795918 | 92 | 0.576691 | 4.0489 | false | false | false | false |
dhis2/dhis2-android-sdk
|
core/src/main/java/org/hisp/dhis/android/core/arch/db/stores/internal/ObjectStoreImpl.kt
|
1
|
5780
|
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.arch.db.stores.internal
import android.content.ContentValues
import android.database.Cursor
import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.SQLStatementBuilder
import org.hisp.dhis.android.core.arch.db.stores.binders.internal.StatementBinder
import org.hisp.dhis.android.core.arch.db.stores.binders.internal.StatementWrapper
import org.hisp.dhis.android.core.arch.helpers.CollectionsHelper
import org.hisp.dhis.android.core.common.CoreColumns
import org.hisp.dhis.android.core.common.CoreObject
@Suppress("TooManyFunctions")
internal open class ObjectStoreImpl<O : CoreObject> internal constructor(
databaseAdapter: DatabaseAdapter,
override val builder: SQLStatementBuilder,
protected val binder: StatementBinder<O>,
objectFactory: (Cursor) -> O
) : ReadableStoreImpl<O>(databaseAdapter, builder, objectFactory), ObjectStore<O> {
private var insertStatement: StatementWrapper? = null
private var adapterHashCode: Int? = null
@Throws(RuntimeException::class)
@Suppress("TooGenericExceptionThrown")
override fun insert(o: O): Long {
CollectionsHelper.isNull(o)
compileStatements()
binder.bindToStatement(o, insertStatement!!)
val insertedRowId = databaseAdapter.executeInsert(insertStatement)
insertStatement!!.clearBindings()
if (insertedRowId == -1L) {
throw RuntimeException("Nothing was inserted.")
}
return insertedRowId
}
@Throws(RuntimeException::class)
override fun insert(objects: Collection<O>) {
for (m in objects) {
insert(m)
}
}
private fun compileStatements() {
resetStatementsIfDbChanged()
if (insertStatement == null) {
insertStatement = databaseAdapter.compileStatement(builder.insert())
}
}
private fun resetStatementsIfDbChanged() {
if (hasAdapterChanged()) {
insertStatement!!.close()
insertStatement = null
}
}
private fun hasAdapterChanged(): Boolean {
val oldCode = adapterHashCode
adapterHashCode = databaseAdapter.hashCode()
return oldCode != null && databaseAdapter.hashCode() != oldCode
}
override fun selectStringColumnsWhereClause(column: String, clause: String): List<String> {
val cursor = databaseAdapter.rawQuery(builder.selectColumnWhere(column, clause))
return mapStringColumnSetFromCursor(cursor)
}
override fun delete(): Int {
return databaseAdapter.delete(builder.tableName)
}
@Throws(RuntimeException::class)
@Suppress("TooGenericExceptionThrown")
fun executeUpdateDelete(statement: StatementWrapper) {
val numberOfAffectedRows = databaseAdapter.executeUpdateDelete(statement)
statement.clearBindings()
if (numberOfAffectedRows == 0) {
throw RuntimeException("No rows affected")
} else if (numberOfAffectedRows > 1) {
throw RuntimeException("Unexpected number of affected rows: $numberOfAffectedRows")
}
}
override fun deleteById(o: O): Boolean {
return deleteWhere(CoreColumns.ID + "='" + o.id() + "';")
}
protected fun popOneWhere(whereClause: String): O? {
val m = selectOneWhere(whereClause)
if (m != null) {
deleteById(m)
}
return m
}
override fun deleteWhere(clause: String): Boolean {
return databaseAdapter.delete(builder.tableName, clause, null) > 0
}
override fun updateWhere(updates: ContentValues, whereClause: String): Int {
return databaseAdapter.update(builder.tableName, updates, whereClause, null)
}
@Throws(RuntimeException::class)
@Suppress("TooGenericExceptionCaught")
override fun deleteWhereIfExists(whereClause: String) {
try {
deleteWhere(whereClause)
} catch (e: RuntimeException) {
if (e.message != "No rows affected") {
throw e
}
}
}
override val isReady: Boolean
get() = databaseAdapter.isReady
}
|
bsd-3-clause
|
dd568acfc22ed67f44547df43191f34b
| 38.319728 | 95 | 0.704671 | 4.710676 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/details/MultipleCommitInfoDialog.kt
|
12
|
5020
|
// 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.vcs.log.ui.details
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.Change
import com.intellij.ui.CollectionListModel
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.ListSpeedSearch
import com.intellij.ui.OnePixelSplitter
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.speedSearch.FilteringListModel
import com.intellij.ui.speedSearch.SpeedSearchUtil
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.vcs.log.VcsCommitMetadata
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NonNls
import javax.swing.JList
import javax.swing.ScrollPaneConstants
@ApiStatus.Experimental
abstract class MultipleCommitInfoDialog(private val project: Project, commits: List<VcsCommitMetadata>)
: DialogWrapper(project, true) {
companion object {
private const val DIALOG_WIDTH = 600
private const val DIALOG_HEIGHT = 400
@NonNls
private const val DIMENSION_KEY = "Vcs.Multiple.Commit.Info.Dialog.Key"
@NonNls
private const val CHANGES_SPLITTER = "Vcs.Multiple.Commit.Info.Dialog.Changes.Splitter"
}
private val commitsList = JBList<VcsCommitMetadata>()
private val modalityState = ModalityState.stateForComponent(window)
private val fullCommitDetailsListPanel = object : FullCommitDetailsListPanel(project, disposable, modalityState) {
@RequiresBackgroundThread
@Throws(VcsException::class)
override fun loadChanges(commits: List<VcsCommitMetadata>): List<Change> = [email protected](commits)
}
init {
commitsList.border = JBUI.Borders.emptyTop(10)
val model = FilteringListModel(CollectionListModel(commits))
commitsList.model = model
resetFilter()
commitsList.cellRenderer = object : ColoredListCellRenderer<VcsCommitMetadata>() {
override fun customizeCellRenderer(
list: JList<out VcsCommitMetadata>,
value: VcsCommitMetadata?,
index: Int,
selected: Boolean,
hasFocus: Boolean
) {
border = JBUI.Borders.empty()
ipad = JBUI.insetsLeft(20)
if (value != null) {
append(value.subject)
SpeedSearchUtil.applySpeedSearchHighlighting(commitsList, this, true, selected)
}
}
}
commitsList.selectionModel.addListSelectionListener { e ->
if (e.valueIsAdjusting) {
return@addListSelectionListener
}
val selectedCommits = commitsList.selectedIndices.map { model.getElementAt(it) }
fullCommitDetailsListPanel.commitsSelected(selectedCommits)
}
installSpeedSearch()
init()
}
final override fun init() {
super.init()
}
override fun getDimensionServiceKey() = DIMENSION_KEY
override fun getPreferredFocusedComponent() = commitsList
@RequiresBackgroundThread
@Throws(VcsException::class)
protected abstract fun loadChanges(commits: List<VcsCommitMetadata>): List<Change>
fun setFilter(condition: (VcsCommitMetadata) -> Boolean) {
val selectedCommits = commitsList.selectedValuesList.toSet()
val model = commitsList.model as FilteringListModel<VcsCommitMetadata>
model.setFilter(condition)
val selectedIndicesAfterFilter = mutableListOf<Int>()
for (index in 0 until model.size) {
val commit = model.getElementAt(index)
if (commit in selectedCommits) {
selectedIndicesAfterFilter.add(index)
}
}
if (selectedIndicesAfterFilter.isEmpty()) {
commitsList.selectedIndex = 0
}
else {
commitsList.selectedIndices = selectedIndicesAfterFilter.toIntArray()
}
}
fun resetFilter() {
setFilter { true }
}
private fun installSpeedSearch() {
ListSpeedSearch(commitsList) { it.subject }
}
override fun createActions() = arrayOf(okAction)
override fun getStyle() = DialogStyle.COMPACT
override fun createCenterPanel() = BorderLayoutPanel().apply {
preferredSize = JBDimension(DIALOG_WIDTH, DIALOG_HEIGHT)
val commitInfoSplitter = OnePixelSplitter(CHANGES_SPLITTER, 0.5f)
commitInfoSplitter.setHonorComponentsMinimumSize(false)
val commitsListScrollPane = JBScrollPane(
commitsList,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
)
commitsListScrollPane.border = JBUI.Borders.empty()
commitInfoSplitter.firstComponent = commitsListScrollPane
commitInfoSplitter.secondComponent = fullCommitDetailsListPanel
addToCenter(commitInfoSplitter)
}
}
|
apache-2.0
|
674308e6d54b8af6f3b03b2c706feef0
| 35.384058 | 140 | 0.758566 | 4.762808 | false | false | false | false |
DreierF/MyTargets
|
app/src/main/java/de/dreier/mytargets/base/db/migrations/Migration25.kt
|
1
|
1078
|
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.base.db.migrations
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.room.migration.Migration
object Migration25 : Migration(24, 25) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("UPDATE Training SET weather = \"\" WHERE weather = NULL")
database.execSQL("UPDATE Training SET location = \"\" WHERE location = NULL")
database.execSQL("DELETE FROM StandardRound WHERE (SELECT COUNT(r._id) FROM RoundTemplate r WHERE r.standardRound=StandardRound._id)=0")
}
}
|
gpl-2.0
|
73c3d55cfa47871b1f1686c2fd7eed3d
| 38.925926 | 144 | 0.74397 | 4.491667 | false | false | false | false |
tateisu/SubwayTooter
|
app/src/main/java/jp/juggler/subwaytooter/api/entity/MisskeyNoteUpdate.kt
|
1
|
2121
|
package jp.juggler.subwaytooter.api.entity
import jp.juggler.subwaytooter.emoji.CustomEmoji
import jp.juggler.util.JsonObject
import jp.juggler.util.LogCategory
class MisskeyNoteUpdate(apDomain: Host, src: JsonObject) {
companion object {
private val log = LogCategory("MisskeyNoteUpdate")
}
enum class Type {
REACTION,
UNREACTION,
DELETED,
VOTED
}
val noteId: EntityId
val type: Type
var reaction: String? = null
var userId: EntityId? = null
var deletedAt: Long? = null
var choice: Int? = null
var emoji: CustomEmoji? = null
init {
noteId = EntityId.mayNull(src.string("id")) ?: error("MisskeyNoteUpdate: missing note id")
// root.body.body
val body2 = src.jsonObject("body") ?: error("MisskeyNoteUpdate: missing body")
when (val strType = src.string("type")) {
"reacted" -> {
type = Type.REACTION
reaction = body2.string("reaction")
userId = EntityId.mayDefault(body2.string("userId"))
emoji = body2.jsonObject("emoji")?.let {
try {
CustomEmoji.decodeMisskey(apDomain, it)
} catch (ex: Throwable) {
log.e(ex, "can't parse custom emoji.")
null
}
}
}
"unreacted" -> {
type = Type.UNREACTION
reaction = body2.string("reaction")
userId = EntityId.mayDefault(body2.string("userId"))
}
"deleted" -> {
type = Type.DELETED
deletedAt = TootStatus.parseTime(body2.string("deletedAt"))
}
"pollVoted" -> {
type = Type.VOTED
choice = body2.int("choice")
userId = EntityId.mayDefault(body2.string("userId"))
}
else -> error("MisskeyNoteUpdate: unknown type $strType")
}
}
}
|
apache-2.0
|
2dca2500dc4b5c88665a76f12376ae5a
| 29.191176 | 98 | 0.507308 | 4.671806 | false | false | false | false |
paplorinc/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/actions/ShowMessageHistoryAction.kt
|
1
|
6089
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.actions
import com.intellij.ide.TextCopyProvider
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys.COPY_PROVIDER
import com.intellij.openapi.application.ApplicationManager.getApplication
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.editor.actions.ContentChooser.RETURN_SYMBOL
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.util.text.StringUtil.convertLineSeparators
import com.intellij.openapi.util.text.StringUtil.first
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.ui.CommitMessage
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.speedSearch.SpeedSearchUtil.applySpeedSearchHighlighting
import com.intellij.util.ObjectUtils.sentinel
import com.intellij.util.containers.nullize
import com.intellij.util.ui.JBUI.scale
import com.intellij.vcs.commit.CommitMessageInspectionProfile.getSubjectRightMargin
import java.awt.Point
import javax.swing.JList
import javax.swing.ListSelectionModel.SINGLE_SELECTION
/**
* Action showing the history of recently used commit messages. Source code of this class is provided
* as a sample of using the [CheckinProjectPanel] API. Actions to be shown in the commit dialog
* should be added to the `Vcs.MessageActionGroup` action group.
*/
class ShowMessageHistoryAction : DumbAwareAction() {
init {
isEnabledInModalContext = true
}
override fun update(e: AnActionEvent) {
val project = e.project
val commitMessage = getCommitMessage(e)
e.presentation.isVisible = project != null && commitMessage != null
e.presentation.isEnabled = e.presentation.isVisible && !VcsConfiguration.getInstance(project!!).recentMessages.isEmpty()
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val commitMessage = getCommitMessage(e)!!
createPopup(project, commitMessage, VcsConfiguration.getInstance(project).recentMessages.reversed())
.showInBestPositionFor(e.dataContext)
}
private fun createPopup(project: Project, commitMessage: CommitMessage, messages: List<String>): JBPopup {
var chosenMessage: String? = null
var selectedMessage: String? = null
val rightMargin = getSubjectRightMargin(project)
val previewCommandGroup = sentinel("Preview Commit Message")
return JBPopupFactory.getInstance().createPopupChooserBuilder(messages)
.setFont(commitMessage.editorField.editor?.colorsScheme?.getFont(EditorFontType.PLAIN))
.setVisibleRowCount(7)
.setSelectionMode(SINGLE_SELECTION)
.setItemSelectedCallback {
selectedMessage = it
it?.let { preview(project, commitMessage, it, previewCommandGroup) }
}
.setItemChosenCallback { chosenMessage = it }
.setRenderer(object : ColoredListCellRenderer<String>() {
override fun customizeCellRenderer(list: JList<out String>, value: String, index: Int, selected: Boolean, hasFocus: Boolean) {
append(first(convertLineSeparators(value, RETURN_SYMBOL), rightMargin, false))
applySpeedSearchHighlighting(list, this, true, selected)
}
})
.addListener(object : JBPopupListener {
override fun beforeShown(event: LightweightWindowEvent) {
val popup = event.asPopup()
val relativePoint = RelativePoint(commitMessage.editorField, Point(0, -scale(3)))
val screenPoint = Point(relativePoint.screenPoint).apply { translate(0, -popup.size.height) }
popup.setLocation(screenPoint)
}
override fun onClosed(event: LightweightWindowEvent) {
// IDEA-195094 Regression: New CTRL-E in "commit changes" breaks keyboard shortcuts
commitMessage.editorField.requestFocusInWindow()
// Use invokeLater() as onClosed() is called before callback from setItemChosenCallback
getApplication().invokeLater { chosenMessage ?: cancelPreview(project, commitMessage) }
}
})
.setNamerForFiltering { it }
.setAutoPackHeightOnFiltering(false)
.createPopup()
.apply {
setDataProvider { dataId ->
when (dataId) {
// default list action does not work as "CopyAction" is invoked first, but with other copy provider
COPY_PROVIDER.name -> object : TextCopyProvider() {
override fun getTextLinesToCopy() = listOfNotNull(selectedMessage).nullize()
}
else -> null
}
}
}
}
private fun preview(project: Project,
commitMessage: CommitMessage,
message: String,
groupId: Any) =
CommandProcessor.getInstance().executeCommand(project, {
commitMessage.setCommitMessage(message)
commitMessage.editorField.selectAll()
}, "", groupId, commitMessage.editorField.document)
private fun cancelPreview(project: Project, commitMessage: CommitMessage) {
val manager = UndoManager.getInstance(project)
val fileEditor = commitMessage.editorField.editor?.let { TextEditorProvider.getInstance().getTextEditor(it) }
if (manager.isUndoAvailable(fileEditor)) manager.undo(fileEditor)
}
private fun getCommitMessage(e: AnActionEvent) = e.getData(VcsDataKeys.COMMIT_MESSAGE_CONTROL) as? CommitMessage
}
|
apache-2.0
|
699a629cfc68ccac952c0726ca8e08aa
| 44.781955 | 140 | 0.748399 | 4.83254 | false | false | false | false |
paplorinc/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/MoveChangesToAnotherListAction.kt
|
1
|
5895
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.actions
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.ui.ChangeListChooser
import com.intellij.openapi.vcs.changes.ui.ChangesListView
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.util.containers.ContainerUtil.intersects
import com.intellij.util.containers.isEmpty
import com.intellij.vcsUtil.VcsUtil
class MoveChangesToAnotherListAction : AbstractChangeListAction() {
override fun update(e: AnActionEvent) {
val project = e.project
val enabled = project != null && ProjectLevelVcsManager.getInstance(project).hasActiveVcss() &&
(!e.getData(ChangesListView.UNVERSIONED_FILES_DATA_KEY).isEmpty() ||
!e.getData(VcsDataKeys.CHANGES).isNullOrEmpty() ||
!e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY).isNullOrEmpty())
updateEnabledAndVisible(e, enabled)
if (!e.getData(VcsDataKeys.CHANGE_LISTS).isNullOrEmpty()) {
e.presentation.text = "Move Files to Another Changelist..."
}
}
override fun actionPerformed(e: AnActionEvent) {
with(MoveChangesHandler(e.project!!)) {
addChanges(e.getData(VcsDataKeys.CHANGES))
if (isEmpty) {
addChangesForFiles(e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY))
}
if (isEmpty) {
VcsBalloonProblemNotifier.showOverChangesView(project, "Nothing is selected that can be moved", MessageType.INFO)
return
}
if (!askAndMove(project, changes, unversionedFiles)) return
if (!changedFiles.isEmpty()) {
selectAndShowFile(project, changedFiles[0])
}
}
}
private fun selectAndShowFile(project: Project, file: VirtualFile) {
val window = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID)
if (!window.isVisible) {
window.activate { ChangesViewManager.getInstance(project).selectFile(file) }
}
}
companion object {
@JvmStatic
fun askAndMove(project: Project, changes: Collection<Change>, unversionedFiles: List<VirtualFile>): Boolean {
if (changes.isEmpty() && unversionedFiles.isEmpty()) return false
val targetList = askTargetList(project, changes)
if (targetList != null) {
val changeListManager = ChangeListManagerImpl.getInstanceImpl(project)
changeListManager.moveChangesTo(targetList, *changes.toTypedArray())
if (!unversionedFiles.isEmpty()) {
changeListManager.addUnversionedFiles(targetList, unversionedFiles)
}
return true
}
return false
}
@JvmStatic
fun guessPreferredList(lists: List<LocalChangeList>): ChangeList? =
lists.find { it.isDefault } ?: lists.find { it.changes.isEmpty() } ?: lists.firstOrNull()
private fun askTargetList(project: Project, changes: Collection<Change>): LocalChangeList? {
val changeListManager = ChangeListManager.getInstance(project)
val nonAffectedLists = getNonAffectedLists(changeListManager.changeLists, changes)
val suggestedLists = nonAffectedLists.ifEmpty { listOf(changeListManager.defaultChangeList) }
val defaultSelection = guessPreferredList(nonAffectedLists)
val chooser = ChangeListChooser(project, suggestedLists, defaultSelection, ActionsBundle.message("action.ChangesView.Move.text"),
null)
chooser.show()
return chooser.selectedList
}
private fun getNonAffectedLists(lists: List<LocalChangeList>, changes: Collection<Change>): List<LocalChangeList> {
val changesSet = changes.toSet()
return lists.filter { !intersects(changesSet, it.changes) }
}
}
}
private class MoveChangesHandler(val project: Project) {
private val changeListManager = ChangeListManager.getInstance(project)
val unversionedFiles = mutableListOf<VirtualFile>()
val changedFiles = mutableListOf<VirtualFile>()
val changes = mutableListOf<Change>()
val isEmpty get() = changes.isEmpty() && unversionedFiles.isEmpty()
fun addChanges(changes: Array<Change>?) {
this.changes.addAll(changes.orEmpty())
}
fun addChangesForFiles(files: Array<VirtualFile>?) {
for (file in files.orEmpty()) {
val change = changeListManager.getChange(file)
if (change == null) {
val status = changeListManager.getStatus(file)
if (FileStatus.UNKNOWN == status) {
unversionedFiles.add(file)
changedFiles.add(file)
}
else if (FileStatus.NOT_CHANGED == status && file.isDirectory) {
addChangesUnder(VcsUtil.getFilePath(file))
}
}
else {
val afterPath = ChangesUtil.getAfterPath(change)
if (afterPath != null && afterPath.isDirectory) {
addChangesUnder(afterPath)
}
else {
changes.add(change)
changedFiles.add(file)
}
}
}
}
private fun addChangesUnder(path: FilePath) {
for (change in changeListManager.getChangesIn(path)) {
changes.add(change)
val file = ChangesUtil.getAfterPath(change)?.virtualFile
file?.let { changedFiles.add(it) }
}
}
}
|
apache-2.0
|
a67b2e4cd93a5664243033f51c6afd39
| 37.285714 | 140 | 0.714334 | 4.630793 | false | false | false | false |
google/intellij-community
|
plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/CompletionUtils.kt
|
2
|
15781
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.*
import com.intellij.openapi.util.Key
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.StandardPatterns
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.completion.handlers.CastReceiverInsertHandler
import org.jetbrains.kotlin.idea.completion.smart.KeywordProbability
import org.jetbrains.kotlin.idea.completion.smart.keywordProbability
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.idea.util.getImplicitReceiversWithInstanceToExpression
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.TypeNullability
import org.jetbrains.kotlin.types.typeUtil.nullability
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
tailrec fun <T : Any> LookupElement.putUserDataDeep(key: Key<T>, value: T?) {
if (this is LookupElementDecorator<*>) {
getDelegate().putUserDataDeep(key, value)
} else {
putUserData(key, value)
}
}
tailrec fun <T : Any> LookupElement.getUserDataDeep(key: Key<T>): T? {
return if (this is LookupElementDecorator<*>) {
getDelegate().getUserDataDeep(key)
} else {
getUserData(key)
}
}
var LookupElement.isDslMember: Boolean? by UserDataProperty(Key.create("DSL_LOOKUP_ITEM"))
fun LookupElement.assignPriority(priority: ItemPriority): LookupElement {
this.priority = priority
return this
}
val STATISTICS_INFO_CONTEXT_KEY = Key<String>("STATISTICS_INFO_CONTEXT_KEY")
val NOT_IMPORTED_KEY = Key<Unit>("NOT_IMPORTED_KEY")
fun LookupElement.withReceiverCast(): LookupElement = LookupElementDecorator.withDelegateInsertHandler(this) { context, element ->
element.handleInsert(context)
CastReceiverInsertHandler.postHandleInsert(context, element)
}
val KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY = Key<Unit>("KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY")
fun LookupElement.keepOldArgumentListOnTab(): LookupElement {
putUserData(KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY, Unit)
return this
}
fun PrefixMatcher.asNameFilter(): (Name) -> Boolean {
return { name -> !name.isSpecial && prefixMatches(name.identifier) }
}
fun PrefixMatcher.asStringNameFilter() = { name: String -> prefixMatches(name) }
fun ((String) -> Boolean).toNameFilter(): (Name) -> Boolean {
return { name -> !name.isSpecial && this(name.identifier) }
}
infix fun <T> ((T) -> Boolean).or(otherFilter: (T) -> Boolean): (T) -> Boolean = { this(it) || otherFilter(it) }
fun LookupElementPresentation.prependTailText(text: String, grayed: Boolean) {
val tails = tailFragments
clearTail()
appendTailText(text, grayed)
tails.forEach { appendTailText(it.text, it.isGrayed) }
}
enum class CallableWeightEnum {
local, // local non-extension
thisClassMember,
baseClassMember,
thisTypeExtension,
baseTypeExtension,
globalOrStatic, // global non-extension
typeParameterExtension,
receiverCastRequired
}
class CallableWeight(val enum: CallableWeightEnum, val receiverIndex: Int?) {
companion object {
val local = CallableWeight(CallableWeightEnum.local, null)
val globalOrStatic = CallableWeight(CallableWeightEnum.globalOrStatic, null)
val receiverCastRequired = CallableWeight(CallableWeightEnum.receiverCastRequired, null)
}
}
val CALLABLE_WEIGHT_KEY = Key<CallableWeight>("CALLABLE_WEIGHT_KEY")
fun InsertionContext.isAfterDot(): Boolean {
var offset = startOffset
val chars = document.charsSequence
while (offset > 0) {
offset--
val c = chars[offset]
if (!Character.isWhitespace(c)) {
return c == '.'
}
}
return false
}
// do not complete this items by prefix like "is"
fun shouldCompleteThisItems(prefixMatcher: PrefixMatcher): Boolean {
val prefix = prefixMatcher.prefix
val s = "this@"
return prefix.startsWith(s) || s.startsWith(prefix)
}
class ThisItemLookupObject(val receiverParameter: ReceiverParameterDescriptor, val labelName: Name?) : KeywordLookupObject()
fun ThisItemLookupObject.createLookupElement() = createKeywordElement("this", labelName.labelNameToTail(), lookupObject = this)
.withTypeText(BasicLookupElementFactory.SHORT_NAMES_RENDERER.renderType(receiverParameter.type))
fun thisExpressionItems(
bindingContext: BindingContext,
position: KtExpression,
prefix: String,
resolutionFacade: ResolutionFacade
): Collection<ThisItemLookupObject> {
val scope = position.getResolutionScope(bindingContext, resolutionFacade)
val psiFactory = KtPsiFactory(position)
val result = ArrayList<ThisItemLookupObject>()
for ((receiver, expressionFactory) in scope.getImplicitReceiversWithInstanceToExpression()) {
if (expressionFactory == null) continue
// if prefix does not start with "this@" do not include immediate this in the form with label
val expression =
expressionFactory.createExpression(psiFactory, shortThis = !prefix.startsWith("this@")) as? KtThisExpression ?: continue
result.add(ThisItemLookupObject(receiver, expression.getLabelNameAsName()))
}
return result
}
fun returnExpressionItems(bindingContext: BindingContext, position: KtElement): Collection<LookupElement> {
val result = mutableListOf<LookupElement>()
for (parent in position.parentsWithSelf.filterIsInstance<KtDeclarationWithBody>()) {
val returnType = parent.returnType(bindingContext)
val isUnit = returnType == null || KotlinBuiltIns.isUnit(returnType)
if (parent is KtFunctionLiteral) {
val (label, call) = parent.findLabelAndCall()
if (label != null) {
result.add(createKeywordElementWithSpace("return", tail = label.labelNameToTail(), addSpaceAfter = !isUnit))
}
// check if the current function literal is inlined and stop processing outer declarations if it's not
val callee = call?.calleeExpression as? KtReferenceExpression ?: break // not inlined
if (!InlineUtil.isInline(bindingContext[BindingContext.REFERENCE_TARGET, callee])) break // not inlined
} else {
if (parent.hasBlockBody()) {
val blockBodyReturns = mutableListOf<LookupElement>()
blockBodyReturns.add(createKeywordElementWithSpace("return", addSpaceAfter = !isUnit))
if (returnType != null) {
if (returnType.nullability() == TypeNullability.NULLABLE) {
blockBodyReturns.add(createKeywordElement("return null"))
}
fun emptyListShouldBeSuggested(): Boolean = KotlinBuiltIns.isCollectionOrNullableCollection(returnType)
|| KotlinBuiltIns.isListOrNullableList(returnType)
|| KotlinBuiltIns.isIterableOrNullableIterable(returnType)
if (KotlinBuiltIns.isBooleanOrNullableBoolean(returnType)) {
blockBodyReturns.add(createKeywordElement("return true"))
blockBodyReturns.add(createKeywordElement("return false"))
} else if (emptyListShouldBeSuggested()) {
blockBodyReturns.add(createKeywordElement("return", tail = " emptyList()"))
} else if (KotlinBuiltIns.isSetOrNullableSet(returnType)) {
blockBodyReturns.add(createKeywordElement("return", tail = " emptySet()"))
}
}
if (isLikelyInPositionForReturn(position, parent, isUnit)) {
blockBodyReturns.forEach { it.keywordProbability = KeywordProbability.HIGH }
}
result.addAll(blockBodyReturns)
}
break
}
}
return result
}
private fun KtDeclarationWithBody.returnType(bindingContext: BindingContext): KotlinType? {
val callable = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? CallableDescriptor ?: return null
return callable.returnType
}
fun BasicLookupElementFactory.createLookupElementForType(type: KotlinType): LookupElement? {
if (type.isError) return null
return if (type.isFunctionType) {
val text = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(type)
val baseLookupElement = LookupElementBuilder.create(text).withIcon(KotlinIcons.LAMBDA)
BaseTypeLookupElement(type, baseLookupElement)
} else {
val classifier = type.constructor.declarationDescriptor ?: return null
val baseLookupElement = createLookupElement(classifier, qualifyNestedClasses = true, includeClassTypeArguments = false)
// if type is simply classifier without anything else, use classifier's lookup element to avoid duplicates (works after "as" in basic completion)
if (type.fqType == IdeDescriptorRenderers.FQ_NAMES_IN_TYPES_WITH_NORMALIZER.renderClassifierName(classifier))
baseLookupElement
else {
val itemText = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(type)
object : BaseTypeLookupElement(type, baseLookupElement) {
override fun renderElement(presentation: LookupElementPresentation) {
super.renderElement(presentation)
presentation.itemText = itemText
}
}
}
}
}
private val KotlinType.fqType: String get() = IdeDescriptorRenderers.FQ_NAMES_IN_TYPES_WITH_NORMALIZER.renderType(this)
private open class BaseTypeLookupElement(type: KotlinType, baseLookupElement: LookupElement) :
LookupElementDecorator<LookupElement>(baseLookupElement) {
private val fullText = type.fqType
override fun equals(other: Any?) = other is BaseTypeLookupElement && fullText == other.fullText
override fun hashCode() = fullText.hashCode()
override fun getDelegateInsertHandler(): InsertHandler<LookupElement> = InsertHandler { context, _ ->
context.document.replaceString(context.startOffset, context.tailOffset, fullText)
context.tailOffset = context.startOffset + fullText.length
shortenReferences(context, context.startOffset, context.tailOffset)
}
}
fun shortenReferences(
context: InsertionContext,
startOffset: Int,
endOffset: Int,
shortenReferences: ShortenReferences = ShortenReferences.DEFAULT
) {
PsiDocumentManager.getInstance(context.project).commitDocument(context.document)
val file = context.file as KtFile
val element = file.findElementAt(startOffset)?.parentsWithSelf?.find {
it.startOffset == startOffset && it.endOffset == endOffset
}?.safeAs<KtElement>()
if (element != null)
shortenReferences.process(element)
else
shortenReferences.process(file, startOffset, endOffset)
}
infix fun <T> ElementPattern<T>.and(rhs: ElementPattern<T>) = StandardPatterns.and(this, rhs)
fun <T> ElementPattern<T>.andNot(rhs: ElementPattern<T>) = StandardPatterns.and(this, StandardPatterns.not(rhs))
infix fun <T> ElementPattern<T>.or(rhs: ElementPattern<T>) = StandardPatterns.or(this, rhs)
fun singleCharPattern(char: Char) = StandardPatterns.character().equalTo(char)
fun LookupElement.decorateAsStaticMember(
memberDescriptor: DeclarationDescriptor,
classNameAsLookupString: Boolean
): LookupElement? {
val container = memberDescriptor.containingDeclaration as? ClassDescriptor ?: return null
val classDescriptor = if (container.isCompanionObject)
container.containingDeclaration as? ClassDescriptor ?: return null
else
container
val containerFqName = container.importableFqName ?: return null
val qualifierPresentation = classDescriptor.name.asString()
return object : LookupElementDecorator<LookupElement>(this) {
private val descriptorIsCallableExtension = (memberDescriptor as? CallableDescriptor)?.extensionReceiverParameter != null
override fun getAllLookupStrings(): Set<String> {
return if (classNameAsLookupString) setOf(delegate.lookupString, qualifierPresentation) else super.getAllLookupStrings()
}
override fun renderElement(presentation: LookupElementPresentation) {
delegate.renderElement(presentation)
if (!descriptorIsCallableExtension) {
presentation.itemText = qualifierPresentation + "." + presentation.itemText
}
val tailText = " (" + DescriptorUtils.getFqName(classDescriptor.containingDeclaration) + ")"
if (memberDescriptor is FunctionDescriptor) {
presentation.appendTailText(tailText, true)
} else {
presentation.setTailText(tailText, true)
}
if (presentation.typeText.isNullOrEmpty()) {
presentation.typeText = BasicLookupElementFactory.SHORT_NAMES_RENDERER.renderType(classDescriptor.defaultType)
}
}
override fun handleInsert(context: InsertionContext) {
val psiDocumentManager = PsiDocumentManager.getInstance(context.project)
val file = context.file as KtFile
fun importFromSameParentIsPresent() = file.importDirectives.any {
!it.isAllUnder && it.importPath?.fqName?.parent() == containerFqName
}
val addMemberImport = descriptorIsCallableExtension || importFromSameParentIsPresent()
if (addMemberImport) {
psiDocumentManager.commitDocument(context.document)
ImportInsertHelper.getInstance(context.project).importDescriptor(file, memberDescriptor)
psiDocumentManager.doPostponedOperationsAndUnblockDocument(context.document)
}
super.handleInsert(context)
}
}
}
fun ImportableFqNameClassifier.isImportableDescriptorImported(descriptor: DeclarationDescriptor): Boolean {
val classification = classify(descriptor.importableFqName!!, false)
return classification != ImportableFqNameClassifier.Classification.notImported
&& classification != ImportableFqNameClassifier.Classification.siblingImported
}
fun OffsetMap.tryGetOffset(key: OffsetKey): Int? {
try {
if (!containsOffset(key)) return null
return getOffset(key).takeIf { it != -1 } // prior to IDEA 2016.3 getOffset() returned -1 if not found, now it throws exception
} catch (e: Exception) {
return null
}
}
var KtCodeFragment.extraCompletionFilter: ((LookupElement) -> Boolean)? by CopyablePsiUserDataProperty(Key.create("EXTRA_COMPLETION_FILTER"))
val DeclarationDescriptor.isArtificialImportAliasedDescriptor: Boolean
get() = original.name != name
|
apache-2.0
|
3e94d25e5e2e7c662120c776d3d59f35
| 42.596685 | 158 | 0.718459 | 4.982949 | false | false | false | false |
nielsutrecht/adventofcode
|
src/main/kotlin/com/nibado/projects/advent/collect/Tree.kt
|
1
|
499
|
package com.nibado.projects.advent.collect
class Tree<E> (val value : E?, private val parent: Tree<E>? = null) {
val nodes = mutableListOf<Tree<E>>()
fun root() = parent == null
fun leaf() = nodes.isEmpty()
fun add(tree: Tree<E>) {
nodes += tree
}
fun add(value: E) {
nodes += Tree(value, this)
}
fun path(): List<Tree<E>> {
return if(root()) {
listOf(this)
} else {
parent!!.path() + this
}
}
}
|
mit
|
78b10a8adf4e92657d4932a8d58f3647
| 20.73913 | 69 | 0.507014 | 3.589928 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.