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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kingsleyadio/android_commons | util/src/main/java/com/kingsleyadio/appcommons/util/Bitmap.kt | 1 | 910 | package com.kingsleyadio.appcommons.util
import android.graphics.*
/**
* @author ADIO Kingsley O.
* @since 16 Feb, 2017
*/
fun Bitmap.trimCircle(): Bitmap {
val self = this
val side = minOf(self.width, self.height)
return Bitmap.createBitmap(side, side, Bitmap.Config.ARGB_8888).apply {
with(Canvas(this)) {
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.shader = BitmapShader(self, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
val radius = side / 2F
drawCircle(radius, radius, radius, paint)
}
}
}
fun Bitmap.scaled(width: Int, height: Int): Bitmap {
return Bitmap.createScaledBitmap(this, width, height, false)
}
fun Bitmap.rotateBitmap(rotationAngle: Int): Bitmap {
val matrix = Matrix()
matrix.postRotate(rotationAngle.toFloat())
return Bitmap.createBitmap(this, 0, 0, width, height, matrix, false)
}
| apache-2.0 | fa22ae7f4fd0d330f0bd8381ed824b00 | 28.354839 | 91 | 0.665934 | 3.714286 | false | false | false | false |
VerifAPS/verifaps-lib | symbex/src/main/kotlin/edu/kit/iti/formal/automation/st0/trans/VariableRenamer.kt | 1 | 2130 | package edu.kit.iti.formal.automation.st0.trans
/*-
* #%L
* iec-symbex
* %%
* Copyright (C) 2016 Alexander Weigl
* %%
* This program isType 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 isType 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 clone of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import edu.kit.iti.formal.automation.st.ast.*
import edu.kit.iti.formal.automation.st.util.AstMutableVisitor
import edu.kit.iti.formal.automation.st.util.setAll
/**
* @author Alexander Weigl (26.06.2014)
*/
open class VariableRenamer(
private val isGlobal: (SymbolicReference) -> Boolean,
private val statements: StatementList?,
private val newName: (String) -> String)
: AstMutableVisitor() {
override fun visit(invocation: Invocation): Expression {
//invocation.callee = invocation.callee.accept(this) as SymbolicReference
invocation.parameters.setAll(
invocation.parameters
.map { p -> p.accept(this) as InvocationParameter }
)
return invocation
}
override fun visit(symbolicReference: SymbolicReference): Expression {
if (!isGlobal(symbolicReference)) {
val name = newName(symbolicReference.identifier)
val ref = SymbolicReference(name, symbolicReference.sub)
ref.subscripts = symbolicReference.sub?.subscripts
return ref
}
return symbolicReference
}
fun rename(): StatementList {
return if (statements != null)
statements.accept(this) as StatementList
else
StatementList()
}
}
| gpl-3.0 | f9cf97d169f755be7b7903a27353a39e | 32.809524 | 81 | 0.676056 | 4.294355 | false | false | false | false |
FutureioLab/FastPeak | app/src/main/java/com/binlly/fastpeak/base/glide/progress/CircleProgressView.kt | 1 | 21356 | package com.binlly.fastpeak.base.glide.progress
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.os.Bundle
import android.os.Parcelable
import android.util.AttributeSet
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ProgressBar
import com.binlly.fastpeak.R
import com.binlly.fastpeak.base.glide.DisplayUtil
private const val STATE = "state"
private const val PROGRESS_STYLE = "progressStyle"
private const val TEXT_COLOR = "textColor"
private const val TEXT_SIZE = "textSize"
private const val TEXT_SKEW_X = "textSkewX"
private const val TEXT_VISIBLE = "textVisible"
private const val TEXT_SUFFIX = "textSuffix"
private const val TEXT_PREFIX = "textPrefix"
private const val REACH_BAR_COLOR = "reachBarColor"
private const val REACH_BAR_SIZE = "reachBarSize"
private const val NORMAL_BAR_COLOR = "normalBarColor"
private const val NORMAL_BAR_SIZE = "normalBarSize"
private const val IS_REACH_CAP_ROUND = "isReachCapRound"
private const val RADIUS = "radius"
private const val START_ARC = "startArc"
private const val INNER_BG_COLOR = "innerBgColor"
private const val INNER_PADDING = "innerPadding"
private const val OUTER_COLOR = "outerColor"
private const val OUTER_SIZE = "outerSize"
class CircleProgressView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null,
defStyleAttr: Int = 0): ProgressBar(context,
attrs, defStyleAttr) {
private var mReachBarSize = DisplayUtil.dip2px(getContext(), 2f) // 未完成进度条大小
private var mNormalBarSize = DisplayUtil.dip2px(getContext(), 2f) // 未完成进度条大小
private var mReachBarColor = Color.parseColor("#108ee9") // 已完成进度颜色
private var mNormalBarColor = Color.parseColor("#FFD3D6DA") // 未完成进度颜色
private var mTextSize = DisplayUtil.sp2px(getContext(), 14f) // 进度值字体大小
private var mTextColor = Color.parseColor("#108ee9") // 进度的值字体颜色
private var mTextSkewX: Float = 0.toFloat() // 进度值字体倾斜角度
private var mTextSuffix: String? = "%" // 进度值前缀
private var mTextPrefix: String? = "" // 进度值后缀
private var mTextVisible = true // 是否显示进度值
private var mReachCapRound: Boolean = false // 画笔是否使用圆角边界,normalStyle下生效
private var mRadius = DisplayUtil.dip2px(getContext(), 20f) // 半径
private var mStartArc: Int = 0 // 起始角度
private var mInnerBackgroundColor: Int = 0 // 内部背景填充颜色
private var mProgressStyle = ProgressStyle.NORMAL // 进度风格
private var mInnerPadding = DisplayUtil.dip2px(getContext(), 1f) // 内部圆与外部圆间距
private var mOuterColor: Int = 0 // 外部圆环颜色
private var needDrawInnerBackground: Boolean = false // 是否需要绘制内部背景
private lateinit var rectF: RectF // 外部圆环绘制区域
private lateinit var rectInner: RectF // 内部圆环绘制区域
private var mOuterSize = DisplayUtil.dip2px(getContext(), 1f) // 外层圆环宽度
private lateinit var mTextPaint: Paint // 绘制进度值字体画笔
private lateinit var mNormalPaint: Paint // 绘制未完成进度画笔
private lateinit var mReachPaint: Paint // 绘制已完成进度画笔
private lateinit var mInnerBackgroundPaint: Paint // 内部背景画笔
private lateinit var mOutPaint: Paint // 外部圆环画笔
private var mRealWidth: Int = 0
private var mRealHeight: Int = 0
companion object ProgressStyle {
val NORMAL = 0
val FILL_IN = 1
val FILL_IN_ARC = 2
}
init {
obtainAttributes(attrs)
initPaint()
}
private fun initPaint() {
mTextPaint = Paint()
mTextPaint.color = mTextColor
mTextPaint.style = Paint.Style.FILL
mTextPaint.textSize = mTextSize.toFloat()
mTextPaint.textSkewX = mTextSkewX
mTextPaint.isAntiAlias = true
mNormalPaint = Paint()
mNormalPaint.color = mNormalBarColor
mNormalPaint.style = if (mProgressStyle == ProgressStyle.FILL_IN_ARC) Paint.Style.FILL else Paint.Style.STROKE
mNormalPaint.isAntiAlias = true
mNormalPaint.strokeWidth = mNormalBarSize.toFloat()
mReachPaint = Paint()
mReachPaint.color = mReachBarColor
mReachPaint.style = if (mProgressStyle == ProgressStyle.FILL_IN_ARC) Paint.Style.FILL else Paint.Style.STROKE
mReachPaint.isAntiAlias = true
mReachPaint.strokeCap = if (mReachCapRound) Paint.Cap.ROUND else Paint.Cap.BUTT
mReachPaint.strokeWidth = mReachBarSize.toFloat()
if (needDrawInnerBackground) {
mInnerBackgroundPaint = Paint()
mInnerBackgroundPaint.style = Paint.Style.FILL
mInnerBackgroundPaint.isAntiAlias = true
mInnerBackgroundPaint.color = mInnerBackgroundColor
}
if (mProgressStyle == ProgressStyle.FILL_IN_ARC) {
mOutPaint = Paint()
mOutPaint.style = Paint.Style.STROKE
mOutPaint.color = mOuterColor
mOutPaint.strokeWidth = mOuterSize.toFloat()
mOutPaint.isAntiAlias = true
}
}
private fun obtainAttributes(attrs: AttributeSet?) {
val ta = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressView)
mProgressStyle = ta.getInt(R.styleable.CircleProgressView_cpv_progressStyle,
ProgressStyle.NORMAL)
// 获取三种风格通用的属性
mNormalBarSize = ta.getDimension(R.styleable.CircleProgressView_cpv_progressNormalSize,
mNormalBarSize.toFloat()).toInt()
mNormalBarColor = ta.getColor(R.styleable.CircleProgressView_cpv_progressNormalColor,
mNormalBarColor)
mReachBarSize = ta.getDimension(R.styleable.CircleProgressView_cpv_progressReachSize,
mReachBarSize.toFloat()).toInt()
mReachBarColor = ta.getColor(R.styleable.CircleProgressView_cpv_progressReachColor,
mReachBarColor)
mTextSize = ta.getDimension(R.styleable.CircleProgressView_cpv_progressTextSize,
mTextSize.toFloat()).toInt()
mTextColor = ta.getColor(R.styleable.CircleProgressView_cpv_progressTextColor, mTextColor)
mTextSkewX = ta.getDimension(R.styleable.CircleProgressView_cpv_progressTextSkewX, 0f)
if (ta.hasValue(R.styleable.CircleProgressView_cpv_progressTextSuffix)) {
mTextSuffix = ta.getString(R.styleable.CircleProgressView_cpv_progressTextSuffix)
}
if (ta.hasValue(R.styleable.CircleProgressView_cpv_progressTextPrefix)) {
mTextPrefix = ta.getString(R.styleable.CircleProgressView_cpv_progressTextPrefix)
}
mTextVisible = ta.getBoolean(R.styleable.CircleProgressView_cpv_progressTextVisible,
mTextVisible)
mRadius = ta.getDimension(R.styleable.CircleProgressView_cpv_radius,
mRadius.toFloat()).toInt()
rectF = RectF((-mRadius).toFloat(), (-mRadius).toFloat(), mRadius.toFloat(),
mRadius.toFloat())
when (mProgressStyle) {
ProgressStyle.FILL_IN -> {
mReachBarSize = 0
mNormalBarSize = 0
mOuterSize = 0
}
ProgressStyle.FILL_IN_ARC -> {
mStartArc = ta.getInt(R.styleable.CircleProgressView_cpv_progressStartArc, 0) + 270
mInnerPadding = ta.getDimension(R.styleable.CircleProgressView_cpv_innerPadding,
mInnerPadding.toFloat()).toInt()
mOuterColor = ta.getColor(R.styleable.CircleProgressView_cpv_outerColor,
mReachBarColor)
mOuterSize = ta.getDimension(R.styleable.CircleProgressView_cpv_outerSize,
mOuterSize.toFloat()).toInt()
mReachBarSize = 0// 将画笔大小重置为0
mNormalBarSize = 0
if (!ta.hasValue(R.styleable.CircleProgressView_cpv_progressNormalColor)) {
mNormalBarColor = Color.TRANSPARENT
}
val mInnerRadius = mRadius - mOuterSize / 2 - mInnerPadding
rectInner = RectF((-mInnerRadius).toFloat(), (-mInnerRadius).toFloat(),
mInnerRadius.toFloat(), mInnerRadius.toFloat())
}
ProgressStyle.NORMAL -> {
mReachCapRound = ta.getBoolean(R.styleable.CircleProgressView_cpv_reachCapRound,
true)
mStartArc = ta.getInt(R.styleable.CircleProgressView_cpv_progressStartArc, 0) + 270
if (ta.hasValue(R.styleable.CircleProgressView_cpv_innerBackgroundColor)) {
mInnerBackgroundColor = ta.getColor(
R.styleable.CircleProgressView_cpv_innerBackgroundColor,
Color.argb(0, 0, 0, 0))
needDrawInnerBackground = true
}
}
}
ta.recycle()
}
@Synchronized override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val maxBarPaintWidth = Math.max(mReachBarSize, mNormalBarSize)
val maxPaintWidth = Math.max(maxBarPaintWidth, mOuterSize)
var height = 0
var width = 0
when (mProgressStyle) {
ProgressStyle.FILL_IN -> {
height = paddingTop + paddingBottom // 边距
+Math.abs(mRadius * 2) // 直径
width = paddingLeft + paddingRight // 边距
+Math.abs(mRadius * 2) // 直径
}
ProgressStyle.FILL_IN_ARC -> {
height = paddingTop + paddingBottom // 边距
+Math.abs(mRadius * 2) // 直径
+maxPaintWidth// 边框
width = paddingLeft + paddingRight // 边距
+Math.abs(mRadius * 2) // 直径
+maxPaintWidth// 边框
}
ProgressStyle.NORMAL -> {
height = paddingTop + paddingBottom // 边距
+Math.abs(mRadius * 2) // 直径
+maxBarPaintWidth// 边框
width = paddingLeft + paddingRight // 边距
+Math.abs(mRadius * 2) // 直径
+maxBarPaintWidth// 边框
}
}
mRealWidth = View.resolveSize(width, widthMeasureSpec)
mRealHeight = View.resolveSize(height, heightMeasureSpec)
setMeasuredDimension(mRealWidth, mRealHeight)
}
@Synchronized override fun onDraw(canvas: Canvas) {
when (mProgressStyle) {
ProgressStyle.NORMAL -> drawNormalCircle(canvas)
ProgressStyle.FILL_IN -> drawFillInCircle(canvas)
ProgressStyle.FILL_IN_ARC -> drawFillInArcCircle(canvas)
}
}
/**
* 绘制PROGRESS_STYLE_FILL_IN_ARC圆形
*/
private fun drawFillInArcCircle(canvas: Canvas) {
canvas.save()
canvas.translate((mRealWidth / 2).toFloat(), (mRealHeight / 2).toFloat())
// 绘制外层圆环
canvas.drawArc(rectF, 0f, 360f, false, mOutPaint)
// 绘制内层进度实心圆弧
// 内层圆弧半径
val reachArc = progress * 1.0f / max * 360
canvas.drawArc(rectInner, mStartArc.toFloat(), reachArc, true, mReachPaint)
// 绘制未到达进度
if (reachArc != 360f) {
canvas.drawArc(rectInner, reachArc + mStartArc, 360 - reachArc, true, mNormalPaint)
}
canvas.restore()
}
/**
* 绘制PROGRESS_STYLE_FILL_IN圆形
*/
private fun drawFillInCircle(canvas: Canvas) {
canvas.save()
canvas.translate((mRealWidth / 2).toFloat(), (mRealHeight / 2).toFloat())
val progressY = progress * 1.0f / max * (mRadius * 2)
val angle = (Math.acos(
((mRadius - progressY) / mRadius).toDouble()) * 180 / Math.PI).toFloat()
val startAngle = 90 + angle
val sweepAngle = 360 - angle * 2
// 绘制未到达区域
rectF = RectF((-mRadius).toFloat(), (-mRadius).toFloat(), mRadius.toFloat(),
mRadius.toFloat())
mNormalPaint.style = Paint.Style.FILL
canvas.drawArc(rectF, startAngle, sweepAngle, false, mNormalPaint)
// 翻转180度绘制已到达区域
canvas.rotate(180f)
mReachPaint.style = Paint.Style.FILL
canvas.drawArc(rectF, 270 - angle, angle * 2, false, mReachPaint)
// 文字显示在最上层最后绘制
canvas.rotate(180f)
// 绘制文字
if (mTextVisible) {
val text = mTextPrefix + progress + mTextSuffix
val textWidth = mTextPaint.measureText(text)
val textHeight = mTextPaint.descent() + mTextPaint.ascent()
canvas.drawText(text, -textWidth / 2, -textHeight / 2, mTextPaint)
}
}
/**
* 绘制PROGRESS_STYLE_NORMAL圆形
*/
private fun drawNormalCircle(canvas: Canvas) {
canvas.save()
canvas.translate((mRealWidth / 2).toFloat(), (mRealHeight / 2).toFloat())
// 绘制内部圆形背景色
if (needDrawInnerBackground) {
canvas.drawCircle(0f, 0f,
(mRadius - Math.min(mReachBarSize, mNormalBarSize) / 2).toFloat(),
mInnerBackgroundPaint)
}
// 绘制文字
if (mTextVisible) {
val text = mTextPrefix + progress + mTextSuffix
val textWidth = mTextPaint.measureText(text)
val textHeight = mTextPaint.descent() + mTextPaint.ascent()
canvas.drawText(text, -textWidth / 2, -textHeight / 2, mTextPaint)
}
// 计算进度值
val reachArc = progress * 1.0f / max * 360
// 绘制未到达进度
if (reachArc != 360f) {
canvas.drawArc(rectF, reachArc + mStartArc, 360 - reachArc, false, mNormalPaint)
}
// 绘制已到达进度
canvas.drawArc(rectF, mStartArc.toFloat(), reachArc, false, mReachPaint)
canvas.restore()
}
/**
* 动画进度(0-当前进度)
*
* @param duration 动画时长
*/
fun runProgressAnim(duration: Long) {
setProgressInTime(0, duration)
}
/**
* @param progress 进度值
* @param duration 动画播放时间
*/
fun setProgressInTime(progress: Int, duration: Long) {
setProgressInTime(progress, getProgress(), duration)
}
/**
* @param startProgress 起始进度
* @param progress 进度值
* @param duration 动画播放时间
*/
fun setProgressInTime(startProgress: Int, progress: Int, duration: Long) {
val valueAnimator = ValueAnimator.ofInt(startProgress, progress)
valueAnimator.addUpdateListener { animator ->
//获得当前动画的进度值,整型,1-100之间
val currentValue = animator.animatedValue as Int
setProgress(currentValue)
}
val interpolator = AccelerateDecelerateInterpolator()
valueAnimator.interpolator = interpolator
valueAnimator.duration = duration
valueAnimator.start()
}
var reachBarSize: Int
get() = mReachBarSize
set(reachBarSize) {
mReachBarSize = DisplayUtil.dip2px(context, reachBarSize.toFloat())
invalidate()
}
var normalBarSize: Int
get() = mNormalBarSize
set(normalBarSize) {
mNormalBarSize = DisplayUtil.dip2px(context, normalBarSize.toFloat())
invalidate()
}
var reachBarColor: Int
get() = mReachBarColor
set(reachBarColor) {
mReachBarColor = reachBarColor
invalidate()
}
var normalBarColor: Int
get() = mNormalBarColor
set(normalBarColor) {
mNormalBarColor = normalBarColor
invalidate()
}
var textSize: Int
get() = mTextSize
set(textSize) {
mTextSize = DisplayUtil.sp2px(context, textSize.toFloat())
invalidate()
}
var textColor: Int
get() = mTextColor
set(textColor) {
mTextColor = textColor
invalidate()
}
var textSkewX: Float
get() = mTextSkewX
set(textSkewX) {
mTextSkewX = textSkewX
invalidate()
}
var textSuffix: String?
get() = mTextSuffix
set(textSuffix) {
mTextSuffix = textSuffix
invalidate()
}
var textPrefix: String?
get() = mTextPrefix
set(textPrefix) {
mTextPrefix = textPrefix
invalidate()
}
var isTextVisible: Boolean
get() = mTextVisible
set(textVisible) {
mTextVisible = textVisible
invalidate()
}
var isReachCapRound: Boolean
get() = mReachCapRound
set(reachCapRound) {
mReachCapRound = reachCapRound
invalidate()
}
var radius: Int
get() = mRadius
set(radius) {
mRadius = DisplayUtil.dip2px(context, radius.toFloat())
invalidate()
}
var startArc: Int
get() = mStartArc
set(startArc) {
mStartArc = startArc
invalidate()
}
var innerBackgroundColor: Int
get() = mInnerBackgroundColor
set(innerBackgroundColor) {
mInnerBackgroundColor = innerBackgroundColor
invalidate()
}
var progressStyle: Int
get() = mProgressStyle
set(progressStyle) {
mProgressStyle = progressStyle
invalidate()
}
var innerPadding: Int
get() = mInnerPadding
set(innerPadding) {
mInnerPadding = DisplayUtil.dip2px(context, innerPadding.toFloat())
val mInnerRadius = mRadius - mOuterSize / 2 - mInnerPadding
rectInner = RectF((-mInnerRadius).toFloat(), (-mInnerRadius).toFloat(),
mInnerRadius.toFloat(), mInnerRadius.toFloat())
invalidate()
}
var outerColor: Int
get() = mOuterColor
set(outerColor) {
mOuterColor = outerColor
invalidate()
}
var outerSize: Int
get() = mOuterSize
set(outerSize) {
mOuterSize = DisplayUtil.dip2px(context, outerSize.toFloat())
invalidate()
}
override fun onSaveInstanceState(): Parcelable? {
val bundle = Bundle()
bundle.putParcelable(STATE, super.onSaveInstanceState())
// 保存当前样式
bundle.putInt(PROGRESS_STYLE, progressStyle)
bundle.putInt(RADIUS, radius)
bundle.putBoolean(IS_REACH_CAP_ROUND, isReachCapRound)
bundle.putInt(START_ARC, startArc)
bundle.putInt(INNER_BG_COLOR, innerBackgroundColor)
bundle.putInt(INNER_PADDING, innerPadding)
bundle.putInt(OUTER_COLOR, outerColor)
bundle.putInt(OUTER_SIZE, outerSize)
// 保存text信息
bundle.putInt(TEXT_COLOR, textColor)
bundle.putInt(TEXT_SIZE, textSize)
bundle.putFloat(TEXT_SKEW_X, textSkewX)
bundle.putBoolean(TEXT_VISIBLE, isTextVisible)
bundle.putString(TEXT_SUFFIX, textSuffix)
bundle.putString(TEXT_PREFIX, textPrefix)
// 保存已到达进度信息
bundle.putInt(REACH_BAR_COLOR, reachBarColor)
bundle.putInt(REACH_BAR_SIZE, reachBarSize)
// 保存未到达进度信息
bundle.putInt(NORMAL_BAR_COLOR, normalBarColor)
bundle.putInt(NORMAL_BAR_SIZE, normalBarSize)
return bundle
}
override fun onRestoreInstanceState(state: Parcelable) {
if (state is Bundle) {
mProgressStyle = state.getInt(PROGRESS_STYLE)
mRadius = state.getInt(RADIUS)
mReachCapRound = state.getBoolean(IS_REACH_CAP_ROUND)
mStartArc = state.getInt(START_ARC)
mInnerBackgroundColor = state.getInt(INNER_BG_COLOR)
mInnerPadding = state.getInt(INNER_PADDING)
mOuterColor = state.getInt(OUTER_COLOR)
mOuterSize = state.getInt(OUTER_SIZE)
mTextColor = state.getInt(TEXT_COLOR)
mTextSize = state.getInt(TEXT_SIZE)
mTextSkewX = state.getFloat(TEXT_SKEW_X)
mTextVisible = state.getBoolean(TEXT_VISIBLE)
mTextSuffix = state.getString(TEXT_SUFFIX)
mTextPrefix = state.getString(TEXT_PREFIX)
mReachBarColor = state.getInt(REACH_BAR_COLOR)
mReachBarSize = state.getInt(REACH_BAR_SIZE)
mNormalBarColor = state.getInt(NORMAL_BAR_COLOR)
mNormalBarSize = state.getInt(NORMAL_BAR_SIZE)
initPaint()
super.onRestoreInstanceState(state.getParcelable(STATE))
return
}
super.onRestoreInstanceState(state)
}
override fun invalidate() {
initPaint()
super.invalidate()
}
}
| mit | 73877630bbef18c85ac721454a54002f | 36.018051 | 118 | 0.618003 | 4.227582 | false | false | false | false |
j-selby/kotgb | core/src/main/kotlin/net/jselby/kotgb/hw/ram/providers/SwitchableRAM.kt | 1 | 1775 | package net.jselby.kotgb.hw.ram.providers
import net.jselby.kotgb.Gameboy
import net.jselby.kotgb.hw.ram.RAMProvider
/**
* Links to a specified Cartridge's RAM.
*/
class SwitchableRAM(private val logger : (String) -> (Unit),
private val gameboy : Gameboy, private val cartridge: Cartridge) : RAMProvider() {
private var dirty: Boolean = false
fun load() {
if (cartridge.isBatteryAssured()) {
val data = gameboy.callbacks.attemptLoad.invoke(cartridge)
if (data != null) {
logger ("Restoring game state...")
val fileSize = data.size
val copySize = if (cartridge.ram.size > fileSize) fileSize else cartridge.ram.size
for (i in 0 .. copySize - 1) {
cartridge.ram[i] = data[i]
}
//System.arraycopy(data, 0, cartridge.ram, 0,
// Math.min(cartridge.ram.size, fileSize))
}
}
}
override fun getByte(pointer: Long): Byte {
if (cartridge.ram.isEmpty()) {
logger ("Reading from RAM on a ROM-only cartridge!")
return 0xFF.toByte()
}
return cartridge.ram[pointer.toInt()]
}
override fun setByte(pointer: Long, value: Byte) {
if (cartridge.ram.isEmpty()) {
logger ("Writing to RAM on a ROM-only cartridge!")
return
}
cartridge.ram[pointer.toInt()] = value
dirty = true
}
fun flush() {
if (cartridge.isBatteryAssured() && dirty) {
dirty = false
// Attempt to write!
gameboy.callbacks.attemptSave.invoke(cartridge)
}
}
override fun getAbsoluteRange() = 0xA000L .. 0xBFFFL
} | mit | 03f92809c00a6eb1a93feed045c3013b | 29.62069 | 102 | 0.556056 | 4.08046 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/command/ticket/TicketTeleportCommand.kt | 1 | 2884 | /*
* Copyright 2021 Ren Binden
* 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.rpkit.moderation.bukkit.command.ticket
import com.rpkit.core.bukkit.location.toBukkitLocation
import com.rpkit.core.service.Services
import com.rpkit.moderation.bukkit.RPKModerationBukkit
import com.rpkit.moderation.bukkit.ticket.RPKTicketId
import com.rpkit.moderation.bukkit.ticket.RPKTicketService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
class TicketTeleportCommand(private val plugin: RPKModerationBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.moderation.command.ticket.teleport")) {
sender.sendMessage(plugin.messages["no-permission-ticket-teleport"])
return true
}
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
if (args.isEmpty()) {
sender.sendMessage(plugin.messages["ticket-teleport-usage"])
return true
}
val ticketService = Services[RPKTicketService::class.java]
if (ticketService == null) {
sender.sendMessage(plugin.messages["no-ticket-service"])
return true
}
try {
ticketService.getTicket(RPKTicketId(args[0].toInt())).thenAccept { ticket ->
if (ticket == null) {
sender.sendMessage(plugin.messages["ticket-teleport-invalid-ticket"])
return@thenAccept
}
val location = ticket.location
if (location == null) {
sender.sendMessage(plugin.messages["ticket-teleport-invalid-location"])
return@thenAccept
}
plugin.server.scheduler.runTask(plugin, Runnable {
location.toBukkitLocation()?.let { sender.teleport(it) }
sender.sendMessage(plugin.messages["ticket-teleport-valid"])
})
}
} catch (exception: NumberFormatException) {
sender.sendMessage(plugin.messages["ticket-teleport-usage"])
}
return true
}
} | apache-2.0 | 628d21b21ddc4101b854b0cce743e901 | 39.633803 | 118 | 0.654993 | 4.743421 | false | false | false | false |
google/summit-ast | src/main/java/com/google/summit/ast/Node.kt | 1 | 3847 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.summit.ast
import com.google.summit.ast.traversal.Visitor
/** Abstract base class for all AST types. */
abstract class Node {
abstract fun getSourceLocation(): SourceLocation
/**
* Walks the subtree rooted at this node in depth-first post-order.
*
* Every node is passed to [Visitor.visit], unless it is skipped or the traversal is stopped.
*
* The traversal is stopped when [Visitor.stopAt] returns `true`. At this point, there will be no
* further calls to [Visitor.visit], including for any of the nodes on the current path as it is
* unwound.
*
* The children and subtree below a node will be skipped when [Visitor.skipBelow] returns `true`.
* The node that triggers this condition will still be passed to [Visitor.visit].
*
* @param visitor the visitor to pass every node
*/
fun walkSubtree(visitor: Visitor) {
/** Recurses on subtree and returns whether the traversal should stop. */
fun recurseOnNode(node: Node, visitor: Visitor): Boolean {
if (visitor.stopAt(node)) {
return true
}
if (!visitor.skipBelow(node)) {
for (child in node.getChildren()) {
if (recurseOnNode(child, visitor)) {
return true
}
}
}
visitor.visit(node)
return false
}
recurseOnNode(this, visitor)
}
/**
* Returns the list of children of this node.
*
* The structure of the AST is primarily defined by this method. Because it is a tree, each node
* should only be the child of exactly one parent, and there must be no cycles in the
* relationship.
*
* The order of the children is stable but may differ from their positional order in the
* input source.
*
* The bottom-up tree creation implies that the children already exist when the parent node is
* constructed, and so the list of children should be fixed from initialization onward.
*/
abstract fun getChildren(): List<Node>
/**
* The parent of this node will return it in [getChildren].
*
* These references are first set in one pass in [setNodeParents] after the creation of the AST.
*/
@Transient var parent: Node? = null
init {
++totalCount
}
companion object {
/**
* Total number of nodes created.
*
* This is used as a part of an efficient check during translation that the number of newly
* created [Node] objects is equal to the number of nodes reachable from the root
* [CompilationUnit] via transitive calls to [getChildren]. (It's easy to add a node property
* and forget to include it in that list.)
*/
var totalCount: Int = 0
private set
/**
* Sets [Node.parent] properties by recursing with [Node.getChildren] and returns the total
* number of nodes traversed.
*/
fun setNodeParents(node: Node): Int {
var reachableCount = 1
for (child in node.getChildren()) {
if (child.parent != null) {
throw Exception(
"Nodes should have a unique parent, but $child has ${child.parent} and $node"
)
}
child.parent = node
reachableCount += setNodeParents(child) // recurse
}
return reachableCount
}
}
}
| apache-2.0 | 09eeda0f144f2ab40668e2b23c05e06e | 32.745614 | 99 | 0.667793 | 4.28874 | false | false | false | false |
quarck/CalendarNotification | app/src/main/java/com/github/quarck/calnotify/prefs/CarModeActivity.kt | 1 | 6579 | //
// Calendar Notifications Plus
// Copyright (C) 2019 Sergey Parshin ([email protected])
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.prefs
import android.bluetooth.BluetoothManager
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.support.v7.widget.Toolbar
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.TextView
import com.github.quarck.calnotify.Consts
import com.github.quarck.calnotify.R
import com.github.quarck.calnotify.Settings
import com.github.quarck.calnotify.bluetooth.BTDeviceManager
import com.github.quarck.calnotify.bluetooth.BTDeviceSummary
import com.github.quarck.calnotify.calendar.CalendarProvider
import com.github.quarck.calnotify.calendar.CalendarRecord
import com.github.quarck.calnotify.logs.DevLog
import com.github.quarck.calnotify.permissions.PermissionsManager
import com.github.quarck.calnotify.utils.background
import com.github.quarck.calnotify.utils.find
import com.github.quarck.calnotify.utils.findOrThrow
class BlueboothDeviceListEntry(
var isHandled: Boolean,
val dev: BTDeviceSummary
)
class BlueboothDeviceListAdapter(val context: Context, var entries: Array<BlueboothDeviceListEntry>)
: RecyclerView.Adapter<BlueboothDeviceListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.bluetooth_device_view, parent, false)
return ViewHolder(view)
}
inner class ViewHolder(itemView: View)
: RecyclerView.ViewHolder(itemView) {
var entry: BlueboothDeviceListEntry? = null
var view: LinearLayout
var deviceName: CheckBox
var deviceAddr: TextView
init {
view = itemView.findOrThrow<LinearLayout>(R.id.linearLayoutBluetoothDeviceListEntry)
deviceAddr = view.findOrThrow<TextView>(R.id.textViewDeviceMac)
deviceName = view.findOrThrow<CheckBox>(R.id.checkBoxBTDeviceSelection)
deviceName.setOnClickListener {
view ->
val action = onListHandledUpdated
entry?.isHandled = deviceName.isChecked
action?.invoke(view, entries.filter { it.isHandled }.map { it.dev.address }.toList() )
}
}
}
var onListHandledUpdated: ((View, List<String>) -> Unit)? = null
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (position >= 0 && position < entries.size) {
val entry = entries[position]
holder.entry = entry
holder.deviceName.text = entry.dev.name // + " " + entry.dev.currentlyConnected
holder.deviceAddr.text = entry.dev.address
holder.deviceName.isChecked = entry.isHandled
}
}
override fun getItemCount(): Int {
return entries.size
}
}
class CarModeActivity : AppCompatActivity() {
private lateinit var adapter: BlueboothDeviceListAdapter
private lateinit var staggeredLayoutManager: StaggeredGridLayoutManager
private lateinit var recyclerView: RecyclerView
private lateinit var noDevicesText: TextView
private lateinit var settings: Settings
private lateinit var bluetoothManager: BTDeviceManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DevLog.debug(LOG_TAG, "onCreate")
setContentView(R.layout.activity_car_mode)
setSupportActionBar(find<Toolbar?>(R.id.toolbar))
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
settings = Settings(this)
adapter = BlueboothDeviceListAdapter(this, arrayOf<BlueboothDeviceListEntry>())
bluetoothManager = BTDeviceManager(this)
adapter.onListHandledUpdated = {
_, newList ->
DevLog.info(LOG_TAG, "New triggers: ${newList.joinToString { ", " }}")
bluetoothManager.storage.carModeTriggerDevices = newList
}
staggeredLayoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
recyclerView = findOrThrow<RecyclerView>(R.id.list_bt_devices)
recyclerView.layoutManager = staggeredLayoutManager;
recyclerView.adapter = adapter;
noDevicesText = findOrThrow<TextView>(R.id.no_devices_text)
}
override fun onResume() {
super.onResume()
if (!PermissionsManager.hasAccessCoarseLocation(this)) {
PermissionsManager.requestLocationPermissions(this)
}
background {
val triggers = bluetoothManager.storage.carModeTriggerDevices
DevLog.info(LOG_TAG, "Known triggers: ${triggers.joinToString { ", " }}")
val triggersHash = triggers.toHashSet()
val devices = bluetoothManager.pairedDevices?.map { BlueboothDeviceListEntry(triggersHash.contains(it.address), it)}?.toList()
runOnUiThread {
// update activity finally
if (devices != null) {
noDevicesText.visibility = if (devices.isNotEmpty()) View.GONE else View.VISIBLE
adapter.entries = devices.toTypedArray()
adapter.notifyDataSetChanged()
} else {
noDevicesText.visibility = View.VISIBLE
}
}
}
}
companion object {
private const val LOG_TAG = "CarModeActivity"
}
} | gpl-3.0 | 5e07b38702cc0166ff3f6e3ab623697d | 34.76087 | 138 | 0.701474 | 4.743331 | false | false | false | false |
MichaelRocks/lightsaber | gradle-plugin/src/main/java/io/michaelrocks/lightsaber/plugin/BackupClassesTask.kt | 1 | 4426 | /*
* Copyright 2017 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.plugin
import io.michaelrocks.lightsaber.processor.watermark.WatermarkChecker
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputDirectories
import org.gradle.api.tasks.TaskAction
import java.io.File
open class BackupClassesTask : DefaultTask() {
@InputFiles
var classesDirs: List<File> = emptyList()
@OutputDirectories
var backupDirs: List<File> = emptyList()
@TaskAction
fun backupClasses() {
validate()
logger.info("Backing up classes...")
logger.info(" from {}", classesDirs)
logger.info(" to {}", backupDirs)
forEach(classesDirs, backupDirs) { classesDir, backupDir ->
if (!classesDir.exists()) {
logger.info("Classes directory doesn't exists. Nothing to backup.")
backupDir.deleteRecursively()
} else {
val visitedFiles = copyUpdatedFiles(classesDir, backupDir)
removeUnvisitedFiles(backupDir, visitedFiles)
}
}
}
private fun copyUpdatedFiles(classesDir: File, backupDir: File): Set<String> {
logger.info("Copying updated files...")
logger.info(" from [{}]", classesDir)
logger.info(" to [{}]", backupDir)
val visitedPaths = mutableSetOf<String>()
classesDir.walk().forEach { file ->
if (!file.isDirectory) {
logger.debug("Checking {}...", file)
val relativePath = file.toRelativeString(classesDir)
visitedPaths.add(relativePath)
if (WatermarkChecker.isLightsaberClass(file)) {
logger.debug("Watermark found - skipping")
} else {
val backupFile = backupDir.resolve(relativePath)
if (!backupFile.exists()) {
logger.debug("Backup file doesn't exist - copying")
file.copyToWithLastModified(backupFile)
} else if (file.lastModified() != backupFile.lastModified()) {
logger.debug("File was updated - copying")
file.copyToWithLastModified(backupFile, true)
} else {
logger.debug("File wasn't updated - skipping")
}
}
}
}
return visitedPaths
}
private fun removeUnvisitedFiles(backupDir: File, visitedPaths: Set<String>) {
logger.info("Removing abandoned files...")
logger.info(" from [{}]", backupDir)
backupDir.walkBottomUp().forEach { file ->
if (file.isDirectory) {
file.delete()
} else {
logger.debug("Checking {}...", file)
val relativePath = file.toRelativeString(backupDir)
if (!visitedPaths.contains(relativePath)) {
logger.debug("File is abandoned - removing")
file.delete()
} else {
logger.debug("File isn't abandoned - skipping")
}
}
}
}
fun clean() {
validate()
logger.info("Restoring patched files...")
logger.info(" from {}", backupDirs)
logger.info(" to {}", classesDirs)
forEach(classesDirs, backupDirs) { classesDir, backupDir ->
if (!classesDir.exists()) {
return
}
backupDir.walk().forEach { file ->
if (!file.isDirectory) {
logger.debug("Reverting {}...", file)
val relativePath = file.toRelativeString(backupDir)
val classesFile = classesDir.resolve(relativePath)
file.copyToWithLastModified(classesFile, true)
}
}
}
}
private fun validate() {
require(classesDirs.isNotEmpty()) { "classesDirs is not set" }
require(backupDirs.isNotEmpty()) { "backupDirs is not set" }
require(classesDirs.size == backupDirs.size) { "classesDirs and backupDirs must have equal size" }
}
private fun File.copyToWithLastModified(target: File, overwrite: Boolean = false) {
copyTo(target, overwrite)
target.setLastModified(lastModified())
}
}
| apache-2.0 | 1fd6cd8bf317d281bff630cd1a5f175c | 32.278195 | 102 | 0.653638 | 4.4572 | false | false | false | false |
jiangkang/KTools | tools/src/main/java/com/jiangkang/tools/widget/FloatingWindow.kt | 1 | 2035 | package com.jiangkang.tools.widget
import android.Manifest
import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.annotation.RequiresPermission
import com.jiangkang.tools.R
/**
* Created by jiangkang on 2017/9/23.
*/
object FloatingWindow {
private var sWindowManager: WindowManager? = null
private var sWindowLayoutParams: WindowManager.LayoutParams? = null
private var sView: View? = null
fun init(context: Context) {
sWindowManager = context.applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
sWindowLayoutParams = WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY else WindowManager.LayoutParams.TYPE_TOAST,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.TRANSLUCENT
)
sWindowLayoutParams!!.gravity = Gravity.TOP + Gravity.RIGHT
sView = LayoutInflater.from(context).inflate(R.layout.layout_floating_window, null)
}
@RequiresPermission(allOf = [Manifest.permission.SYSTEM_ALERT_WINDOW])
fun show(context: Context, content: String?) {
if (sWindowManager == null) {
init(context)
}
val tvContent = sView!!.findViewById<View>(R.id.tv_window_content) as TextView
tvContent.text = content
if (!sView!!.isAttachedToWindow) {
sWindowManager!!.addView(sView, sWindowLayoutParams)
}
}
fun dismiss() {
if (sWindowManager != null && sView != null && sView!!.isAttachedToWindow) {
sWindowManager!!.removeView(sView)
}
}
} | mit | a03f2c9ef14d41c540bb0fc3d65f58b7 | 38.153846 | 162 | 0.705651 | 4.635535 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/features/ores/Blocks.kt | 2 | 3927 | package com.cout970.magneticraft.features.ores
import com.cout970.magneticraft.misc.CreativeTabMg
import com.cout970.magneticraft.misc.RegisterBlocks
import com.cout970.magneticraft.systems.blocks.*
import com.cout970.magneticraft.systems.itemblocks.itemBlockListOf
import net.minecraft.block.Block
import net.minecraft.block.material.Material
import net.minecraft.block.properties.IProperty
import net.minecraft.block.properties.PropertyEnum
import net.minecraft.block.state.IBlockState
import net.minecraft.item.ItemBlock
import net.minecraft.item.ItemStack
import net.minecraft.util.IStringSerializable
/**
* Created by cout970 on 2017/06/11.
*/
@RegisterBlocks
object Blocks : IBlockMaker {
val PROPERTY_ORE_TYPE: PropertyEnum<OreType> =
PropertyEnum.create("ore_type", OreType::class.java)
val PROPERTY_OIL_AMOUNT: PropertyEnum<OilAmount> =
PropertyEnum.create("oil_amount", OilAmount::class.java)
lateinit var ores: BlockBase private set
lateinit var oilSource: BlockBase private set
lateinit var storageBlocks: BlockBase private set
override fun initBlocks(): List<Pair<Block, ItemBlock>> {
val builder = BlockBuilder().apply {
material = Material.ROCK
creativeTab = CreativeTabMg
}
ores = builder.withName("ores").copy {
states = OreType.values().toList()
}.build()
oilSource = builder.withName("oil_source").copy {
states = OilAmount.values().toList()
pickBlock = CommonMethods::pickDefaultBlock
onDrop = { listOf(ItemStack.EMPTY) }
}.build()
storageBlocks = builder.withName("storage_blocks").copy {
states = OreType.values().toList()
}.build()
ores.setHarvestLevel("pickaxe", 1, OreType.COPPER.getBlockState(ores))
ores.setHarvestLevel("pickaxe", 1, OreType.LEAD.getBlockState(ores))
ores.setHarvestLevel("pickaxe", 2, OreType.COBALT.getBlockState(ores))
ores.setHarvestLevel("pickaxe", 2, OreType.TUNGSTEN.getBlockState(ores))
ores.setHarvestLevel("pickaxe", 1, OreType.PYRITE.getBlockState(ores))
return itemBlockListOf(ores, oilSource, storageBlocks)
}
enum class OilAmount(override val stateName: String,
override val isVisible: Boolean,
val amount: Int) : IStatesEnum, IStringSerializable {
FULL_100("full_100", true, 10),
FULL_90("full_90", false, 9),
FULL_80("full_80", false, 8),
FULL_70("full_70", false, 7),
FULL_60("full_60", false, 6),
FULL_50("full_50", false, 5),
FULL_40("full_40", false, 4),
FULL_30("full_30", false, 3),
FULL_20("full_20", false, 2),
FULL_10("full_10", false, 1),
EMPTY("empty", true, 0);
override fun getName() = name.toLowerCase()
override val properties: List<IProperty<*>> get() = listOf(PROPERTY_OIL_AMOUNT)
override fun getBlockState(block: Block): IBlockState {
return block.defaultState.withProperty(PROPERTY_OIL_AMOUNT, this)
}
companion object {
fun fromAmount(amount: Int) = values().find { it.amount == amount }
}
}
enum class OreType(override val stateName: String,
override val isVisible: Boolean) : IStatesEnum, IStringSerializable {
COPPER("copper", true),
LEAD("lead", true),
COBALT("cobalt", true),
TUNGSTEN("tungsten", true),
PYRITE("pyrite", true);
fun stack(amount: Int = 1) = ItemStack(ores, amount, ordinal)
override fun getName() = name.toLowerCase()
override val properties: List<IProperty<*>> get() = listOf(PROPERTY_ORE_TYPE)
override fun getBlockState(block: Block): IBlockState {
return block.defaultState.withProperty(PROPERTY_ORE_TYPE, this)
}
}
} | gpl-2.0 | aa8d9c84b4166bee6e9510d91f64cfb6 | 35.71028 | 92 | 0.652152 | 4.019447 | false | false | false | false |
Magneticraft-Team/Magneticraft | ignore/test/block/BlockCrushingTable.kt | 2 | 4015 | package block
import com.cout970.magneticraft.api.internal.registries.machines.crushingtable.CrushingTableRecipeManager
import com.cout970.magneticraft.item.hammers.ItemHammer
import com.cout970.magneticraft.misc.tileentity.getTile
import com.cout970.magneticraft.tileentity.TileCrushingTable
import com.cout970.magneticraft.util.vector.toAABBWith
import com.teamwizardry.librarianlib.common.base.block.BlockModContainer
import net.minecraft.block.material.Material
import net.minecraft.block.state.IBlockState
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.init.Items
import net.minecraft.item.ItemStack
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumHand
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
import net.minecraft.world.IBlockAccess
import net.minecraft.world.World
object BlockCrushingTable : BlockModContainer("crushing_table", Material.ROCK) {
val boundingBox = Vec3d.ZERO toAABBWith Vec3d(1.0, 0.875, 1.0)
override fun isFullBlock(state: IBlockState?) = false
override fun isOpaqueCube(state: IBlockState?) = false
override fun isFullCube(state: IBlockState?) = false
override fun isVisuallyOpaque() = false
override fun getBoundingBox(state: IBlockState?, source: IBlockAccess?, pos: BlockPos?) = boundingBox
override fun createTileEntity(world: World, state: IBlockState) = TileCrushingTable()
override fun onBlockActivated(
world: World, pos: BlockPos, state: IBlockState,
player: EntityPlayer, hand: EnumHand, heldItem: ItemStack?,
side: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float
): Boolean {
if (side != EnumFacing.UP) {
return super.onBlockActivated(world, pos, state, player, hand, heldItem, side, hitX, hitY, hitZ)
}
val tile = world.getTile<TileCrushingTable>(pos) ?: return super.onBlockActivated(world, pos, state, player, hand, heldItem, side, hitX, hitY, hitZ)
if (tile.getStack() != null) {
val item = heldItem?.item
if (tile.canDamage() && item is ItemHammer) {
tile.doDamage(item.damage)
if (tile.getStack()!!.isItemEqual(ItemStack(Items.BLAZE_ROD))) {
player.setFire(5)
}
item.onHit(heldItem!!, player)
} else {
player.inventory.addItemStackToInventory(tile.getStack())
tile.setStack(null)
tile.sendUpdateToNearPlayers()
}
return true
} else {
if (heldItem != null) {
if (heldItem.item is ItemHammer) {
for (slot in 0 until player.inventory.sizeInventory) {
val stack = player.inventory.getStackInSlot(slot)
if (stack != null && CrushingTableRecipeManager.findRecipe(stack) != null) {
if (!player.capabilities.isCreativeMode) {
stack.stackSize--
if (stack.stackSize <= 0) {
player.inventory.setInventorySlotContents(slot, null)
}
}
tile.setStack(stack.copy().apply { stackSize = 1 })
tile.sendUpdateToNearPlayers()
return true
}
}
} else {
if (!player.capabilities.isCreativeMode) {
heldItem.stackSize--
if (heldItem.stackSize <= 0) {
player.setHeldItem(hand, null)
}
}
tile.setStack(heldItem.copy().apply { stackSize = 1 })
tile.sendUpdateToNearPlayers()
return true
}
}
return false
}
}
} | gpl-2.0 | 8b0f246e05ee7ed00fb31133f644b8dd | 40.402062 | 156 | 0.589539 | 4.73467 | false | false | false | false |
robinverduijn/gradle | .teamcity/Gradle_Promotion/buildTypes/PublishNightlySnapshotFromQuickFeedback.kt | 1 | 1187 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package Gradle_Promotion.buildTypes
class PublishNightlySnapshotFromQuickFeedback(uuid: String, branch: String) : PublishGradleDistribution(
branch = branch,
task = branch.promoteNightlyTaskName(),
triggerName = "QuickFeedback"
) {
init {
this.uuid = uuid
id("Gradle_Promotion_${branch.capitalize()}SnapshotFromQuickFeedback")
name = "${branch.capitalize()} - Nightly Snapshot (from QuickFeedback)"
description = "Promotes the latest successful changes on '$branch' from Quick Feedback as a new nightly snapshot"
}
}
| apache-2.0 | b10d172b532866871472f2a3617d4727 | 38.566667 | 121 | 0.727043 | 4.462406 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/execution/ProgramParser.kt | 1 | 4491 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.execution
import org.gradle.kotlin.dsl.support.compilerMessageFor
import com.google.common.annotations.VisibleForTesting
@VisibleForTesting
object ProgramParser {
fun parse(source: ProgramSource, kind: ProgramKind, target: ProgramTarget): Packaged<Program> = try {
programFor(source, kind, target)
} catch (unexpectedBlock: UnexpectedBlock) {
handleUnexpectedBlock(unexpectedBlock, source.text, source.path)
}
private
fun programFor(source: ProgramSource, kind: ProgramKind, target: ProgramTarget): Packaged<Program> {
val topLevelBlockIds = topLevelBlockIdsFor(target)
return lex(source.text, *topLevelBlockIds).map { (comments, topLevelBlocks) ->
checkForSingleBlocksOf(topLevelBlockIds, topLevelBlocks)
val sourceWithoutComments =
source.map { it.erase(comments) }
val buildscriptFragment =
topLevelBlocks
.singleSectionOf(topLevelBlockIds[0])
?.let { sourceWithoutComments.fragment(it) }
val pluginsFragment =
topLevelBlocks
.takeIf { target == ProgramTarget.Project && kind == ProgramKind.TopLevel }
?.singleSectionOf("plugins")
?.let { sourceWithoutComments.fragment(it) }
val buildscript =
buildscriptFragment?.takeIf { it.isNotBlank() }?.let(Program::Buildscript)
val plugins =
pluginsFragment?.takeIf { it.isNotBlank() }?.let(Program::Plugins)
val stage1 =
buildscript?.let { bs ->
plugins?.let { ps ->
Program.Stage1Sequence(bs, ps)
} ?: bs
} ?: plugins
val remainingSource =
sourceWithoutComments.map {
it.erase(
listOfNotNull(
buildscriptFragment?.range,
pluginsFragment?.range))
}
val stage2 = remainingSource
.takeIf { it.text.isNotBlank() }
?.let(Program::Script)
stage1?.let { s1 ->
stage2?.let { s2 ->
Program.Staged(s1, s2)
} ?: s1
} ?: stage2
?: Program.Empty
}
}
private
fun topLevelBlockIdsFor(target: ProgramTarget): Array<String> = when (target) {
ProgramTarget.Project -> arrayOf("buildscript", "plugins")
ProgramTarget.Settings -> arrayOf("buildscript", "pluginManagement")
ProgramTarget.Gradle -> arrayOf("initscript")
}
private
fun checkForSingleBlocksOf(
topLevelBlockIds: Array<String>,
topLevelBlocks: List<TopLevelBlock>
) {
topLevelBlockIds.forEach { id ->
topLevelBlocks
.filter { it.identifier === id }
.singleBlockSectionOrNull()
}
}
private
fun ProgramSourceFragment.isNotBlank() =
source.text.subSequence(section.block.first + 1, section.block.last).isNotBlank()
}
private
fun List<TopLevelBlock>.singleSectionOf(topLevelBlockId: String) =
singleOrNull { it.identifier == topLevelBlockId }?.section
private
fun handleUnexpectedBlock(unexpectedBlock: UnexpectedBlock, script: String, scriptPath: String): Nothing {
val (line, column) = script.lineAndColumnFromRange(unexpectedBlock.location)
val message = compilerMessageFor(scriptPath, line, column, unexpectedBlockMessage(unexpectedBlock))
throw IllegalStateException(message, unexpectedBlock)
}
private
fun unexpectedBlockMessage(block: UnexpectedBlock) =
"Unexpected `${block.identifier}` block found. Only one `${block.identifier}` block is allowed per script."
| apache-2.0 | c946dc6370cee47ca8b8a35eec84a798 | 33.546154 | 111 | 0.62436 | 4.956954 | false | false | false | false |
jilees/Fuel | fuel/src/test/kotlin/com/github/kittinunf/fuel/RequestDownloadTest.kt | 1 | 4832 | package com.github.kittinunf.fuel
import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import org.hamcrest.CoreMatchers.*
import org.junit.Assert.assertThat
import org.junit.Test
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import org.hamcrest.CoreMatchers.`is` as isEqualTo
class RequestDownloadTest : BaseTestCase() {
val manager: FuelManager by lazy {
FuelManager().apply {
basePath = "http://httpbin.org"
}
}
@Test
fun httpDownloadCase() {
var request: Request? = null
var response: Response? = null
var data: Any? = null
var error: FuelError? = null
val numberOfBytes = 32768L
manager.download("/bytes/$numberOfBytes").destination { response, url ->
val f = File.createTempFile(numberOfBytes.toString(), null)
println(f.absolutePath)
f
}.responseString { req, res, result ->
request = req
response = res
val (d, err) = result
data = d
error = err
}
assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, nullValue())
assertThat(data, notNullValue())
val statusCode = HttpURLConnection.HTTP_OK
assertThat(response?.httpStatusCode, isEqualTo(statusCode))
}
@Test
fun httpDownloadWithProgressValidCase() {
var request: Request? = null
var response: Response? = null
var data: Any? = null
var error: FuelError? = null
var read = -1L
var total = -1L
val numberOfBytes = 1048576L
manager.download("/bytes/$numberOfBytes").destination { response, url ->
val f = File.createTempFile(numberOfBytes.toString(), null)
println(f.absolutePath)
f
}.progress { readBytes, totalBytes ->
read = readBytes
total = totalBytes
println("read: $read, total: $total")
}.responseString { req, res, result ->
request = req
response = res
val (d, err) = result
data = d
error = err
}
assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, nullValue())
assertThat(data, notNullValue())
assertThat("read bytes and total bytes should be equal", read == total && read != -1L && total != -1L, isEqualTo(true))
val statusCode = HttpURLConnection.HTTP_OK
assertThat(response?.httpStatusCode, isEqualTo(statusCode))
}
@Test
fun httpDownloadWithProgressInvalidEndPointCase() {
var request: Request? = null
var response: Response? = null
var data: Any? = null
var error: FuelError? = null
val numberOfBytes = 131072
manager.download("/byte/$numberOfBytes").destination { response, url ->
val f = File.createTempFile(numberOfBytes.toString(), null)
println(f.absolutePath)
f
}.progress { readBytes, totalBytes ->
}.responseString { req, res, result ->
request = req
response = res
val (d, err) = result
data = d
error = err
}
assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, notNullValue())
assertThat(data, nullValue())
val statusCode = HttpURLConnection.HTTP_NOT_FOUND
assertThat(response?.httpStatusCode, isEqualTo(statusCode))
}
@Test
fun httpDownloadWithProgressInvalidFileCase() {
var request: Request? = null
var response: Response? = null
var data: Any? = null
var error: FuelError? = null
val numberOfBytes = 131072
manager.download("/bytes/$numberOfBytes").destination { response, url ->
val dir = System.getProperty("user.dir")
File.createTempFile("not_found_file", null, File(dir, "not-a-folder"))
}.progress { readBytes, totalBytes ->
}.responseString { req, res, result ->
request = req
response = res
val (d, err) = result
data = d
error = err
}
assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, notNullValue())
assertThat(data, nullValue())
val statusCode = -1
assertThat(error?.exception as IOException, isA(IOException::class.java))
assertThat(response?.httpStatusCode, isEqualTo(statusCode))
}
}
| mit | aac506618f4191d31d3490e06c4da759 | 30.789474 | 127 | 0.600786 | 4.870968 | false | false | false | false |
nestlabs/connectedhomeip | src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt | 1 | 3289 | /*
* Copyright (c) 2020 Project CHIP Authors
* 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.chip.chiptool
import android.content.Context
import android.util.Log
import chip.devicecontroller.ChipDeviceController
import chip.devicecontroller.GetConnectedDeviceCallbackJni.GetConnectedDeviceCallback
import chip.platform.AndroidBleManager
import chip.platform.AndroidChipPlatform
import chip.platform.ChipMdnsCallbackImpl
import chip.platform.DiagnosticDataProviderImpl
import chip.platform.NsdManagerServiceBrowser
import chip.platform.NsdManagerServiceResolver
import chip.platform.PreferencesConfigurationManager
import chip.platform.PreferencesKeyValueStoreManager
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
/** Lazily instantiates [ChipDeviceController] and holds a reference to it. */
object ChipClient {
private const val TAG = "ChipClient"
private lateinit var chipDeviceController: ChipDeviceController
private lateinit var androidPlatform: AndroidChipPlatform
fun getDeviceController(context: Context): ChipDeviceController {
getAndroidChipPlatform(context)
if (!this::chipDeviceController.isInitialized) {
chipDeviceController = ChipDeviceController()
}
return chipDeviceController
}
fun getAndroidChipPlatform(context: Context?): AndroidChipPlatform {
if (!this::androidPlatform.isInitialized && context != null) {
//force ChipDeviceController load jni
ChipDeviceController.loadJni()
androidPlatform = AndroidChipPlatform(AndroidBleManager(), PreferencesKeyValueStoreManager(context), PreferencesConfigurationManager(context), NsdManagerServiceResolver(context), NsdManagerServiceBrowser(context), ChipMdnsCallbackImpl(), DiagnosticDataProviderImpl(context))
}
return androidPlatform
}
/**
* Wrapper around [ChipDeviceController.getConnectedDevicePointer] to return the value directly.
*/
suspend fun getConnectedDevicePointer(context: Context, nodeId: Long): Long {
return suspendCoroutine { continuation ->
getDeviceController(context).getConnectedDevicePointer(
nodeId,
object : GetConnectedDeviceCallback {
override fun onDeviceConnected(devicePointer: Long) {
Log.d(TAG, "Got connected device pointer")
continuation.resume(devicePointer)
}
override fun onConnectionFailure(nodeId: Long, error: Exception) {
val errorMessage = "Unable to get connected device with nodeId $nodeId"
Log.e(TAG, errorMessage, error)
continuation.resumeWithException(IllegalStateException(errorMessage))
}
})
}
}
}
| apache-2.0 | 73807969d2457d7b718718525ae35f27 | 39.604938 | 280 | 0.764974 | 4.990895 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/kotlin/collection/PaginationCollectionKComponent.kt | 1 | 3464 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.samples.litho.kotlin.collection
import android.os.Handler
import android.os.Looper
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Style
import com.facebook.litho.core.height
import com.facebook.litho.dp
import com.facebook.litho.kotlin.widget.Progress
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.useCached
import com.facebook.litho.useState
import com.facebook.litho.widget.collection.LazyList
import com.facebook.litho.widget.collection.OnNearCallback
import com.facebook.yoga.YogaAlign
class PaginationCollectionKComponent : KComponent() {
override fun ComponentScope.render(): Component {
val paginatedData = useCached {
PagedDataWithDelay(data = (0..100).map { Item(it, "$it") }, pageSize = 40)
}
val list = useState { paginatedData.next() }
return PagedExample(
PaginatedList(
list = list.value,
fetchNextPage = {
paginatedData.fetchDelayed { newData -> list.update { it + newData } }
},
hasNextPage = paginatedData.hasNext))
}
}
class PaginatedList<T>(val list: List<T>, val fetchNextPage: () -> Unit, val hasNextPage: Boolean)
class Item(val id: Int, val text: String)
// start_example
class PagedExample(private val pagedList: PaginatedList<Item>) : KComponent() {
override fun ComponentScope.render(): Component =
LazyList(
onNearEnd = OnNearCallback { if (pagedList.hasNextPage) pagedList.fetchNextPage() },
) {
// Add the retrieved items
children(items = pagedList.list, id = { it.id }) { Text(it.text) }
// Optionally add a progress spinner
if (pagedList.hasNextPage) {
child(ProgressSpinner())
}
}
}
// end_example
// A progress spinner centered in a Column
class ProgressSpinner : KComponent() {
override fun ComponentScope.render(): Component =
Column(alignItems = YogaAlign.CENTER) {
child(component = Progress(style = Style.height(50.dp).height(50.dp)))
}
}
// A paged datasource with a simulated network delay
class PagedDataWithDelay<T>(data: List<T>, pageSize: Int) {
private val pagedData = data.chunked(pageSize).iterator()
private var isFetching = false
val hasNext
get() = pagedData.hasNext()
fun next(): List<T> = pagedData.next()
fun fetchDelayed(callback: (newData: List<T>) -> Unit) {
if (isFetching || !hasNext) return
isFetching = true
Handler(Looper.getMainLooper())
.postDelayed(
{
callback.invoke(next())
isFetching = false
},
simulatedNetworkDelayMs)
}
companion object {
const val simulatedNetworkDelayMs = 1000L
}
}
| apache-2.0 | 0554fcc8dde14d2335a66feca55421b9 | 31.679245 | 98 | 0.694284 | 4.173494 | false | false | false | false |
Ekito/koin | koin-projects/examples/android-samples/src/main/java/org/koin/sample/android/dynamic/DynamicActivity.kt | 1 | 1383 | package org.koin.sample.android.dynamic
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import kotlinx.android.synthetic.main.dynamic_activity.*
import org.koin.android.ext.android.get
import org.koin.android.ext.android.getKoin
import org.koin.core.context.loadKoinModules
import org.koin.core.context.unloadKoinModules
import org.koin.core.qualifier.named
import org.koin.sample.android.R
import org.koin.sample.android.components.dynamic.DynScoped
import org.koin.sample.android.components.dynamic.DynSingle
import org.koin.sample.android.di.dynamicModule
class DynamicActivity : AppCompatActivity() {
val single: DynSingle = get()
val scope: DynScoped = getKoin().createScope("id", named("dynamic_scope")).get()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
title = "Dynamic Activity"
setContentView(R.layout.dynamic_activity)
dyn_button.setOnClickListener {
unloadKoinModules(dynamicModule)
loadKoinModules(dynamicModule)
dyn_button.visibility = View.GONE
assert(single != get<DynSingle>())
val scope1 = getKoin().getOrCreateScope("id", named("dynamic_scope"))
assert(scope != scope1.get<DynScoped>())
dyn_label.text = "reload ok!"
}
}
} | apache-2.0 | b3eb1c56edd013aa2272780644ad9588 | 32.756098 | 84 | 0.723066 | 4.153153 | false | false | false | false |
mrebollob/LoteriadeNavidad | androidApp/src/main/java/com/mrebollob/loteria/android/presentation/settings/menu/SettingsViewModelState.kt | 1 | 690 | package com.mrebollob.loteria.android.presentation.settings.menu
import com.mrebollob.loteria.android.presentation.platform.ErrorMessage
import com.mrebollob.loteria.domain.entity.SortingMethod
data class SettingsViewModelState(
val isLoading: Boolean = false,
val settings: List<SettingsItem> = emptyList(),
val sortingMethod: SortingMethod = SortingMethod.NAME,
val appVersion: String = "",
val errorMessages: List<ErrorMessage> = emptyList(),
) {
fun toUiState() = SettingsUiState(
isLoading = isLoading,
settings = settings,
sortingMethod = sortingMethod,
appVersion = appVersion,
errorMessages = errorMessages
)
}
| apache-2.0 | 4aa06599f311f9617313dbed7bc002fe | 31.857143 | 71 | 0.726087 | 4.791667 | false | false | false | false |
Kotlin/dokka | plugins/base/src/main/kotlin/parsers/MarkdownParser.kt | 1 | 26301 | package org.jetbrains.dokka.base.parsers
import com.intellij.psi.PsiElement
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.ast.ASTNode
import org.intellij.markdown.ast.CompositeASTNode
import org.intellij.markdown.ast.LeafASTNode
import org.intellij.markdown.ast.impl.ListItemCompositeNode
import org.intellij.markdown.flavours.gfm.GFMElementTypes
import org.intellij.markdown.flavours.gfm.GFMFlavourDescriptor
import org.intellij.markdown.flavours.gfm.GFMTokenTypes
import org.intellij.markdown.html.HtmlGenerator
import org.jetbrains.dokka.base.parsers.factories.DocTagsFromIElementFactory
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.links.PointingToDeclaration
import org.jetbrains.dokka.model.doc.*
import org.jetbrains.dokka.model.doc.Suppress
import org.jetbrains.kotlin.kdoc.parser.KDocKnownTag
import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection
import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag
import java.net.MalformedURLException
import java.net.URL
import org.intellij.markdown.parser.MarkdownParser as IntellijMarkdownParser
open class MarkdownParser(
private val externalDri: (String) -> DRI?,
private val kdocLocation: String?,
) : Parser() {
private lateinit var destinationLinksMap: Map<String, String>
private lateinit var text: String
override fun parseStringToDocNode(extractedString: String): DocTag {
val gfmFlavourDescriptor = GFMFlavourDescriptor()
val markdownAstRoot = IntellijMarkdownParser(gfmFlavourDescriptor).buildMarkdownTreeFromString(extractedString)
destinationLinksMap = getAllDestinationLinks(extractedString, markdownAstRoot).toMap()
text = extractedString
val parsed = visitNode(markdownAstRoot)
if (parsed.size == 1) {
return parsed.first()
}
return CustomDocTag(children = parsed, params = emptyMap(), name = "")
}
override fun preparse(text: String) = text.replace("\r\n", "\n").replace("\r", "\n")
override fun parseTagWithBody(tagName: String, content: String): TagWrapper =
when (tagName) {
"see" -> {
val referencedName = content.substringBefore(' ')
val dri = externalDri(referencedName)
See(
parseStringToDocNode(content.substringAfter(' ')),
dri?.fqDeclarationName() ?: referencedName,
dri
)
}
"throws", "exception" -> {
val dri = externalDri(content.substringBefore(' '))
Throws(
parseStringToDocNode(content.substringAfter(' ')),
dri?.fqDeclarationName() ?: content.substringBefore(' '),
dri
)
}
else -> super.parseTagWithBody(tagName, content)
}
private fun headersHandler(node: ASTNode) =
DocTagsFromIElementFactory.getInstance(
node.type,
visitNode(node.children.find { it.type == MarkdownTokenTypes.ATX_CONTENT }
?: throw detailedException("Wrong AST Tree. Header does not contain expected content", node)
).flatMap { it.children }
)
private fun horizontalRulesHandler() =
DocTagsFromIElementFactory.getInstance(MarkdownTokenTypes.HORIZONTAL_RULE)
private fun emphasisHandler(node: ASTNode) =
DocTagsFromIElementFactory.getInstance(
node.type,
children = node.children.evaluateChildrenWithDroppedEnclosingTokens(1)
)
private fun strongHandler(node: ASTNode) =
DocTagsFromIElementFactory.getInstance(
node.type,
children = node.children.evaluateChildrenWithDroppedEnclosingTokens(2)
)
private fun List<ASTNode>.evaluateChildrenWithDroppedEnclosingTokens(count: Int) =
drop(count).dropLast(count).evaluateChildren()
private fun blockquotesHandler(node: ASTNode) =
DocTagsFromIElementFactory.getInstance(
node.type, children = node.children
.filterIsInstance<CompositeASTNode>()
.evaluateChildren()
)
private fun listsHandler(node: ASTNode): List<DocTag> {
val children = node.children.filterIsInstance<ListItemCompositeNode>().flatMap {
if (it.children.last().type in listOf(
MarkdownElementTypes.ORDERED_LIST,
MarkdownElementTypes.UNORDERED_LIST
)
) {
val nestedList = it.children.last()
(it.children as MutableList).removeAt(it.children.lastIndex)
listOf(it, nestedList)
} else
listOf(it)
}
return DocTagsFromIElementFactory.getInstance(
node.type,
children =
children
.flatMap {
if (it.type == MarkdownElementTypes.LIST_ITEM)
DocTagsFromIElementFactory.getInstance(
it.type,
children = it
.children
.filterIsInstance<CompositeASTNode>()
.evaluateChildren()
)
else
visitNode(it)
},
params =
if (node.type == MarkdownElementTypes.ORDERED_LIST) {
val listNumberNode = node.children.first().children.first()
mapOf(
"start" to text.substring(
listNumberNode.startOffset,
listNumberNode.endOffset
).trim().dropLast(1)
)
} else
emptyMap()
)
}
private fun resolveDRI(mdLink: String): DRI? =
mdLink
.removePrefix("[")
.removeSuffix("]")
.let { link ->
try {
URL(link)
null
} catch (e: MalformedURLException) {
externalDri(link)
}
}
private fun getAllDestinationLinks(text: String, node: ASTNode): List<Pair<String, String>> =
node.children
.filter { it.type == MarkdownElementTypes.LINK_DEFINITION }
.map {
text.substring(it.children[0].startOffset, it.children[0].endOffset).toLowerCase() to
text.substring(it.children[2].startOffset, it.children[2].endOffset)
} +
node.children.filterIsInstance<CompositeASTNode>().flatMap { getAllDestinationLinks(text, it) }
private fun referenceLinksHandler(node: ASTNode): List<DocTag> {
val linkLabel = node.children.find { it.type == MarkdownElementTypes.LINK_LABEL }
?: throw detailedException("Wrong AST Tree. Reference link does not contain link label", node)
val linkText = node.children.findLast { it.type == MarkdownElementTypes.LINK_TEXT } ?: linkLabel
val linkKey = text.substring(linkLabel.startOffset, linkLabel.endOffset)
val link = destinationLinksMap[linkKey.toLowerCase()] ?: linkKey
return linksHandler(linkText, link)
}
private fun inlineLinksHandler(node: ASTNode): List<DocTag> {
val linkText = node.children.find { it.type == MarkdownElementTypes.LINK_TEXT }
?: throw detailedException("Wrong AST Tree. Inline link does not contain link text", node)
val linkDestination = node.children.find { it.type == MarkdownElementTypes.LINK_DESTINATION }
val linkTitle = node.children.find { it.type == MarkdownElementTypes.LINK_TITLE }
// Link destination may be ommited: https://github.github.com/gfm/#example-495
val link = linkDestination?.let { text.substring(it.startOffset, it.endOffset) }
return linksHandler(linkText, link, linkTitle)
}
private fun markdownFileHandler(node: ASTNode) =
DocTagsFromIElementFactory.getInstance(
node.type,
children = node.children
.filterSpacesAndEOL()
.evaluateChildren()
)
private fun autoLinksHandler(node: ASTNode): List<DocTag> {
val link = text.substring(node.startOffset + 1, node.endOffset - 1)
return linksHandler(node, link)
}
private fun linksHandler(linkText: ASTNode, link: String?, linkTitle: ASTNode? = null): List<DocTag> {
val dri: DRI? = link?.let { resolveDRI(it) }
val linkOrEmpty = link ?: ""
val linkTextString =
if (linkTitle == null) linkOrEmpty else text.substring(linkTitle.startOffset + 1, linkTitle.endOffset - 1)
val params = if (linkTitle == null)
mapOf("href" to linkOrEmpty)
else
mapOf("href" to linkOrEmpty, "title" to linkTextString)
return if (link != null && dri == null && !linkOrEmpty.isRemoteLink()) {
DocTagsFromIElementFactory.getInstance(
MarkdownTokenTypes.TEXT,
params = params,
children = linkText.children.drop(1).dropLast(1).evaluateChildren(),
body = linkTextString.removeSurrounding("[", "]")
)
} else {
DocTagsFromIElementFactory.getInstance(
MarkdownElementTypes.INLINE_LINK,
params = params,
children = linkText.children.drop(1).dropLast(1).evaluateChildren(),
dri = dri
)
}
}
private fun codeLineHandler(node: ASTNode) = DocTagsFromIElementFactory.getInstance(
MarkdownElementTypes.CODE_BLOCK,
body = text.substring(node.startOffset, node.endOffset)
)
private fun textHandler(node: ASTNode, keepAllFormatting: Boolean) = DocTagsFromIElementFactory.getInstance(
MarkdownTokenTypes.TEXT,
body = text.substring(node.startOffset, node.endOffset).transform(),
keepFormatting = keepAllFormatting
)
private fun strikeThroughHandler(node: ASTNode) = DocTagsFromIElementFactory.getInstance(
node.type,
children = node.children.evaluateChildrenWithDroppedEnclosingTokens(2)
)
private fun tableHandler(node: ASTNode) = DocTagsFromIElementFactory.getInstance(
GFMElementTypes.TABLE,
children = node.children
.filter { it.type == GFMElementTypes.ROW || it.type == GFMElementTypes.HEADER }
.evaluateChildren()
)
private fun headerHandler(node: ASTNode) = DocTagsFromIElementFactory.getInstance(
GFMElementTypes.HEADER,
children = node.children
.filter { it.type == GFMTokenTypes.CELL }
.evaluateChildren()
)
private fun rowHandler(node: ASTNode) = DocTagsFromIElementFactory.getInstance(
GFMElementTypes.ROW,
children = node.children
.filter { it.type == GFMTokenTypes.CELL }
.evaluateChildren()
)
private fun cellHandler(node: ASTNode) = DocTagsFromIElementFactory.getInstance(
GFMTokenTypes.CELL,
children = node.children.filterTabSeparators().evaluateChildren().trimSurroundingTokensIfText()
)
private fun String.isRemoteLink() = try {
URL(this)
true
} catch (e: MalformedURLException) {
false
}
private fun imagesHandler(node: ASTNode): List<DocTag> =
with(node.children.last().children) {
val destination = find { it.type == MarkdownElementTypes.LINK_DESTINATION }
val description = find { it.type == MarkdownElementTypes.LINK_TEXT }
val src = destination?.let {
mapOf("href" to text.substring(it.startOffset, it.endOffset))
} ?: emptyMap()
val alt = description?.let {
mapOf("alt" to text.substring(it.startOffset + 1, it.endOffset - 1))
} ?: emptyMap()
return DocTagsFromIElementFactory.getInstance(
node.type,
params = src + alt
)
}
private fun rawHtmlHandler(node: ASTNode): List<DocTag> =
DocTagsFromIElementFactory.getInstance(
node.type,
body = text.substring(node.startOffset, node.endOffset)
)
private fun codeSpansHandler(node: ASTNode) =
DocTagsFromIElementFactory.getInstance(
node.type,
children = DocTagsFromIElementFactory.getInstance(
MarkdownTokenTypes.TEXT,
body = text.substring(node.startOffset + 1, node.endOffset - 1).replace('\n', ' ').trimIndent(),
keepFormatting = true
)
)
private fun codeFencesHandler(node: ASTNode) =
DocTagsFromIElementFactory.getInstance(
node.type,
children = node
.children
.dropWhile { it.type != MarkdownTokenTypes.CODE_FENCE_CONTENT }
.dropLastWhile { it.type != MarkdownTokenTypes.CODE_FENCE_CONTENT }
.filter { it.type != MarkdownTokenTypes.WHITE_SPACE }
.map {
if (it.type == MarkdownTokenTypes.EOL)
LeafASTNode(MarkdownTokenTypes.HARD_LINE_BREAK, 0, 0)
else
it
}.evaluateChildren(keepAllFormatting = true),
params = node
.children
.find { it.type == MarkdownTokenTypes.FENCE_LANG }
?.let { mapOf("lang" to text.substring(it.startOffset, it.endOffset)) }
?: emptyMap()
)
private fun codeBlocksHandler(node: ASTNode) =
DocTagsFromIElementFactory.getInstance(node.type, children = node.children.mergeLeafASTNodes().flatMap {
DocTagsFromIElementFactory.getInstance(
MarkdownTokenTypes.TEXT,
body = HtmlGenerator.trimIndents(text.substring(it.startOffset, it.endOffset), 4).toString()
)
})
private fun defaultHandler(node: ASTNode) =
DocTagsFromIElementFactory.getInstance(
MarkdownElementTypes.PARAGRAPH,
children = node.children.evaluateChildren()
)
private fun visitNode(node: ASTNode, keepAllFormatting: Boolean = false): List<DocTag> =
when (node.type) {
MarkdownElementTypes.ATX_1,
MarkdownElementTypes.ATX_2,
MarkdownElementTypes.ATX_3,
MarkdownElementTypes.ATX_4,
MarkdownElementTypes.ATX_5,
MarkdownElementTypes.ATX_6,
-> headersHandler(node)
MarkdownTokenTypes.HORIZONTAL_RULE -> horizontalRulesHandler()
MarkdownElementTypes.STRONG -> strongHandler(node)
MarkdownElementTypes.EMPH -> emphasisHandler(node)
MarkdownElementTypes.FULL_REFERENCE_LINK,
MarkdownElementTypes.SHORT_REFERENCE_LINK,
-> referenceLinksHandler(node)
MarkdownElementTypes.INLINE_LINK -> inlineLinksHandler(node)
MarkdownElementTypes.AUTOLINK -> autoLinksHandler(node)
MarkdownElementTypes.BLOCK_QUOTE -> blockquotesHandler(node)
MarkdownElementTypes.UNORDERED_LIST,
MarkdownElementTypes.ORDERED_LIST,
-> listsHandler(node)
MarkdownElementTypes.CODE_BLOCK -> codeBlocksHandler(node)
MarkdownElementTypes.CODE_FENCE -> codeFencesHandler(node)
MarkdownElementTypes.CODE_SPAN -> codeSpansHandler(node)
MarkdownElementTypes.IMAGE -> imagesHandler(node)
MarkdownElementTypes.HTML_BLOCK,
MarkdownTokenTypes.HTML_TAG,
MarkdownTokenTypes.HTML_BLOCK_CONTENT,
-> rawHtmlHandler(node)
MarkdownTokenTypes.HARD_LINE_BREAK -> DocTagsFromIElementFactory.getInstance(node.type)
MarkdownTokenTypes.CODE_FENCE_CONTENT,
MarkdownTokenTypes.CODE_LINE,
-> codeLineHandler(node)
MarkdownTokenTypes.TEXT -> textHandler(node, keepAllFormatting)
MarkdownElementTypes.MARKDOWN_FILE -> markdownFileHandler(node)
GFMElementTypes.STRIKETHROUGH -> strikeThroughHandler(node)
GFMElementTypes.TABLE -> tableHandler(node)
GFMElementTypes.HEADER -> headerHandler(node)
GFMElementTypes.ROW -> rowHandler(node)
GFMTokenTypes.CELL -> cellHandler(node)
else -> defaultHandler(node)
}
private fun List<ASTNode>.filterTabSeparators() =
this.filterNot { it.type == GFMTokenTypes.TABLE_SEPARATOR }
private fun List<ASTNode>.filterSpacesAndEOL() =
this.filterNot { it.type == MarkdownTokenTypes.WHITE_SPACE || it.type == MarkdownTokenTypes.EOL }
private fun List<ASTNode>.evaluateChildren(keepAllFormatting: Boolean = false): List<DocTag> =
this.removeUselessTokens().swapImagesThatShouldBeLinks(keepAllFormatting).mergeLeafASTNodes().flatMap { visitNode(it, keepAllFormatting) }
private fun List<ASTNode>.swapImagesThatShouldBeLinks(keepAllFormatting: Boolean): List<ASTNode> =
if (keepAllFormatting) {
this
} else {
flatMap { node ->
if (node.type == MarkdownElementTypes.IMAGE
&& node.children.firstOrNull()?.let { it is LeafASTNode && it.type.name == "!" } == true
&& node.children.lastOrNull()?.type == MarkdownElementTypes.SHORT_REFERENCE_LINK
) {
node.children
} else {
listOf(node)
}
}
}
private fun List<ASTNode>.removeUselessTokens(): List<ASTNode> =
this.filterIndexed { index, node ->
!(node.type == MarkdownElementTypes.LINK_DEFINITION || (
node.type == MarkdownTokenTypes.EOL &&
this.getOrNull(index - 1)?.type == MarkdownTokenTypes.HARD_LINE_BREAK
))
}
private fun List<DocTag>.trimSurroundingTokensIfText() = mapIndexed { index, elem ->
val elemTransformed = if (index == 0 && elem is Text) elem.copy(elem.body.trimStart()) else elem
if (index == lastIndex && elemTransformed is Text) elemTransformed.copy(elemTransformed.body.trimEnd()) else elemTransformed
}
private val notLeafNodes = listOf(
MarkdownTokenTypes.HORIZONTAL_RULE,
MarkdownTokenTypes.HARD_LINE_BREAK,
MarkdownTokenTypes.HTML_TAG,
MarkdownTokenTypes.HTML_BLOCK_CONTENT
)
private fun ASTNode.isNotLeaf() = this is CompositeASTNode || this.type in notLeafNodes
private fun List<ASTNode>.isNotLeaf(index: Int): Boolean =
if (index in 0..this.lastIndex)
this[index].isNotLeaf()
else
false
private fun List<ASTNode>.mergeLeafASTNodes(): List<ASTNode> {
val children: MutableList<ASTNode> = mutableListOf()
var index = 0
while (index <= this.lastIndex) {
if (this.isNotLeaf(index)) {
children += this[index]
} else {
val startOffset = this[index].startOffset
val sIndex = index
while (index < this.lastIndex) {
if (this.isNotLeaf(index + 1) || this[index + 1].startOffset != this[index].endOffset) {
children += mergedLeafNode(this, index, startOffset, sIndex)
break
}
index++
}
if (index == this.lastIndex) {
children += mergedLeafNode(this, index, startOffset, sIndex)
}
}
index++
}
return children
}
private fun mergedLeafNode(nodes: List<ASTNode>, index: Int, startOffset: Int, sIndex: Int): LeafASTNode {
val endOffset = nodes[index].endOffset
val type = if (nodes.subList(sIndex, index)
.any { it.type == MarkdownTokenTypes.CODE_LINE }
) MarkdownTokenTypes.CODE_LINE else MarkdownTokenTypes.TEXT
return LeafASTNode(type, startOffset, endOffset)
}
private fun String.transform() = this
.replace(Regex("\n\n+"), "") // Squashing new lines between paragraphs
.replace(Regex("\n"), " ")
.replace(Regex(" >+ +"), " ") // Replacement used in blockquotes, get rid of garbage
private fun detailedException(baseMessage: String, node: ASTNode) =
IllegalStateException(
baseMessage + " in ${kdocLocation ?: "unspecified location"}, element starts from offset ${node.startOffset} and ends ${node.endOffset}: ${
text.substring(
node.startOffset,
node.endOffset
)
}"
)
companion object {
fun parseFromKDocTag(
kDocTag: KDocTag?,
externalDri: (String) -> DRI?,
kdocLocation: String?,
parseWithChildren: Boolean = true
): DocumentationNode {
return if (kDocTag == null) {
DocumentationNode(emptyList())
} else {
fun parseStringToDocNode(text: String) =
MarkdownParser(externalDri, kdocLocation).parseStringToDocNode(text)
fun pointedLink(tag: KDocTag): DRI? = (parseStringToDocNode("[${tag.getSubjectName()}]")).let {
val link = it.children[0].children[0]
if (link is DocumentationLink) link.dri else null
}
val allTags =
listOf(kDocTag) + if (kDocTag.canHaveParent() && parseWithChildren) getAllKDocTags(findParent(kDocTag)) else emptyList()
DocumentationNode(
allTags.map {
when (it.knownTag) {
null -> if (it.name == null) Description(parseStringToDocNode(it.getContent())) else CustomTagWrapper(
parseStringToDocNode(it.getContent()),
it.name!!
)
KDocKnownTag.AUTHOR -> Author(parseStringToDocNode(it.getContent()))
KDocKnownTag.THROWS -> {
val dri = pointedLink(it)
Throws(
parseStringToDocNode(it.getContent()),
dri?.fqDeclarationName() ?: it.getSubjectName().orEmpty(),
dri,
)
}
KDocKnownTag.EXCEPTION -> {
val dri = pointedLink(it)
Throws(
parseStringToDocNode(it.getContent()),
dri?.fqDeclarationName() ?: it.getSubjectName().orEmpty(),
dri
)
}
KDocKnownTag.PARAM -> Param(
parseStringToDocNode(it.getContent()),
it.getSubjectName().orEmpty()
)
KDocKnownTag.RECEIVER -> Receiver(parseStringToDocNode(it.getContent()))
KDocKnownTag.RETURN -> Return(parseStringToDocNode(it.getContent()))
KDocKnownTag.SEE -> {
val dri = pointedLink(it)
See(
parseStringToDocNode(it.getContent()),
dri?.fqDeclarationName() ?: it.getSubjectName().orEmpty(),
dri,
)
}
KDocKnownTag.SINCE -> Since(parseStringToDocNode(it.getContent()))
KDocKnownTag.CONSTRUCTOR -> Constructor(parseStringToDocNode(it.getContent()))
KDocKnownTag.PROPERTY -> Property(
parseStringToDocNode(it.getContent()),
it.getSubjectName().orEmpty()
)
KDocKnownTag.SAMPLE -> Sample(
parseStringToDocNode(it.getContent()),
it.getSubjectName().orEmpty()
)
KDocKnownTag.SUPPRESS -> Suppress(parseStringToDocNode(it.getContent()))
}
}
)
}
}
//Horrible hack but since link resolution is passed as a function i am not able to resolve them otherwise
@kotlin.Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("This function makes wrong assumptions and is missing a lot of corner cases related to generics, " +
"parameters and static members. This is not supposed to be public API and will not be supported in the future")
fun DRI.fqName(): String? = "$packageName.$classNames".takeIf { packageName != null && classNames != null }
private fun DRI.fqDeclarationName(): String? {
if (this.target !is PointingToDeclaration) {
return null
}
return listOfNotNull(this.packageName, this.classNames, this.callable?.name)
.joinToString(separator = ".")
.takeIf { it.isNotBlank() }
}
private fun findParent(kDoc: PsiElement): PsiElement =
if (kDoc.canHaveParent()) findParent(kDoc.parent) else kDoc
private fun PsiElement.canHaveParent(): Boolean = this is KDocSection && knownTag != KDocKnownTag.PROPERTY
private fun getAllKDocTags(kDocImpl: PsiElement): List<KDocTag> =
kDocImpl.children.filterIsInstance<KDocTag>().filterNot { it is KDocSection } + kDocImpl.children.flatMap {
getAllKDocTags(it)
}
}
}
| apache-2.0 | ee72a3a9765e68733a6e4f737cea52cb | 42.544702 | 151 | 0.582715 | 5.190645 | false | false | false | false |
HendraAnggrian/kota | kota/src/Permissions.kt | 1 | 899 | @file:Suppress("NOTHING_TO_INLINE", "UNUSED")
package kota
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build.VERSION.SDK_INT
inline fun Context.isSelfPermissionsGranted(vararg permissions: String): Boolean = if (SDK_INT < 23) false
else permissions.all { checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }
inline fun Fragment.isSelfPermissionsGranted(vararg permissions: String): Boolean = activity.isSelfPermissionsGranted(*permissions)
inline fun Activity.shouldShowRationales(vararg permissions: String): Boolean = if (SDK_INT < 23) false
else permissions.none { shouldShowRequestPermissionRationale(it) }
inline fun Fragment.shouldShowRationales(vararg permissions: String): Boolean = if (SDK_INT < 23) false
else permissions.none { shouldShowRequestPermissionRationale(it) } | apache-2.0 | 764f09e2f141d675cb03d76415568f79 | 44 | 131 | 0.817575 | 4.472637 | false | false | false | false |
AllanWang/Frost-for-Facebook | app/src/main/kotlin/com/pitchedapps/frost/intro/IntroImageFragments.kt | 1 | 5873 | /*
* Copyright 2018 Allan Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pitchedapps.frost.intro
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import ca.allanwang.kau.utils.bindViewResettable
import ca.allanwang.kau.utils.colorToForeground
import ca.allanwang.kau.utils.setIcon
import ca.allanwang.kau.utils.tint
import ca.allanwang.kau.utils.visible
import ca.allanwang.kau.utils.withAlpha
import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial
import com.pitchedapps.frost.R
import com.pitchedapps.frost.utils.launchTabCustomizerActivity
import kotlin.math.abs
/** Created by Allan Wang on 2017-07-28. */
abstract class BaseImageIntroFragment(val titleRes: Int, val imageRes: Int, val descRes: Int) :
BaseIntroFragment(R.layout.intro_image) {
val imageDrawable: LayerDrawable by lazyResettableRegistered { image.drawable as LayerDrawable }
val phone: Drawable by lazyResettableRegistered {
imageDrawable.findDrawableByLayerId(R.id.intro_phone)
}
val screen: Drawable by lazyResettableRegistered {
imageDrawable.findDrawableByLayerId(R.id.intro_phone_screen)
}
val icon: ImageView by bindViewResettable(R.id.intro_button)
override fun viewArray(): Array<Array<out View>> = arrayOf(arrayOf(title), arrayOf(desc))
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
title.setText(titleRes)
image.setImageResource(imageRes)
desc.setText(descRes)
super.onViewCreated(view, savedInstanceState)
}
override fun themeFragmentImpl() {
super.themeFragmentImpl()
title.setTextColor(themeProvider.textColor)
desc.setTextColor(themeProvider.textColor)
phone.tint(themeProvider.textColor)
screen.tint(themeProvider.bgColor)
}
fun themeImageComponent(color: Int, vararg id: Int) {
id.forEach { imageDrawable.findDrawableByLayerId(it).tint(color) }
}
override fun onPageScrolledImpl(positionOffset: Float) {
super.onPageScrolledImpl(positionOffset)
val alpha = ((1 - abs(positionOffset)) * 255).toInt()
// apply alpha to all layers except the phone base
(0 until imageDrawable.numberOfLayers).forEach {
val d = imageDrawable.getDrawable(it)
if (d != phone) d.alpha = alpha
}
}
fun firstImageFragmentTransition(offset: Float) {
if (offset < 0) image.alpha = 1 + offset
}
fun lastImageFragmentTransition(offset: Float) {
if (offset > 0) image.alpha = 1 - offset
}
}
class IntroAccountFragment :
BaseImageIntroFragment(
R.string.intro_multiple_accounts,
R.drawable.intro_phone_nav,
R.string.intro_multiple_accounts_desc
) {
override fun themeFragmentImpl() {
super.themeFragmentImpl()
themeImageComponent(
themeProvider.iconColor,
R.id.intro_phone_avatar_1,
R.id.intro_phone_avatar_2
)
themeImageComponent(themeProvider.bgColor.colorToForeground(), R.id.intro_phone_nav)
themeImageComponent(themeProvider.headerColor, R.id.intro_phone_header)
}
override fun onPageScrolledImpl(positionOffset: Float) {
super.onPageScrolledImpl(positionOffset)
firstImageFragmentTransition(positionOffset)
}
}
class IntroTabTouchFragment :
BaseImageIntroFragment(
R.string.intro_easy_navigation,
R.drawable.intro_phone_tab,
R.string.intro_easy_navigation_desc
) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
icon.visible().setIcon(GoogleMaterial.Icon.gmd_edit, 24)
icon.setOnClickListener { activity?.launchTabCustomizerActivity() }
}
override fun themeFragmentImpl() {
super.themeFragmentImpl()
themeImageComponent(
themeProvider.iconColor,
R.id.intro_phone_icon_1,
R.id.intro_phone_icon_2,
R.id.intro_phone_icon_3,
R.id.intro_phone_icon_4
)
themeImageComponent(themeProvider.headerColor, R.id.intro_phone_tab)
themeImageComponent(themeProvider.textColor.withAlpha(80), R.id.intro_phone_icon_ripple)
}
}
class IntroTabContextFragment :
BaseImageIntroFragment(
R.string.intro_context_aware,
R.drawable.intro_phone_long_press,
R.string.intro_context_aware_desc
) {
override fun themeFragmentImpl() {
super.themeFragmentImpl()
themeImageComponent(themeProvider.headerColor, R.id.intro_phone_toolbar)
themeImageComponent(themeProvider.bgColor.colorToForeground(0.1f), R.id.intro_phone_image)
themeImageComponent(
themeProvider.bgColor.colorToForeground(0.2f),
R.id.intro_phone_like,
R.id.intro_phone_share
)
themeImageComponent(themeProvider.bgColor.colorToForeground(0.3f), R.id.intro_phone_comment)
themeImageComponent(
themeProvider.bgColor.colorToForeground(0.1f),
R.id.intro_phone_card_1,
R.id.intro_phone_card_2
)
themeImageComponent(
themeProvider.textColor,
R.id.intro_phone_image_indicator,
R.id.intro_phone_comment_indicator,
R.id.intro_phone_card_indicator
)
}
override fun onPageScrolledImpl(positionOffset: Float) {
super.onPageScrolledImpl(positionOffset)
lastImageFragmentTransition(positionOffset)
}
}
| gpl-3.0 | 54b3096b0f5325fd109e621aa00af5e9 | 32.947977 | 98 | 0.749021 | 3.949563 | false | false | false | false |
http4k/http4k | http4k-serverless/lambda-runtime/src/main/kotlin/org/http4k/serverless/LambdaEnvironmentContext.kt | 1 | 1814 | package org.http4k.serverless
import com.amazonaws.services.lambda.runtime.ClientContext
import com.amazonaws.services.lambda.runtime.CognitoIdentity
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.LambdaLogger
import org.http4k.core.Request
import org.http4k.serverless.LambdaRuntimeAPI.Companion.deadline
import org.http4k.serverless.LambdaRuntimeAPI.Companion.lambdaArn
import org.http4k.serverless.LambdaRuntimeAPI.Companion.requestId
import java.time.Clock
import java.time.Duration.between
/**
* Custom http4k version of the Lambda Context interface.
*/
class LambdaEnvironmentContext(
private val req: Request,
private val env: Map<String, String>,
private val clock: Clock = Clock.systemUTC()
) : Context {
override fun getAwsRequestId() = requestId(req)?.toString()
override fun getLogGroupName() = env["AWS_LAMBDA_LOG_GROUP_NAME"]
override fun getLogStreamName() = env["AWS_LAMBDA_LOG_STREAM_NAME"]
override fun getFunctionName() = env["AWS_LAMBDA_FUNCTION_NAME"]
override fun getFunctionVersion() = env["AWS_LAMBDA_FUNCTION_VERSION"]
override fun getInvokedFunctionArn() = lambdaArn(req)
override fun getRemainingTimeInMillis() =
between(clock.instant(), deadline(req)).toMillis().toInt()
override fun getMemoryLimitInMB() = env["AWS_LAMBDA_FUNCTION_MEMORY_SIZE"]?.toInt() ?: 0
override fun getLogger() = object : LambdaLogger {
override fun log(message: String) = println(message)
override fun log(message: ByteArray) = println(String(message))
}
override fun getIdentity(): CognitoIdentity = throw UnsupportedOperationException("not implemented")
override fun getClientContext(): ClientContext = throw UnsupportedOperationException("not implemented")
}
| apache-2.0 | 602f8b96def1b6fb314be247a172cf8b | 37.595745 | 107 | 0.764057 | 4.228438 | false | false | false | false |
Sjtek/sjtekcontrol-core | data/src/main/kotlin/nl/sjtek/control/data/parsers/ResponseParser.kt | 1 | 1310 | package nl.sjtek.control.data.parsers
import com.google.gson.*
import com.google.gson.reflect.TypeToken
import nl.sjtek.control.data.response.Response
import java.lang.reflect.Type
object ResponseParser {
fun parse(input: String?): ResponseHolder {
val type = object : TypeToken<Map<String, Response>>() {}.type
val gson = GsonBuilder().registerTypeAdapter(Response::class.java, ResponseAdapter()).create()
return try {
val holder = ResponseHolder(gson.fromJson<Map<String, Response>>(input, type))
holder.test()
holder
} catch (e: Exception) {
ResponseHolder(exception = e)
}
}
private class ResponseAdapter : JsonDeserializer<Response> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Response? {
val jsonObject = json.asJsonObject ?: throw JsonParseException("Invalid json")
val type = jsonObject.get("type")?.asString ?: throw JsonParseException("Response is missing a string")
try {
return context.deserialize(json, Class.forName(type))
} catch (e: ClassNotFoundException) {
throw JsonParseException("Unknown element type $type", e)
}
}
}
} | gpl-3.0 | 823784625ab62388b59a5660b137b67e | 39.96875 | 116 | 0.648855 | 4.869888 | false | false | false | false |
alashow/music-android | modules/core-playback/src/main/java/tm/alashow/datmusic/playback/players/DatmusicPlayer.kt | 1 | 22687 | /*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.datmusic.playback.players
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.content.Context
import android.content.Intent
import android.media.session.PlaybackState
import android.os.Bundle
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.MediaMetadataCompat.*
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.support.v4.media.session.PlaybackStateCompat.*
import androidx.core.net.toUri
import androidx.core.os.bundleOf
import com.google.firebase.analytics.FirebaseAnalytics
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import timber.log.Timber
import tm.alashow.base.imageloading.getBitmap
import tm.alashow.base.util.event
import tm.alashow.base.util.extensions.plus
import tm.alashow.data.PreferencesStore
import tm.alashow.datmusic.data.db.daos.AlbumsDao
import tm.alashow.datmusic.data.db.daos.ArtistsDao
import tm.alashow.datmusic.data.db.daos.AudiosDao
import tm.alashow.datmusic.data.db.daos.DownloadRequestsDao
import tm.alashow.datmusic.data.db.daos.findAudio
import tm.alashow.datmusic.domain.entities.Audio
import tm.alashow.datmusic.domain.entities.AudioDownloadItem
import tm.alashow.datmusic.domain.entities.CoverImageSize
import tm.alashow.datmusic.downloader.artworkFromFile
import tm.alashow.datmusic.playback.AudioFocusHelperImpl
import tm.alashow.datmusic.playback.AudioQueueManagerImpl
import tm.alashow.datmusic.playback.BY_UI_KEY
import tm.alashow.datmusic.playback.R
import tm.alashow.datmusic.playback.REPEAT_ALL
import tm.alashow.datmusic.playback.REPEAT_ONE
import tm.alashow.datmusic.playback.createDefaultPlaybackState
import tm.alashow.datmusic.playback.isPlaying
import tm.alashow.datmusic.playback.models.MEDIA_TYPE_AUDIO
import tm.alashow.datmusic.playback.models.MediaId
import tm.alashow.datmusic.playback.models.QueueState
import tm.alashow.datmusic.playback.models.toAudioList
import tm.alashow.datmusic.playback.models.toMediaId
import tm.alashow.datmusic.playback.models.toMediaMetadata
import tm.alashow.datmusic.playback.models.toQueueTitle
import tm.alashow.datmusic.playback.position
import tm.alashow.datmusic.playback.repeatMode
import tm.alashow.datmusic.playback.shuffleMode
typealias OnPrepared<T> = T.() -> Unit
typealias OnError<T> = T.(error: Throwable) -> Unit
typealias OnCompletion<T> = T.() -> Unit
typealias OnBuffering<T> = T.() -> Unit
typealias OnReady<T> = T.() -> Unit
typealias OnMetaDataChanged = DatmusicPlayer.() -> Unit
typealias OnIsPlaying<T> = T.(playing: Boolean, byUi: Boolean) -> Unit
const val REPEAT_MODE = "repeat_mode"
const val SHUFFLE_MODE = "shuffle_mode"
const val QUEUE_CURRENT_INDEX = "queue_current_index"
const val QUEUE_HAS_PREVIOUS = "queue_has_previous"
const val QUEUE_HAS_NEXT = "queue_has_next"
const val DEFAULT_FORWARD_REWIND = 10 * 1000
interface DatmusicPlayer {
fun getSession(): MediaSessionCompat
fun playAudio(extras: Bundle = bundleOf(BY_UI_KEY to true))
suspend fun playAudio(id: String, index: Int? = null)
suspend fun playAudio(audio: Audio, index: Int? = null)
fun seekTo(position: Long)
fun fastForward()
fun rewind()
fun pause(extras: Bundle = bundleOf(BY_UI_KEY to true))
suspend fun nextAudio(): String?
suspend fun repeatAudio()
suspend fun repeatQueue()
suspend fun previousAudio()
fun playNext(id: String)
suspend fun skipTo(position: Int)
fun removeFromQueue(position: Int)
fun removeFromQueue(id: String)
fun swapQueueAudios(from: Int, to: Int)
fun stop(byUser: Boolean = true)
fun release()
fun onPlayingState(playing: OnIsPlaying<DatmusicPlayer>)
fun onPrepared(prepared: OnPrepared<DatmusicPlayer>)
fun onError(error: OnError<DatmusicPlayer>)
fun onCompletion(completion: OnCompletion<DatmusicPlayer>)
fun onMetaDataChanged(metaDataChanged: OnMetaDataChanged)
fun updatePlaybackState(applier: PlaybackStateCompat.Builder.() -> Unit = {})
fun setPlaybackState(state: PlaybackStateCompat)
fun updateData(list: List<String> = emptyList(), title: String? = null)
fun setData(list: List<String> = emptyList(), title: String? = null)
suspend fun setDataFromMediaId(_mediaId: String, extras: Bundle = bundleOf())
suspend fun saveQueueState()
suspend fun restoreQueueState()
fun clearRandomAudioPlayed()
fun setCurrentAudioId(audioId: String, index: Int? = null)
fun shuffleQueue(isShuffle: Boolean)
}
@Singleton
class DatmusicPlayerImpl @Inject constructor(
@ApplicationContext private val context: Context,
private val audioPlayer: AudioPlayerImpl,
private val queueManager: AudioQueueManagerImpl,
private val audioFocusHelper: AudioFocusHelperImpl,
private val audiosDao: AudiosDao,
private val artistsDao: ArtistsDao,
private val albumsDao: AlbumsDao,
private val downloadsDao: DownloadRequestsDao,
private val preferences: PreferencesStore,
private val analytics: FirebaseAnalytics,
) : DatmusicPlayer, CoroutineScope by MainScope() {
companion object {
private const val queueStateKey = "player_queue_state"
}
private var isInitialized: Boolean = false
private var isPlayingCallback: OnIsPlaying<DatmusicPlayer> = { _, _ -> }
private var preparedCallback: OnPrepared<DatmusicPlayer> = {}
private var errorCallback: OnError<DatmusicPlayer> = {}
private var completionCallback: OnCompletion<DatmusicPlayer> = {}
private var metaDataChangedCallback: OnMetaDataChanged = {}
private val metadataBuilder = MediaMetadataCompat.Builder()
private val stateBuilder = createDefaultPlaybackState()
private val pendingIntent = PendingIntent.getBroadcast(context, 0, Intent(Intent.ACTION_MEDIA_BUTTON), FLAG_IMMUTABLE)
private val mediaSession = MediaSessionCompat(context, context.getString(R.string.app_name), null, pendingIntent).apply {
setCallback(
MediaSessionCallback(this, this@DatmusicPlayerImpl, audioFocusHelper)
)
setPlaybackState(stateBuilder.build())
val sessionIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)
val sessionActivityPendingIntent = PendingIntent.getActivity(context, 0, sessionIntent, FLAG_IMMUTABLE)
setSessionActivity(sessionActivityPendingIntent)
isActive = true
}
init {
queueManager.setMediaSession(mediaSession)
audioPlayer.onPrepared {
preparedCallback(this@DatmusicPlayerImpl)
launch {
if (!mediaSession.isPlaying()) audioPlayer.seekTo(mediaSession.position())
playAudio()
}
}
audioPlayer.onCompletion {
completionCallback(this@DatmusicPlayerImpl)
val controller = getSession().controller
when (controller.repeatMode) {
REPEAT_MODE_ONE -> controller.transportControls.sendCustomAction(REPEAT_ONE, null)
REPEAT_MODE_ALL -> controller.transportControls.sendCustomAction(REPEAT_ALL, null)
else -> launch { if (nextAudio() == null) goToStart() }
}
}
audioPlayer.onBuffering {
updatePlaybackState {
setState(STATE_BUFFERING, mediaSession.position(), 1F)
}
}
audioPlayer.onIsPlaying { playing, byUi ->
if (playing)
updatePlaybackState {
setState(STATE_PLAYING, mediaSession.position(), 1F)
setExtras(
bundleOf(
REPEAT_MODE to getSession().repeatMode,
SHUFFLE_MODE to getSession().shuffleMode
)
)
}
isPlayingCallback(playing, byUi)
}
audioPlayer.onReady {
if (!audioPlayer.isPlaying()) {
Timber.d("Player ready but not currently playing, requesting to play")
audioPlayer.play()
}
updatePlaybackState {
setState(STATE_PLAYING, mediaSession.position(), 1F)
}
}
audioPlayer.onError { throwable ->
Timber.e(throwable, "AudioPlayer error")
errorCallback(this@DatmusicPlayerImpl, throwable)
isInitialized = false
updatePlaybackState {
setState(STATE_ERROR, 0, 1F)
}
}
}
override fun getSession(): MediaSessionCompat = mediaSession
override fun pause(extras: Bundle) {
if (isInitialized && (audioPlayer.isPlaying() || audioPlayer.isBuffering())) {
audioPlayer.pause()
updatePlaybackState {
setState(STATE_PAUSED, mediaSession.position(), 1F)
setExtras(
extras + bundleOf(
REPEAT_MODE to getSession().repeatMode,
SHUFFLE_MODE to getSession().shuffleMode
)
)
}
} else {
Timber.d("Couldn't pause player: ${audioPlayer.isPlaying()}, $isInitialized")
}
}
override fun playAudio(extras: Bundle) {
if (isInitialized) {
audioPlayer.play()
return
}
val isSourceSet = when (val audio = queueManager.currentAudio) {
is Audio -> {
when (val downloadItem = audio.audioDownloadItem) {
is AudioDownloadItem -> audioPlayer.setSource(downloadItem.downloadInfo.fileUri, true)
else -> {
val uri = audio.streamUrl?.toUri()
if (uri != null)
audioPlayer.setSource(uri, false)
else false
}
}
}
else -> false
}
if (isSourceSet) {
isInitialized = true
audioPlayer.prepare()
} else {
Timber.e("Couldn't set new source")
}
}
override suspend fun playAudio(id: String, index: Int?) {
if (audioFocusHelper.requestPlayback()) {
val audio = (audiosDao to downloadsDao).findAudio(id)
if (audio != null) playAudio(audio, index)
else {
Timber.e("Audio by id: $id not found")
updatePlaybackState {
setState(STATE_ERROR, 0, 1F)
}
}
}
}
override suspend fun playAudio(audio: Audio, index: Int?) {
setCurrentAudioId(audio.id, index)
val refreshedAudio = queueManager.refreshCurrentAudio()
isInitialized = false
updatePlaybackState {
setState(mediaSession.controller.playbackState.state, 0, 1F)
}
setMetaData(refreshedAudio ?: audio)
playAudio()
}
override suspend fun skipTo(position: Int) {
if (queueManager.currentAudioIndex == position) {
Timber.d("Not skipping to index=$position")
return
}
queueManager.skipTo(position)
playAudio(queueManager.currentAudioId, position)
updatePlaybackState()
}
override fun seekTo(position: Long) {
if (isInitialized) {
audioPlayer.seekTo(position)
updatePlaybackState {
setState(
mediaSession.controller.playbackState.state,
position,
1F
)
}
} else updatePlaybackState {
setState(
mediaSession.controller.playbackState.state,
position,
1F
)
}
logEvent("seekTo")
}
override fun fastForward() {
val forwardTo = mediaSession.position() + DEFAULT_FORWARD_REWIND
queueManager.currentAudio?.apply {
val duration = durationMillis()
if (forwardTo > duration) {
seekTo(duration)
} else {
seekTo(forwardTo)
}
}
logEvent("fastForward")
}
override fun rewind() {
val rewindTo = mediaSession.position() - DEFAULT_FORWARD_REWIND
if (rewindTo < 0) {
seekTo(0)
} else {
seekTo(rewindTo)
}
logEvent("rewind")
}
override suspend fun nextAudio(): String? {
val index = queueManager.nextAudioIndex
if (index != null) {
val id = queueManager.queue[index]
playAudio(id, index)
logEvent("nextAudio")
return id
}
return null
}
override suspend fun previousAudio() {
if (queueManager.queue.isNotEmpty())
queueManager.previousAudioIndex?.let {
playAudio(queueManager.queue[it], it)
logEvent("previousAudio")
} ?: repeatAudio()
}
override suspend fun repeatAudio() {
playAudio(queueManager.currentAudioId)
logEvent("repeatAudio")
}
override suspend fun repeatQueue() {
if (queueManager.queue.isNotEmpty()) {
if (queueManager.currentAudioId == queueManager.queue.last())
playAudio(queueManager.queue.first())
else {
nextAudio()
}
logEvent("repeatQueue")
}
}
override fun playNext(id: String) {
if (queueManager.queue.isEmpty()) {
launch {
setDataFromMediaId(MediaId(MEDIA_TYPE_AUDIO, id).toString())
}
} else {
queueManager.playNext(id)
}
logEvent("playNext", id)
}
override fun removeFromQueue(position: Int) {
queueManager.remove(position)
logEvent("removeFromQueue", "position=$position")
}
override fun removeFromQueue(id: String) {
queueManager.remove(id)
logEvent("removeFromQueue", id)
}
override fun swapQueueAudios(from: Int, to: Int) {
queueManager.swap(from, to)
queueManager.currentAudio?.apply { setMetaData(this) }
logEvent("nextAudio")
}
override fun stop(byUser: Boolean) {
updatePlaybackState {
setState(if (byUser) STATE_NONE else STATE_STOPPED, 0, 1F)
}
isInitialized = false
audioPlayer.stop()
isPlayingCallback(false, byUser)
queueManager.clear()
launch { saveQueueState() }
}
override fun release() {
mediaSession.apply {
isActive = false
release()
}
audioPlayer.release()
queueManager.clear()
}
override fun onPlayingState(playing: OnIsPlaying<DatmusicPlayer>) {
this.isPlayingCallback = playing
}
override fun onPrepared(prepared: OnPrepared<DatmusicPlayer>) {
this.preparedCallback = prepared
}
override fun onError(error: OnError<DatmusicPlayer>) {
this.errorCallback = error
}
override fun onCompletion(completion: OnCompletion<DatmusicPlayer>) {
this.completionCallback = completion
}
override fun onMetaDataChanged(metaDataChanged: OnMetaDataChanged) {
this.metaDataChangedCallback = metaDataChanged
}
override fun updatePlaybackState(applier: PlaybackStateCompat.Builder.() -> Unit) {
applier(stateBuilder)
stateBuilder.setExtras(
stateBuilder.build().extras + bundleOf(
QUEUE_CURRENT_INDEX to queueManager.currentAudioIndex,
QUEUE_HAS_PREVIOUS to (queueManager.previousAudioIndex != null),
QUEUE_HAS_NEXT to (queueManager.nextAudioIndex != null),
)
)
setPlaybackState(stateBuilder.build())
}
override fun setPlaybackState(state: PlaybackStateCompat) {
mediaSession.setPlaybackState(state)
state.extras?.let { bundle ->
mediaSession.setRepeatMode(bundle.getInt(REPEAT_MODE))
mediaSession.setShuffleMode(bundle.getInt(SHUFFLE_MODE))
}
}
override fun updateData(list: List<String>, title: String?) {
if (mediaSession.shuffleMode == SHUFFLE_MODE_NONE)
if (title == queueManager.queueTitle) {
queueManager.queue = list
queueManager.queueTitle = title
queueManager.currentAudio?.apply { setMetaData(this) }
}
}
override fun setData(list: List<String>, title: String?) {
// reset shuffle mode on new data
getSession().setShuffleMode(SHUFFLE_MODE_NONE)
updatePlaybackState {
setExtras(bundleOf(SHUFFLE_MODE to SHUFFLE_MODE_NONE))
}
queueManager.queue = list
queueManager.queueTitle = title ?: ""
}
override suspend fun setDataFromMediaId(_mediaId: String, extras: Bundle) {
val mediaId = _mediaId.toMediaId()
var audioId = extras.getString(QUEUE_MEDIA_ID_KEY) ?: mediaId.value
var queue = extras.getStringArray(QUEUE_LIST_KEY)?.toList()
var queueTitle = extras.getString(QUEUE_TITLE_KEY)
val seekTo = extras.getLong(SEEK_TO)
if (seekTo > 0) seekTo(seekTo)
if (queue == null) {
queue = mediaId.toAudioList(audiosDao, artistsDao, albumsDao)?.map { it.id }?.apply {
if (mediaId.index >= 0 && isNotEmpty())
audioId = if (mediaId.index < size) get(mediaId.index) else first()
}
queueTitle = mediaId.toQueueTitle(audiosDao, artistsDao, albumsDao).toString()
}
if (queue != null && queue.isNotEmpty()) {
setData(queue, queueTitle)
playAudio(audioId, queue.indexOf(audioId))
// delay for new queue to apply first
delay(2000)
saveQueueState()
} else {
Timber.e("Queue is null or empty: $mediaId")
}
logEvent("playMedia", _mediaId)
}
override suspend fun saveQueueState() {
val mediaSession = getSession()
val controller = mediaSession.controller
if (controller == null || controller.playbackState == null) {
Timber.d("Not saving queue state")
return
}
val queueState = QueueState(
queue = queueManager.queue,
currentIndex = queueManager.currentAudioIndex,
seekPosition = controller.playbackState?.position ?: 0,
repeatMode = controller.repeatMode,
shuffleMode = controller.shuffleMode,
state = controller.playbackState?.state ?: PlaybackState.STATE_NONE,
title = controller.queueTitle?.toString()
)
Timber.d("Saving queue state: idx=${queueState.currentIndex}, size=${queueState.queue.size}, title=${queueState.title}")
preferences.save(queueStateKey, queueState, QueueState.serializer())
}
override suspend fun restoreQueueState() {
Timber.d("Restoring queue state")
var queueState = preferences.get(queueStateKey, QueueState.serializer(), QueueState(emptyList())).first()
Timber.d("Restoring state: ${queueState.currentIndex}, size=${queueState.queue.size}")
if (queueState.state in listOf(STATE_PLAYING, STATE_BUFFERING, STATE_BUFFERING, STATE_ERROR)) {
queueState = queueState.copy(state = STATE_PAUSED)
}
if (queueState.queue.isNotEmpty()) {
setCurrentAudioId(queueState.queue[queueState.currentIndex], queueState.currentIndex)
setData(queueState.queue, queueState.title ?: "")
queueManager.refreshCurrentAudio()?.apply {
Timber.d("Setting metadata from saved state: currentAudio=$id")
setMetaData(this)
}
}
val extras = bundleOf(
REPEAT_MODE to queueState.repeatMode,
SHUFFLE_MODE to SHUFFLE_MODE_NONE
)
updatePlaybackState {
setState(queueState.state, queueState.seekPosition, 1F)
setExtras(extras)
}
}
override fun clearRandomAudioPlayed() {
queueManager.clearPlayedAudios()
}
override fun setCurrentAudioId(audioId: String, index: Int?) {
val audioIndex = index ?: queueManager.queue.indexOfFirst { it == audioId }
if (audioIndex < 0) {
Timber.e("Audio id isn't in the queue, what it do?")
} else queueManager.currentAudioIndex = audioIndex
}
override fun shuffleQueue(isShuffle: Boolean) {
launch {
queueManager.shuffleQueue(isShuffle)
queueManager.currentAudio?.apply { setMetaData(this) }
updatePlaybackState {
setState(mediaSession.controller.playbackState.state, mediaSession.position(), 1F)
}
logEvent("shuffleQueue")
}
}
private fun goToStart() {
isInitialized = false
stop()
if (queueManager.queue.isEmpty()) return
launch {
setCurrentAudioId(queueManager.queue.first())
queueManager.refreshCurrentAudio()?.apply { setMetaData(this) }
}
}
private fun setMetaData(audio: Audio) {
val player = this
launch {
val mediaMetadata = audio.toMediaMetadata(metadataBuilder).apply {
val artworkFromFile = audio.artworkFromFile(context)
if (artworkFromFile != null) {
putBitmap(METADATA_KEY_ALBUM_ART, artworkFromFile)
}
}
mediaSession.setMetadata(mediaMetadata.build())
metaDataChangedCallback(player)
// cover image is applied separately to avoid delaying metadata setting while fetching bitmap from network
val smallCoverBitmap = context.getBitmap(audio.coverUri(CoverImageSize.SMALL), CoverImageSize.SMALL.maxSize)
val updatedMetadata = mediaMetadata.apply { putBitmap(METADATA_KEY_ALBUM_ART, smallCoverBitmap) }.build()
mediaSession.setMetadata(updatedMetadata)
metaDataChangedCallback(player)
}
}
private fun logEvent(event: String, mediaId: String = queueManager.currentAudioId) = analytics.event("player.$event", mapOf("mediaId" to mediaId))
}
| apache-2.0 | ca2ca447a11c219c3bcdfcbdaa47b000 | 35.533011 | 150 | 0.636708 | 4.780236 | false | false | false | false |
vhromada/Catalog-Swing | src/main/kotlin/cz/vhromada/catalog/gui/music/MusicDataPanel.kt | 1 | 5707 | package cz.vhromada.catalog.gui.music
import cz.vhromada.catalog.entity.Music
import cz.vhromada.catalog.facade.SongFacade
import cz.vhromada.catalog.gui.common.AbstractDataPanel
import cz.vhromada.catalog.gui.common.WebPageButtonType
import cz.vhromada.common.entity.Time
import cz.vhromada.common.result.Status
import javax.swing.GroupLayout
import javax.swing.JButton
import javax.swing.JLabel
/**
* A class represents panel with music data.
*
* @author Vladimir Hromada
*/
class MusicDataPanel(
music: Music,
private val songFacade: SongFacade) : AbstractDataPanel<Music>() {
/**
* Label for name
*/
private val nameLabel = JLabel("Name")
/**
* Label with name
*/
private val nameData = JLabel()
/**
* Label for count of media
*/
private val mediaCountLabel = JLabel("Count of media")
/**
* Label with count of media
*/
private val mediaCountData = JLabel()
/**
* Label for count of songs
*/
private val songsCountLabel = JLabel("Count of songs")
/**
* Label with count of songs
*/
private val songsCountData = JLabel()
/**
* Label for total length
*/
private val totalLengthLabel = JLabel("Total length")
/**
* Label with total length
*/
private val totalLengthData = JLabel()
/**
* Label for note
*/
private val noteLabel = JLabel("Note")
/**
* Label with note
*/
private val noteData = JLabel()
/**
* Button for showing music czech Wikipedia page
*/
private val wikiCzButton = JButton("Czech Wikipedia")
/**
* Button for showing music english Wikipedia page
*/
private val wikiEnButton = JButton("English Wikipedia")
/**
* URL to czech Wikipedia page about music
*/
private var wikiCz: String? = null
/**
* URL to english Wikipedia page about music
*/
private var wikiEn: String? = null
init {
updateData(music)
initData(nameLabel, nameData)
initData(mediaCountLabel, mediaCountData)
initData(songsCountLabel, songsCountData)
initData(totalLengthLabel, totalLengthData)
initData(noteLabel, noteData)
initButton(wikiCzButton, WebPageButtonType.WIKI_CZ)
initButton(wikiEnButton, WebPageButtonType.WIKI_EN)
createLayout()
}
@Suppress("DuplicatedCode")
override fun updateComponentData(data: Music) {
nameData.text = data.name
mediaCountData.text = data.mediaCount?.toString()
songsCountData.text = getSongsCount(data)
totalLengthData.text = getMusicLength(data)
noteData.text = data.note
wikiCz = data.wikiCz
wikiEn = data.wikiEn
wikiCzButton.isEnabled = !wikiCz.isNullOrBlank()
wikiEnButton.isEnabled = !wikiEn.isNullOrBlank()
}
override fun getCzWikiUrl(): String {
return wikiCz!!
}
override fun getEnWikiUrl(): String {
return wikiEn!!
}
override fun getCsfdUrl(): String {
error { "Getting URL to ČSFD page is not allowed for music." }
}
override fun getImdbUrl(): Int {
error { "Getting URL to IMDB page is not allowed for music." }
}
override fun getHorizontalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group {
return group
.addGroup(createHorizontalDataComponents(layout, nameLabel, nameData))
.addGroup(createHorizontalDataComponents(layout, mediaCountLabel, mediaCountData))
.addGroup(createHorizontalDataComponents(layout, songsCountLabel, songsCountData))
.addGroup(createHorizontalDataComponents(layout, totalLengthLabel, totalLengthData))
.addGroup(createHorizontalDataComponents(layout, noteLabel, noteData))
.addGroup(createHorizontalButtons(layout, wikiCzButton, wikiEnButton))
}
override fun getVerticalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group {
return group
.addGroup(createVerticalComponents(layout, nameLabel, nameData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, mediaCountLabel, mediaCountData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, songsCountLabel, songsCountData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, totalLengthLabel, totalLengthData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, noteLabel, noteData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalButtons(layout, wikiCzButton, wikiEnButton))
}
/**
* Returns count of music songs.
*
* @param music music
* @return count of music songs
*/
private fun getSongsCount(music: Music): String {
val result = songFacade.find(music)
if (Status.OK == result.status) {
return result.data!!.size.toString()
}
throw IllegalArgumentException("Can't get data. $result")
}
/**
* Returns total length of all music songs.
*
* @param music music
* @return total length of all music songs
*/
private fun getMusicLength(music: Music): String {
val result = songFacade.find(music)
if (Status.OK == result.status) {
return Time(result.data!!.sumBy { it.length!! }).toString()
}
throw IllegalArgumentException("Can't get data. $result")
}
}
| mit | 881d0e6bed9e663046e0facd406dc09e | 28.564767 | 118 | 0.643708 | 4.819257 | false | false | false | false |
square/duktape-android | zipline-kotlin-plugin/src/main/kotlin/app/cash/zipline/kotlin/BridgedInterface.kt | 1 | 10779 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.cash.zipline.kotlin
import org.jetbrains.kotlin.backend.common.ScopeWithIr
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.backend.common.ir.isSuspend
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.builders.IrBuilderWithScope
import org.jetbrains.kotlin.ir.builders.IrStatementsBuilder
import org.jetbrains.kotlin.ir.builders.irCall
import org.jetbrains.kotlin.ir.builders.irGet
import org.jetbrains.kotlin.ir.builders.irInt
import org.jetbrains.kotlin.ir.builders.irTemporary
import org.jetbrains.kotlin.ir.builders.irVararg
import org.jetbrains.kotlin.ir.declarations.IrTypeParameter
import org.jetbrains.kotlin.ir.declarations.IrValueParameter
import org.jetbrains.kotlin.ir.declarations.IrVariable
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
import org.jetbrains.kotlin.ir.types.IrSimpleType
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.classFqName
import org.jetbrains.kotlin.ir.types.getClass
import org.jetbrains.kotlin.ir.types.isSubtypeOfClass
import org.jetbrains.kotlin.ir.types.starProjectedType
import org.jetbrains.kotlin.ir.types.typeWith
import org.jetbrains.kotlin.ir.util.defaultType
import org.jetbrains.kotlin.ir.util.functions
import org.jetbrains.kotlin.ir.util.isInterface
import org.jetbrains.kotlin.ir.util.substitute
import org.jetbrains.kotlin.name.FqName
/**
* A user-defined interface (like `EchoService` or `Callback<String>`) and support for generating
* its `ZiplineServiceAdapter`.
*
* This class tracks the interface type (like `EchoService` or `Callback<String>`) and its
* implementation class (that doesn't know its generic parameters).
*
* This class can declare a `KSerializer` property for each unique parameter type and return type on
* the interface. Use [declareSerializerTemporaries] to create these, then the resulting elements
* access a specific serializer. Declaring serializers is useful to fast fail if ever a serializer
* is required but not configured.
*/
internal class BridgedInterface(
private val pluginContext: IrPluginContext,
private val ziplineApis: ZiplineApis,
private val scope: ScopeWithIr,
/** A specific type identifier that knows the values of its generic parameters. */
val type: IrType,
/** A potentially-generic declaration that doesn't have values for its generic parameters. */
private val classSymbol: IrClassSymbol,
) {
val typeIrClass = classSymbol.owner
// TODO(jwilson): support overloaded functions?
val bridgedFunctionsWithOverrides: Map<String, List<IrSimpleFunctionSymbol>>
get() {
val result = mutableMapOf<String, MutableList<IrSimpleFunctionSymbol>>()
for (supertype in listOf(classSymbol.owner.defaultType) + classSymbol.owner.superTypes) {
val supertypeClass = supertype.getClass() ?: continue
for (function in supertypeClass.functions) {
if (function.name.identifier in NON_INTERFACE_FUNCTION_NAMES) continue
val overrides = result.getOrPut(function.name.identifier) { mutableListOf() }
overrides += function.symbol
}
}
return result
}
val bridgedFunctions: List<IrSimpleFunctionSymbol>
get() = bridgedFunctionsWithOverrides.values.map { it[0] }
/** Declares local vars for all the serializers needed to bridge this interface. */
fun declareSerializerTemporaries(
statementsBuilder: IrStatementsBuilder<*>,
serializersModuleParameter: IrValueParameter,
serializersExpression: IrVariable,
): Map<IrType, IrVariable> {
return statementsBuilder.irDeclareSerializerTemporaries(
serializersModuleParameter = serializersModuleParameter,
serializersExpression = serializersExpression,
)
}
private fun IrStatementsBuilder<*>.irDeclareSerializerTemporaries(
serializersModuleParameter: IrValueParameter,
serializersExpression: IrVariable,
): Map<IrType, IrVariable> {
val requiredTypes = mutableSetOf<IrType>()
for (bridgedFunction in bridgedFunctions) {
for (valueParameter in bridgedFunction.owner.valueParameters) {
requiredTypes += resolveTypeParameters(valueParameter.type)
}
val resolvedReturnType = resolveTypeParameters(bridgedFunction.owner.returnType)
requiredTypes += when {
bridgedFunction.isSuspend -> ziplineApis.suspendCallback.typeWith(resolvedReturnType)
else -> resolvedReturnType
}
}
val result = mutableMapOf<IrType, IrVariable>()
for (requiredType in requiredTypes) {
val serializerExpression = serializerExpression(
type = requiredType,
serializersModuleParameter = serializersModuleParameter,
serializersExpression = serializersExpression,
contextual = false,
)
result[requiredType] = irTemporary(
value = serializerExpression.expression,
nameHint = "serializer",
isMutable = false,
)
}
return result
}
class SerializerExpression(
val expression: IrExpression,
val hasTypeParameter: Boolean,
)
/**
* To serialize generic types that include type variables ('T'), we use [serializersExpression] to
* extract the corresponding serializer from the list, matching by index.
*
* Whenever serializers for type parameters are returned they must be used! Otherwise, we will try
* to look up a serializer for a type variable, and that will fail because the concrete type is
* not known.
*/
private fun IrBuilderWithScope.serializerExpression(
type: IrType,
serializersModuleParameter: IrValueParameter,
serializersExpression: IrVariable,
contextual: Boolean,
): SerializerExpression {
val originalArguments = (type as IrSimpleType).arguments
val resolvedArguments = originalArguments.map { resolveTypeParameters(it as IrType) }
val parameterExpressions = resolvedArguments.map { argumentType ->
serializerExpression(
type = argumentType,
serializersModuleParameter = serializersModuleParameter,
serializersExpression = serializersExpression,
contextual = false,
)
}
val parameterList = irCall(ziplineApis.listOfFunction).apply {
this.type = ziplineApis.listOfKSerializerStar
putTypeArgument(0, ziplineApis.kSerializer.starProjectedType)
putValueArgument(
0,
irVararg(
ziplineApis.kSerializer.starProjectedType,
parameterExpressions.map { it.expression },
)
)
}
val hasTypeParameter = parameterExpressions.any { it.hasTypeParameter }
val classifierOwner = type.classifier.owner
val isTypeParameter = classifierOwner is IrTypeParameter
val expression = when {
classifierOwner is IrTypeParameter -> {
// serializers.get(0)
irCall(
callee = ziplineApis.listGetFunction,
type = ziplineApis.kSerializer.starProjectedType,
).apply {
dispatchReceiver = irGet(serializersExpression)
putValueArgument(0, irInt(classifierOwner.index))
}
}
type.isSubtypeOfClass(ziplineApis.ziplineService) -> {
// ServiceType.Companion.Adapter(serializers)
AdapterGenerator(
pluginContext,
ziplineApis,
[email protected],
pluginContext.referenceClass(type.classFqName!!)!!.owner,
).adapterExpression(parameterList)
}
hasTypeParameter || contextual || type.isFlow -> {
// serializersModule.requireContextual<T>(root KClass, recurse on type args)
irCall(
callee = ziplineApis.requireContextual,
type = ziplineApis.kSerializer.starProjectedType,
).apply {
extensionReceiver = irGet(serializersModuleParameter)
// TODO: call remapTypeParameters passing typeIrClass and the AdapterClass we're making
putTypeArgument(0, type)
putValueArgument(
0,
irKClass(pluginContext.referenceClass(type.classFqName!!)!!.owner)
)
putValueArgument(1, parameterList)
}
}
else -> {
// serializersModule.serializer<T>()
irCall(
callee = ziplineApis.serializerFunctionTypeParam,
type = ziplineApis.kSerializer.starProjectedType,
).apply {
// TODO: call remapTypeParameters passing typeIrClass and the AdapterClass we're making
putTypeArgument(0, type)
extensionReceiver = irGet(serializersModuleParameter)
}
}
}
return SerializerExpression(
expression = expression,
hasTypeParameter = hasTypeParameter || isTypeParameter,
)
}
private val IrType.isFlow
get() = classFqName == ziplineApis.flowFqName
/** Call this on any declaration returned by [classSymbol] to fill in the generic parameters. */
fun resolveTypeParameters(type: IrType): IrType {
val simpleType = this.type as? IrSimpleType ?: return type
val parameters = typeIrClass.typeParameters
val arguments = simpleType.arguments.map { it as IrType }
return type.substitute(parameters, arguments)
}
companion object {
/** Don't bridge these. */
private val NON_INTERFACE_FUNCTION_NAMES = mutableSetOf(
"equals",
"hashCode",
"toString",
)
fun create(
pluginContext: IrPluginContext,
ziplineApis: ZiplineApis,
scope: ScopeWithIr,
element: IrElement,
functionName: String,
type: IrType,
): BridgedInterface {
val classSymbol = pluginContext.referenceClass(type.classFqName ?: FqName.ROOT)
if (classSymbol == null || !classSymbol.owner.isInterface) {
throw ZiplineCompilationException(
element = element,
message = "The type argument to $functionName must be an interface type" +
" (but was ${type.classFqName})",
)
}
return BridgedInterface(
pluginContext,
ziplineApis,
scope,
type,
classSymbol
)
}
}
}
| apache-2.0 | 2e7c557caf09dcc3d3435b9f55a606cd | 36.821053 | 100 | 0.718991 | 4.833632 | false | false | false | false |
pdvrieze/ProcessManager | ProcessEngine/core/src/commonMain/kotlin/nl/adaptivity/process/engine/processModel/ProcessNodeInstance.kt | 1 | 25504 | /*
* Copyright (c) 2019.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.processModel
import net.devrieze.util.*
import net.devrieze.util.collection.replaceBy
import net.devrieze.util.security.SecureObject
import nl.adaptivity.messaging.EndpointDescriptor
import nl.adaptivity.process.IMessageService
import nl.adaptivity.process.engine.*
import nl.adaptivity.process.engine.impl.*
import nl.adaptivity.process.engine.processModel.NodeInstanceState.*
import nl.adaptivity.process.processModel.IPlatformXmlResultType
import nl.adaptivity.process.processModel.MessageActivity
import nl.adaptivity.process.processModel.StartNode
import nl.adaptivity.process.processModel.engine.ExecutableJoin
import nl.adaptivity.process.processModel.engine.ExecutableProcessNode
import nl.adaptivity.util.multiplatform.addSuppressedCompat
import nl.adaptivity.util.multiplatform.assert
import nl.adaptivity.util.security.Principal
import nl.adaptivity.xmlutil.*
import nl.adaptivity.xmlutil.serialization.XML
import nl.adaptivity.xmlutil.util.ICompactFragment
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
/**
* Base interface for process instance.
* @property node The node that this is an instance of.
* @param predecessors The node instances that are direct predecessors of this one
* @property hProcessInstance The handle to the owning process instance.
* @property owner The owner of the node (generally the owner of the instance)
* @param handle The handle for this instance (or invalid if not registered yet)
* @property state The current state of the instance
* @param results A list of the results associated with this node. This would imply a state of [NodeInstanceState.Complete]
* @property entryNo The sequence number of this instance. Normally this will be 1, but for nodes that allow reentry,
* this may be a higher number. Values below 1 are invalid.
* @property failureCause For a failure, the cause of the failure
*/
abstract class ProcessNodeInstance<T : ProcessNodeInstance<T>>(
override val node: ExecutableProcessNode,
predecessors: Iterable<Handle<SecureObject<ProcessNodeInstance<*>>>>,
processInstanceBuilder: ProcessInstance.Builder,
override val hProcessInstance: Handle<SecureObject<ProcessInstance>>,
final override val owner: Principal,
final override val entryNo: Int,
handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(),
final override val state: NodeInstanceState = Pending,
results: Iterable<ProcessData> = emptyList(),
val failureCause: Throwable? = null
) : SecureObject<ProcessNodeInstance<T>>,
ReadableHandleAware<SecureObject<ProcessNodeInstance<*>>>,
IProcessNodeInstance {
private val _handle: Handle<SecureObject<ProcessNodeInstance<*>>> = handle
override val handle: Handle<SecureObject<ProcessNodeInstance<*>>> get() = _handle
override val results: List<ProcessData> = results.toList()
override val predecessors: Set<Handle<SecureObject<ProcessNodeInstance<*>>>> =
predecessors.asSequence().filter { it.isValid }.toArraySet()
init {
@Suppress("LeakingThis")
if (state != SkippedInvalidated &&
!(node.isMultiInstance || ((node as? ExecutableJoin)?.isMultiMerge == true))
) {
if (processInstanceBuilder.allChildNodeInstances { it.node == node && it.entryNo != entryNo && it.state != SkippedInvalidated }
.any()) {
throw ProcessException("Attempting to create a new instance $entryNo for node $node that does not support reentry")
}
}
}
constructor(builder: Builder<*, T>) : this(
builder.node, builder.predecessors,
builder.processInstanceBuilder,
builder.hProcessInstance, builder.owner,
builder.entryNo, builder.handle, builder.state,
builder.results, builder.failureCause
)
override val processContext: ProcessInstanceContext
get() = object : ProcessInstanceContext {
override val handle: Handle<SecureObject<ProcessInstance>> get() = hProcessInstance
}
override fun build(processInstanceBuilder: ProcessInstance.Builder): ProcessNodeInstance<T> = this
override abstract fun builder(processInstanceBuilder: ProcessInstance.Builder): ExtBuilder<out ExecutableProcessNode, T>
private fun precedingClosure(processData: ProcessEngineDataAccess): Sequence<SecureObject<ProcessNodeInstance<*>>> {
return predecessors.asSequence().flatMap { predHandle ->
val pred = processData.nodeInstance(predHandle).withPermission()
pred.precedingClosure(processData) + sequenceOf(pred)
}
}
fun update(
processInstanceBuilder: ProcessInstance.Builder,
body: Builder<out ExecutableProcessNode, T>.() -> Unit
): Future<out T>? {
val builder = builder(processInstanceBuilder).apply(body)
return processInstanceBuilder.storeChild(builder)
.let { if (builder.changed) it else null }
}
@Suppress("UNCHECKED_CAST")
private inline val asT
get() = this as T
override fun withPermission(): ProcessNodeInstance<T> = this
private fun hasDirectPredecessor(handle: Handle<SecureObject<ProcessNodeInstance<*>>>): Boolean {
return predecessors.any { it.handleValue == handle.handleValue }
}
fun resolvePredecessors(engineData: ProcessEngineDataAccess): Collection<ProcessNodeInstance<*>> {
return predecessors.asSequence().map {
engineData.nodeInstance(it).withPermission()
}.toList()
}
fun getHandleValue(): Long {
return _handle.handleValue
}
override fun toString(): String {
return "nodeInstance ($handle, ${node.id}[$entryNo] - $state)"
}
fun serialize(nodeInstanceSource: IProcessInstance, out: XmlWriter, localEndpoint: EndpointDescriptor) {
out.smartStartTag(XmlProcessNodeInstance.ELEMENTNAME) {
writeAttribute("state", state.name)
writeAttribute("processinstance", hProcessInstance.handleValue)
if (_handle.isValid) writeAttribute("handle", _handle.handleValue)
writeAttribute("nodeid", node.id)
predecessors.forEach {
writeSimpleElement(
XmlProcessNodeInstance.PREDECESSOR_ELEMENTNAME,
it.handleValue.toString()
)
}
for (result in results) {
XML.encodeToWriter(this, result)
}
(node as? MessageActivity)?.message?.messageBody?.let { body ->
instantiateXmlPlaceholders(nodeInstanceSource, body.getXmlReader(), out, true, localEndpoint)
}
}
}
fun toSerializable(engineData: ProcessEngineDataAccess, localEndpoint: EndpointDescriptor): XmlProcessNodeInstance {
val builder = builder(engineData.instance(hProcessInstance).withPermission().builder())
val body: ICompactFragment? = (node as? MessageActivity)?.message?.let { message ->
try {
val xmlReader = message.messageBody.getXmlReader()
instantiateXmlPlaceholders(builder.processInstanceBuilder, xmlReader, true, localEndpoint)
} catch (e: XmlException) {
engineData.logger.log(LogLevel.WARNING, "Error processing body", e)
throw e
}
}
return builder.toXmlInstance(body)
}
interface Builder<N : ExecutableProcessNode, T : ProcessNodeInstance<*>> : IProcessNodeInstance {
override var node: N
override val predecessors: MutableSet<Handle<SecureObject<ProcessNodeInstance<*>>>>
val processInstanceBuilder: ProcessInstance.Builder
override val hProcessInstance: Handle<SecureObject<ProcessInstance>> get() = processInstanceBuilder.handle
override var owner: Principal
override var handle: Handle<SecureObject<ProcessNodeInstance<*>>>
override var state: NodeInstanceState
override val results: MutableList<ProcessData>
fun toXmlInstance(body: ICompactFragment?): XmlProcessNodeInstance
override val entryNo: Int
var failureCause: Throwable?
fun invalidateBuilder(engineData: ProcessEngineDataAccess)
fun build(): T
override fun builder(processInstanceBuilder: ProcessInstance.Builder) = this
fun failTaskCreation(cause: Throwable) {
failureCause = cause
state = FailRetry
}
fun failTaskExecution(cause: Throwable) {
failureCause = cause
state = Failed
}
/**
* Store the current state of the builder to the database.
*/
fun store(engineData: MutableProcessEngineDataAccess) {
val mutableNodeInstances =
engineData.nodeInstances as MutableHandleMap<SecureObject<ProcessNodeInstance<*>>>
if (handle.isValid) {
mutableNodeInstances[handle] = build()
} else {
processInstanceBuilder.storeChild(this)
}
// Must be updated as well as the process node instance may mean the process instance is changed.
processInstanceBuilder.store(engineData)
engineData.commit()
}
fun failTask(engineData: MutableProcessEngineDataAccess, cause: Throwable)
/** Function that will eventually do progression */
fun provideTask(engineData: MutableProcessEngineDataAccess)
/** Function that will do provision, but not progress. This is where custom implementations live */
fun doProvideTask(engineData: MutableProcessEngineDataAccess): Boolean
fun takeTask(engineData: MutableProcessEngineDataAccess)
fun doTakeTask(engineData: MutableProcessEngineDataAccess): Boolean
fun startTask(engineData: MutableProcessEngineDataAccess)
fun doStartTask(engineData: MutableProcessEngineDataAccess): Boolean
fun skipTask(engineData: MutableProcessEngineDataAccess, newState: NodeInstanceState)
fun doSkipTask(engineData: MutableProcessEngineDataAccess, newState: NodeInstanceState) {
if (state.isFinal && state != newState) {
throw ProcessException("Attempting to skip a finalised node ${node.id}($handle-$entryNo)")
}
state = newState
}
fun invalidateTask(engineData: MutableProcessEngineDataAccess)
fun cancel(engineData: MutableProcessEngineDataAccess)
fun doCancel(engineData: MutableProcessEngineDataAccess) {
state = Cancelled
}
fun cancelAndSkip(engineData: MutableProcessEngineDataAccess)
fun doCancelAndSkip(engineData: MutableProcessEngineDataAccess) {
@Suppress("NON_EXHAUSTIVE_WHEN")
when (state) {
Pending,
FailRetry -> state = Skipped
Sent,
Taken,
Started,
Acknowledged -> {
// The full cancel will trigger successors. We only want to do the actual cancellation
// action without triggering successors. This is still marked as cancelled, but successors
// may be marked as skipped.
doCancel(engineData)
if (!state.isSkipped) { // allow skipping if that is more appropriate
state = AutoCancelled
}
}
Complete -> if(node is StartNode) { // just special case start nodes
state = AutoCancelled
}
}
}
fun finishTask(engineData: MutableProcessEngineDataAccess, resultPayload: ICompactFragment? = null)
fun doFinishTask(engineData: MutableProcessEngineDataAccess, resultPayload: ICompactFragment? = null) {
if (state.isFinal) {
throw ProcessException("instance ${node.id}:${handle.handleValue}($state) cannot be finished as it is already in a final state.")
}
state = Complete
node.results.mapTo(results.apply { clear() }) { (it as IPlatformXmlResultType).applyData(resultPayload) }
}
fun tickle(engineData: MutableProcessEngineDataAccess, messageService: IMessageService<*>) {
@Suppress("NON_EXHAUSTIVE_WHEN")
when (state) {
FailRetry,
Pending -> provideTask(engineData)
}// ignore
}
}
abstract class AbstractBuilder<N : ExecutableProcessNode, T : ProcessNodeInstance<*>> : Builder<N, T> {
override val processContext: ProcessInstanceContext
get() = processInstanceBuilder
override fun toXmlInstance(body: ICompactFragment?): XmlProcessNodeInstance {
return XmlProcessNodeInstance(
nodeId = node.id,
predecessors = predecessors.map { if (it.handleValue < 0) Handle.invalid() else Handle(handleValue = it.handleValue) },
processInstance = hProcessInstance.handleValue,
handle = if (handle.handleValue < 0) Handle.invalid() else Handle(handleValue = handle.handleValue),
state = state,
results = results,
body = body
)
}
override var failureCause: Throwable? = null
/**
* Update the state if the current state would indicate that to be the expected action
*/
private fun softUpdateState(engineData: MutableProcessEngineDataAccess, targetState: NodeInstanceState) {
invalidateBuilder(engineData)
if (state == targetState) return
val doSet = when (targetState) {
Pending -> throw IllegalArgumentException("Updating a state to pending is not allowed")
Sent -> state == Pending
Acknowledged -> state == Pending || state == Sent
Taken -> state == Sent || state == Acknowledged
Started -> state == Taken || state == Sent || state == Acknowledged
Complete -> state == Started
SkippedCancel -> state == Pending
SkippedFail -> state == Pending
Skipped -> state == Pending
SkippedInvalidated -> state == Pending
Cancelled,
AutoCancelled -> !state.isFinal
FailRetry -> throw ProcessException("Recovering a retryable failed state is not a soft state update")
Failed -> throw ProcessException("Failed states can not be changed, this should not be attempted")
}
if (doSet) {
state = targetState
store(engineData)
}
}
final override fun provideTask(engineData: MutableProcessEngineDataAccess) {
if (this !is JoinInstance.Builder) {
val predecessors = predecessors.map { engineData.nodeInstance(it).withPermission() }
for (predecessor in predecessors) {
if (predecessor !is SplitInstance && !predecessor.state.isFinal) {
throw ProcessException("Attempting to start successor ${node.id}[$handle] for non-final predecessor ${predecessor.node.id}[${predecessor._handle} - ${predecessor.state}]")
}
}
}
if (doProvideTask(engineData).also { softUpdateState(engineData, Sent) }) {
takeTask(engineData)
}
}
final override fun takeTask(engineData: MutableProcessEngineDataAccess) {
if (doTakeTask(engineData).also { softUpdateState(engineData, Taken) })
startTask(engineData)
}
final override fun startTask(engineData: MutableProcessEngineDataAccess) {
if (doStartTask(engineData).also { softUpdateState(engineData, Started) }) {
finishTask(engineData)
}
}
final override fun finishTask(engineData: MutableProcessEngineDataAccess, resultPayload: ICompactFragment?) {
if (state.isFinal) {
throw ProcessException("instance ${node.id}:${handle.handleValue}($state) cannot be finished as it is already in a final state.")
}
doFinishTask(engineData, resultPayload)
state = Complete
processInstanceBuilder.store(engineData)
store(engineData)
engineData.commit()
engineData.processContextFactory.onActivityTermination(engineData, this)
// TODO use tickle instead
// The splits need to be updated before successors are started. This prevents unneeded/unexpected cancellations.
// Joins should trigger updates before cancellations anyway though as a safeguard.
processInstanceBuilder.updateSplits(engineData)
processInstanceBuilder.startSuccessors(engineData, this)
//TODO may not do anything
processInstanceBuilder.updateSplits(engineData)
processInstanceBuilder.updateState(engineData)
}
override fun skipTask(engineData: MutableProcessEngineDataAccess, newState: NodeInstanceState) {
assert(newState == Skipped || newState == SkippedCancel || newState == SkippedFail) {
"Skipping task with unsupported new state $newState"
}
doSkipTask(engineData, newState)
store(engineData)
processInstanceBuilder.storeChild(this)
assert(state == Skipped || state == SkippedCancel || state == SkippedFail) {
"When skipping a task ($node:$handle) the current state was not a skipped type as expected: $state"
}
processInstanceBuilder.skipSuccessors(engineData, this, newState)
}
override fun invalidateTask(engineData: MutableProcessEngineDataAccess) {
if (!(state.isSkipped || state == Pending || state == Sent)) {
throw ProcessException("Attempting to invalidate a non-skipped node $this with state: $state")
}
state = SkippedInvalidated
store(engineData)
engineData.processContextFactory.onActivityTermination(engineData, this)
processInstanceBuilder.storeChild(this)
}
final override fun failTask(engineData: MutableProcessEngineDataAccess, cause: Throwable) {
failureCause = cause
state = if (state == Pending) FailRetry else Failed
engineData.processContextFactory.onActivityTermination(engineData, this)
store(engineData)
processInstanceBuilder.skipSuccessors(engineData, this, SkippedFail)
}
final override fun cancel(engineData: MutableProcessEngineDataAccess) {
doCancel(engineData)
softUpdateState(engineData, Cancelled)
// processInstanceBuilder.storeChild(this)
// processInstanceBuilder.store(engineData)
engineData.processContextFactory.onActivityTermination(engineData, this)
engineData.queueTickle(processInstanceBuilder.handle)
// processInstanceBuilder.skipSuccessors(engineData, this, SkippedCancel)
}
final override fun cancelAndSkip(
engineData: MutableProcessEngineDataAccess
) {
doCancelAndSkip(engineData)
engineData.processContextFactory.onActivityTermination(engineData, this)
processInstanceBuilder.skipSuccessors(engineData, this, Skipped)
}
override fun toString(): String {
return "${node::class} ($handle, ${node.id}[$entryNo] - $state)"
}
}
abstract class BaseBuilder<N : ExecutableProcessNode, T : ProcessNodeInstance<T>>(
final override var node: N,
predecessors: Iterable<Handle<SecureObject<ProcessNodeInstance<*>>>>,
final override val processInstanceBuilder: ProcessInstance.Builder,
final override var owner: Principal,
final override val entryNo: Int,
handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(),
state: NodeInstanceState = Pending
) : AbstractBuilder<N, T>() {
final override var handle: Handle<SecureObject<ProcessNodeInstance<*>>> = handle
final override var state = state
set(value) {
field = value
processInstanceBuilder.storeChild(this)
}
override fun invalidateBuilder(engineData: ProcessEngineDataAccess) {
engineData.nodeInstances[handle]?.withPermission()?.let { newBase ->
@Suppress("UNCHECKED_CAST")
node = newBase.node as N
predecessors.replaceBy(newBase.predecessors)
owner = newBase.owner
state = newBase.state
}
}
final override var predecessors: MutableSet<Handle<SecureObject<ProcessNodeInstance<*>>>> =
predecessors.asSequence().toMutableArraySet()
final override val results = mutableListOf<ProcessData>()
}
abstract class ExtBuilder<N : ExecutableProcessNode, T : ProcessNodeInstance<*>>(
protected var base: T,
override val processInstanceBuilder: ProcessInstance.Builder
) : AbstractBuilder<N, T>() {
private val observer: Observer<Any?> = { newValue -> changed = true; newValue }
@Suppress("UNCHECKED_CAST")
protected fun <T> observer(): Observer<T> = observer as Observer<T>
final override val predecessors = ObservableSet(base.predecessors.toMutableArraySet(), { changed = true })
final override var owner by overlay(observer()) { base.owner }
final override var handle: Handle<SecureObject<ProcessNodeInstance<*>>> by overlay(observer()) { base.handle }
private var _state: NodeInstanceState = base.state
final override var state
get() = _state
set(value) {
if (_state != value) {
_state = value
changed = true
processInstanceBuilder.storeChild(this)
}
}
final override var results = ObservableList(base.results.toMutableList(), { changed = true })
var changed: Boolean = false
final override val entryNo: Int = base.entryNo
fun invalidateBuilder(newBase: T) {
changed = false
base = newBase
predecessors.replaceBy(newBase.predecessors)
owner = newBase.owner
handle = newBase.handle
_state = newBase.state
results.replaceBy(newBase.results)
}
override fun invalidateBuilder(engineData: ProcessEngineDataAccess) {
@Suppress("UNCHECKED_CAST")
invalidateBuilder(engineData.nodeInstance(handle).withPermission() as T)
}
override abstract fun build(): T
}
companion object {
}
}
private typealias Observer<T> = (T) -> T
@OptIn(ExperimentalContracts::class)
internal inline fun <R> ProcessNodeInstance.Builder<*, *>.tryCreateTask(body: () -> R): R {
contract {
callsInPlace(body, InvocationKind.EXACTLY_ONCE)
}
return _tryHelper(body) { e ->
failTaskCreation(e)
}
}
@OptIn(ExperimentalContracts::class)
internal inline fun <R> ProcessNodeInstance.Builder<*, *>.tryRunTask(body: () -> R): R {
contract {
callsInPlace(body, InvocationKind.EXACTLY_ONCE)
}
return _tryHelper(body) { e ->
failTaskExecution(e)
}
}
@OptIn(ExperimentalContracts::class)
@Suppress("unused", "FunctionName")
@PublishedApi
internal inline fun <R> _tryHelper(
engineData: MutableProcessEngineDataAccess,
processInstance: ProcessInstance,
body: () -> R, failHandler: (MutableProcessEngineDataAccess, ProcessInstance, Exception) -> Unit
): R {
contract {
callsInPlace(body, InvocationKind.EXACTLY_ONCE)
}
return try {
body()
} catch (e: Exception) {
try {
failHandler(engineData, processInstance, e)
} catch (f: Exception) {
e.addSuppressedCompat(f)
}
throw e
}
}
@OptIn(ExperimentalContracts::class)
@PublishedApi
internal inline fun <R> _tryHelper(body: () -> R, failHandler: (Exception) -> Unit): R {
contract {
callsInPlace(body, InvocationKind.EXACTLY_ONCE)
}
return try {
body()
} catch (e: Exception) {
try {
failHandler(e)
} catch (f: Exception) {
e.addSuppressedCompat(f)
}
throw e
}
}
| lgpl-3.0 | 66ca7ac98e0ee666d5eaff23c5f287d9 | 40.878489 | 195 | 0.651702 | 5.491817 | false | false | false | false |
wleroux/fracturedskies | src/main/kotlin/com/fracturedskies/api/GameMessages.kt | 1 | 3672 | package com.fracturedskies.api
import com.fracturedskies.api.block.Block
import com.fracturedskies.api.entity.ItemType
import com.fracturedskies.api.task.*
import com.fracturedskies.engine.Id
import com.fracturedskies.engine.api.*
import com.fracturedskies.engine.collections.*
import com.fracturedskies.engine.math.Vector3i
enum class GameSpeed(val msBetweenUpdates: Long) { PAUSE(Long.MAX_VALUE), SLOW(450L), NORMAL(150L), FAST(50L), UNLIMITED(0L) }
data class NewGameRequested(val dimension: Dimension, val seed: Int,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class GameSpeedUpdated(val gameSpeed: GameSpeed,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class WorldGenerated(val blocks: ObjectSpace<Block>,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class BlockUpdate(val position: Vector3i, val original: Block, val target: Block)
data class BlocksUpdated(val blocks: List<BlockUpdate>,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class TimeUpdated(val time: Float,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class ColonistSpawned(val colonistId: Id, val position: Vector3i,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class ColonistMoved(val colonistId: Id, val position: Vector3i, val direction: Vector3i,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class ColonistPickedItem(val colonistId: Id, val itemId: Id,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class ColonistDroppedItem(val colonistId: Id, val itemId: Id,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class ColonistTaskSelected(val colonistId: Id, val taskId: Id?,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class ColonistRejectedTask(val colonistId: Id, val taskId: Id,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class TaskCreated(val taskId: Id, val taskType: TaskType, val taskPriority: TaskPriority,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class TaskCancelled(val colonistId: Id, val taskId: Id,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class TaskCompleted(val colonistId: Id, val taskId: Id,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class ItemMoved(val itemId: Id, val position: Vector3i,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class ItemSpawned(val itemId: Id, val itemType: ItemType, val position: Vector3i,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
data class ZoneCreated(val zoneId: Id, val positions: List<Vector3i>,
override val cause: Cause, override val context: MultiTypeMap = MultiTypeMap()) : Message
| unlicense | f61ccdb9d4e3e4f19d6848d79ef72d77 | 68.283019 | 126 | 0.695534 | 4.636364 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/network/rest/wpcom/dashboard/CardsRestClient.kt | 2 | 7133 | package org.wordpress.android.fluxc.network.rest.wpcom.dashboard
import android.content.Context
import com.android.volley.RequestQueue
import com.google.gson.annotations.SerializedName
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.generated.endpoint.WPCOMV2
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.dashboard.CardModel
import org.wordpress.android.fluxc.model.dashboard.CardModel.PostsCardModel
import org.wordpress.android.fluxc.model.dashboard.CardModel.PostsCardModel.PostCardModel
import org.wordpress.android.fluxc.model.dashboard.CardModel.TodaysStatsCardModel
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest.WPComGsonNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Error
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Success
import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken
import org.wordpress.android.fluxc.store.dashboard.CardsStore.CardsError
import org.wordpress.android.fluxc.store.dashboard.CardsStore.CardsErrorType
import org.wordpress.android.fluxc.store.dashboard.CardsStore.CardsPayload
import org.wordpress.android.fluxc.store.dashboard.CardsStore.PostCardError
import org.wordpress.android.fluxc.store.dashboard.CardsStore.PostCardErrorType
import org.wordpress.android.fluxc.store.dashboard.CardsStore.TodaysStatsCardError
import org.wordpress.android.fluxc.store.dashboard.CardsStore.TodaysStatsCardErrorType
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
@Singleton
class CardsRestClient @Inject constructor(
private val wpComGsonRequestBuilder: WPComGsonRequestBuilder,
dispatcher: Dispatcher,
appContext: Context?,
@Named("regular") requestQueue: RequestQueue,
accessToken: AccessToken,
userAgent: UserAgent
) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) {
suspend fun fetchCards(site: SiteModel, cardTypes: List<CardModel.Type>): CardsPayload<CardsResponse> {
val url = WPCOMV2.sites.site(site.siteId).dashboard.cards_data.url
val params = buildDashboardCardsParams(cardTypes)
val response = wpComGsonRequestBuilder.syncGetRequest(
this,
url,
params,
CardsResponse::class.java
)
return when (response) {
is Success -> CardsPayload(response.data)
is Error -> CardsPayload(response.error.toCardsError())
}
}
private fun buildDashboardCardsParams(cardTypes: List<CardModel.Type>) =
mapOf(CARDS to cardTypes.joinToString(",") { it.label })
data class CardsResponse(
@SerializedName("todays_stats") val todaysStats: TodaysStatsResponse? = null,
@SerializedName("posts") val posts: PostsResponse? = null
) {
fun toCards() = arrayListOf<CardModel>().apply {
todaysStats?.let { add(it.toTodaysStatsCard()) }
posts?.let { add(it.toPosts()) }
}.toList()
}
data class TodaysStatsResponse(
@SerializedName("views") val views: Int? = null,
@SerializedName("visitors") val visitors: Int? = null,
@SerializedName("likes") val likes: Int? = null,
@SerializedName("comments") val comments: Int? = null,
@SerializedName("error") val error: String? = null
) {
fun toTodaysStatsCard() = TodaysStatsCardModel(
views = views ?: 0,
visitors = visitors ?: 0,
likes = likes ?: 0,
comments = comments ?: 0,
error = error?.let { toTodaysStatsCardsError(it) }
)
private fun toTodaysStatsCardsError(error: String): TodaysStatsCardError {
val errorType = when (error) {
JETPACK_DISCONNECTED -> TodaysStatsCardErrorType.JETPACK_DISCONNECTED
JETPACK_DISABLED -> TodaysStatsCardErrorType.JETPACK_DISABLED
UNAUTHORIZED -> TodaysStatsCardErrorType.UNAUTHORIZED
else -> TodaysStatsCardErrorType.GENERIC_ERROR
}
return TodaysStatsCardError(errorType, error)
}
}
data class PostsResponse(
@SerializedName("has_published") val hasPublished: Boolean? = null,
@SerializedName("draft") val draft: List<PostResponse>? = null,
@SerializedName("scheduled") val scheduled: List<PostResponse>? = null,
@SerializedName("error") val error: String? = null
) {
fun toPosts() = PostsCardModel(
hasPublished = hasPublished ?: false,
draft = draft?.map { it.toPost() } ?: emptyList(),
scheduled = scheduled?.map { it.toPost() } ?: emptyList(),
error = error?.let { toPostCardError(it) }
)
private fun toPostCardError(error: String): PostCardError {
val errorType = when (error) {
UNAUTHORIZED -> PostCardErrorType.UNAUTHORIZED
else -> PostCardErrorType.GENERIC_ERROR
}
return PostCardError(errorType, error)
}
}
data class PostResponse(
@SerializedName("id") val id: Int,
@SerializedName("title") val title: String,
@SerializedName("content") val content: String,
@SerializedName("featured_image") val featuredImage: String?,
@SerializedName("date") val date: String
) {
fun toPost() = PostCardModel(
id = id,
title = title,
content = content,
featuredImage = featuredImage,
date = CardsUtils.fromDate(date)
)
}
companion object {
private const val CARDS = "cards"
private const val JETPACK_DISCONNECTED = "jetpack_disconnected"
private const val JETPACK_DISABLED = "jetpack_disabled"
private const val UNAUTHORIZED = "unauthorized"
}
}
fun WPComGsonNetworkError.toCardsError(): CardsError {
val type = when (type) {
GenericErrorType.TIMEOUT -> CardsErrorType.TIMEOUT
GenericErrorType.NO_CONNECTION,
GenericErrorType.SERVER_ERROR,
GenericErrorType.INVALID_SSL_CERTIFICATE,
GenericErrorType.NETWORK_ERROR -> CardsErrorType.API_ERROR
GenericErrorType.PARSE_ERROR,
GenericErrorType.NOT_FOUND,
GenericErrorType.CENSORED,
GenericErrorType.INVALID_RESPONSE -> CardsErrorType.INVALID_RESPONSE
GenericErrorType.HTTP_AUTH_ERROR,
GenericErrorType.AUTHORIZATION_REQUIRED,
GenericErrorType.NOT_AUTHENTICATED -> CardsErrorType.AUTHORIZATION_REQUIRED
GenericErrorType.UNKNOWN,
null -> CardsErrorType.GENERIC_ERROR
}
return CardsError(type, message)
}
| gpl-2.0 | 3393827b49603277ec72394268e62a50 | 43.861635 | 107 | 0.692556 | 4.578306 | false | false | false | false |
SerCeMan/franky | franky-intellij/src/main/kotlin/me/serce/franky/ui/jvmTab.kt | 1 | 4373 | package me.serce.franky.ui
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.components.BorderLayoutPanel
import me.serce.franky.Protocol
import me.serce.franky.jvm.AttachableJVM
import me.serce.franky.jvm.JVMAttachService
import me.serce.franky.jvm.JVMSession
import me.serce.franky.util.Lifetime
import me.serce.franky.util.create
import me.serce.franky.util.subscribeUI
import rx.lang.kotlin.AsyncSubject
import rx.lang.kotlin.PublishSubject
import java.awt.Color
import java.awt.FlowLayout
import javax.swing.BorderFactory
import javax.swing.JButton
import javax.swing.JTextArea
import javax.swing.ScrollPaneConstants
class JvmTabViewModel(lifetime: Lifetime, vm: AttachableJVM) : ViewModel {
private val state = JvmTabState()
private val view = JvmTabView(state, lifetime)
private val model = JvmTabConntoller(state, lifetime, vm)
override fun createComponent() = view.createComponent()
}
private class JvmTabState {
val connected = AsyncSubject<Boolean>()
val isProfilingStarted = PublishSubject<Boolean>()
val profilingResult = PublishSubject<Protocol.Response>()
}
private class JvmTabView(val state: JvmTabState, val lifetime: Lifetime) : View {
val tabPanel = BorderLayoutPanel()
val startButton = JButton("Start profiling")
val stopButton = jButton {
text = "Stop profiling"
isEnabled = false
}
val buttonsPanel = jPanel {
layout = FlowLayout()
add(startButton)
add(stopButton)
}
val profilerPanel = BorderLayoutPanel()
private var profResultViewModel: ProfResultViewModel? = null
init {
val throbber = JTextArea("Awaiting connection")
tabPanel.add(throbber)
state.connected.subscribeUI {
tabPanel.apply {
remove(throbber)
addToTop(buttonsPanel)
addToCenter(profilerPanel)
revalidate()
}
}
state.isProfilingStarted.subscribeUI {
startButton.isEnabled = !it
stopButton.isEnabled = it
}
startButton.addActionListener {
state.isProfilingStarted.onNext(true)
}
stopButton.addActionListener { state.isProfilingStarted.onNext(false) }
state.profilingResult.subscribeUI { result: Protocol.Response ->
tabPanel.apply {
// TODO DEV-MODE
// FileOutputStream("/home/serce/tmp/ResultData").use { fos ->
// val out = CodedOutputStream.newInstance(fos)
// result.writeTo(out)
// out.flush()
// }
profResultViewModel?.lifetime?.terminate()
val profResView = ProfResultViewModel(result, lifetime.create()).apply {
profResultViewModel = this
}
profilerPanel.apply {
removeAll()
addToCenter(JBScrollPane(profResView.createComponent()).apply {
verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS
verticalScrollBar.unitIncrement = 16
border = BorderFactory.createLineBorder(Color.RED)
})
revalidate()
repaint()
}
}
}
}
override fun createComponent() = tabPanel
}
private class JvmTabConntoller(state: JvmTabState, lifetime: Lifetime, vm: AttachableJVM) {
val jvmService = JVMAttachService.getInstance()
val sessionObservable = jvmService.connect(vm)
init {
sessionObservable.subscribe { session ->
lifetime += {
session.close()
}
state.connected.onNext(true)
state.connected.onCompleted()
initSession(session, state)
}
}
private fun initSession(session: JVMSession, state: JvmTabState) {
state.isProfilingStarted.subscribeUI {
when {
it -> session.startProfiling()
else -> session.stopProfiling()
}
}
session.profilingResult().subscribe { response ->
state.profilingResult.onNext(response)
}
}
}
| apache-2.0 | 77aeef9bc4d16f43b06b9b45c503bc45 | 31.154412 | 95 | 0.610794 | 4.913483 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/test/kotlin/org/wfanet/measurement/integration/postgres/PrivacyBudgetPostgresSchemaTest.kt | 1 | 3373 | // Copyright 2022 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.integration.postgres
import com.opentable.db.postgres.junit.EmbeddedPostgresRules
import com.opentable.db.postgres.junit.SingleInstancePostgresRule
import java.sql.Connection
import java.sql.ResultSet
import java.sql.Statement
import kotlin.test.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import src.main.kotlin.org.wfanet.measurement.integration.deploy.postgres.POSTGRES_LEDGER_SCHEMA_FILE
@RunWith(JUnit4::class)
class PrivacyBudgetPostgresSchemaTest {
val schema = POSTGRES_LEDGER_SCHEMA_FILE.readText()
@get:Rule val pg: SingleInstancePostgresRule = EmbeddedPostgresRules.singleInstance()
@Test
fun `privacy budget ledger sql file is valid for postgres`() {
val connection: Connection = pg.embeddedPostgres.postgresDatabase.connection
val statement: Statement = connection.createStatement()
statement.execute(schema)
}
@Test
fun `privacy budget balance can be written and read`() {
val connection: Connection = pg.embeddedPostgres.postgresDatabase.connection
val statement = connection.createStatement()
val insertSql =
"""
INSERT INTO PrivacyBucketCharges (
MeasurementConsumerId,
Date,
AgeGroup,
Gender,
VidStart,
Delta,
Epsilon,
RepetitionCount
) VALUES (
'MC1',
'2022-01-01',
'18_34',
'F',
100,
0.1,
0.01,
10
);
"""
val selectSql = """
SELECT Gender, Delta from PrivacyBucketCharges
"""
statement.execute(schema)
statement.execute(insertSql)
val result: ResultSet = statement.executeQuery(selectSql)
result.next()
assertEquals("F", result.getString("gender"))
assertEquals(0.1f, result.getFloat("delta"))
}
@Test
fun `privacy budget ledger can be written and read`() {
val connection: Connection = pg.embeddedPostgres.postgresDatabase.connection
val statement = connection.createStatement()
val insertSql =
"""
INSERT INTO LedgerEntries (
MeasurementConsumerId,
ReferenceId,
IsRefund,
CreateTime
) VALUES (
'MC1',
'Ref1',
false,
NOW()
);
"""
val selectSql =
"""
SELECT MeasurementConsumerId, ReferenceId, IsRefund from LedgerEntries
"""
statement.execute(schema)
statement.execute(insertSql)
val result: ResultSet = statement.executeQuery(selectSql)
result.next()
assertEquals("MC1", result.getString("measurementConsumerId"))
assertEquals("Ref1", result.getString("referenceId"))
assertEquals(false, result.getBoolean("isRefund"))
}
}
| apache-2.0 | 36c4897ffd97587d69d8b6efbeb45cd3 | 29.944954 | 101 | 0.693448 | 4.380519 | false | true | false | false |
PaulWoitaschek/Voice | app/src/main/kotlin/voice/app/features/widget/WidgetUpdater.kt | 1 | 8666 | package voice.app.features.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.support.v4.media.session.PlaybackStateCompat.ACTION_FAST_FORWARD
import android.support.v4.media.session.PlaybackStateCompat.ACTION_PLAY_PAUSE
import android.support.v4.media.session.PlaybackStateCompat.ACTION_REWIND
import android.view.View
import android.widget.RemoteViews
import androidx.core.graphics.drawable.toBitmap
import androidx.datastore.core.DataStore
import androidx.media.session.MediaButtonReceiver.buildMediaButtonPendingIntent
import coil.imageLoader
import coil.request.ImageRequest
import dagger.Reusable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import voice.app.R
import voice.app.features.MainActivity
import voice.common.BookId
import voice.common.dpToPxRounded
import voice.common.pref.CurrentBook
import voice.data.Book
import voice.data.repo.BookRepository
import voice.playback.playstate.PlayStateManager
import javax.inject.Inject
@Reusable
class WidgetUpdater @Inject constructor(
private val context: Context,
private val repo: BookRepository,
@CurrentBook
private val currentBook: DataStore<BookId?>,
private val playStateManager: PlayStateManager,
) {
private val appWidgetManager = AppWidgetManager.getInstance(context)
private val scope = CoroutineScope(Dispatchers.IO)
fun update() {
scope.launch {
val book = currentBook.data.first()?.let {
repo.get(it)
}
val componentName = ComponentName([email protected], BaseWidgetProvider::class.java)
val ids = appWidgetManager.getAppWidgetIds(componentName)
for (widgetId in ids) {
updateWidgetForId(book, widgetId)
}
}
}
private suspend fun updateWidgetForId(book: Book?, widgetId: Int) {
if (book != null) {
initWidgetForPresentBook(widgetId, book)
} else {
initWidgetForAbsentBook(widgetId)
}
}
private suspend fun initWidgetForPresentBook(widgetId: Int, book: Book) {
val opts = appWidgetManager.getAppWidgetOptions(widgetId)
val useWidth = widgetWidth(opts)
val useHeight = widgetHeight(opts)
val remoteViews = RemoteViews(context.packageName, R.layout.widget)
initElements(remoteViews = remoteViews, book = book, coverSize = useHeight)
if (useWidth > 0 && useHeight > 0) {
setVisibilities(remoteViews, useWidth, useHeight, book.content.chapters.size == 1)
}
appWidgetManager.updateAppWidget(widgetId, remoteViews)
}
private fun widgetWidth(opts: Bundle): Int {
val key = if (isPortrait) {
AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH
} else {
AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH
}
val dp = opts.getInt(key)
return context.dpToPxRounded(dp.toFloat())
}
private fun widgetHeight(opts: Bundle): Int {
val key = if (isPortrait) {
AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT
} else {
AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT
}
val dp = opts.getInt(key)
return context.dpToPxRounded(dp.toFloat())
}
private fun initWidgetForAbsentBook(widgetId: Int) {
val remoteViews = RemoteViews(context.packageName, R.layout.widget)
// directly going back to bookChoose
val wholeWidgetClickI = Intent(context, MainActivity::class.java)
wholeWidgetClickI.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
val wholeWidgetClickPI = PendingIntent.getActivity(
context,
System.currentTimeMillis().toInt(),
wholeWidgetClickI,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
remoteViews.setImageViewResource(R.id.imageView, R.drawable.album_art)
remoteViews.setOnClickPendingIntent(R.id.wholeWidget, wholeWidgetClickPI)
appWidgetManager.updateAppWidget(widgetId, remoteViews)
}
private val isPortrait: Boolean
get() {
val orientation = context.resources.configuration.orientation
return orientation == Configuration.ORIENTATION_PORTRAIT
}
private suspend fun initElements(remoteViews: RemoteViews, book: Book, coverSize: Int) {
val playPausePI = buildMediaButtonPendingIntent(context, ACTION_PLAY_PAUSE)
remoteViews.setOnClickPendingIntent(R.id.playPause, playPausePI)
val fastForwardPI = buildMediaButtonPendingIntent(context, ACTION_FAST_FORWARD)
remoteViews.setOnClickPendingIntent(R.id.fastForward, fastForwardPI)
val rewindPI = buildMediaButtonPendingIntent(context, ACTION_REWIND)
remoteViews.setOnClickPendingIntent(R.id.rewind, rewindPI)
val playIcon = if (playStateManager.playState == PlayStateManager.PlayState.Playing) {
R.drawable.ic_pause_white_36dp
} else {
R.drawable.ic_play_white_36dp
}
remoteViews.setImageViewResource(R.id.playPause, playIcon)
// if we have any book, init the views and have a click on the whole widget start BookPlay.
// if we have no book, simply have a click on the whole widget start BookChoose.
remoteViews.setTextViewText(R.id.title, book.content.name)
val name = book.currentChapter.name
remoteViews.setTextViewText(R.id.summary, name)
val wholeWidgetClickI = MainActivity.goToBookIntent(context, book.id)
val wholeWidgetClickPI = PendingIntent.getActivity(
context,
System.currentTimeMillis().toInt(),
wholeWidgetClickI,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val coverFile = book.content.cover
if (coverFile != null && coverSize > 0) {
val bitmap = context.imageLoader
.execute(
ImageRequest.Builder(context)
.data(coverFile)
.size(coverSize, coverSize)
.fallback(R.drawable.album_art)
.error(R.drawable.album_art)
.allowHardware(false)
.build(),
)
.drawable!!.toBitmap()
remoteViews.setImageViewBitmap(R.id.imageView, bitmap)
} else {
remoteViews.setImageViewResource(R.id.imageView, R.drawable.album_art)
}
remoteViews.setOnClickPendingIntent(R.id.wholeWidget, wholeWidgetClickPI)
}
private fun setVisibilities(
remoteViews: RemoteViews,
width: Int,
height: Int,
singleChapter: Boolean,
) {
setHorizontalVisibility(remoteViews, width, height)
setVerticalVisibility(remoteViews, height, singleChapter)
}
private fun setHorizontalVisibility(remoteViews: RemoteViews, widgetWidth: Int, coverSize: Int) {
val singleButtonSize = context.dpToPxRounded(8F + 36F + 8F)
// widget height because cover is square
var summarizedItemWidth = 3 * singleButtonSize + coverSize
// set all views visible
remoteViews.setViewVisibility(R.id.imageView, View.VISIBLE)
remoteViews.setViewVisibility(R.id.rewind, View.VISIBLE)
remoteViews.setViewVisibility(R.id.fastForward, View.VISIBLE)
// hide cover if we need space
if (summarizedItemWidth > widgetWidth) {
remoteViews.setViewVisibility(R.id.imageView, View.GONE)
summarizedItemWidth -= coverSize
}
// hide fast forward if we need space
if (summarizedItemWidth > widgetWidth) {
remoteViews.setViewVisibility(R.id.fastForward, View.GONE)
summarizedItemWidth -= singleButtonSize
}
// hide rewind if we need space
if (summarizedItemWidth > widgetWidth) {
remoteViews.setViewVisibility(R.id.rewind, View.GONE)
}
}
private fun setVerticalVisibility(
remoteViews: RemoteViews,
widgetHeight: Int,
singleChapter: Boolean,
) {
val buttonSize = context.dpToPxRounded(8F + 36F + 8F)
val titleSize = context.resources.getDimensionPixelSize(R.dimen.list_text_primary_size)
val summarySize = context.resources.getDimensionPixelSize(R.dimen.list_text_secondary_size)
var summarizedItemsHeight = buttonSize + titleSize + summarySize
// first setting all views visible
remoteViews.setViewVisibility(R.id.summary, View.VISIBLE)
remoteViews.setViewVisibility(R.id.title, View.VISIBLE)
// when we are in a single chapter or we are to high, hide summary
if (singleChapter || widgetHeight < summarizedItemsHeight) {
remoteViews.setViewVisibility(R.id.summary, View.GONE)
summarizedItemsHeight -= summarySize
}
// if we ar still to high, hide title
if (summarizedItemsHeight > widgetHeight) {
remoteViews.setViewVisibility(R.id.title, View.GONE)
}
}
}
| gpl-3.0 | 5aa87acee8f698aaa2cbcbec1e5d5d8a | 34.662551 | 99 | 0.740826 | 4.359155 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/services/InMemoryCacheService.kt | 1 | 3937 | package com.pr0gramm.app.services
import androidx.collection.LruCache
import com.pr0gramm.app.api.pr0gramm.Api
import com.pr0gramm.app.feed.ContentType
import com.pr0gramm.app.feed.FeedItem
import com.pr0gramm.app.feed.FeedService
import com.pr0gramm.app.util.LongSparseArray
import com.pr0gramm.app.util.catchAll
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/**
* This service helps to locally cache deltas to the pr0gramm. Those
* deltas might arise because of cha0s own caching.
*/
class InMemoryCacheService {
private val tagsCache = LruCache<Long, ExpiringValue<List<Api.Tag>>>(256)
private val userInfoCache = LruCache<String, ExpiringValue<UserInfo>>(24)
private val repostCache = AtomicReference(LongSparseArray<Unit>())
/**
* Invalidates all caches
*/
@Synchronized
fun invalidate() {
tagsCache.evictAll()
userInfoCache.evictAll()
}
/**
* Caches (or enhanced) a list of tags for the given itemId.
* @param tags The list with the tags you know about
* *
* @return A list containing all previously seen tags for this item.
*/
fun enhanceTags(itemId: Long, tags: List<Api.Tag>): List<Api.Tag> {
val result = tagsCache.get(itemId)?.value?.let { cached ->
if (tags.isNotEmpty()) {
(HashSet(cached) + tags).toList()
} else {
cached
}
} ?: tags.toList()
tagsCache.put(itemId, ExpiringValue(result, 5, TimeUnit.MINUTES))
return result
}
/**
* Caches the given items as reposts.
*/
private fun cacheReposts(newRepostIds: List<Long>) {
if (newRepostIds.isEmpty())
return
synchronized(repostCache) {
val copy = repostCache.get().clone()
newRepostIds.forEach { copy.put(it, Unit) }
repostCache.set(copy)
}
}
/**
* Checks if the given item is a repost or not.
* @param itemId The item to check
*/
fun isRepost(itemId: Long): Boolean {
return repostCache.get().contains(itemId)
}
fun isRepost(item: FeedItem): Boolean {
return isRepost(item.id)
}
/**
* Stores the given entry for a few minutes in the cache
*/
fun cacheUserInfo(contentTypes: Set<ContentType>, info: UserInfo) {
val name = info.info.user.name.trim().lowercase(Locale.getDefault())
val key = name + ContentType.combine(contentTypes)
userInfoCache.put(key, ExpiringValue(info, 1, TimeUnit.MINUTES))
}
/**
* Gets a cached instance, if there is one.
*/
fun getUserInfo(contentTypes: Set<ContentType>, name: String): UserInfo? {
val key = name.trim().lowercase(Locale.getDefault()) + ContentType.combine(contentTypes)
return userInfoCache[key]?.value
}
/**
* Caches the given tags. They will be added with an id of 0 and a confidence value of 0.5f.
*/
fun cacheTags(itemId: Long, tags: List<String>) {
enhanceTags(itemId, tags.map { tag -> Api.Tag(0L, 0.5f, tag) })
}
suspend fun refreshRepostsCache(feedService: FeedService, query: FeedService.FeedQuery): Boolean {
catchAll {
return withContext(NonCancellable) {
val feed = feedService.load(query)
cacheReposts(feed.items.map { it.id })
true
}
}
return false
}
private class ExpiringValue<out T : Any>(value: T, expireTime: Long, timeUnit: TimeUnit) {
private val deadline: Long = System.currentTimeMillis() + timeUnit.toMillis(expireTime)
val expired: Boolean get() = System.currentTimeMillis() > deadline
val value: T? = value
get() = field.takeIf { !expired }
}
}
| mit | b48d8193be2c11d2ad0ee4140e3cdd44 | 30.246032 | 102 | 0.637033 | 4.054583 | false | false | false | false |
FHannes/intellij-community | java/java-tests/testSrc/com/intellij/testFramework/fixtures/MultiModuleJava9ProjectDescriptor.kt | 3 | 4687 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testFramework.fixtures
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.*
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.ex.temp.TempFileSystem
import com.intellij.pom.java.LanguageLevel
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.LightPlatformTestCase
import org.jetbrains.jps.model.java.JavaSourceRootType
/**
* Dependencies: 'main' -> 'm2', 'main' -> 'm4', 'main' -> 'm5', 'main' -> 'm6' => 'm7'
*/
object MultiModuleJava9ProjectDescriptor : DefaultLightProjectDescriptor() {
enum class ModuleDescriptor(internal val moduleName: String, internal val rootName: String) {
MAIN(TEST_MODULE_NAME, "/not_used/"),
M2("${TEST_MODULE_NAME}_m2", "src_m2"),
M3("${TEST_MODULE_NAME}_m3", "src_m3"),
M4("${TEST_MODULE_NAME}_m4", "src_m4"),
M5("${TEST_MODULE_NAME}_m5", "src_m5"),
M6("${TEST_MODULE_NAME}_m6", "src_m6"),
M7("${TEST_MODULE_NAME}_m7", "src_m7");
fun root(): VirtualFile =
if (this == MAIN) LightPlatformTestCase.getSourceRoot() else TempFileSystem.getInstance().findFileByPath("/$rootName")!!
fun testRoot(): VirtualFile? =
if (this == MAIN) TempFileSystem.getInstance().findFileByPath("/test_src")!! else null
}
override fun getSdk(): Sdk = IdeaTestUtil.getMockJdk9()
override fun setUpProject(project: Project, handler: SetupHandler) {
super.setUpProject(project, handler)
runWriteAction {
val main = ModuleManager.getInstance(project).findModuleByName(TEST_MODULE_NAME)!!
val m2 = makeModule(project, ModuleDescriptor.M2)
ModuleRootModificationUtil.addDependency(main, m2)
makeModule(project, ModuleDescriptor.M3)
val m4 = makeModule(project, ModuleDescriptor.M4)
ModuleRootModificationUtil.addDependency(main, m4)
val m5 = makeModule(project, ModuleDescriptor.M5)
ModuleRootModificationUtil.addDependency(main, m5)
val m6 = makeModule(project, ModuleDescriptor.M6)
ModuleRootModificationUtil.addDependency(main, m6)
val m7 = makeModule(project, ModuleDescriptor.M7)
ModuleRootModificationUtil.addDependency(m6, m7, DependencyScope.COMPILE, true)
val libDir = "jar://${PathManagerEx.getTestDataPath()}/codeInsight/jigsaw"
ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-named-1.0.jar!/")
ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-auto-1.0.jar!/")
ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-auto-2.0.jar!/")
ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-multi-release.jar!/")
}
}
private fun makeModule(project: Project, descriptor: ModuleDescriptor): Module {
val path = FileUtil.join(FileUtil.getTempDirectory(), "${descriptor.moduleName}.iml")
val module = createModule(project, path)
val sourceRoot = createSourceRoot(module, descriptor.rootName)
createContentEntry(module, sourceRoot)
return module
}
override fun configureModule(module: Module, model: ModifiableRootModel, contentEntry: ContentEntry) {
model.getModuleExtension(LanguageLevelModuleExtension::class.java).languageLevel = LanguageLevel.JDK_1_9
if (module.name == TEST_MODULE_NAME) {
val testRoot = createSourceRoot(module, "test_src")
registerSourceRoot(module.project, testRoot)
model.addContentEntry(testRoot).addSourceFolder(testRoot, JavaSourceRootType.TEST_SOURCE)
}
}
fun cleanupSourceRoots() = runWriteAction {
ModuleDescriptor.values().asSequence()
.filter { it != ModuleDescriptor.MAIN }
.flatMap { it.root().children.asSequence() }
.plus(ModuleDescriptor.MAIN.testRoot()!!.children.asSequence())
.forEach { it.delete(this) }
}
} | apache-2.0 | 85f32f816598516f9cb79ee76a311095 | 41.618182 | 126 | 0.735865 | 4.264786 | false | true | false | false |
didi/DoraemonKit | Android/app/src/main/java/com/didichuxing/doraemondemo/mc/NetMainActivity.kt | 1 | 1483 | package com.didichuxing.doraemondemo.mc
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.didichuxing.doraemondemo.R
import kotlinx.coroutines.*
import okhttp3.*
import java.io.IOException
class NetMainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_net_main)
}
override fun onResume() {
super.onResume()
request()
}
fun request() {
val httpRequest = Request.Builder()
.header("User-Agent", "mc-test")
.url("https://www.tianqiapi.com/free/week?appid=68852321&appsecret=BgGLDVc7")
.build()
val client = OkHttpClient.Builder().build()
client.newCall(httpRequest).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
GlobalScope.launch(Dispatchers.Main) {
val view = findViewById<TextView>(R.id.text)
view.text = e.message
}
}
override fun onResponse(call: Call, response: Response) {
GlobalScope.launch(Dispatchers.Main) {
val text: String? = response.body()?.string()
val view = findViewById<TextView>(R.id.text)
view.text = text
}
}
})
}
}
| apache-2.0 | eba5240514744285531827330e0e24ca | 29.895833 | 89 | 0.595415 | 4.563077 | false | false | false | false |
Light-Team/ModPE-IDE-Source | data/src/main/kotlin/com/brackeys/ui/data/repository/themes/ThemesRepositoryImpl.kt | 1 | 10911 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.brackeys.ui.data.repository.themes
import android.content.Context
import android.net.Uri
import android.os.Environment
import com.brackeys.ui.data.converter.ThemeConverter
import com.brackeys.ui.data.model.themes.ExternalTheme
import com.brackeys.ui.data.storage.database.AppDatabase
import com.brackeys.ui.data.storage.database.entity.theme.ThemeEntity
import com.brackeys.ui.data.storage.keyvalue.SettingsManager
import com.brackeys.ui.domain.model.themes.Meta
import com.brackeys.ui.domain.model.themes.Property
import com.brackeys.ui.domain.model.themes.PropertyItem
import com.brackeys.ui.domain.model.themes.ThemeModel
import com.brackeys.ui.domain.providers.coroutines.DispatcherProvider
import com.brackeys.ui.domain.repository.themes.ThemesRepository
import com.brackeys.ui.filesystem.base.Filesystem
import com.brackeys.ui.filesystem.base.model.FileModel
import com.brackeys.ui.filesystem.base.model.FileParams
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.File
@Suppress("BlockingMethodInNonBlockingContext")
class ThemesRepositoryImpl(
private val dispatcherProvider: DispatcherProvider,
private val settingsManager: SettingsManager,
private val appDatabase: AppDatabase,
private val filesystem: Filesystem,
private val context: Context
) : ThemesRepository {
companion object {
private const val FALLBACK_COLOR = "#000000"
}
// region PROPERTIES
private var textColor: String = FALLBACK_COLOR
private var backgroundColor: String = FALLBACK_COLOR
private var gutterColor: String = FALLBACK_COLOR
private var gutterDividerColor: String = FALLBACK_COLOR
private var gutterCurrentLineNumberColor: String = FALLBACK_COLOR
private var gutterTextColor: String = FALLBACK_COLOR
private var selectedLineColor: String = FALLBACK_COLOR
private var selectionColor: String = FALLBACK_COLOR
private var suggestionQueryColor: String = FALLBACK_COLOR
private var findResultBackgroundColor: String = FALLBACK_COLOR
private var delimiterBackgroundColor: String = FALLBACK_COLOR
private var numberColor: String = FALLBACK_COLOR
private var operatorColor: String = FALLBACK_COLOR
private var keywordColor: String = FALLBACK_COLOR
private var typeColor: String = FALLBACK_COLOR
private var langConstColor: String = FALLBACK_COLOR
private var preprocessorColor: String = FALLBACK_COLOR
private var variableColor: String = FALLBACK_COLOR
private var methodColor: String = FALLBACK_COLOR
private var stringColor: String = FALLBACK_COLOR
private var commentColor: String = FALLBACK_COLOR
private var tagColor: String = FALLBACK_COLOR
private var tagNameColor: String = FALLBACK_COLOR
private var attrNameColor: String = FALLBACK_COLOR
private var attrValueColor: String = FALLBACK_COLOR
private var entityRefColor: String = FALLBACK_COLOR
// endregion PROPERTIES
override suspend fun fetchThemes(searchQuery: String): List<ThemeModel> {
return withContext(dispatcherProvider.io()) {
appDatabase.themeDao()
.loadAll(searchQuery)
.map(ThemeConverter::toModel)
}
}
override suspend fun fetchTheme(uuid: String): ThemeModel {
return withContext(dispatcherProvider.io()) {
val themeEntity = appDatabase.themeDao().load(uuid)
ThemeConverter.toModel(themeEntity)
}
}
override suspend fun importTheme(uri: Uri): ThemeModel {
return withContext(dispatcherProvider.io()) {
val inputStream = context.contentResolver.openInputStream(uri)
val themeJson = inputStream?.bufferedReader()?.use(BufferedReader::readText)!!
val externalTheme = ExternalTheme.deserialize(themeJson)
ThemeConverter.toModel(externalTheme)
}
}
override suspend fun exportTheme(themeModel: ThemeModel) {
withContext(dispatcherProvider.io()) {
val externalTheme = ThemeConverter.toExternalTheme(themeModel)
val fileName = "${themeModel.name}.json"
val fileText = ExternalTheme.serialize(externalTheme)
val directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
val fileModel = FileModel(File(directory, fileName).absolutePath)
filesystem.saveFile(fileModel, fileText, FileParams())
}
}
override suspend fun createTheme(meta: Meta, properties: List<PropertyItem>) {
return withContext(dispatcherProvider.io()) {
for (property in properties) {
when (property.propertyKey) {
Property.TEXT_COLOR -> textColor = property.propertyValue
Property.BACKGROUND_COLOR -> backgroundColor = property.propertyValue
Property.GUTTER_COLOR -> gutterColor = property.propertyValue
Property.GUTTER_DIVIDER_COLOR -> gutterDividerColor = property.propertyValue
Property.GUTTER_CURRENT_LINE_NUMBER_COLOR -> gutterCurrentLineNumberColor = property.propertyValue
Property.GUTTER_TEXT_COLOR -> gutterTextColor = property.propertyValue
Property.SELECTED_LINE_COLOR -> selectedLineColor = property.propertyValue
Property.SELECTION_COLOR -> selectionColor = property.propertyValue
Property.SUGGESTION_QUERY_COLOR -> suggestionQueryColor = property.propertyValue
Property.FIND_RESULT_BACKGROUND_COLOR -> findResultBackgroundColor = property.propertyValue
Property.DELIMITER_BACKGROUND_COLOR -> delimiterBackgroundColor = property.propertyValue
Property.NUMBER_COLOR -> numberColor = property.propertyValue
Property.OPERATOR_COLOR -> operatorColor = property.propertyValue
Property.KEYWORD_COLOR -> keywordColor = property.propertyValue
Property.TYPE_COLOR -> typeColor = property.propertyValue
Property.LANG_CONST_COLOR -> langConstColor = property.propertyValue
Property.PREPROCESSOR_COLOR -> preprocessorColor = property.propertyValue
Property.VARIABLE_COLOR -> variableColor = property.propertyValue
Property.METHOD_COLOR -> methodColor = property.propertyValue
Property.STRING_COLOR -> stringColor = property.propertyValue
Property.COMMENT_COLOR -> commentColor = property.propertyValue
Property.TAG_COLOR -> tagColor = property.propertyValue
Property.TAG_NAME_COLOR -> tagNameColor = property.propertyValue
Property.ATTR_NAME_COLOR -> attrNameColor = property.propertyValue
Property.ATTR_VALUE_COLOR -> attrValueColor = property.propertyValue
Property.ENTITY_REF_COLOR -> entityRefColor = property.propertyValue
}
}
val themeEntity = ThemeEntity(
uuid = meta.uuid,
name = meta.name,
author = meta.author,
description = meta.description,
textColor = textColor,
backgroundColor = backgroundColor,
gutterColor = gutterColor,
gutterDividerColor = gutterDividerColor,
gutterCurrentLineNumberColor = gutterCurrentLineNumberColor,
gutterTextColor = gutterTextColor,
selectedLineColor = selectedLineColor,
selectionColor = selectionColor,
suggestionQueryColor = suggestionQueryColor,
findResultBackgroundColor = findResultBackgroundColor,
delimiterBackgroundColor = delimiterBackgroundColor,
numberColor = numberColor,
operatorColor = operatorColor,
keywordColor = keywordColor,
typeColor = typeColor,
langConstColor = langConstColor,
preprocessorColor = preprocessorColor,
variableColor = variableColor,
methodColor = methodColor,
stringColor = stringColor,
commentColor = commentColor,
tagColor = tagColor,
tagNameColor = tagNameColor,
attrNameColor = attrNameColor,
attrValueColor = attrValueColor,
entityRefColor = entityRefColor
)
appDatabase.themeDao().insert(themeEntity)
textColor = FALLBACK_COLOR
backgroundColor = FALLBACK_COLOR
gutterColor = FALLBACK_COLOR
gutterDividerColor = FALLBACK_COLOR
gutterCurrentLineNumberColor = FALLBACK_COLOR
gutterTextColor = FALLBACK_COLOR
selectedLineColor = FALLBACK_COLOR
selectionColor = FALLBACK_COLOR
suggestionQueryColor = FALLBACK_COLOR
findResultBackgroundColor = FALLBACK_COLOR
delimiterBackgroundColor = FALLBACK_COLOR
numberColor = FALLBACK_COLOR
operatorColor = FALLBACK_COLOR
keywordColor = FALLBACK_COLOR
typeColor = FALLBACK_COLOR
langConstColor = FALLBACK_COLOR
variableColor = FALLBACK_COLOR
methodColor = FALLBACK_COLOR
stringColor = FALLBACK_COLOR
commentColor = FALLBACK_COLOR
tagColor = FALLBACK_COLOR
tagNameColor = FALLBACK_COLOR
attrNameColor = FALLBACK_COLOR
attrValueColor = FALLBACK_COLOR
entityRefColor = FALLBACK_COLOR
}
}
override suspend fun removeTheme(themeModel: ThemeModel) {
withContext(dispatcherProvider.io()) {
appDatabase.themeDao().delete(ThemeConverter.toEntity(themeModel))
if (settingsManager.colorScheme == themeModel.uuid) {
settingsManager.remove(SettingsManager.KEY_COLOR_SCHEME)
}
}
}
override suspend fun selectTheme(themeModel: ThemeModel) {
withContext(dispatcherProvider.io()) {
settingsManager.colorScheme = themeModel.uuid
}
}
} | apache-2.0 | 534fa28a031e10902935f61f1578af66 | 46.859649 | 118 | 0.676198 | 5.563998 | false | false | false | false |
groupdocs-comparison/GroupDocs.Comparison-for-Java | Demos/Compose/src/main/kotlin/com/groupdocs/ui/theme/Theme.kt | 1 | 983 | package com.groupdocs.ui.theme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
// https://material.io/design/color/the-color-system.html#color-theme-creation
private val LightColorPalette = lightColors(
primary = Green,
primaryVariant = GreenLight,
onPrimary = BlackDark,
secondary = WhiteLight,
secondaryVariant = WhiteDark,
onSecondary = BlueLight,
error = RedDark,
onError = WhiteLight,
background = Blue,
onBackground = WhiteLight,
surface = BlackDark,
onSurface = WhiteLight,
)
@Composable
fun GroupDocsTheme(content: @Composable () -> Unit) {
CompositionLocalProvider(LocalSpaces provides Spaces()) {
MaterialTheme(
colors = LightColorPalette,
typography = Typography,
shapes = Shapes,
content = content
)
}
} | mit | 5ec8864c55b6b88406144011500e89c0 | 27.114286 | 78 | 0.707019 | 4.725962 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/main/kotlin/co/nums/intellij/aem/errorreports/FeedbackSubmitter.kt | 1 | 2800 | package co.nums.intellij.aem.errorreports
import co.nums.intellij.aem.service.PluginInfoProvider
import com.intellij.openapi.diagnostic.SubmittedReportInfo
import com.intellij.openapi.diagnostic.SubmittedReportInfo.SubmissionStatus
import org.eclipse.egit.github.core.*
object FeedbackSubmitter {
fun submitFeedback(pluginInfoProvider: PluginInfoProvider, gitHubIssueService: GitHubIssueService, errorBean: GitHubErrorBean): SubmittedReportInfo {
try {
val issueTitle = errorBean.issueTitle
var issue = gitHubIssueService.findAutoGeneratedIssueByTitle(issueTitle)
if (issue == null) {
issue = gitHubIssueService.submitIssue(errorBean.buildGitHubIssue())
return createSubmittedReportInfo(issue, SubmissionStatus.NEW_ISSUE)
} else {
val fixedVersion = issue.getFixedVersion()
if (fixedVersion == null) {
gitHubIssueService.addComment(issue.number, errorBean.issueDetailsWithoutException)
return createSubmittedReportInfo(issue, SubmissionStatus.DUPLICATE)
} else if (pluginInfoProvider.runningVersionIsOlderThan(fixedVersion)) {
val message = ErrorReportingBundle.message("error.report.github.submission.status.fixed", fixedVersion, issue.htmlUrl, issue.number)
return SubmittedReportInfo(issue.htmlUrl, message, SubmissionStatus.DUPLICATE)
} else {
// error was reported in past and fixed, but exists again
val newIssue = gitHubIssueService.submitIssue(errorBean.buildGitHubIssue())
gitHubIssueService.addComment(newIssue.number, "The same as in #${issue.number}.")
return createSubmittedReportInfo(newIssue, SubmissionStatus.NEW_ISSUE)
}
}
} catch (e: Exception) {
return SubmittedReportInfo(null, ErrorReportingBundle.message("error.report.connection.failure"), SubmissionStatus.FAILED)
}
}
private fun GitHubErrorBean.buildGitHubIssue() = Issue().apply {
title = issueTitle
body = issueDetails
labels = listOf(Label().apply { this.name = AUTO_GENERATED_LABEL_NAME })
}
private fun Issue.getFixedVersion() =
if (body?.startsWith(FIXED_PREFIX) == true) body.lines().first().removePrefix(FIXED_PREFIX).trim()
else null
private fun createSubmittedReportInfo(issue: Issue, submissionStatus: SubmissionStatus): SubmittedReportInfo {
val message = ErrorReportingBundle.message("error.report.github.submission.status.$submissionStatus", issue.htmlUrl, issue.number)
return SubmittedReportInfo(issue.htmlUrl, message, submissionStatus)
}
}
| gpl-3.0 | 49d33ebacc0fed4aba3da3bb22c2f21f | 52.846154 | 153 | 0.6875 | 5.054152 | false | false | false | false |
apixandru/intellij-community | plugins/git4idea/src/git4idea/GitApplyChangesProcess.kt | 1 | 21536 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea
import com.intellij.dvcs.DvcsUtil
import com.intellij.dvcs.DvcsUtil.getShortRepositoryName
import com.intellij.notification.Notification
import com.intellij.notification.NotificationListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.util.text.StringUtil.pluralize
import com.intellij.openapi.vcs.AbstractVcsHelper
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vcs.merge.MergeDialogCustomizer
import com.intellij.openapi.vcs.update.RefreshVFsSynchronously
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.text.UniqueNameGenerator
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.VcsFullCommitDetails
import com.intellij.vcs.log.util.VcsUserUtil
import git4idea.commands.*
import git4idea.commands.GitSimpleEventDetector.Event.CHERRY_PICK_CONFLICT
import git4idea.commands.GitSimpleEventDetector.Event.LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK
import git4idea.merge.GitConflictResolver
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.util.GitUntrackedFilesHelper
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import javax.swing.event.HyperlinkEvent
/**
* Applies the given Git operation (e.g. cherry-pick or revert) to the current working tree,
* waits for the [ChangeListManager] update, shows the commit dialog and removes the changelist after commit,
* if the commit was successful.
*/
class GitApplyChangesProcess(private val project: Project,
private val commits: List<VcsFullCommitDetails>,
private val autoCommit: Boolean,
private val operationName: String,
private val appliedWord: String,
private val command: (GitRepository, Hash, Boolean, List<GitLineHandlerListener>) -> GitCommandResult,
private val emptyCommitDetector: (GitCommandResult) -> Boolean,
private val defaultCommitMessageGenerator: (VcsFullCommitDetails) -> String,
private val findLocalChanges: (Collection<Change>) -> Collection<Change>,
private val preserveCommitMetadata: Boolean,
private val cleanupBeforeCommit: (GitRepository) -> Unit = {}) {
private val LOG = logger<GitApplyChangesProcess>()
private val git = Git.getInstance()
private val repositoryManager = GitRepositoryManager.getInstance(project)
private val vcsNotifier = VcsNotifier.getInstance(project)
private val changeListManager = ChangeListManager.getInstance(project)
private val vcsHelper = AbstractVcsHelper.getInstance(project)
fun execute() {
val commitsInRoots = DvcsUtil.groupCommitsByRoots<GitRepository>(repositoryManager, commits)
LOG.info("${operationName}ing commits: " + toString(commitsInRoots))
val successfulCommits = mutableListOf<VcsFullCommitDetails>()
val skippedCommits = mutableListOf<VcsFullCommitDetails>()
val token = DvcsUtil.workingTreeChangeStarted(project)
try {
for ((repository, value) in commitsInRoots) {
val result = executeForRepo(repository, value, successfulCommits, skippedCommits)
repository.update()
if (!result) {
return
}
}
notifyResult(successfulCommits, skippedCommits)
}
finally {
token.finish()
}
}
// return true to continue with other roots, false to break execution
private fun executeForRepo(repository: GitRepository,
commits: List<VcsFullCommitDetails>,
successfulCommits: MutableList<VcsFullCommitDetails>,
alreadyPicked: MutableList<VcsFullCommitDetails>): Boolean {
for (commit in commits) {
val conflictDetector = GitSimpleEventDetector(CHERRY_PICK_CONFLICT)
val localChangesOverwrittenDetector = GitSimpleEventDetector(LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK)
val untrackedFilesDetector = GitUntrackedFilesOverwrittenByOperationDetector(repository.root)
val result = command(repository, commit.id, autoCommit,
listOf(conflictDetector, localChangesOverwrittenDetector, untrackedFilesDetector))
if (result.success()) {
if (autoCommit) {
successfulCommits.add(commit)
}
else {
val committed = updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository, commit,
successfulCommits, alreadyPicked)
if (!committed) {
notifyCommitCancelled(commit, successfulCommits)
return false
}
}
}
else if (conflictDetector.hasHappened()) {
val mergeCompleted = ConflictResolver(project, git, repository.root,
commit.id.asString(), VcsUserUtil.getShortPresentation(commit.author),
commit.subject, operationName).merge()
if (mergeCompleted) {
val committed = updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository, commit,
successfulCommits, alreadyPicked)
if (!committed) {
notifyCommitCancelled(commit, successfulCommits)
return false
}
}
else {
updateChangeListManager(commit)
notifyConflictWarning(repository, commit, successfulCommits)
return false
}
}
else if (untrackedFilesDetector.wasMessageDetected()) {
var description = commitDetails(commit) +
"<br/>Some untracked working tree files would be overwritten by $operationName.<br/>" +
"Please move, remove or add them before you can $operationName. <a href='view'>View them</a>"
description += getSuccessfulCommitDetailsIfAny(successfulCommits)
GitUntrackedFilesHelper.notifyUntrackedFilesOverwrittenBy(project, repository.root,
untrackedFilesDetector.relativeFilePaths, operationName, description)
return false
}
else if (localChangesOverwrittenDetector.hasHappened()) {
notifyError("Your local changes would be overwritten by $operationName.<br/>Commit your changes or stash them to proceed.",
commit, successfulCommits)
return false
}
else if (emptyCommitDetector(result)) {
alreadyPicked.add(commit)
}
else {
notifyError(result.errorOutputAsHtmlString, commit, successfulCommits)
return false
}
}
return true
}
private fun updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository: GitRepository,
commit: VcsFullCommitDetails,
successfulCommits: MutableList<VcsFullCommitDetails>,
alreadyPicked: MutableList<VcsFullCommitDetails>): Boolean {
val data = updateChangeListManager(commit)
if (data == null) {
alreadyPicked.add(commit)
return true
}
val committed = showCommitDialogAndWaitForCommit(repository, commit, data.changeList, data.commitMessage)
if (committed) {
changeListManager.removeChangeList(data.changeList)
successfulCommits.add(commit)
return true
}
return false
}
private fun updateChangeListManager(commit: VcsFullCommitDetails): ChangeListData? {
val changes = commit.changes
RefreshVFsSynchronously.updateChanges(changes)
val commitMessage = defaultCommitMessageGenerator(commit)
val paths = ChangesUtil.getPaths(changes)
val changeList = createChangeListAfterUpdate(commit, paths, commitMessage)
return if (changeList == null) null else ChangeListData(changeList, commitMessage)
}
private fun createChangeListAfterUpdate(commit: VcsFullCommitDetails, paths: Collection<FilePath>,
commitMessage: String): LocalChangeList? {
val waiter = CountDownLatch(1)
val changeList = Ref.create<LocalChangeList>()
changeListManager.invokeAfterUpdate({
changeList.set(createChangeListIfThereAreChanges(commit, commitMessage))
waiter.countDown()
}, InvokeAfterUpdateMode.SILENT_CALLBACK_POOLED, operationName.capitalize(),
{ vcsDirtyScopeManager -> vcsDirtyScopeManager.filePathsDirty(paths, null) },
ModalityState.NON_MODAL)
try {
val success = waiter.await(100, TimeUnit.SECONDS)
if (!success) {
LOG.error("Couldn't await for changelist manager refresh")
}
}
catch (e: InterruptedException) {
LOG.error(e)
return null
}
return changeList.get()
}
private fun showCommitDialogAndWaitForCommit(repository: GitRepository, commit: VcsFullCommitDetails,
changeList: LocalChangeList, commitMessage: String): Boolean {
val commitSucceeded = AtomicBoolean()
val sem = Semaphore(0)
ApplicationManager.getApplication().invokeAndWait({
try {
cleanupBeforeCommit(repository)
val commitNotCancelled = vcsHelper.commitChanges(
findLocalChanges(commit.changes), changeList, commitMessage,
object : CommitResultHandler {
override fun onSuccess(commitMessage1: String) {
commitSucceeded.set(true)
sem.release()
}
override fun onFailure() {
commitSucceeded.set(false)
sem.release()
}
})
if (!commitNotCancelled) {
commitSucceeded.set(false)
sem.release()
}
}
catch (t: Throwable) {
LOG.error(t)
commitSucceeded.set(false)
sem.release()
}
}, ModalityState.NON_MODAL)
// need additional waiting, because commitChanges is asynchronous
try {
sem.acquire()
}
catch (e: InterruptedException) {
LOG.error(e)
return false
}
return commitSucceeded.get()
}
private fun createChangeListIfThereAreChanges(commit: VcsFullCommitDetails, commitMessage: String): LocalChangeList? {
val originalChanges = commit.changes
if (originalChanges.isEmpty()) {
LOG.info("Empty commit " + commit.id)
return null
}
if (noChangesAfterApply(originalChanges)) {
LOG.info("No changes after executing for commit ${commit.id}")
return null
}
val changeListName = createNameForChangeList(commitMessage)
val createdChangeList = (changeListManager as ChangeListManagerEx).addChangeList(changeListName, commitMessage,
if (preserveCommitMetadata) commit else null)
val actualChangeList = moveChanges(originalChanges, createdChangeList)
if (actualChangeList != null && !actualChangeList.changes.isEmpty()) {
return createdChangeList
}
LOG.warn("No changes were moved to the changelist. Changes from commit: " + originalChanges +
"\nAll changes: " + changeListManager.getAllChanges())
changeListManager.removeChangeList(createdChangeList)
return null
}
private fun noChangesAfterApply(originalChanges: Collection<Change>): Boolean {
return findLocalChanges(originalChanges).isEmpty()
}
private fun moveChanges(originalChanges: Collection<Change>, targetChangeList: LocalChangeList): LocalChangeList? {
val localChanges = findLocalChanges(originalChanges)
// 1. We have to listen to CLM changes, because moveChangesTo is asynchronous
// 2. We have to collect the real target change list, because the original target list (passed to moveChangesTo) is not updated in time.
val moveChangesWaiter = CountDownLatch(1)
val resultingChangeList = AtomicReference<LocalChangeList>()
val listener = object : ChangeListAdapter() {
override fun changesMoved(changes: Collection<Change>, fromList: ChangeList, toList: ChangeList) {
if (toList is LocalChangeList && targetChangeList.id == toList.id) {
resultingChangeList.set(toList)
moveChangesWaiter.countDown()
}
}
}
try {
changeListManager.addChangeListListener(listener)
changeListManager.moveChangesTo(targetChangeList, *localChanges.toTypedArray())
val success = moveChangesWaiter.await(100, TimeUnit.SECONDS)
if (!success) {
LOG.error("Couldn't await for changes move.")
}
return resultingChangeList.get()
}
catch (e: InterruptedException) {
LOG.error(e)
return null
}
finally {
changeListManager.removeChangeListListener(listener)
}
}
private fun createNameForChangeList(commitMessage: String): String {
val proposedName = commitMessage.trim()
.substringBefore('\n')
.trim()
.replace("[ ]{2,}".toRegex(), " ")
return UniqueNameGenerator.generateUniqueName(proposedName, "", "", "-", "", { changeListManager.findChangeList(it) == null })
}
private fun notifyResult(successfulCommits: List<VcsFullCommitDetails>, skipped: List<VcsFullCommitDetails>) {
if (skipped.isEmpty()) {
vcsNotifier.notifySuccess("${operationName.capitalize()} successful", getCommitsDetails(successfulCommits))
}
else if (!successfulCommits.isEmpty()) {
val title = String.format("${operationName.capitalize()}ed %d commits from %d", successfulCommits.size,
successfulCommits.size + skipped.size)
val description = getCommitsDetails(successfulCommits) + "<hr/>" + formSkippedDescription(skipped, true)
vcsNotifier.notifySuccess(title, description)
}
else {
vcsNotifier.notifyImportantWarning("Nothing to $operationName", formSkippedDescription(skipped, false))
}
}
private fun notifyConflictWarning(repository: GitRepository,
commit: VcsFullCommitDetails,
successfulCommits: List<VcsFullCommitDetails>) {
val resolveLinkListener = ResolveLinkListener(repository.root,
commit.id.toShortString(),
VcsUserUtil.getShortPresentation(commit.author),
commit.subject)
var description = commitDetails(commit) + "<br/>Unresolved conflicts remain in the working tree. <a href='resolve'>Resolve them.<a/>"
description += getSuccessfulCommitDetailsIfAny(successfulCommits)
vcsNotifier.notifyImportantWarning("${operationName.capitalize()}ed with conflicts", description, resolveLinkListener)
}
private fun notifyCommitCancelled(commit: VcsFullCommitDetails, successfulCommits: List<VcsFullCommitDetails>) {
if (successfulCommits.isEmpty()) {
// don't notify about cancelled commit. Notify just in the case when there were already successful commits in the queue.
return
}
var description = commitDetails(commit)
description += getSuccessfulCommitDetailsIfAny(successfulCommits)
vcsNotifier.notifyMinorWarning("${operationName.capitalize()} cancelled", description, null)
}
private fun notifyError(content: String,
failedCommit: VcsFullCommitDetails,
successfulCommits: List<VcsFullCommitDetails>) {
var description = commitDetails(failedCommit) + "<br/>" + content
description += getSuccessfulCommitDetailsIfAny(successfulCommits)
vcsNotifier.notifyError("${operationName.capitalize()} Failed", description)
}
private fun getSuccessfulCommitDetailsIfAny(successfulCommits: List<VcsFullCommitDetails>): String {
var description = ""
if (!successfulCommits.isEmpty()) {
description += "<hr/>However ${operationName} succeeded for the following " + pluralize("commit", successfulCommits.size) + ":<br/>"
description += getCommitsDetails(successfulCommits)
}
return description
}
private fun formSkippedDescription(skipped: List<VcsFullCommitDetails>, but: Boolean): String {
val hashes = StringUtil.join(skipped, { commit -> commit.id.toShortString() }, ", ")
if (but) {
val was = if (skipped.size == 1) "was" else "were"
val it = if (skipped.size == 1) "it" else "them"
return String.format("%s %s skipped, because all changes have already been ${appliedWord}.", hashes, was, it)
}
return String.format("All changes from %s have already been ${appliedWord}", hashes)
}
private fun getCommitsDetails(successfulCommits: List<VcsFullCommitDetails>): String {
var description = ""
for (commit in successfulCommits) {
description += commitDetails(commit) + "<br/>"
}
return description.substring(0, description.length - "<br/>".length)
}
private fun commitDetails(commit: VcsFullCommitDetails): String {
return commit.id.toShortString() + " " + commit.subject
}
private fun toString(commitsInRoots: Map<GitRepository, List<VcsFullCommitDetails>>): String {
return commitsInRoots.entries.joinToString("; ") { entry ->
val commits = entry.value.joinToString { it.id.asString() }
getShortRepositoryName(entry.key) + ": [" + commits + "]"
}
}
private inner class ResolveLinkListener(private val root: VirtualFile,
private val hash: String,
private val author: String,
private val message: String) : NotificationListener {
override fun hyperlinkUpdate(notification: Notification, event: HyperlinkEvent) {
if (event.eventType == HyperlinkEvent.EventType.ACTIVATED) {
if (event.description == "resolve") {
GitApplyChangesProcess.ConflictResolver(project, git, root, hash, author, message, operationName).mergeNoProceed()
}
}
}
}
private data class ChangeListData(val changeList: LocalChangeList, val commitMessage: String)
class ConflictResolver(project: Project,
git: Git,
root: VirtualFile,
commitHash: String,
commitAuthor: String,
commitMessage: String,
operationName: String
) : GitConflictResolver(project, git, setOf(root), makeParams(commitHash, commitAuthor, commitMessage, operationName)) {
override fun notifyUnresolvedRemain() {/* we show a [possibly] compound notification after applying all commits.*/
}
}
}
private fun makeParams(commitHash: String, commitAuthor: String, commitMessage: String, operationName: String): GitConflictResolver.Params {
val params = GitConflictResolver.Params()
params.setErrorNotificationTitle("${operationName.capitalize()}ed with conflicts")
params.setMergeDialogCustomizer(MergeDialogCustomizer(commitHash, commitAuthor, commitMessage, operationName))
return params
}
private class MergeDialogCustomizer(private val commitHash: String,
private val commitAuthor: String,
private val commitMessage: String,
private val operationName: String) : MergeDialogCustomizer() {
override fun getMultipleFileMergeDescription(files: Collection<VirtualFile>) =
"<html>Conflicts during ${operationName}ing commit <code>$commitHash</code> " +
"made by $commitAuthor<br/><code>\"$commitMessage\"</code></html>"
override fun getLeftPanelTitle(file: VirtualFile) = "Local changes"
override fun getRightPanelTitle(file: VirtualFile, revisionNumber: VcsRevisionNumber?) =
"<html>Changes from $operationName <code>$commitHash</code>"
}
| apache-2.0 | 4631b6c60865923f885dbe7009100499 | 44.918977 | 142 | 0.666744 | 5.353219 | false | false | false | false |
SapuSeven/BetterUntis | app/src/main/java/com/sapuseven/untis/data/connectivity/UntisRequest.kt | 1 | 2019 | package com.sapuseven.untis.data.connectivity
import android.net.Uri
import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.fuel.coroutines.awaitStringResult
import com.github.kittinunf.fuel.httpPost
import com.github.kittinunf.result.Result
import com.sapuseven.untis.data.connectivity.UntisApiConstants.DEFAULT_WEBUNTIS_HOST
import com.sapuseven.untis.data.databases.UserDatabase
import com.sapuseven.untis.helpers.SerializationUtils.getJSON
import com.sapuseven.untis.models.untis.params.BaseParams
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import java.io.UnsupportedEncodingException
import java.net.URISyntaxException
class UntisRequest {
suspend fun request(query: UntisRequestQuery): Result<String, FuelError> {
return query.getUri().toString().httpPost()
.header(mapOf("Content-Type" to "application/json; charset=UTF-8"))
.body(getJSON().encodeToString(query.data))
.awaitStringResult()
}
class UntisRequestQuery(val user: UserDatabase.User? = null, apiUrl: String? = null) {
var url = apiUrl ?: user?.apiUrl ?: user?.schoolId?.let {
UntisApiConstants.DEFAULT_WEBUNTIS_PROTOCOL + DEFAULT_WEBUNTIS_HOST + UntisApiConstants.DEFAULT_WEBUNTIS_PATH + it
} ?: ""
var data: UntisRequestData = UntisRequestData()
var proxyHost: String? = null
@Throws(URISyntaxException::class, UnsupportedEncodingException::class)
internal fun getUri(): Uri {
return Uri.parse(url).buildUpon().apply {
if (!proxyHost.isNullOrBlank())
authority(proxyHost)
//appendQueryParameter("m", data.method) // optional
appendQueryParameter("v", "a5.2.3") // required, value taken from Untis Mobile
//appendQueryParameter("anonymous", "true") // optional
//appendQueryParameter("server", "euterpe.webuntis.com") // optional
}.build()
}
}
@Serializable
class UntisRequestData {
var id: String = "-1"
var jsonrpc: String = "2.0"
var method: String = ""
var params: List<BaseParams> = emptyList()
}
}
| gpl-3.0 | 0f700ace004a7db3bd4d805215ebe4e9 | 37.09434 | 117 | 0.760277 | 3.823864 | false | false | false | false |
AndroidX/androidx | compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/IsDisplayedTest.kt | 3 | 8304 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.activity.ComponentActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.util.BoundaryNode
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.ViewInteraction
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withParent
import androidx.test.filters.MediumTest
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.not
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@MediumTest
@RunWith(Parameterized::class)
class IsDisplayedTest(val config: TestConfig) {
data class TestConfig(
val activityClass: Class<out ComponentActivity>
)
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun createTestSet(): List<TestConfig> = listOf(
TestConfig(ComponentActivity::class.java),
TestConfig(ActivityWithActionBar::class.java)
)
}
@get:Rule
val rule = createAndroidComposeRule(config.activityClass)
private val colors = listOf(Color.Red, Color.Green, Color.Blue)
@Composable
private fun Item(i: Int, width: Dp? = null, height: Dp? = null) {
BoundaryNode("item$i") {
Box(
modifier =
with(Modifier) { width?.let { requiredWidth(it) } ?: fillMaxWidth() }
.then(
with(Modifier) { height?.let { requiredHeight(it) } ?: fillMaxHeight() }
)
.background(colors[i % colors.size])
)
}
}
@Composable
fun PlaceConditionally(place: Boolean, content: @Composable () -> Unit) {
Layout(content = content) { measurables, constraints ->
if (place) {
val placeable = measurables[0].measure(constraints)
layout(placeable.width, placeable.height) {
placeable.placeRelative(0, 0)
}
} else {
layout(0, 0) {}
}
}
}
@Test
fun componentInScrollable_isDisplayed() {
setContent {
Column(modifier = Modifier.requiredSize(100.dp).verticalScroll(rememberScrollState())) {
repeat(10) { Item(it, height = 30.dp) }
}
}
rule.onNodeWithTag("item0")
.assertIsDisplayed()
}
@Test
fun componentInScrollable_isNotDisplayed() {
setContent {
Column(modifier = Modifier.requiredSize(100.dp).verticalScroll(rememberScrollState())) {
repeat(10) { Item(it, height = 30.dp) }
}
}
rule.onNodeWithTag("item4")
.assertIsNotDisplayed()
}
@Test
fun togglePlacement() {
var place by mutableStateOf(true)
setContent {
PlaceConditionally(place) {
// Item instead of BoundaryNode because we need non-zero size
Item(0)
}
}
rule.onNodeWithTag("item0")
.assertIsDisplayed()
rule.runOnIdle {
place = false
}
rule.onNodeWithTag("item0")
.assertIsNotDisplayed()
}
@Test
fun toggleParentPlacement() {
var place by mutableStateOf(true)
setContent {
PlaceConditionally(place) {
Box {
// Item instead of BoundaryNode because we need non-zero size
Item(0)
}
}
}
rule.onNodeWithTag("item0")
.assertIsDisplayed()
rule.runOnIdle {
place = false
}
rule.onNodeWithTag("item0")
.assertIsNotDisplayed()
}
@Test
fun rowTooSmall() {
setContent {
Row(modifier = Modifier.requiredSize(100.dp)) {
repeat(10) { Item(it, width = 30.dp) }
}
}
rule.onNodeWithTag("item9")
.assertIsNotDisplayed()
}
@Test
fun viewVisibility_androidComposeView() {
lateinit var androidComposeView: View
rule.activityRule.scenario.onActivity { activity ->
// FrameLayout(id=100, w=100, h=100)
// '- AndroidComposeView
androidComposeView = ComposeView(activity).apply {
id = 100
layoutParams = ViewGroup.MarginLayoutParams(100, 100)
activity.setContentView(this)
setContent {
Item(0)
}
}.getChildAt(0)
}
fun onComposeView(): ViewInteraction {
return onView(allOf(withParent(withId(100))))
}
onComposeView().check(matches(isDisplayed()))
rule.onNodeWithTag("item0").assertIsDisplayed()
rule.runOnIdle {
androidComposeView.visibility = View.GONE
}
onComposeView().check(matches(not(isDisplayed())))
rule.onNodeWithTag("item0").assertIsNotDisplayed()
}
@Test
fun viewVisibility_parentView() {
lateinit var composeContainer: View
rule.activityRule.scenario.onActivity { activity ->
// FrameLayout
// '- FrameLayout(id=100, w=100, h=100) -> composeContainer
// '- AndroidComposeView
composeContainer = ComposeView(activity).apply {
id = 100
layoutParams = ViewGroup.MarginLayoutParams(100, 100)
activity.setContentView(FrameLayout(activity).also { it.addView(this) })
setContent {
Item(0)
}
}
}
fun onComposeView(): ViewInteraction {
return onView(allOf(withParent(withId(100))))
}
onComposeView().check(matches(isDisplayed()))
rule.onNodeWithTag("item0").assertIsDisplayed()
rule.runOnIdle {
composeContainer.visibility = View.GONE
}
onComposeView().check(matches(not(isDisplayed())))
rule.onNodeWithTag("item0").assertIsNotDisplayed()
}
private fun setContent(content: @Composable () -> Unit) {
when (val activity = rule.activity) {
is ActivityWithActionBar -> activity.setContent(content)
else -> rule.setContent(content)
}
}
}
| apache-2.0 | ed08cd7fdcad48de75d668f6b4845a18 | 30.938462 | 100 | 0.627288 | 4.919431 | false | true | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/handlers/RequestException.kt | 1 | 1743 | package au.com.codeka.warworlds.server.handlers
import java.util.*
import javax.servlet.http.HttpServletResponse
/** This exception is thrown when you want to pass an error back to the client. */
class RequestException : Exception {
var errorCode = 0
private set
constructor(httpErrorCode: Int)
: super(String.format(Locale.US, "HTTP Error: %d", httpErrorCode)) {
errorCode = httpErrorCode
}
constructor(httpErrorCode: Int, message: String?)
: super(String.format(message!!, httpErrorCode)) {
errorCode = httpErrorCode
}
constructor(httpErrorCode: Int, message: String?, innerException: Throwable?)
: super(String.format(message!!, httpErrorCode), innerException) {
errorCode = httpErrorCode
}
constructor(innerException: Throwable)
: super(getExceptionDescription(innerException), innerException) {
val reqExc = findInnerException(innerException, RequestException::class.java)
errorCode = reqExc?.errorCode ?: 500
}
fun populate(response: HttpServletResponse?) {
response!!.status = errorCode
}
companion object {
private const val serialVersionUID = 1L
private fun getExceptionDescription(e: Throwable): String {
val reqExc = findInnerException(e, RequestException::class.java)
return if (reqExc != null) {
"HTTP Error: " + reqExc.errorCode
} else "Unknown Exception"
}
private fun <T : Exception?> findInnerException(e: Throwable, exceptionType: Class<T>): T? {
var inner: Throwable? = e
while (inner != null) {
if (inner.javaClass == exceptionType) {
@Suppress("UNCHECKED_CAST")
return inner as T
}
inner = inner.cause
}
return null
}
}
} | mit | 5d0cffbc724a43c15b3fcd6d084ff7c9 | 29.596491 | 96 | 0.680436 | 4.379397 | false | false | false | false |
exponent/exponent | packages/expo-dev-launcher/android/src/main/java/expo/modules/devlauncher/launcher/manifest/DevLauncherManifestParser.kt | 2 | 1851 | package expo.modules.devlauncher.launcher.manifest
import android.net.Uri
import expo.modules.devlauncher.helpers.await
import expo.modules.devlauncher.helpers.fetch
import expo.modules.manifests.core.Manifest
import okhttp3.Headers
import okhttp3.OkHttpClient
import org.json.JSONObject
import java.io.Reader
class DevLauncherManifestParser(
private val httpClient: OkHttpClient,
private val url: Uri,
private val installationID: String?
) {
suspend fun isManifestUrl(): Boolean {
val response = fetch(url, "HEAD", getHeaders()).await(httpClient)
val contentType = response.header("Content-Type")
// published projects may respond unsuccessfully to HEAD requests sent with no headers
return !response.isSuccessful
|| response.header("Exponent-Server", null) != null
|| (contentType != null && contentType.startsWith("application/json"))
}
private suspend fun downloadManifest(): Reader {
val response = fetch(url, "GET", getHeaders()).await(httpClient)
if (!response.isSuccessful) {
throw Exception("Failed to open app.\n\nIf you are trying to load the app from a development server, check your network connectivity and make sure you can access the server from your device.\n\nIf you are trying to open a published project, install a compatible version of expo-updates and follow all setup and integration steps.")
}
@Suppress("DEPRECATION_ERROR")
return response.body()!!.charStream()
}
suspend fun parseManifest(): Manifest {
downloadManifest().use {
return Manifest.fromManifestJson(JSONObject(it.readText()))
}
}
private fun getHeaders(): Headers {
val headersMap = mutableMapOf("expo-platform" to "android")
if (installationID != null) {
headersMap["expo-dev-client-id"] = installationID
}
return Headers.of(headersMap)
}
}
| bsd-3-clause | d752ffd15668ecdf38a7de74fc3efa01 | 37.5625 | 337 | 0.735278 | 4.449519 | false | false | false | false |
deeplearning4j/deeplearning4j | codegen/op-codegen/src/main/ops/org/nd4j/codegen/ops/Math.kt | 1 | 58031 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
/**
* Generated using ExtractFromExisting.kt
*/
package org.nd4j.codegen.ops
import org.nd4j.codegen.api.AtLeast
import org.nd4j.codegen.api.DataType
import org.nd4j.codegen.api.DataType.*
import org.nd4j.codegen.api.Language
import org.nd4j.codegen.api.doc.DocScope
import org.nd4j.codegen.dsl.*
import org.nd4j.codegen.mixins.*
fun Math() = Namespace("Math") {
Op("abs", transformSame) {
javaOpClass = "Abs"
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise absolute value operation: out = abs(x)
""".trimIndent()
}
}
Op("acos", transformStrict) {
javaOpClass = "ACos"
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise acos (arccosine, inverse cosine) operation: out = arccos(x)
""".trimIndent()
}
}
Op("acosh", transformStrict) {
javaOpClass = "ACosh"
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise acosh (inverse hyperbolic cosine) function: out = acosh(x)
""".trimIndent()
}
}
Op("add", transformArithmetic){
javaOpClass = "AddOp"
Doc(Language.ANY, DocScope.ALL){
"""
Pairwise addition operation, out = x + y
""".trimIndent()
}
useMixin(broadcastingDoc)
}
Op("add", scalar){
javaOpClass = "ScalarAdd"
Doc(Language.ANY, DocScope.ALL){
"""
Scalar add operation, out = in + scalar
""".trimIndent()
}
}
Op("reduceAMax", reduceSame) {
javaOpClass = "AMax"
Doc(Language.ANY, DocScope.ALL){
"""
Absolute max array reduction operation, optionally along specified dimensions: out = max(abs(x))
""".trimIndent()
}
}
Op("reduceAMax", reduceSameVariable) {
javaOpClass = "AMax"
Doc(Language.ANY, DocScope.ALL){
"""
Absolute max array reduction operation, optionally along specified dimensions: out = max(abs(x))
""".trimIndent()
}
}
Op("reduceAmean", reduceFloating) {
javaOpClass = "AMean"
Doc(Language.ANY, DocScope.ALL){
"""
Absolute mean array reduction operation, optionally along specified dimensions: out = mean(abs(x))
""".trimIndent()
}
}
Op("reduceAmean", reduceFloatingVariable) {
javaOpClass = "AMean"
Doc(Language.ANY, DocScope.ALL){
"""
Absolute mean array reduction operation, optionally along specified dimensions: out = mean(abs(x))
""".trimIndent()
}
}
// TODO: There are 2 implementations of amax in org.nd4j.linalg.api.ops.impl
Op("reduceAmin", reduceSame) {
javaOpClass = "AMin"
Doc(Language.ANY, DocScope.ALL){
"""
Absolute min array reduction operation, optionally along specified dimensions: out = min(abs(x))
""".trimIndent()
}
}
Op("reduceAmin", reduceSameVariable) {
javaOpClass = "AMin"
Doc(Language.ANY, DocScope.ALL){
"""
Absolute min array reduction operation, optionally along specified dimensions: out = min(abs(x))
""".trimIndent()
}
}
Op("and") {
legacy = true
javaOpClass = "And"
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.pairwise.bool"
Input(BOOL, "x") { description = "Input 1" }
Input(BOOL, "y") { description = "Input 2" }
Output(BOOL, "output"){ description = "%INPUT_TYPE% with values 0 and 1 based on where the condition is satisfied" }
Doc(Language.ANY, DocScope.ALL){
"""
Boolean AND operation: elementwise (x != 0) && (y != 0)
If x and y arrays have equal shape, the output shape is the same as these inputs.
Note: supports broadcasting if x and y have different shapes and are broadcastable.
Returns an array with values 1 where condition is satisfied, or value 0 otherwise.
""".trimIndent()
}
}
Op("asin", transformStrict) {
javaOpClass = "ASin"
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise asin (arcsin, inverse sine) operation: out = arcsin(x)
""".trimIndent()
}
}
// TODO: There are 2 implementations
Op("asinh", transformStrict) {
javaOpClass = "ASinh"
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise asinh (inverse hyperbolic sine) function: out = asinh(x)
""".trimIndent()
}
}
Op("asum", reduceSame) {
javaOpClass = "ASum"
Doc(Language.ANY, DocScope.ALL){
"""
Absolute sum array reduction operation, optionally along specified dimensions: out = sum(abs(x))
""".trimIndent()
}
}
Op("atan", transformStrict) {
javaOpClass = "ATan"
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise atan (arctangent, inverse tangent) operation: out = arctangent(x)
""".trimIndent()
}
}
Op("atan2") {// TODO: We need to generate a constructor that includes SameDiff().
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
javaOpClass = "ATan2"
Input(NUMERIC, "y") { description = "Input Y variable" }
Input(NUMERIC, "x") { description = "Input X variable" }
Output(NUMERIC, "output"){ description = "Output variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise atan (arctangent, inverse tangent) operation: out = atan2(x,y).
Similar to atan(y/x) but sigts of x and y are used to determine the location of the result
""".trimIndent()
}
}
Op("atanh", transformStrict) {
javaOpClass = "ATanh"
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise atanh (inverse hyperbolic tangent) function: out = atanh(x)
""".trimIndent()
}
}
Op("ceil", transformSame) {
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise ceiling function: out = ceil(x).
Rounds each value up to the nearest integer value (if not already an integer)
""".trimIndent()
}
}
Op("clipByNorm") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.clip"
val x = Input(NUMERIC, "x") { description = "Input variable" }
val clipValue = Arg(NUMERIC, "clipValue") { description = "Clipping value (maximum l2 norm)" }
Arg(INT, "dimensions"){ count = AtLeast(0); description = "Dimensions to reduce over. If dimensions are not specified, full array reduction is performed"} //; defaultValue = intArrayOf(0) } //TODO
Output(NUMERIC, "output"){ description = "Output variable" }
// AllParamSignature(withOutput = false)
// Signature(x, clipValue)
Doc(Language.ANY, DocScope.ALL){
"""
Clipping by L2 norm, optionally along dimension(s)
if l2Norm(x,dimension) < clipValue, then input is returned unmodifed
Otherwise, out[i] = in[i] * clipValue / l2Norm(in, dimensions) where each value is clipped according
to the corresponding l2Norm along the specified dimensions
""".trimIndent()
}
}
Op("clipByValue") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.clip"
javaOpClass = "ClipByValue"
Input(NUMERIC, "x") { description = "Input variable" }
Arg(NUMERIC, "clipValueMin") { description = "Minimum value for clipping" }
Arg(NUMERIC, "clipValueMax") { description = "Maximum value for clipping" }
Output(NUMERIC, "output"){ description = "Output variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise clipping function:
out[i] = in[i] if in[i] >= clipValueMin and in[i] <= clipValueMax
out[i] = clipValueMin if in[i] < clipValueMin
out[i] = clipValueMax if in[i] > clipValueMax
""".trimIndent()
}
}
Op("ClipByAvgNorm") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.clip"
javaOpClass = "ClipByAvgNorm"
Input(NUMERIC, "x") { description = "Input variable" }
Arg(NUMERIC, "clipValue") { description = "Value for clipping" }
Arg(INT, "dimensions"){ count = AtLeast(0); description = "Dimensions to reduce over"}
Output(NUMERIC, "output"){ description = "Output variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Clips tensor values to a maximum average L2-norm.
""".trimIndent()
}
}
//TODO consolidate these confusionMatrix ops into one?
Op("confusionMatrix") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Input(NUMERIC, "labels") { description = "Labels - 1D array of integer values representing label values" }
Input(NUMERIC, "pred") { description = "Predictions - 1D array of integer values representing predictions. Same length as labels" }
Arg(DATA_TYPE, "dataType") { description = "Data type" }
Output(NUMERIC, "output"){ description = "variable (2D, shape [numClasses, numClasses})" }
Doc(Language.ANY, DocScope.ALL){
"""
Compute the 2d confusion matrix of size [numClasses, numClasses] from a pair of labels and predictions, both of
which are represented as integer values. This version assumes the number of classes is 1 + max(max(labels), max(pred))
For example, if labels = [0, 1, 1] and predicted = [0, 2, 1] then output is:
[1, 0, 0]
[0, 1, 1]
[0, 0, 0]
""".trimIndent()
}
}
Op("confusionMatrix") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Input(NUMERIC, "labels") { description = "Labels - 1D array of integer values representing label values" }
Input(NUMERIC, "pred") { description = "Predictions - 1D array of integer values representing predictions. Same length as labels" }
Arg(INT, "numClasses") { description = "Number of classes" }
Output(NUMERIC, "output"){ description = "variable (2D, shape [numClasses, numClasses})" }
Doc(Language.ANY, DocScope.ALL){
"""
Compute the 2d confusion matrix of size [numClasses, numClasses] from a pair of labels and predictions, both of
which are represented as integer values.
For example, if labels = [0, 1, 1], predicted = [0, 2, 1], and numClasses=4 then output is:
[1, 0, 0, 0]
[0, 1, 1, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
""".trimIndent()
}
}
Op("confusionMatrix") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Input(NUMERIC, "labels") { description = "Labels - 1D array of integer values representing label values" }
Input(NUMERIC, "pred") { description = "Predictions - 1D array of integer values representing predictions. Same length as labels" }
Input(NUMERIC, "weights") { description = "Weights - 1D array of values (may be real/decimal) representing the weight/contribution of each prediction. Must be same length as both labels and predictions arrays" }
Output(NUMERIC, "output"){ description = "variable (2D, shape [numClasses, numClasses})" }
Doc(Language.ANY, DocScope.ALL){
"""
Compute the 2d confusion matrix of size [numClasses, numClasses] from a pair of labels and predictions, both of
which are represented as integer values. This version assumes the number of classes is 1 + max(max(labels), max(pred))
For example, if labels = [0, 1, 1], predicted = [0, 2, 1] and weights = [1, 2, 3]
[1, 0, 0]
[0, 3, 2]
[0, 0, 0]
""".trimIndent()
}
}
Op("confusionMatrix") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Input(NUMERIC, "labels") { description = "Labels - 1D array of integer values representing label values" }
Input(NUMERIC, "pred") { description = "Predictions - 1D array of integer values representing predictions. Same length as labels" }
Arg(INT, "numClasses") { description = "" }
Input(NUMERIC, "weights") { description = "Weights - 1D array of values (may be real/decimal) representing the weight/contribution of each prediction. Must be same length as both labels and predictions arrays" }
Output(NUMERIC, "output"){ description = "Output variable (2D, shape [numClasses, numClasses})" }
Doc(Language.ANY, DocScope.ALL){
"""
Compute the 2d confusion matrix of size [numClasses, numClasses] from a pair of labels and predictions, both of
which are represented as integer values.
For example, if labels = [0, 1, 1], predicted = [0, 2, 1], numClasses = 4, and weights = [1, 2, 3]
[1, 0, 0, 0]
[0, 3, 2, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
""".trimIndent()
}
}
Op("cos", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise cosine operation: out = cos(x)
""".trimIndent()
}
}
Op("cosh", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise cosh (hyperbolic cosine) operation: out = cosh(x)
""".trimIndent()
}
}
Op("cosineDistance", reduce3) {
Doc(Language.ANY, DocScope.ALL){
"""
Cosine distance reduction operation. The output contains the cosine distance for each
tensor/subset along the specified dimensions:
out = 1.0 - cosineSimilarity(x,y)
""".trimIndent()
}
}
Op("cosineSimilarity", reduce3) {
Doc(Language.ANY, DocScope.ALL){
"""
Cosine similarity pairwise reduction operation. The output contains the cosine similarity for each tensor/subset
along the specified dimensions:
out = (sum_i x[i] * y[i]) / ( sqrt(sum_i x[i]^2) * sqrt(sum_i y[i]^2)
""".trimIndent()
}
}
Op("countNonZero", reduceLong) {
Doc(Language.ANY, DocScope.ALL){
"""
Count non zero array reduction operation, optionally along specified dimensions: out = count(x != 0)
""".trimIndent()
}
}
Op("countZero", reduceLong) {
Doc(Language.ANY, DocScope.ALL){
"""
Count zero array reduction operation, optionally along specified dimensions: out = count(x == 0)
""".trimIndent()
}
}
Op("cross") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Input(NUMERIC, "a") { description = "First input" }
Input(NUMERIC, "b") { description = "Second input" }
Output(NUMERIC, "output"){ description = "Element-wise cross product" }
Doc(Language.ANY, DocScope.ALL){
"""
Returns the pair-wise cross product of equal size arrays a and b: a x b = ||a||x||b|| sin(theta).
Can take rank 1 or above inputs (of equal shapes), but note that the last dimension must have dimension 3
""".trimIndent()
}
}
Op("cube", transformSame) {
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise cube function: out = x^3
""".trimIndent()
}
}
Op("diag") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Input(NUMERIC, "x") { description = "Input variable" }
Output(NUMERIC, "output"){ description = "Output variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Returns an output variable with diagonal values equal to the specified values; off-diagonal values will be set to 0
For example, if input = [1,2,3], then output is given by:
[ 1, 0, 0]
[ 0, 2, 0]
[ 0, 0, 3]
Higher input ranks are also supported: if input has shape [a,...,R-1] then output[i,...,k,i,...,k] = input[i,...,k].
i.e., for input rank R, output has rank 2R
""".trimIndent()
}
}
Op("diagPart") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Input(NUMERIC, "x") { description = "Input variable" }
Output(NUMERIC, "output"){ description = "Diagonal part of the input" }
Doc(Language.ANY, DocScope.ALL){
"""
Extract the diagonal part from the input array.
If input is
[ 1, 0, 0]
[ 0, 2, 0]
[ 0, 0, 3]
then output is [1, 2, 3].
Supports higher dimensions: in general, out[i,...,k] = in[i,...,k,i,...,k]
""".trimIndent()
}
}
Op("div", transformArithmetic){
javaOpClass = "DivOp"
Doc(Language.ANY, DocScope.ALL){
"""
Pairwise division operation, out = x / y
""".trimIndent()
}
useMixin(broadcastingDoc)
}
Op("div", scalar){
javaOpClass = "ScalarDivision"
Doc(Language.ANY, DocScope.ALL){
"""
Scalar division operation, out = in / scalar
""".trimIndent()
}
}
Op("entropy", reduceFloating) {
Doc(Language.ANY, DocScope.ALL){
"""
Entropy reduction: -sum(x * log(x))
""".trimIndent()
}
}
Op("erf", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise Gaussian error function - out = erf(in)
""".trimIndent()
}
}
Op("erfc", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise complementary Gaussian error function - out = erfc(in) = 1 - erf(in)
""".trimIndent()
}
}
Op("euclideanDistance", reduce3) {
Doc(Language.ANY, DocScope.ALL){
"""
Euclidean distance (l2 norm, l2 distance) reduction operation. The output contains the Euclidean distance for each
tensor/subset along the specified dimensions:
out = sqrt( sum_i (x[i] - y[i])^2 )
""".trimIndent()
}
}
Op("exp", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise exponent function: out = exp(x) = 2.71828...^x
""".trimIndent()
}
}
Op("expm1", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise 1.0 - exponent function: out = 1.0 - exp(x) = 1.0 - 2.71828...^x
""".trimIndent()
}
}
//TODO consolidate eye ops into one and use different signatures?
Op("eye") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Arg(INT, "rows") { description = "Number of rows" }
Output(NUMERIC, "output"){ description = "Identity matrix" }
Doc(Language.ANY, DocScope.ALL){
"""
Generate an identity matrix with the specified number of rows and columns.
""".trimIndent()
}
}
Op("eye") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Arg(INT, "rows") { description = "Number of rows" }
Arg(INT, "cols") { description = "Number of columns" }
Output(NUMERIC, "output"){ description = "" }
Doc(Language.ANY, DocScope.ALL){
"""
As per eye(String, int, int, DataType) but with the default datatype, Eye.DEFAULT_DTYPE
""".trimIndent()
}
}
Op("eye") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Arg(INT, "rows") { description = "Number of rows" }
Arg(INT, "cols") { description = "Number of columns" }
Arg(DATA_TYPE, "dataType") { description = "Data type" } //TODO: Mapped DataType to INT.
Arg(DataType.INT, "dimensions"){ count = AtLeast(0)}
Output(NUMERIC, "output"){ description = "Identity matrix" }
Doc(Language.ANY, DocScope.ALL){
"""
Generate an identity matrix with the specified number of rows and columns
Example:
<pre>
{@code %INPUT_TYPE% eye = eye(3,2)
eye:
[ 1, 0]
[ 0, 1]
[ 0, 0]}
</pre>
""".trimIndent()
}
}
Op("eye") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Input(INT, "rows") { description = "Number of rows" }
Input(INT, "cols") { description = "Number of columns" }
Output(NUMERIC, "output"){ description = "Identity matrix" }
Doc(Language.ANY, DocScope.ALL){
"""
As per eye(int, int) bit with the number of rows/columns specified as scalar %INPUT_TYPE%s
""".trimIndent()
}
}
Op("eye") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Input(INT, "rows") { description = "Number of rows" }
Output(NUMERIC, "output"){ description = "SDVaribable identity matrix" }
Doc(Language.ANY, DocScope.ALL){
"""
As per eye(String, int) but with the number of rows specified as a scalar %INPUT_TYPE%
""".trimIndent()
}
}
Op("firstIndex", indexAccum, keepSignatures=false) {
var c = Arg(CONDITION, "condition") { description = "Condition to check on input variable" }
Signature(this.inputs.get(0), c, this.args.get(1)) //in, condition, dimensions - for vararg
Signature(this.inputs.get(0), c, this.args.get(0), this.args.get(1)) //in, condition, keepDims, dimensions
Doc(Language.ANY, DocScope.ALL){
"""
First index reduction operation.
Returns a variable that contains the index of the first element that matches the specified condition (for each
slice along the specified dimensions)
Note that if keepDims = true, the output variable has the same rank as the input variable,
with the reduced dimensions having size 1. This can be useful for later broadcast operations (such as subtracting
the mean along a dimension).
Example: if input has shape [a,b,c] and dimensions=[1] then output has shape:
keepDims = true: [a,1,c]
keepDims = false: [a,c]
""".trimIndent()
}
}
Op("floor", transformSame) {
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise floor function: out = floor(x).
Rounds each value down to the nearest integer value (if not already an integer)
""".trimIndent()
}
}
Op("floorDiv", transformArithmetic){
javaOpClass = "FloorDivOp"
Doc(Language.ANY, DocScope.ALL){
"""
Pairwise floor division operation, out = floor(x / y)
""".trimIndent()
}
useMixin(broadcastingDoc)
}
Op("floorMod", transformArithmetic){
javaOpClass = "FloorModOp"
Doc(Language.ANY, DocScope.ALL){
"""
Pairwise Modulus division operation
""".trimIndent()
}
useMixin(broadcastingDoc)
}
Op("floorMod", scalar){
javaOpClass = "ScalarFMod"
Doc(Language.ANY, DocScope.ALL){
"""
Scalar floor modulus operation
""".trimIndent()
}
}
Op("hammingDistance", reduce3) {
Doc(Language.ANY, DocScope.ALL){
"""
Hamming distance reduction operation. The output contains the cosine distance for each
tensor/subset along the specified dimensions:
out = count( x[i] != y[i] )
""".trimIndent()
}
}
Op("iamax", indexAccumCustom) {
javaOpClass = "ArgMax"
//Signature(in, dimensions)
Doc(Language.ANY, DocScope.ALL){
"""
Index of the max absolute value: argmax(abs(in))
see argmax(String, %INPUT_TYPE%, boolean, int...)
""".trimIndent()
}
}
Op("iamin", indexAccumCustom) {
javaOpClass = "ArgMin"
Doc(Language.ANY, DocScope.ALL){
"""
Index of the min absolute value: argmin(abs(in))
see argmin(String, %INPUT_TYPE%, boolean, int...)
""".trimIndent()
}
}
Op("isFinite", transformBool) {
Doc(Language.ANY, DocScope.ALL){
"""
Is finite operation: elementwise isFinite(x)
Returns an array with the same shape/size as the input, with values 1 where condition is satisfied, or
value 0 otherwise
""".trimIndent()
}
}
Op("isInfinite", transformBool) {
javaOpClass = "IsInf"
Doc(Language.ANY, DocScope.ALL){
"""
Is infinite operation: elementwise isInfinite(x)
Returns an array with the same shape/size as the input, with values 1 where condition is satisfied, or
value 0 otherwise
""".trimIndent()
}
}
Op("isMax", transformAny) {
legacy = false
Doc(Language.ANY, DocScope.ALL){
"""
Is maximum operation: elementwise x == max(x)
Returns an array with the same shape/size as the input, with values 1 where condition is satisfied, or
value 0 otherwise
""".trimIndent()
}
}
Op("isNaN", transformBool) {
Doc(Language.ANY, DocScope.ALL){
"""
Is Not a Number operation: elementwise isNaN(x)
Returns an array with the same shape/size as the input, with values 1 where condition is satisfied, or
value 0 otherwise
""".trimIndent()
}
}
Op("isNonDecreasing") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
Input(NUMERIC, "x") { description = "Input variable" }
Output(NUMERIC, "output"){ description = "Scalar variable with value 1 if non-decreasing, or 0 otherwise" }
Doc(Language.ANY, DocScope.ALL){
"""
Is the array non decreasing?
An array is non-decreasing if for every valid i, x[i] <= x[i+1]. For Rank 2+ arrays, values are compared
in 'c' (row major) order
""".trimIndent()
}
}
Op("isStrictlyIncreasing") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
Input(NUMERIC, "x") { description = "Input variable" }
Output(NUMERIC, "output"){ description = "Scalar variable with value 1 if strictly increasing, or 0 otherwise" }
Doc(Language.ANY, DocScope.ALL){
"""
Is the array strictly increasing?
An array is strictly increasing if for every valid i, x[i] < x[i+1]. For Rank 2+ arrays, values are compared
in 'c' (row major) order
""".trimIndent()
}
}
Op("jaccardDistance", reduce3) {
Doc(Language.ANY, DocScope.ALL){
"""Jaccard similarity reduction operation. The output contains the Jaccard distance for each
tensor along the specified dimensions.
""".trimIndent()
}
}
Op("lastIndex", indexAccum, keepSignatures=false) {
var c = Arg(CONDITION, "condition") { description = "Condition to check on input variable" }
Signature(this.inputs.get(0), c, this.args.get(1)) //in, condition, dimensions - for vararg
Signature(this.inputs.get(0), c, this.args.get(0), this.args.get(1)) //in, condition, keepDims, dimensions
Doc(Language.ANY, DocScope.ALL){
"""
Last index reduction operation.
Returns a variable that contains the index of the last element that matches the specified condition (for each
slice along the specified dimensions)
Note that if keepDims = true, the output variable has the same rank as the input variable,
with the reduced dimensions having size 1. This can be useful for later broadcast operations (such as subtracting
the mean along a dimension).
Example: if input has shape [a,b,c] and dimensions=[1] then output has shape:
keepDims = true: [a,1,c]
keepDims = false: [a,c]
""".trimIndent()
}
}
Op("log", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise logarithm function (base e - natural logarithm): out = log(x)
""".trimIndent()
}
}
Op("log", transformStrict) {
javaOpClass = "LogX"
javaPackage = "org.nd4j.linalg.api.ops.impl.scalar"
Arg(NUMERIC, "base") { description = "Logarithm base" }
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise logarithm function (with specified base): out = log_{base}(x)
""".trimIndent()
}
}
Op("log1p", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise natural logarithm function: out = log_e (1 + x)
""".trimIndent()
}
}
Op("logEntropy", reduceFloating) {
Doc(Language.ANY, DocScope.ALL){
"""
Log entropy reduction: log(-sum(x * log(x)))
""".trimIndent()
}
}
Op("logSumExp") {
javaPackage = "org.nd4j.linalg.api.ops.impl.reduce.custom"
Input(NUMERIC, "input") { description = "Input variable" }
Arg(INT, "dimensions"){ count = AtLeast(0); description = "Optional dimensions to reduce along" }
Output(NUMERIC, "output"){ description = "Output variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Log-sum-exp reduction (optionally along dimension).
Computes log(sum(exp(x))
""".trimIndent()
}
}
Op("manhattanDistance", reduce3) {
Doc(Language.ANY, DocScope.ALL){
"""
Manhattan distance (l1 norm, l1 distance) reduction operation. The output contains the Manhattan distance for each
tensor/subset along the specified dimensions:
out = sum_i abs(x[i]-y[i])
""".trimIndent()
}
}
Op("matrixDeterminant") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
Input(NUMERIC, "in") { description = "Input" }
Output(NUMERIC, "output"){ description = "Matrix determinant variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Matrix determinant op. For 2D input, this returns the standard matrix determinant.
For higher dimensional input with shape [..., m, m] the matrix determinant is returned for each
shape [m,m] sub-matrix.
""".trimIndent()
}
}
Op("matrixInverse") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
Input(NUMERIC, "in") { description = "Input" }
Output(NUMERIC, "output"){ description = "Matrix inverse variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Matrix inverse op. For 2D input, this returns the standard matrix inverse.
For higher dimensional input with shape [..., m, m] the matrix inverse is returned for each
shape [m,m] sub-matrix.
""".trimIndent()
}
}
Op("reduceMax", reduceSame) {
javaOpClass = "Max"
Doc(Language.ANY, DocScope.ALL){
"""
The max of an array along each dimension
""".trimIndent()
}
}
Op("reduceMax", reduceSameVariable) {
javaOpClass = "Max"
Doc(Language.ANY, DocScope.ALL) {
"""
The max of an array long each dimension
""".trimIndent()
}
}
Op("mean", reduceFloating) {
javaOpClass = "Mean"
Doc(Language.ANY, DocScope.ALL){
"""
Mean array reduction operation, optionally along specified dimensions: out = mean(abs(x))
""".trimIndent()
}
}
Op("mean", reduceFloatingVariable) {
javaOpClass = "Mean"
Doc(Language.ANY, DocScope.ALL){
"""
Mean array reduction operation, optionally along specified dimensions: out = mean(abs(x))
""".trimIndent()
}
}
Op("reduceMin", reduceSame) {
javaOpClass = "Min"
Doc(Language.ANY, DocScope.ALL){
"""
The minimum of an array along each dimension
""".trimIndent()
}
}
Op("reduceMin", reduceSameVariable) {
javaOpClass = "Min"
Doc(Language.ANY, DocScope.ALL) {
"""
The minimum of an array long each dimension
""".trimIndent()
}
}
Op("mergeAdd") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.pairwise.arithmetic"
javaOpClass = "MergeAddOp"
Input(NUMERIC, "inputs"){ count = AtLeast(1); description = "Input variables" }
Output(NUMERIC, "output"){ description = "Output variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Merge add function: merges an arbitrary number of equal shaped arrays using element-wise addition:
out = sum_i in[i]
""".trimIndent()
}
}
Op("mergeAvg") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Input(NUMERIC, "inputs"){ count = AtLeast(1); description = "Input variables" }
Output(NUMERIC, "output"){ description = "Output variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Merge average function: merges an arbitrary number of equal shaped arrays using element-wise mean operation:
out = mean_i in[i]
""".trimIndent()
}
}
Op("mergeMax") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
Input(NUMERIC, "inputs"){ count = AtLeast(1); description = "Input variables" }
Output(NUMERIC, "output"){ description = "Output variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Merge max function: merges an arbitrary number of equal shaped arrays using element-wise maximum operation:
out = max_i in[i]
""".trimIndent()
}
}
Op("mod", transformArithmetic){
javaOpClass = "ModOp"
Doc(Language.ANY, DocScope.ALL){
"""
Pairwise modulus (remainder) operation, out = x % y
""".trimIndent()
}
useMixin(broadcastingDoc)
}
Op("moments") {
javaPackage = "org.nd4j.linalg.api.ops.impl.reduce"
Input(NUMERIC, "input") { description = "Input to calculate moments for" }
Arg(INT, "axes"){ count = AtLeast(0); description = "Dimensions to perform calculation over" }
Arg(BOOL,"keepDims") { description = "Whether to keep dimensions during reduction or not. "}
Output(NUMERIC, "output_mean"){ description = "Mean variable" }
Output(NUMERIC, "output_variance"){ description = "Variance variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Calculate the mean and (population) variance for the input variable, for the specified axis
""".trimIndent()
}
}
Op("moments") {
javaPackage = "org.nd4j.linalg.api.ops.impl.reduce"
Input(NUMERIC, "input") { description = "Input to calculate moments for" }
Input(NUMERIC, "axes"){ description = "Dimensions to perform calculation over" }
Arg(BOOL,"keepDims") { description = "Whether to keep dimensions during reduction or not. "}
Output(NUMERIC, "output_mean"){ description = "Mean variable" }
Output(NUMERIC, "output_variance"){ description = "Variance variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Calculate the mean and (population) variance for the input variable, for the specified axis
""".trimIndent()
}
}
Op("neg", transformSame) {
javaOpClass = "Negative"
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise negative operation: out = -x
""".trimIndent()
}
}
Op("normalizeMoments") {
javaPackage = "org.nd4j.linalg.api.ops.impl.reduce"
Input(NUMERIC, "counts") { description = "Rank 0 (scalar) value with the total number of values used to calculate the sufficient statistics" }
Input(NUMERIC, "means") { description = "Mean-value sufficient statistics: this is the SUM of all data values" }
Input(NUMERIC, "variances") { description = "Variaance sufficient statistics: this is the squared sum of all data values" }
Arg(NUMERIC, "shift") { description = "Shift value, possibly 0, used when calculating the sufficient statistics (for numerical stability)" }
Output(NUMERIC, "output_mean"){ description = "Mean variable" }
Output(NUMERIC, "output_population"){ description = "Population variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Calculate the mean and variance from the sufficient statistics
""".trimIndent()
}
}
Op("norm1", reduceFloating) {
javaOpClass = "Norm1"
Doc(Language.ANY, DocScope.ALL){
"""
Mean array reduction operation, optionally along specified dimensions: out = mean(abs(x))
""".trimIndent()
}
}
Op("norm1", reduceFloatingVariable) {
javaOpClass = "Norm1"
Doc(Language.ANY, DocScope.ALL){
"""
Sum of absolute differences.
""".trimIndent()
}
}
Op("norm2", reduceFloating) {
javaOpClass = "Norm2"
Doc(Language.ANY, DocScope.ALL){
"""
Euclidean norm: euclidean distance of a vector from the origin
""".trimIndent()
}
}
Op("norm2", reduceFloatingVariable) {
javaOpClass = "Norm2"
Doc(Language.ANY, DocScope.ALL){
"""
Euclidean norm: euclidean distance of a vector from the origin
""".trimIndent()
}
}
Op("normMax", reduceFloating) {
javaOpClass = "NormMax"
Doc(Language.ANY, DocScope.ALL){
"""
Differences between max absolute value
""".trimIndent()
}
}
Op("normMax", reduceFloatingVariable) {
javaOpClass = "NormMax"
Doc(Language.ANY, DocScope.ALL){
"""
Differences between max absolute value
""".trimIndent()
}
}
Op("or") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.pairwise.bool"
Input(BOOL, "x") { description = "Input 1" }
Input(BOOL, "y") { description = "Input 2" }
Output(BOOL, "output"){ description = "%INPUT_TYPE% with values 0 and 1 based on where the condition is satisfied" }
legacy = true
Doc(Language.ANY, DocScope.ALL){
"""
Boolean OR operation: elementwise (x != 0) || (y != 0)
If x and y arrays have equal shape, the output shape is the same as these inputs.
Note: supports broadcasting if x and y have different shapes and are broadcastable.
Returns an array with values 1 where condition is satisfied, or value 0 otherwise.
""".trimIndent()
}
}
Op("pow", scalar) {
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise power function: out = x^value
""".trimIndent()
}
}
Op("pow") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
Input(NUMERIC, "x") { description = "Input variable" }
Input(NUMERIC, "y") { description = "Power" }
Output(NUMERIC, "output"){ description = "Output variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise (broadcastable) power function: out = x[i]^y[i]
""".trimIndent()
}
}
Op("prod", reduceSame) {
javaOpClass = "Prod"
Doc(Language.ANY, DocScope.ALL){
"""
The max of an array along each dimension
""".trimIndent()
}
}
Op("prod", reduceSameVariable) {
javaOpClass = "Prod"
Doc(Language.ANY, DocScope.ALL) {
"""
The product of an array long each dimension
""".trimIndent()
}
}
Op("rationalTanh", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Rational Tanh Approximation elementwise function, as described in the paper:
Compact Convolutional Neural Network Cascade for Face Detection
This is a faster Tanh approximation
""".trimIndent()
}
}
Op("rectifiedTanh", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Rectified tanh operation: max(0, tanh(in))
""".trimIndent()
}
}
Op("reciprocal", transformSame) {
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise reciprocal (inverse) function: out[i] = 1 / in[i]
""".trimIndent()
}
}
Op("rdiv", transformArithmetic){
javaOpClass = "RDivOp"
Doc(Language.ANY, DocScope.ALL){
"""
Pairwise reverse division operation, out = y / x
""".trimIndent()
}
useMixin(broadcastingDoc)
}
Op("rdiv", scalar){
javaOpClass = "ScalarReverseDivision"
Doc(Language.ANY, DocScope.ALL){
"""
Scalar reverse division operation, out = scalar / in
""".trimIndent()
}
}
Op("round", transformSame) {
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise round function: out = round(x).
Rounds (up or down depending on value) to the nearest integer value.
""".trimIndent()
}
}
Op("rsqrt", transformFloating) {
javaOpClass = "RSqrt"
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise reciprocal (inverse) of square root: out = 1.0 / sqrt(x)
""".trimIndent()
}
}
Op("rsub", transformArithmetic){
javaOpClass = "RSubOp"
Doc(Language.ANY, DocScope.ALL){
"""
Pairwise reverse subtraction operation, out = y - x
""".trimIndent()
}
useMixin(broadcastingDoc)
}
Op("rsub", scalar){
javaOpClass = "ScalarReverseSubtraction"
Doc(Language.ANY, DocScope.ALL){
"""
Scalar reverse subtraction operation, out = scalar - in
""".trimIndent()
}
}
Op("setDiag") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
javaOpClass = "MatrixSetDiag"
Input(NUMERIC, "in") { description = "Input variable" }
Input(NUMERIC, "diag") { description = "Diagonal" }
Output(NUMERIC, "output"){ description = "Output variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Set the diagonal value to the specified values
If input is
[ a, b, c]
[ d, e, f]
[ g, h, i]
and diag = [ 1, 2, 3] then output is
[ 1, b, c]
[ d, 2, f]
[ g, h, 3]
""".trimIndent()
}
}
Op("shannonEntropy", reduceFloating) {
Doc(Language.ANY, DocScope.ALL){
"""
Shannon Entropy reduction: -sum(x * log2(x))
""".trimIndent()
}
}
Op("shannonEntropy", reduceFloatingVariable) {
Doc(Language.ANY, DocScope.ALL){
"""
Shannon Entropy reduction: -sum(x * log2(x))
""".trimIndent()
}
}
Op("sign", transformSame) {
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise sign (signum) function:
out = -1 if in < 0
out = 0 if in = 0
out = 1 if in > 0
""".trimIndent()
}
}
Op("sin", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise sine operation: out = sin(x)
""".trimIndent()
}
}
Op("sinh", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise sinh (hyperbolic sine) operation: out = sinh(x)
""".trimIndent()
}
}
Op("sqrt", transformFloating) {
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise square root function: out = sqrt(x)
""".trimIndent()
}
}
Op("square", transformSame) {
Doc(Language.ANY, DocScope.ALL){
"""
Element-wise square function: out = x^2
""".trimIndent()
}
}
Op("squaredDifference", transformArithmetic) {
javaOpClass = "SquaredDifferenceOp"
Doc(Language.ANY, DocScope.ALL){
"""
Pairwise squared difference operation.
""".trimIndent()
}
useMixin(broadcastingDoc)
}
Op("squaredNorm", reduceFloating) {
javaOpClass = "SquaredNorm"
Doc(Language.ANY, DocScope.ALL){
"""
Sum of squared differences.
""".trimIndent()
}
}
Op("squaredNorm", reduceFloatingVariable) {
javaOpClass = "SquaredNorm"
Doc(Language.ANY, DocScope.ALL){
"""
Sum of squared differences.
""".trimIndent()
}
}
Op("step", scalar) {
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise step function:
out(x) = 1 if x >= cutoff
out(x) = 0 otherwise
""".trimIndent()
}
}
Op("standardize") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
Input(NUMERIC, "x") { description = "Input variable" }
Arg(INT, "dimensions"){ count = AtLeast(1); description = "" } //TODO: Missing description for dimension.
Output(NUMERIC, "output"){ description = "Output variable" }
Doc(Language.ANY, DocScope.ALL){
"""
Standardize input variable along given axis
<p>
out = (x - mean) / stdev
<p>
with mean and stdev being calculated along the given dimension.
<p>
For example: given x as a mini batch of the shape [numExamples, exampleLength]:
<ul>
<li>use dimension 1 too use the statistics (mean, stdev) for each example</li>
<li>use dimension 0 if you want to use the statistics for each column across all examples</li>
<li>use dimensions 0,1 if you want to use the statistics across all columns and examples</li>
</ul>
""".trimIndent()
}
}
Op("sub", transformArithmetic){
javaOpClass = "SubOp"
Doc(Language.ANY, DocScope.ALL){
"""
Pairwise subtraction operation, out = x - y
""".trimIndent()
}
useMixin(broadcastingDoc)
}
Op("sub", scalar){
javaOpClass = "ScalarSubtraction"
Doc(Language.ANY, DocScope.ALL){
"""
Scalar subtraction operation, out = in - scalar
""".trimIndent()
}
}
Op("sum", reduceSame) {
javaOpClass = "Sum"
Doc(Language.ANY, DocScope.ALL){
"""
Sum of an array, optionally along specified dimensions: out = sum(x))
""".trimIndent()
}
}
Op("sum", reduceSameVariable) {
javaOpClass = "Sum"
Doc(Language.ANY, DocScope.ALL) {
"""
Sum of an array, optionally along specified dimensions: out = sum(x))
""".trimIndent()
}
}
Op("tan", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise tangent operation: out = tan(x)
""".trimIndent()
}
}
Op("tanh", transformStrict) {
Doc(Language.ANY, DocScope.ALL){
"""
Elementwise tanh (hyperbolic tangent) operation: out = tanh(x)
""".trimIndent()
}
}
Op("trace") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
Input(NUMERIC, "in") { description = "Input variable" }
Output(NUMERIC, "output"){ description = "Trace" }
Doc(Language.ANY, DocScope.ALL){
"""
Matrix trace operation
For rank 2 matrices, the output is a scalar with the trace - i.e., sum of the main diagonal.
For higher rank inputs, output[a,b,c] = trace(in[a,b,c,:,:])
""".trimIndent()
}
}
Op("xor") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.pairwise.bool"
legacy = true
Input(BOOL, "x") { description = "Input 1" }
Input(BOOL, "y") { description = "Input 2" }
Output(BOOL, "output"){ description = "%INPUT_TYPE% with values 0 and 1 based on where the condition is satisfied" }
Doc(Language.ANY, DocScope.ALL){
"""
Boolean XOR (exclusive OR) operation: elementwise (x != 0) XOR (y != 0)
If x and y arrays have equal shape, the output shape is the same as these inputs.
Note: supports broadcasting if x and y have different shapes and are broadcastable.
Returns an array with values 1 where condition is satisfied, or value 0 otherwise.
""".trimIndent()
}
}
Op("zeroFraction") {
javaPackage = "org.nd4j.linalg.api.ops.impl.reduce"
Input(NUMERIC, "input") { description = "Input variable" }
Output(NUMERIC, "output"){ description = "Reduced array of rank 0 (scalar)" }
Doc(Language.ANY, DocScope.ALL){
"""
Full array zero fraction array reduction operation, optionally along specified dimensions: out = (count(x == 0) / length(x))
""".trimIndent()
}
}
Op("listDiff") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
Input(NUMERIC, "x") { description = "Input variable X" }
Input(NUMERIC, "y") { description = "Input variable Y" }
Output(NUMERIC, "output1"){ description = "Calculated difference between X and Y" }
Output(NUMERIC, "output2"){ description = "Calculated difference between X and Y" }
Doc(Language.ANY, DocScope.ALL){
"""
Calculates difference between inputs X and Y.
""".trimIndent()
}
}
Op("max", transformCustom2){
javaOpClass = "Max"
Doc(Language.ANY, DocScope.ALL){
"""
Pairwise max operation, out = max(x, y)
""".trimIndent()
}
useMixin(broadcastingDoc)
}
Op("meshgrid") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
javaOpClass = "MeshGrid"
Arg(BOOL, "cartesian")
Input(NUMERIC, "inputs") { count = AtLeast(0) }
Output(NUMERIC, "output1"){ description = "Output array" }
Output(NUMERIC, "output2"){ description = "Output array" }
Doc(Language.ANY, DocScope.ALL){
"""
Broadcasts parameters for evaluation on an N-D grid.
""".trimIndent()
}
}
Op("min", transformCustom2){
javaOpClass = "Min"
Doc(Language.ANY, DocScope.ALL){
"""
Pairwise max operation, out = min(x, y)
""".trimIndent()
}
useMixin(broadcastingDoc)
}
Op("mul", transformArithmetic){
javaOpClass = "MulOp"
Doc(Language.ANY, DocScope.ALL){
"""
Pairwise multiplication operation, out = x * y
""".trimIndent()
}
useMixin(broadcastingDoc)
}
Op("mul", scalar){
javaOpClass = "ScalarMultiplication"
Doc(Language.ANY, DocScope.ALL){
"""
Scalar multiplication operation, out = in * scalar
""".trimIndent()
}
}
Op("bitShift") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
javaOpClass = "ShiftBits"
Input(NUMERIC, "x") {description = "input"}
Input(NUMERIC, "shift") {description = "shift value"}
Output(NUMERIC, "output") {description = "shifted output"}
Doc(Language.ANY, DocScope.ALL){
"""
Bit shift operation
""".trimIndent()
}
}
Op("bitShiftRight") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
javaOpClass = "RShiftBits"
Input(NUMERIC, "x") {description = "Input tensor"}
Input(NUMERIC, "shift") {description = "shift argument"}
Output(NUMERIC, "output") {description = "shifted output"}
Doc(Language.ANY, DocScope.ALL){
"""
Right bit shift operation
""".trimIndent()
}
}
Op("bitShiftRotl") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
javaOpClass = "CyclicShiftBits"
Input(NUMERIC, "x") {description = "Input tensor"}
Input(NUMERIC, "shift") {description = "shift argy=ument"}
Output(NUMERIC, "output") {description = "shifted output"}
Doc(Language.ANY, DocScope.ALL){
"""
Cyclic bit shift operation
""".trimIndent()
}
}
Op("bitShiftRotr") {
javaPackage = "org.nd4j.linalg.api.ops.impl.transforms.custom"
javaOpClass = "CyclicRShiftBits"
Input(NUMERIC, "x") {description = "Input tensor"}
Input(NUMERIC, "shift") {description = "Shift argument"}
Output(NUMERIC, "output") {description = "Shifted output"}
Doc(Language.ANY, DocScope.ALL){
"""
Cyclic right shift operation
""".trimIndent()
}
}
Op("EmbeddingLookup") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape.tensorops"
javaOpClass = "EmbeddingLookup"
Input(NUMERIC, "x") {description = "Input tensor"}
Input(INT, "indices") {count = AtLeast(1); description = "A Tensor containing the ids to be looked up."}
Arg(ENUM, "PartitionMode") { possibleValues = listOf( "MOD","DIV"); description ="partition_mode == 0 - i.e. 'mod' , 1 - 'div'"}
Output(NUMERIC, "output") {description = "Shifted output"}
Doc(Language.ANY, DocScope.ALL){
"""
Looks up ids in a list of embedding tensors.
""".trimIndent()
}
}
Op("MergeMaxIndex") {
javaPackage = "org.nd4j.linalg.api.ops.impl.shape"
javaOpClass = "MergeMaxIndex"
Input(NUMERIC, "x") {count = AtLeast(1); description = "Input tensor"}
Arg(DATA_TYPE, "dataType") { description = "Data type"; defaultValue = org.nd4j.linalg.api.buffer.DataType.INT }
Output(INT, "output") {description = "Array max elements indices with along dimensions."}
Doc(Language.ANY, DocScope.ALL){
"""
Return array of max elements indices with along tensor dimensions
""".trimIndent()
}
}
} | apache-2.0 | 061ffab74fd1f123362e6bd1291dfc5f | 35.179551 | 219 | 0.543709 | 4.275158 | false | false | false | false |
philo-dragon/CoolWeather-kotlin | app/src/main/java/com/pfl/coolweather/service/AutoUpdateService.kt | 1 | 3359 | package com.pfl.coolweather.service
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.IBinder
import android.os.SystemClock
import android.preference.PreferenceManager
import android.support.annotation.IntDef
import com.pfl.coolweather.db.Weather
import com.pfl.coolweather.util.HttpUtil
import com.pfl.coolweather.util.Utility
import java.io.IOException
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
class AutoUpdateService : Service() {
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
updateWeather()
updateBingPic()
val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val anHour = 8 * 60 * 60 * 1000
val triggerAtTime = SystemClock.elapsedRealtime() + anHour
val i = Intent(this, AutoUpdateService::class.java)
val pendingIntent = PendingIntent.getService(this, 0, i, 0)
manager.cancel(pendingIntent)
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pendingIntent)
return super.onStartCommand(intent, flags, startId)
}
/**
* 更新天气信息
*/
private fun updateWeather() {
val prefs = PreferenceManager.getDefaultSharedPreferences(this)
val weaterString = prefs.getString("weater", null)
if (null != weaterString) {
val weather = Utility.handleWeatherResponse(weaterString)
val weatherId = weather!!.basic!!.id
val weatherUrl = "http://guolin.tech/api/weather?cityid=$weatherId&key=0dff9c2f64ca467088a0853001b26d4d"
HttpUtil.sendOkHttpRequest(weatherUrl, object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val responseText = response.body().string()
val weather = Utility.handleWeatherResponse(responseText)
if (null != weather && "ok" == weather.status) {
val editor = PreferenceManager.getDefaultSharedPreferences(this@AutoUpdateService).edit()
editor.putString("weather", responseText)
editor.apply()
}
}
})
}
}
/**
* 更新每日一图
*/
private fun updateBingPic() {
val weatherUrl = "http://guolin.tech/api/bing_pic"
HttpUtil.sendOkHttpRequest(weatherUrl, object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val bingPic = response.body().string()
val editor = PreferenceManager.getDefaultSharedPreferences(this@AutoUpdateService).edit()
editor.putString("bing_pic", bingPic)
editor.apply()
}
})
}
}
| apache-2.0 | 4336ad8f6534bcd133a9e5f1b0667bb8 | 31.696078 | 116 | 0.632984 | 4.664336 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/stats/dto/StatsReach.kt | 1 | 2354 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.stats.dto
import com.google.gson.annotations.SerializedName
import kotlin.Int
import kotlin.collections.List
/**
* Reach stats
* @param age
* @param cities
* @param countries
* @param mobileReach - Reach count from mobile devices
* @param reach - Reach count
* @param reachSubscribers - Subscribers reach count
* @param sex
* @param sexAge
*/
data class StatsReach(
@SerializedName("age")
val age: List<StatsSexAge>? = null,
@SerializedName("cities")
val cities: List<StatsCity>? = null,
@SerializedName("countries")
val countries: List<StatsCountry>? = null,
@SerializedName("mobile_reach")
val mobileReach: Int? = null,
@SerializedName("reach")
val reach: Int? = null,
@SerializedName("reach_subscribers")
val reachSubscribers: Int? = null,
@SerializedName("sex")
val sex: List<StatsSexAge>? = null,
@SerializedName("sex_age")
val sexAge: List<StatsSexAge>? = null
)
| mit | 10877195e1a2cd56effd559bd7da1f63 | 36.967742 | 81 | 0.680544 | 4.303473 | false | false | false | false |
pbauerochse/youtrack-worklog-viewer | application/src/main/java/de/pbauerochse/worklogviewer/timereport/fx/table/columns/context/ContextMenuItems.kt | 1 | 3073 | package de.pbauerochse.worklogviewer.timereport.fx.table.columns.context
import de.pbauerochse.worklogviewer.details.events.ShowIssueDetailsRequestEvent
import de.pbauerochse.worklogviewer.events.EventBus
import de.pbauerochse.worklogviewer.favourites.FavouritesService
import de.pbauerochse.worklogviewer.favourites.fx.FavouritesModel
import de.pbauerochse.worklogviewer.openInBrowser
import de.pbauerochse.worklogviewer.timereport.Issue
import de.pbauerochse.worklogviewer.util.FormattingUtil.getFormatted
import de.pbauerochse.worklogviewer.workitem.add.fx.AddWorkItemDialog
import javafx.beans.binding.Bindings
import javafx.beans.binding.Bindings.`when`
import javafx.event.EventHandler
import javafx.scene.Scene
import javafx.scene.control.MenuItem
import org.slf4j.LoggerFactory
import java.time.LocalDate
class OpenIssueInBrowserMenuItem(issue: Issue) : MenuItem(getFormatted("contextmenu.issue.openinyoutrack", issue.humanReadableId)) {
init {
onAction = EventHandler { issue.externalUrl.openInBrowser() }
}
}
class OpenIssueInDetailsPaneMenuItem(issue: Issue) : MenuItem(getFormatted("contextmenu.issue.openindetails", issue.humanReadableId)) {
init {
onAction = EventHandler { EventBus.publish(ShowIssueDetailsRequestEvent(issue)) }
}
}
class AddWorkItemToIssueMenuItem(private val issue: Issue, private val date: LocalDate = LocalDate.now(), private val sceneProvider: () -> Scene) :
MenuItem(getFormatted("contextmenu.issue.addworkitem", issue.humanReadableId)) {
init {
onAction = EventHandler { showAddWorkItemToIssueDialog() }
}
internal fun showAddWorkItemToIssueDialog() {
AddWorkItemDialog.show(sceneProvider.invoke(), date, issue)
}
}
class AddWorkItemToOtherIssueMenuItem(date: LocalDate = LocalDate.now(), private val sceneProvider: () -> Scene) : MenuItem(getFormatted("contextmenu.issue.addanyworkitem")) {
init {
onAction = EventHandler { AddWorkItemDialog.show(sceneProvider.invoke(), date) }
}
}
class ToggleFavouriteMenuItem(issue: Issue) : MenuItem() {
init {
val issueAlreadyMarkedAsFavourite = Bindings.createBooleanBinding({ FavouritesService.isFavourite(issue) }, FavouritesModel.favouriteIssues)
textProperty().bind(
`when`(issueAlreadyMarkedAsFavourite)
.then(getFormatted("contextmenu.issue.removefavourite", issue.humanReadableId))
.otherwise(
getFormatted("contextmenu.issue.addfavourite", issue.humanReadableId)
)
)
onAction = EventHandler {
if (issueAlreadyMarkedAsFavourite.get()) {
LoggerFactory.getLogger(ToggleFavouriteMenuItem::class.java).info("Removing ${issue.humanReadableId} from Favourites")
FavouritesService.removeFavourite(issue)
} else {
LoggerFactory.getLogger(ToggleFavouriteMenuItem::class.java).info("Marking ${issue.humanReadableId} as Favourite")
FavouritesService.addFavourite(issue)
}
}
}
}
| mit | daa1c1e61e6a879ed01118a703ea06fa | 44.191176 | 175 | 0.741621 | 4.641994 | false | false | false | false |
inorichi/tachiyomi-extensions | multisrc/overrides/wpmangastream/silencescan/src/SilenceScan.kt | 1 | 4710 | package eu.kanade.tachiyomi.extension.pt.silencescan
import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor
import eu.kanade.tachiyomi.multisrc.wpmangastream.WPMangaStream
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import uy.kohesive.injekt.injectLazy
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.TimeUnit
class SilenceScan : WPMangaStream(
"Silence Scan",
"https://silencescan.net",
"pt-BR",
SimpleDateFormat("MMMM dd, yyyy", Locale("pt", "BR"))
) {
override val client: OkHttpClient = network.cloudflareClient.newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.addNetworkInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS))
.build()
private val json: Json by injectLazy()
override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply {
val infoEl = document.select("div.bigcontent, div.animefull, div.main-info").first()
author = infoEl.select("div.imptdt:contains(Autor) i").text()
artist = infoEl.select("div.imptdt:contains(Artista) + i").text()
status = parseStatus(infoEl.select("div.imptdt:contains(Status) i").text())
description = infoEl.select("h2:contains(Sinopse) + div p:not([class])").joinToString("\n") { it.text() }
thumbnail_url = infoEl.select("div.thumb img").imgAttr()
val genres = infoEl.select("span.mgen a[rel]")
.map { element -> element.text() }
.toMutableSet()
// add series type(manga/manhwa/manhua/other) thinggy to genre
document.select(seriesTypeSelector).firstOrNull()?.ownText()?.let {
if (it.isEmpty().not() && genres.contains(it).not()) {
genres.add(it)
}
}
genre = genres.toList().joinToString()
// add alternative name to manga description
document.select(altNameSelector).firstOrNull()?.ownText()?.let {
if (it.isEmpty().not() && it != "N/A" && it != "-") {
description += when {
description!!.isEmpty() -> altName + it
else -> "\n\n$altName" + it
}
}
}
}
override val seriesTypeSelector = ".imptdt:contains(Tipo) a, a[href*=type\\=]"
override val altName: String = "Nome alternativo: "
override fun parseStatus(element: String?): Int = when {
element == null -> SManga.UNKNOWN
element.contains("em andamento", true) -> SManga.ONGOING
element.contains("completo", true) -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply {
name = element.select("span.chapternum").text()
scanlator = [email protected]
date_upload = element.select("span.chapterdate").firstOrNull()?.text()
?.let { parseChapterDate(it) } ?: 0
setUrlWithoutDomain(element.select("div.eph-num > a").attr("href"))
}
override fun getGenreList(): List<Genre> = listOf(
Genre("4-koma", "4-koma"),
Genre("Ação", "acao"),
Genre("Adulto", "adulto"),
Genre("Artes marciais", "artes-marciais"),
Genre("Comédia", "comedia"),
Genre("Comedy", "comedy"),
Genre("Culinária", "culinaria"),
Genre("Drama", "drama"),
Genre("Ecchi", "ecchi"),
Genre("Esporte", "esporte"),
Genre("Fantasia", "fantasia"),
Genre("Gore", "gore"),
Genre("Harém", "harem"),
Genre("Horror", "horror"),
Genre("Isekai", "isekai"),
Genre("Militar", "militar"),
Genre("Mistério", "misterio"),
Genre("Oneshot", "oneshot"),
Genre("Parcialmente Dropado", "parcialmente-dropado"),
Genre("Psicológico", "psicologico"),
Genre("Romance", "romance"),
Genre("School Life", "school-life"),
Genre("Sci-fi", "sci-fi"),
Genre("Seinen", "seinen"),
Genre("Shoujo Ai", "shoujo-ai"),
Genre("Shounen", "shounen"),
Genre("Slice of life", "slice-of-life"),
Genre("Sobrenatural", "sobrenatural"),
Genre("Supernatural", "supernatural"),
Genre("Tragédia", "tragedia"),
Genre("Vida Escolar", "vida-escolar"),
Genre("Violência sexual", "violencia-sexual"),
Genre("Yuri", "yuri")
)
companion object {
private val PORTUGUESE_LOCALE = Locale("pt", "BR")
}
}
| apache-2.0 | bbe4e4a7efc686ec7532321ac5e14b9e | 37.85124 | 113 | 0.612636 | 3.878713 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/database/Converters.kt | 1 | 1195 | package de.tum.`in`.tumcampusapp.database
import androidx.room.TypeConverter
import com.google.gson.Gson
import de.tum.`in`.tumcampusapp.component.ui.alarm.model.FcmNotificationLocation
import de.tum.`in`.tumcampusapp.component.ui.chat.model.ChatMember
import de.tum.`in`.tumcampusapp.utils.DateTimeUtils
import de.tum.`in`.tumcampusapp.utils.tryOrNull
import org.joda.time.DateTime
class Converters {
@TypeConverter
fun isoToDateTime(str: String?): DateTime? {
return if (str == null) null else DateTimeUtils.getDateTime(str)
}
@TypeConverter
fun fromDateTime(date: DateTime?): String? {
return if (date == null) null else DateTimeUtils.getDateTimeString(date)
}
@TypeConverter
fun toJson(location: FcmNotificationLocation): String = Gson().toJson(location)
@TypeConverter
fun toLocation(json: String): FcmNotificationLocation = Gson().fromJson(json, FcmNotificationLocation::class.java)
@TypeConverter
fun fromMember(member: ChatMember?): String = Gson().toJson(member)
@TypeConverter
fun toMember(member: String): ChatMember? {
return tryOrNull { Gson().fromJson(member, ChatMember::class.java) }
}
}
| gpl-3.0 | 111903177afdd3e61890dd8742cd5433 | 33.142857 | 118 | 0.736402 | 4.134948 | false | false | false | false |
fredyw/leetcode | src/main/kotlin/leetcode/Problem1514.kt | 1 | 1664 | package leetcode
import java.util.PriorityQueue
/**
* https://leetcode.com/problems/path-with-maximum-probability/
*/
class Problem1514 {
fun maxProbability(n: Int, edges: Array<IntArray>, succProb: DoubleArray, start: Int,
end: Int): Double {
val adjList = buildAdjList(n, edges, succProb)
val dist = DoubleArray(n) { Double.NEGATIVE_INFINITY }
val queue = PriorityQueue<Node>()
queue += Node(start, dist[start])
while (queue.isNotEmpty()) {
val node = queue.remove()
for (edge in adjList[node.n]) {
val prob = if (dist[edge.from] == Double.NEGATIVE_INFINITY) edge.prob
else dist[edge.from] * edge.prob
if (prob > dist[edge.to]) {
dist[edge.to] = prob
queue += Node(edge.to, prob)
}
}
}
return if (dist[end] == Double.NEGATIVE_INFINITY) 0.0 else dist[end]
}
private fun buildAdjList(n: Int, edges: Array<IntArray>, succProb: DoubleArray): Array<MutableList<Edge>> {
val adjList = Array(n) { mutableListOf<Edge>() }
for ((i, e) in edges.withIndex()) {
val (from, to) = e
adjList[from].add(Edge(from, to, succProb[i]))
adjList[to].add(Edge(to, from, succProb[i]))
}
return adjList
}
private data class Node(val n: Int, val prob: Double) : Comparable<Node> {
override fun compareTo(other: Node): Int {
return other.prob.compareTo(prob)
}
}
private data class Edge(val from: Int, val to: Int, val prob: Double)
}
| mit | e8468eab2b0514ab82e2ca60bceb4bde | 35.173913 | 111 | 0.560697 | 3.869767 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/accepts_cash/AddAcceptsCash.kt | 1 | 3373 | package de.westnordost.streetcomplete.quests.accepts_cash
import de.westnordost.osmfeatures.FeatureDictionary
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.quest.NoCountriesExcept
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.ktx.arrayOfNotNull
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
import java.util.concurrent.FutureTask
class AddAcceptsCash(
private val featureDictionaryFuture: FutureTask<FeatureDictionary>
) : OsmFilterQuestType<Boolean>() {
override val elementFilter: String get() {
val amenities = listOf(
"bar", "cafe", "fast_food", "food_court", "ice_cream", "pub", "biergarten",
"restaurant", "cinema", "nightclub", "planetarium", "theatre", "marketplace",
"internet_cafe", "car_wash", "fuel", "pharmacy", "telephone", "vending_machine"
)
val tourismsWithImpliedFees = listOf(
"zoo", "aquarium", "theme_park", "hotel", "hostel", "motel", "guest_house",
"apartment", "camp_site"
)
val tourismsWithoutImpliedFees = listOf(
"attraction", "museum", "gallery"
)
val leisures = listOf(
"adult_gaming_centre", "amusement_arcade", "bowling_alley", "escape_game", "miniature_golf",
"sauna", "trampoline_park", "tanning_salon"
)
val crafts = listOf(
"carpenter", "shoemaker", "tailor", "photographer", "dressmaker",
"electronics_repair", "key_cutter", "stonemason"
)
return """
nodes, ways, relations with
(
(shop and shop !~ no|vacant|mall)
or amenity ~ ${amenities.joinToString("|")}
or leisure ~ ${leisures.joinToString("|")}
or craft ~ ${crafts.joinToString("|")}
or tourism ~ ${tourismsWithImpliedFees.joinToString("|")}
or tourism ~ ${tourismsWithoutImpliedFees.joinToString("|")} and fee = yes
)
and (name or brand) and !payment:cash and !payment:coins and !payment:notes
"""}
override val commitMessage = "Add whether this place accepts cash as payment"
override val defaultDisabledMessage = R.string.default_disabled_msg_go_inside
override val wikiLink = "Key:payment"
override val icon = R.drawable.ic_quest_cash
override val isReplaceShopEnabled = true
override val enabledInCountries = NoCountriesExcept("SE")
override fun getTitle(tags: Map<String, String>) =
if (hasFeatureName(tags)) R.string.quest_accepts_cash_type_title
else R.string.quest_accepts_cash_title
override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>): Array<String> =
arrayOfNotNull(tags["name"] ?: tags["brand"], featureName.value.toString())
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("payment:cash", answer.toYesNo())
}
private fun hasFeatureName(tags: Map<String, String>): Boolean =
featureDictionaryFuture.get().byTags(tags).isSuggestion(false).find().isNotEmpty()
}
| gpl-3.0 | a74d7a321451adfafccc204b01f97261 | 44.581081 | 104 | 0.673881 | 4.13865 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/splitway/SplitSingleWayUploader.kt | 1 | 17215 | package de.westnordost.streetcomplete.data.osm.splitway
import de.westnordost.streetcomplete.data.MapDataApi
import de.westnordost.osmapi.common.errors.OsmConflictException
import de.westnordost.osmapi.common.errors.OsmNotFoundException
import de.westnordost.osmapi.map.data.*
import javax.inject.Inject
import de.westnordost.osmapi.map.data.Element.Type.*
import de.westnordost.streetcomplete.data.osm.upload.*
import de.westnordost.streetcomplete.ktx.*
import de.westnordost.streetcomplete.util.measuredLength
import de.westnordost.streetcomplete.util.pointOnPolylineFromStart
import kotlin.math.sign
/** Uploads one split way
* Returns only the ways that have been updated or throws a ConflictException */
class SplitSingleWayUploader @Inject constructor(private val mapDataApi: MapDataApi) {
fun upload(changesetId: Long, way: Way, splits: List<SplitPolylineAtPosition>): List<Way> {
val updatedWay = way.fetchUpdated()
?: throw ElementDeletedException("Way #${way.id} has been deleted")
if(updatedWay.isClosed() && splits.size < 2)
throw ElementConflictException("Must specify at least two split positions for a closed way")
checkForConflicts(way, updatedWay)
val nodes = updatedWay.fetchNodes()
val positions = nodes.map { it.position }
/* the splits must be sorted strictly from start to end of way because the algorithm may
insert nodes in the way */
val sortedSplits = splits.flatMap { it.toSplitWay(positions) }.sorted()
val uploadElements = mutableListOf<Element>()
var newNodeId = -1L
val splitAtIndices = mutableListOf<Int>()
var insertedNodeCount = 0
for (split in sortedSplits) {
when(split) {
is SplitWayAtPoint -> {
splitAtIndices.add(split.index + insertedNodeCount)
}
is SplitWayAtLinePosition -> {
val splitNode = OsmNode(newNodeId--, 1, split.pos, null)
uploadElements.add(splitNode)
val nodeIndex = split.index2 + insertedNodeCount
updatedWay.nodeIds.add(nodeIndex, splitNode.id)
splitAtIndices.add(nodeIndex)
++insertedNodeCount
}
}
}
uploadElements.addAll(splitWayAtIndices(updatedWay, splitAtIndices))
val handler = UpdateElementsHandler()
try {
mapDataApi.uploadChanges(changesetId, uploadElements, handler)
} catch (e: OsmConflictException) {
throw ChangesetConflictException(e.message, e)
}
// the added nodes and updated relations are not relevant for quest creation, only the way are
return handler.getElementUpdates(uploadElements).updated.filterIsInstance<Way>()
}
private fun checkForConflicts(old: Way, new: Way) {
if(old.version != new.version) {
// unsolvable conflict if other was shortened (e.g. cut in two) or extended
if(old.nodeIds.first() != new.nodeIds.first() || old.nodeIds.last() != new.nodeIds.last())
throw ElementConflictException("Way #${old.id} has been changed and the conflict cannot be solved automatically")
}
}
private fun splitWayAtIndices(originalWay: Way, splitIndices: List<Int>): List<Element> {
val newWays = createSplitWays(originalWay, splitIndices)
val updatedRelations = updateRelations(originalWay, newWays)
return newWays + updatedRelations
}
/** Returns the elements that have been changed */
private fun createSplitWays(originalWay: Way, splitIndices: List<Int>): List<Way> {
val nodesChunks = originalWay.nodeIds.splitIntoChunks(splitIndices)
/* Handle circular ways specially: If you split at a circular way at two nodes, you just
want to split it at these points, not also at the former endpoint. So if the last node is
the same first node, join the last and the first way chunk. (copied from JOSM) */
if (nodesChunks.size > 1 && nodesChunks.first().first() == nodesChunks.last().last()) {
val lastChunk = nodesChunks.removeAt(nodesChunks.lastIndex)
lastChunk.removeAt(lastChunk.lastIndex)
nodesChunks.first().addAll(0, lastChunk)
}
/* Instead of deleting the old way and replacing it with the new splitted chunks, one of the
chunks should use the id of the old way, so that it inherits the OSM history of the
previous way. The chunk with the most nodes is selected for this.
This is the same behavior as JOSM and Vespucci. */
val indexOfChunkToKeep = nodesChunks.indexOfMaxBy { it.size }
val tags = originalWay.tags?.toMutableMap()
tags?.transformTagsForSplit()
var newWayId = -1L
return nodesChunks.mapIndexed { index, nodes ->
if(index == indexOfChunkToKeep) {
OsmWay(originalWay.id, originalWay.version, nodes, tags).apply {
isModified = true
}
}
else {
OsmWay(newWayId--, 0, nodes, tags)
}
}
}
/** Returns the elements that have been changed */
private fun updateRelations(originalWay: Way, newWays: List<Way>) : Collection<Relation> {
val relations = originalWay.fetchParentRelations()
val result = mutableSetOf<Relation>()
for (relation in relations) {
/* iterating in reverse because the relation member for the original way is replaced
by one or several new ways in-place within the loop. So, no relation member is
iterated twice. If in the future, there will be any special relation that removes
a relation member or replaces several relation members with only one relation member,
then this here won't work anymore and the algorithm needs to modify a copy of the
relation members list. */
for(i in relation.members.size - 1 downTo 0) {
val relationMember = relation.members[i]
if (relationMember.type == WAY && relationMember.ref == originalWay.id) {
if (!updateSpecialRelation(relation, i, newWays)) {
updateNormalRelation(relation, i, originalWay, newWays)
}
result.add(relation)
}
}
}
return result
}
/** Returns whether it has been treated as a special relation type */
private fun updateSpecialRelation(relation: Relation, indexOfWayInRelation: Int, newWays: List<Way>): Boolean {
val relationType = relation.tags?.get("type") ?: ""
val originalWayRole = relation.members[indexOfWayInRelation].role
/* for a from-to-relation (i.e. turn restriction, destination sign, ...) only the two ways
directly connecting with the via node/way should be kept in the relation. If one of these
ways is split up, the correct way chunk must be selected to replace the old way. */
if (originalWayRole == "from" || originalWayRole == "to") {
val viaNodeIds = relation.fetchViaNodeIds(relationType)
if (viaNodeIds.isNotEmpty()) {
val newWay = newWays.find { viaNodeIds.containsAny(it.nodeIds.firstAndLast()) }
if (newWay != null) {
val newRelationMember = OsmRelationMember(newWay.id, originalWayRole, WAY)
relation.members[indexOfWayInRelation] = newRelationMember
return true
}
}
}
// room for handling other special relation types here
return false
}
private fun updateNormalRelation(relation: Relation, indexOfWayInRelation: Int,
originalWay: Way, newWays: List<Way>) {
/* for any (non-special, see above) relation, the new way chunks that replace the original
way must be all inserted into each relation. In the correct order, if the relation is
ordered at all. */
val originalWayRole = relation.members[indexOfWayInRelation].role
val newRelationMembers = newWays.map { way ->
OsmRelationMember(way.id, originalWayRole, WAY) }.toMutableList()
val isOrientedBackwards = originalWay.isOrientedForwardInOrderedRelation(relation, indexOfWayInRelation) == false
if (isOrientedBackwards) newRelationMembers.reverse()
relation.members.removeAt(indexOfWayInRelation)
relation.members.addAll(indexOfWayInRelation, newRelationMembers)
}
private fun Way.fetchNodes(): List<Node> {
try {
val nodesMap = mapDataApi.getNodes(nodeIds).associateBy { node -> node.id }
// the fetched nodes must be returned ordered in the way
return nodeIds.map { nodeId -> nodesMap.getValue(nodeId) }
} catch (e: OsmNotFoundException) {
throw ConflictException("Way was modified right while uploading the changes (what's the chance?)", e)
}
}
private fun Way.fetchUpdated(): Way? = mapDataApi.getWay(id)
private fun Way.fetchParentRelations() = mapDataApi.getRelationsForWay(id)
/** returns null if the relation is not ordered, false if oriented backwards, true if oriented forward */
private fun Way.isOrientedForwardInOrderedRelation(relation: Relation, indexInRelation: Int): Boolean? {
val wayIdBefore = relation.members.findPrevious(indexInRelation) { it.type == WAY }?.ref
val wayBefore = wayIdBefore?.let { mapDataApi.getWay(it) }
if (wayBefore != null) {
if (isAfterWayInChain(wayBefore)) return true
if (isBeforeWayInChain(wayBefore)) return false
}
val wayIdAfter = relation.members.findNext(indexInRelation+1) { it.type == WAY }?.ref
val wayAfter = wayIdAfter?.let { mapDataApi.getWay(it) }
if (wayAfter != null) {
if (isBeforeWayInChain(wayAfter)) return true
if (isAfterWayInChain(wayAfter)) return false
}
return null
}
private fun Relation.fetchViaNodeIds(relationType: String): Set<Long> {
val vias = findVias(relationType)
val nodeIds = mutableSetOf<Long>()
for (via in vias) {
if (via.type == NODE) {
nodeIds.add(via.ref)
} else if (via.type == WAY) {
val way = mapDataApi.getWay(via.ref)
if (way != null) nodeIds.addAll(way.nodeIds.firstAndLast())
}
}
return nodeIds
}
}
/** data class that carries the information for one split to perform on a random position on a way.
* So, same as SplitPolylineAtPosition, but additionally with the index of the split in the way. */
private sealed class SplitWay : Comparable<SplitWay> {
abstract val pos: LatLon
protected abstract val index: Int
protected abstract val delta: Double
/** sort by index, then delta, ascending. The algorithm relies on this order! */
override fun compareTo(other: SplitWay): Int {
val diffIndex = index - other.index
if (diffIndex != 0) return diffIndex
val diffDelta = delta - other.delta
return diffDelta.sign.toInt()
}
}
private data class SplitWayAtPoint(override val pos: LatLon, public override val index: Int) : SplitWay() {
override val delta get() = 0.0
}
private data class SplitWayAtLinePosition( val pos1: LatLon, val index1: Int,
val pos2: LatLon, val index2: Int,
public override val delta: Double) : SplitWay() {
override val index get() = index1
override val pos: LatLon get() {
val line = listOf(pos1, pos2)
return line.pointOnPolylineFromStart(line.measuredLength() * delta)!!
}
}
/** creates a SplitWay from a SplitLineAtPosition, given the nodes of the way. So, basically it
* simply finds the node index/indices at which the split should be made.
* One SplitPolylineAtPosition will map to several SplitWays for self-intersecting ways that have
* a split at the position where they self-intersect. I.e. a way in the shape of an 8 split exactly
* in the centre.
* If the way changed significantly in the meantime, it will throw an ElementConflictException */
private fun SplitPolylineAtPosition.toSplitWay(positions: List<LatLon>): Collection<SplitWay> {
return when(this) {
is SplitAtPoint -> toSplitWay(positions)
is SplitAtLinePosition -> toSplitWay(positions)
}
}
private fun SplitAtPoint.toSplitWay(positions: List<LatLon>): Collection<SplitWayAtPoint> {
// could be several indices, for example if the way has the shape of an 8.
var indicesOf = positions.osmIndicesOf(pos)
if (indicesOf.isEmpty()) throw ElementConflictException("To be split point has been moved")
indicesOf = indicesOf.filter { index -> index > 0 && index < positions.lastIndex }
if (indicesOf.isEmpty())
throw ElementConflictException("Split position is now at the very start or end of the way - can't split there")
return indicesOf.map { indexOf -> SplitWayAtPoint(pos, indexOf) }
}
private fun SplitAtLinePosition.toSplitWay(positions: List<LatLon>): Collection<SplitWayAtLinePosition> {
// could be several indices, for example if the way has the shape of an 8...
val indicesOf1 = positions.osmIndicesOf(pos1)
if (indicesOf1.isEmpty()) throw ElementConflictException("To be split line has been moved")
val indicesOf2 = positions.osmIndicesOf(pos2)
if (indicesOf2.isEmpty()) throw ElementConflictException("To be split line has been moved")
// ...and we need to find out which of the lines is meant
val result = mutableListOf<SplitWayAtLinePosition>()
for (i1 in indicesOf1) {
for (i2 in indicesOf2) {
/* For SplitAtLinePosition, the direction of the way does not matter. But for the
SplitWayAtLinePosition it must be in the same order as the OSM way. */
if (i1 + 1 == i2) result.add(SplitWayAtLinePosition(pos1, i1, pos2, i2, delta))
if (i2 + 1 == i1) result.add(SplitWayAtLinePosition(pos2, i2, pos1, i1, 1.0 - delta))
}
}
if (result.isNotEmpty())
return result
else
throw ElementConflictException("End points of the to be split line are not directly successive anymore")
}
/** returns the indices at which the given pos is found in this list, taking into accound the limited
* precision of positions in OSM. */
private fun List<LatLon>.osmIndicesOf(pos: LatLon): List<Int> =
mapIndexedNotNull { i, p -> if (p.equalsInOsm(pos)) i else null }
/** returns a copy of the list split at the given indices with each chunk sharing each the first and last element */
private fun <E> List<E>.splitIntoChunks(indices: List<Int>): MutableList<MutableList<E>> {
val result = mutableListOf<MutableList<E>>()
var lastIndex = 0
for (index in indices) {
result.add(subList(lastIndex, index+1).toMutableList())
lastIndex = index
}
result.add(subList(lastIndex, size).toMutableList())
return result
}
/** returns whether this way immediately precedes the given way in a chain */
private fun Way.isBeforeWayInChain(way: Way) =
nodeIds.last() == way.nodeIds.last() || nodeIds.last() == way.nodeIds.first()
/** returns whether this way immediately follows the given way in a chain */
private fun Way.isAfterWayInChain(way: Way) =
nodeIds.first() == way.nodeIds.last() || nodeIds.first() == way.nodeIds.first()
private fun Relation.findVias(relationType: String): List<RelationMember> {
val nodesAndWays = members.filter { it.type == NODE || it.type == WAY }
return when (relationType) {
"restriction" -> nodesAndWays.filter { it.role == "via" }
"destination_sign" -> {
nodesAndWays.filter { it.role == "intersection" }.takeUnless { it.isEmpty() } ?:
nodesAndWays.filter { it.role == "sign" }
}
else -> nodesAndWays.filter { it.role == "via" }
}
}
/** transform the tags because some tags shouldn't be carried over to the new ways as they may
* be incorrect now */
private fun MutableMap<String, String>.transformTagsForSplit() {
remove("step_count")
// only remove "incline" if it contains a number
val inclineNumberRegex = Regex("[0-9]")
val inclineValue = get("incline")
if (inclineValue != null && inclineNumberRegex.containsMatchIn(inclineValue)) remove("incline")
// only remove if "steps" is a number cause it is apparently also used to denote kind of steps
if (get("steps")?.toIntOrNull() != null) remove("steps")
remove("seats")
// remove any capacity: "capacity", "bicycle_parking:capacity", "parking:lane:both:capacity", "parking:lane:right:capacity:disabled" etc.
val capacityRegex = Regex("^(.*:)?capacity(:.*)?$")
val keysToDelete = keys.filter { capacityRegex.matches(it) }
for (key in keysToDelete) {
remove(key)
}
} | gpl-3.0 | 546e84ad210054313938acfa1fb7e998 | 46.822222 | 141 | 0.658031 | 4.363752 | false | false | false | false |
fredyw/leetcode | src/main/kotlin/leetcode/Problem2134.kt | 1 | 789 | package leetcode
import kotlin.math.min
/**
* https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/
*/
class Problem2134 {
fun minSwaps(nums: IntArray): Int {
var numOnes = 0
for (num in nums) {
if (num == 1) {
numOnes++
}
}
var answer = Int.MAX_VALUE
var numZeros = 0
var j = 0
for (i in nums.indices) {
while (j < i + numOnes) {
if (nums[j % nums.size] == 0) {
numZeros++
}
j++
}
answer = min(answer, numZeros)
if (nums[i] == 0) {
numZeros--
}
}
return if (answer == Int.MAX_VALUE) 0 else answer
}
}
| mit | bf15aea2dc75363cc0e49a3be8122abe | 22.909091 | 75 | 0.42839 | 3.793269 | false | false | false | false |
robfletcher/orca | orca-dry-run/src/main/kotlin/com/netflix/spinnaker/orca/dryrun/stub/TitusBakeOutputStub.kt | 4 | 1652 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.dryrun.stub
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import org.springframework.stereotype.Component
@Component
class TitusBakeOutputStub : OutputStub {
override fun supports(stage: StageExecution) =
stage.type == "bake" && stage.context["cloudProviderType"] == "titus"
override fun outputs(stage: StageExecution) =
if (stage.parent?.type == "bake") {
emptyMap()
} else {
val app = stage.execution.application
mapOf(
"deploymentDetails" to (stage.regions).map { region ->
val ami = "$app/basic:master-h${randomNumeric(5)}.${randomHex(7)}"
mapOf(
"ami" to ami,
"imageId" to ami,
"amiSuffix" to timestamp(),
"baseOs" to "trusty",
"storeType" to "docker",
"region" to region,
"package" to "ssh://[email protected]:7999/$app/docker-build-repo.git?${randomHex(40)}",
"cloudProviderType" to "titus"
)
}
)
}
}
| apache-2.0 | 43379798c080910629cebc0cf57c10c3 | 32.714286 | 101 | 0.652542 | 3.952153 | false | false | false | false |
robfletcher/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/ResumeExecutionHandlerTest.kt | 4 | 3010 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.PAUSED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.api.test.stage
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.ResumeExecution
import com.netflix.spinnaker.orca.q.ResumeStage
import com.netflix.spinnaker.q.Queue
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions
import com.nhaarman.mockito_kotlin.whenever
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
object ResumeExecutionHandlerTest : SubjectSpek<ResumeExecutionHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
subject(GROUP) {
ResumeExecutionHandler(queue, repository)
}
fun resetMocks() = reset(queue, repository)
describe("resuming a paused execution") {
val pipeline = pipeline {
application = "spinnaker"
status = PAUSED
stage {
refId = "1"
status = SUCCEEDED
}
stage {
refId = "2a"
requisiteStageRefIds = listOf("1")
status = PAUSED
}
stage {
refId = "2b"
requisiteStageRefIds = listOf("1")
status = PAUSED
}
stage {
refId = "3"
requisiteStageRefIds = listOf("2a", "2b")
status = NOT_STARTED
}
}
val message = ResumeExecution(pipeline.type, pipeline.id, pipeline.application)
beforeGroup {
whenever(repository.retrieve(pipeline.type, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("resumes all paused stages") {
verify(queue).push(ResumeStage(message, pipeline.stageByRef("2a").id))
verify(queue).push(ResumeStage(message, pipeline.stageByRef("2b").id))
verifyNoMoreInteractions(queue)
}
}
})
| apache-2.0 | cefd9a875a0b4e015ae8c4ae49ac291a | 31.717391 | 83 | 0.727243 | 4.180556 | false | true | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/model/api/Diff.kt | 2 | 675 | package com.commit451.gitlab.model.api
import android.os.Parcelable
import com.squareup.moshi.Json
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Diff(
@Json(name = "old_path")
var oldPath: String? = null,
@Json(name = "new_path")
var newPath: String? = null,
@Json(name = "a_mode")
var aMode: Int = 0,
@Json(name = "b_mode")
var bMode: Int = 0,
@Json(name = "diff")
var diff: String? = null,
@Json(name = "new_file")
var isNewFile: Boolean = false,
@Json(name = "renamed_file")
var isRenamedFile: Boolean = false,
@Json(name = "deleted_file")
var isDeletedFile: Boolean = false
) : Parcelable
| apache-2.0 | fd134fefa7f5844aad9ba5f1c5b36177 | 26 | 39 | 0.641481 | 3.229665 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/webview/WebViewScreen.kt | 1 | 6403 | package eu.kanade.presentation.webview
import android.content.pm.ApplicationInfo
import android.webkit.WebResourceRequest
import android.webkit.WebView
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import com.google.accompanist.web.AccompanistWebViewClient
import com.google.accompanist.web.LoadingState
import com.google.accompanist.web.WebView
import com.google.accompanist.web.rememberWebViewNavigator
import com.google.accompanist.web.rememberWebViewState
import eu.kanade.presentation.components.AppBar
import eu.kanade.presentation.components.AppBarActions
import eu.kanade.presentation.components.Scaffold
import eu.kanade.tachiyomi.BuildConfig
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.system.setDefaultSettings
@Composable
fun WebViewScreen(
onNavigateUp: () -> Unit,
initialTitle: String?,
url: String,
headers: Map<String, String> = emptyMap(),
onShare: (String) -> Unit,
onOpenInBrowser: (String) -> Unit,
onClearCookies: (String) -> Unit,
) {
val state = rememberWebViewState(url = url, additionalHttpHeaders = headers)
val navigator = rememberWebViewNavigator()
Scaffold(
topBar = {
Box {
AppBar(
title = state.pageTitle ?: initialTitle,
subtitle = state.content.getCurrentUrl(),
navigateUp = onNavigateUp,
navigationIcon = Icons.Default.Close,
actions = {
AppBarActions(
listOf(
AppBar.Action(
title = stringResource(R.string.action_webview_back),
icon = Icons.Default.ArrowBack,
onClick = {
if (navigator.canGoBack) {
navigator.navigateBack()
}
},
enabled = navigator.canGoBack,
),
AppBar.Action(
title = stringResource(R.string.action_webview_forward),
icon = Icons.Default.ArrowForward,
onClick = {
if (navigator.canGoForward) {
navigator.navigateForward()
}
},
enabled = navigator.canGoForward,
),
AppBar.OverflowAction(
title = stringResource(R.string.action_webview_refresh),
onClick = { navigator.reload() },
),
AppBar.OverflowAction(
title = stringResource(R.string.action_share),
onClick = { onShare(state.content.getCurrentUrl()!!) },
),
AppBar.OverflowAction(
title = stringResource(R.string.action_open_in_browser),
onClick = { onOpenInBrowser(state.content.getCurrentUrl()!!) },
),
AppBar.OverflowAction(
title = stringResource(R.string.pref_clear_cookies),
onClick = { onClearCookies(state.content.getCurrentUrl()!!) },
),
),
)
},
)
when (val loadingState = state.loadingState) {
is LoadingState.Initializing -> LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.align(Alignment.BottomCenter),
)
is LoadingState.Loading -> LinearProgressIndicator(
progress = (loadingState as? LoadingState.Loading)?.progress ?: 1f,
modifier = Modifier
.fillMaxWidth()
.align(Alignment.BottomCenter),
)
else -> {}
}
}
},
) { contentPadding ->
val webClient = remember {
object : AccompanistWebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?,
): Boolean {
request?.let {
view?.loadUrl(it.url.toString(), headers)
}
return super.shouldOverrideUrlLoading(view, request)
}
}
}
WebView(
state = state,
modifier = Modifier.padding(contentPadding),
navigator = navigator,
onCreated = { webView ->
webView.setDefaultSettings()
// Debug mode (chrome://inspect/#devices)
if (BuildConfig.DEBUG &&
0 != webView.context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
) {
WebView.setWebContentsDebuggingEnabled(true)
}
headers["user-agent"]?.let {
webView.settings.userAgentString = it
}
},
client = webClient,
)
}
}
| apache-2.0 | 7d03bdcc3002ba7d1e47b44dffacb79c | 42.557823 | 99 | 0.494612 | 6.339604 | false | false | false | false |
apollostack/apollo-android | apollo-graphql-ast/src/main/kotlin/com/apollographql/apollo3/graphql/ast/gqltype.kt | 1 | 2285 | package com.apollographql.apollo3.graphql.ast
fun GQLType.leafType(): GQLNamedType = when (this) {
is GQLNonNullType -> type.leafType()
is GQLListType -> type.leafType()
is GQLNamedType -> this
}
fun GQLType.pretty(): String = when (this) {
is GQLNonNullType -> "${type.pretty()}!"
is GQLListType -> "[${type.pretty()}]"
is GQLNamedType -> this.name
}
internal fun GQLType.canInputValueBeAssignedTo(target: GQLType): Boolean {
return when (this) {
is GQLNonNullType -> when (target) {
// non-null can always be assigned to their nullable equivalents
is GQLNonNullType -> type.canInputValueBeAssignedTo(target.type)
is GQLListType -> type.canInputValueBeAssignedTo(target)
is GQLNamedType -> type.canInputValueBeAssignedTo(target)
}
is GQLListType -> when (target) {
// lists are covariant. [CatInput!] can be passed where [CatInput] is expected
is GQLListType -> type.canInputValueBeAssignedTo(target.type)
is GQLNonNullType -> false
is GQLNamedType -> false
}
is GQLNamedType -> when (target) {
is GQLNonNullType -> false
is GQLListType -> false
is GQLNamedType -> {
/**
* At this point, both this and target must be input objects
* If this is not the case, this means variables validation has failed
*/
return name == target.name
}
}
}
}
internal fun GQLType.isInputType(typeDefinitions: Map<String, GQLTypeDefinition>): Boolean = when (this) {
is GQLNonNullType -> this.type.isInputType(typeDefinitions)
is GQLListType -> this.type.isInputType(typeDefinitions)
is GQLNamedType -> typeDefinitions[name].let {
it is GQLInputObjectTypeDefinition
|| it is GQLScalarTypeDefinition
|| it is GQLEnumTypeDefinition
}
}
internal fun GQLType.isOutputType(typeDefinitions: Map<String, GQLTypeDefinition>): Boolean = when (this) {
is GQLNonNullType -> this.type.isInputType(typeDefinitions)
is GQLListType -> this.type.isInputType(typeDefinitions)
is GQLNamedType -> typeDefinitions[name].let {
it is GQLObjectTypeDefinition
|| it is GQLUnionTypeDefinition
|| it is GQLInterfaceTypeDefinition
|| it is GQLScalarTypeDefinition
|| it is GQLEnumTypeDefinition
}
}
| mit | 7042c4b50c7d83508396eacf6146bf0e | 34.703125 | 107 | 0.693654 | 4.231481 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/skins/SkinInterface.kt | 1 | 4154 | package info.nightscout.androidaps.skins
import android.util.DisplayMetrics
import android.util.TypedValue.COMPLEX_UNIT_PX
import android.view.View
import android.widget.LinearLayout
import androidx.annotation.StringRes
import androidx.constraintlayout.widget.ConstraintLayout
import info.nightscout.androidaps.R
import info.nightscout.androidaps.databinding.ActionsFragmentBinding
import info.nightscout.androidaps.databinding.OverviewFragmentBinding
interface SkinInterface {
@get:StringRes val description: Int
val mainGraphHeight: Int // in dp
val secondaryGraphHeight: Int // in dp
// no pre processing by default
fun preProcessLandscapeActionsLayout(dm: DisplayMetrics, binding: ActionsFragmentBinding) {
}
fun preProcessLandscapeOverviewLayout(dm: DisplayMetrics, binding: OverviewFragmentBinding, isLandscape: Boolean, isTablet: Boolean, isSmallHeight: Boolean) {
// pre-process landscape mode
val screenWidth = dm.widthPixels
val screenHeight = dm.heightPixels
val landscape = screenHeight < screenWidth
if (landscape) {
val iobLayout = binding.infoLayout.iobLayout
val iobLayoutParams = iobLayout.layoutParams as ConstraintLayout.LayoutParams
val timeLayout = binding.infoLayout.timeLayout
iobLayoutParams.startToStart = ConstraintLayout.LayoutParams.UNSET
iobLayoutParams.startToEnd = timeLayout.id
iobLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET
iobLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
val timeLayoutParams = timeLayout.layoutParams as ConstraintLayout.LayoutParams
timeLayoutParams.endToEnd = ConstraintLayout.LayoutParams.UNSET
timeLayoutParams.endToStart = iobLayout.id
val cobLayoutParams = binding.infoLayout.cobLayout.layoutParams as ConstraintLayout.LayoutParams
cobLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
val basalLayoutParams = binding.infoLayout.basalLayout.layoutParams as ConstraintLayout.LayoutParams
basalLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
val extendedLayoutParams = binding.infoLayout.extendedLayout.layoutParams as ConstraintLayout.LayoutParams
extendedLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
val asLayoutParams = binding.infoLayout.asLayout.layoutParams as ConstraintLayout.LayoutParams
asLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
if (isTablet) {
binding.infoLayout.apply {
val texts = listOf(bg, iob, cob, baseBasal, extendedBolus, sensitivity)
for (v in texts) v.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.5f)
val textsTime = listOf(time, timeAgoShort)
for (v in textsTime) v.setTextSize(COMPLEX_UNIT_PX, v.textSize * 2.25f)
}
binding.apply {
val texts = listOf(pump, openaps, uploader)
for (v in texts) v.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.3f)
}
binding.statusLightsLayout.apply {
val texts = listOf(cannulaAge, insulinAge, reservoirLevel, sensorAge, pbAge, batteryLevel)
for (v in texts) v.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.3f)
}
timeLayout.orientation = LinearLayout.HORIZONTAL
binding.infoLayout.timeAgoShort.setTextSize(COMPLEX_UNIT_PX, binding.infoLayout.time.textSize)
binding.infoLayout.deltaLarge.visibility = View.VISIBLE
} else {
binding.infoLayout.deltaLarge.visibility = View.GONE
}
}
}
fun moveButtonsLayout(root: LinearLayout) {
val buttonsLayout = root.findViewById<LinearLayout>(R.id.buttons_layout)
root.removeView(buttonsLayout)
val innerLayout = root.findViewById<LinearLayout>(R.id.inner_layout)
innerLayout.addView(buttonsLayout)
}
}
| agpl-3.0 | 8aa1c51453985b036a725df6a141d259 | 49.658537 | 162 | 0.697159 | 5.041262 | false | false | false | false |
wesamhaboush/kotlin-algorithms | src/main/kotlin/algorithms/pentagonal-numbers.kt | 1 | 2274 | package algorithms
/*
Pentagon numbers
Problem 44
Pentagonal numbers are generated by the formula,
P_n=n(3n−1)/2.
The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8.
However, their difference, 70 − 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal
and D = |Pk − Pj| is minimised; what is the value of D?
Solution:
P_n=n(3n−1)/2
n (3n - 1) = 2P_n
3n^2 - n = 2P_n
3n^2 - n - 2P_n = 0
we know that:
x = (-b +- sqrt(b^2 - 4ac))/2a
so:
a = 3, b = -1, c = -2P_n
n = (1 +- sqrt(1 + 4 * 3 * 2 * P_n)) / 6
= (1 +- sqrt(1 + 24 * P_n)) / 6
so, to use a brutal solutions, we start by looking at the following algorithm:
* for each pentagonal number N
* for each pentagonal number M < N, starting from the first M below N and moving downwards
* calculate different and sum and test for pentagonal-numberness
* if not found for N, move on to N+1, and repeat the whole thing until you find your target.
*/
fun findTargetPentagonalPair(): Pair<Pair<Long, Long>, Pair<Long, Long>> =
// for each pentagonal number Pk
pentagonals()
// get all the Pj pentagonal numbers below it starting from the one just below it
// note, we start from top down here to minimize the difference
.flatMap { maxPn ->
pentagonalsDownwards(maxPn.first)
.map { Pair(maxPn, it) }
}
// find those ones that have both sum and difference to be also pentagonal
.filter { it ->
val difference = it.first.second - it.second.second
val sum = it.first.second + it.second.second
isPentagonal(difference) && isPentagonal(sum)
}
// we need the first of those only
.first()
// give a sequence of pentagonal numbers starting from P(n), P(n - 1), P(n - 2), ..., P(1).
fun pentagonalsDownwards(n: Long): Sequence<Pair<Long, Long>> =
generateSequence(n) { it - 1 }
.takeWhile { it > 0 }
.map { Pair(it, pentagonal(it)) }
| gpl-3.0 | f8e463eb3a6ccaf6a387cd6e9a2cb5f3 | 28.815789 | 97 | 0.582083 | 3.428139 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/common/DigraphSequence.kt | 1 | 8067 | /*
* 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.common
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.common.DigraphResult.Companion.done
import com.maddyhome.idea.vim.common.DigraphResult.Companion.handled
import com.maddyhome.idea.vim.diagnostic.vimLogger
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.options.OptionScope
import java.awt.event.KeyEvent
import javax.swing.KeyStroke
class DigraphSequence {
private var digraphState = DIG_STATE_PENDING
private var digraphChar = 0.toChar()
private lateinit var codeChars: CharArray
private var codeCnt = 0
private var codeType = 0
private var codeMax = 0
fun isDigraphStart(key: KeyStroke): Boolean {
return digraphState == DIG_STATE_PENDING && // if state has changed, then it's not a start
key.keyCode == KeyEvent.VK_K && key.modifiers and KeyEvent.CTRL_DOWN_MASK != 0
}
fun isLiteralStart(key: KeyStroke): Boolean {
return digraphState == DIG_STATE_PENDING && // if state has changed, then it's not a start
(key.keyCode == KeyEvent.VK_V || key.keyCode == KeyEvent.VK_Q) && key.modifiers and KeyEvent.CTRL_DOWN_MASK != 0
}
fun startDigraphSequence(): DigraphResult {
logger.debug("startDigraphSequence")
digraphState = DIG_STATE_DIG_ONE
return DigraphResult.HANDLED_DIGRAPH
}
fun startLiteralSequence(): DigraphResult {
logger.debug("startLiteralSequence")
digraphState = DIG_STATE_CODE_START
codeChars = CharArray(8)
codeCnt = 0
return DigraphResult.HANDLED_LITERAL
}
fun processKey(key: KeyStroke, editor: VimEditor): DigraphResult {
return when (digraphState) {
DIG_STATE_PENDING -> {
logger.debug("DIG_STATE_PENDING")
if (key.keyCode == KeyEvent.VK_BACK_SPACE &&
injector.optionService.isSet(OptionScope.LOCAL(editor), OptionConstants.digraphName)
) {
digraphState = DIG_STATE_BACK_SPACE
} else if (key.keyChar != KeyEvent.CHAR_UNDEFINED) {
digraphChar = key.keyChar
}
DigraphResult.UNHANDLED
}
DIG_STATE_BACK_SPACE -> {
logger.debug("DIG_STATE_BACK_SPACE")
digraphState = DIG_STATE_PENDING
if (key.keyChar != KeyEvent.CHAR_UNDEFINED) {
val ch = injector.digraphGroup.getDigraph(digraphChar, key.keyChar)
digraphChar = 0.toChar()
return done(KeyStroke.getKeyStroke(ch))
}
DigraphResult.UNHANDLED
}
DIG_STATE_DIG_ONE -> {
logger.debug("DIG_STATE_DIG_ONE")
if (key.keyChar != KeyEvent.CHAR_UNDEFINED) {
digraphChar = key.keyChar
digraphState = DIG_STATE_DIG_TWO
return handled(digraphChar)
}
digraphState = DIG_STATE_PENDING
DigraphResult.BAD
}
DIG_STATE_DIG_TWO -> {
logger.debug("DIG_STATE_DIG_TWO")
digraphState = DIG_STATE_PENDING
if (key.keyChar != KeyEvent.CHAR_UNDEFINED) {
val ch = injector.digraphGroup.getDigraph(digraphChar, key.keyChar)
return done(KeyStroke.getKeyStroke(ch))
}
DigraphResult.BAD
}
DIG_STATE_CODE_START -> {
logger.debug("DIG_STATE_CODE_START")
when (key.keyChar) {
'o', 'O' -> {
codeMax = 3
digraphState = DIG_STATE_CODE_CHAR
codeType = 8
logger.debug("Octal")
DigraphResult.HANDLED_LITERAL
}
'x', 'X' -> {
codeMax = 2
digraphState = DIG_STATE_CODE_CHAR
codeType = 16
logger.debug("hex2")
DigraphResult.HANDLED_LITERAL
}
'u' -> {
codeMax = 4
digraphState = DIG_STATE_CODE_CHAR
codeType = 16
logger.debug("hex4")
DigraphResult.HANDLED_LITERAL
}
'U' -> {
codeMax = 8
digraphState = DIG_STATE_CODE_CHAR
codeType = 16
logger.debug("hex8")
DigraphResult.HANDLED_LITERAL
}
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> {
codeMax = 3
digraphState = DIG_STATE_CODE_CHAR
codeType = 10
codeChars[codeCnt++] = key.keyChar
logger.debug("decimal")
DigraphResult.HANDLED_LITERAL
}
else -> {
if (key.keyCode == KeyEvent.VK_TAB) {
val code = KeyStroke.getKeyStroke('\t')
digraphState = DIG_STATE_PENDING
return done(code)
}
val ks = specialKeyToKeyCode(key)
if (ks != null) {
return done(ks)
}
logger.debug("unknown")
digraphState = DIG_STATE_PENDING
done(key)
}
}
}
DIG_STATE_CODE_CHAR -> {
logger.debug("DIG_STATE_CODE_CHAR")
var valid = false
when (codeType) {
10 -> if (key.keyChar in '0'..'9') {
valid = true
}
8 -> if (key.keyChar in '0'..'7') {
valid = true
}
16 -> if (key.keyChar in '0'..'9' || key.keyChar in 'a'..'f' || key.keyChar in 'A'..'F') {
valid = true
}
}
if (valid) {
logger.debug("valid")
codeChars[codeCnt++] = key.keyChar
return if (codeCnt == codeMax) {
val digits = String(codeChars, 0, codeCnt)
val `val` = digits.toInt(codeType)
val code = KeyStroke.getKeyStroke(`val`.toChar())
digraphState = DIG_STATE_PENDING
done(code)
} else {
DigraphResult.HANDLED_LITERAL
}
} else if (codeCnt > 0) {
logger.debug("invalid")
val digits = String(codeChars, 0, codeCnt)
val `val` = digits.toInt(codeType)
digraphState = DIG_STATE_PENDING
val code = KeyStroke.getKeyStroke(`val`.toChar())
if (!injector.application.isUnitTest()) {
// The key we received isn't part of the literal, so post it to be handled after we've handled the literal.
// This requires swing, so we can't run it in tests.
injector.application.postKey(key, editor)
}
return done(code)
} else if (codeCnt == 0) {
digraphState = DIG_STATE_PENDING
return if (specialKeyToKeyCode(key) != null) {
done(specialKeyToKeyCode(key))
} else {
done(key)
}
}
DigraphResult.BAD
}
else -> DigraphResult.BAD
}
}
private fun specialKeyToKeyCode(key: KeyStroke): KeyStroke? {
if (key.modifiers and KeyEvent.CTRL_DOWN_MASK != 0) {
val specialKeyCode = injector.parser.parseVimScriptString("\\" + injector.parser.toKeyNotation(key))
if (specialKeyCode.length == 1) {
return if (specialKeyCode[0].code == 10) {
KeyStroke.getKeyStroke(0.toChar())
} else {
KeyStroke.getKeyStroke(specialKeyCode[0])
}
} else {
logger.error("Digraph char was recognized as multiple chars")
}
} else {
return when (key.keyCode) {
10 -> KeyStroke.getKeyStroke(13.toChar())
27 -> KeyStroke.getKeyStroke(27.toChar())
else -> null
}
}
return null
}
fun reset() {
digraphState = DIG_STATE_PENDING
codeChars = CharArray(8)
}
companion object {
private const val DIG_STATE_PENDING = 1
private const val DIG_STATE_DIG_ONE = 2
private const val DIG_STATE_DIG_TWO = 3
private const val DIG_STATE_CODE_START = 10
private const val DIG_STATE_CODE_CHAR = 11
private const val DIG_STATE_BACK_SPACE = 20
private val logger = vimLogger<DigraphSequence>()
}
}
| mit | 5ff5d76ff1a9579e0645e42b9b9a1331 | 33.037975 | 119 | 0.582868 | 3.991588 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/CanSealedSubClassBeObjectInspection.kt | 1 | 6889 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.getModalityFromDescriptor
import org.jetbrains.kotlin.idea.quickfix.sealedSubClassToObject.ConvertSealedSubClassToObjectFix
import org.jetbrains.kotlin.idea.quickfix.sealedSubClassToObject.GenerateIdentityEqualsFix
import org.jetbrains.kotlin.idea.refactoring.isAbstract
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.isEffectivelyActual
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.inspections.CanSealedSubClassBeObjectInspection.Holder.matchesCanBeObjectCriteria
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class CanSealedSubClassBeObjectInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
fun reportPossibleObject(klass: KtClass) {
val keyword = klass.getClassOrInterfaceKeyword() ?: return
val isExpectClass = klass.isExpectDeclaration()
val fixes = listOfNotNull(
createFixIfPossible(!isExpectClass && !klass.isEffectivelyActual(), ::ConvertSealedSubClassToObjectFix),
createFixIfPossible(!isExpectClass && klass.module?.platform?.isJvm() == true, ::GenerateIdentityEqualsFix),
).toTypedArray()
holder.registerProblem(
keyword,
KotlinBundle.message("sealed.sub.class.has.no.state.and.no.overridden.equals"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixes,
)
}
return object : KtVisitorVoid() {
override fun visitClass(klass: KtClass) {
if (klass.matchesCanBeObjectCriteria()) {
reportPossibleObject(klass)
}
}
}
}
private object Holder {
val EQUALS: String = OperatorNameConventions.EQUALS.asString()
const val HASH_CODE: String = "hashCode"
val CLASS_MODIFIERS: List<KtModifierKeywordToken> = listOf(
KtTokens.ANNOTATION_KEYWORD,
KtTokens.DATA_KEYWORD,
KtTokens.ENUM_KEYWORD,
KtTokens.INNER_KEYWORD,
KtTokens.SEALED_KEYWORD,
)
fun KtClass.matchesCanBeObjectCriteria(): Boolean {
return isSubclassOfStatelessSealed()
&& withEmptyConstructors()
&& hasNoClassModifiers()
&& isFinal()
&& typeParameters.isEmpty()
&& hasNoInnerClass()
&& companionObjects.isEmpty()
&& hasNoStateOrEquals()
}
fun KtClass.isSubclassOfStatelessSealed(): Boolean {
fun KtSuperTypeListEntry.asKtClass(): KtClass? = typeAsUserType?.referenceExpression?.mainReference?.resolve() as? KtClass
return superTypeListEntries.asSequence().mapNotNull { it.asKtClass() }.any {
it.isSealed() && it.hasNoStateOrEquals() && it.baseClassHasNoStateOrEquals()
}
}
fun KtClass.withEmptyConstructors(): Boolean =
primaryConstructorParameters.isEmpty() && secondaryConstructors.all { it.valueParameters.isEmpty() }
fun KtClass.hasNoClassModifiers(): Boolean {
val modifierList = modifierList ?: return true
return CLASS_MODIFIERS.none { modifierList.hasModifier(it) }
}
fun KtClass.isFinal(): Boolean = getModalityFromDescriptor() == KtTokens.FINAL_KEYWORD
tailrec fun KtClass.baseClassHasNoStateOrEquals(): Boolean {
val descriptor = resolveToDescriptorIfAny() ?: return false
val superDescriptor = descriptor.getSuperClassNotAny() ?: return true // No super class -- no state
val superClass = DescriptorToSourceUtils.descriptorToDeclaration(superDescriptor) as? KtClass ?: return false
if (!superClass.hasNoStateOrEquals()) return false
return superClass.baseClassHasNoStateOrEquals()
}
fun KtClass.hasNoStateOrEquals(): Boolean {
if (primaryConstructor?.valueParameters?.isNotEmpty() == true) return false
val body = body
return body == null || run {
val declarations = body.declarations
declarations.asSequence().filterIsInstance<KtProperty>().none { property ->
// Simplified "backing field required"
when {
property.isAbstract() -> false
property.initializer != null -> true
property.delegate != null -> false
!property.isVar -> property.getter == null
else -> property.getter == null || property.setter == null
}
} && declarations.asSequence().filterIsInstance<KtNamedFunction>().none { function ->
val name = function.name
val valueParameters = function.valueParameters
val noTypeParameters = function.typeParameters.isEmpty()
noTypeParameters && (name == EQUALS && valueParameters.size == 1 || name == HASH_CODE && valueParameters.isEmpty())
}
}
}
fun KtClass.hasNoInnerClass(): Boolean {
val internalClasses = body
?.declarations
?.filterIsInstance<KtClass>() ?: return true
return internalClasses.none { klass -> klass.isInner() }
}
}
}
private fun <T : LocalQuickFix> createFixIfPossible(
flag: Boolean,
quickFixFactory: () -> T,
): T? = quickFixFactory.takeIf { flag }?.invoke()
| apache-2.0 | 5d4d0f28a86e2c24bf6936ae831c807d | 47.174825 | 158 | 0.665554 | 5.520032 | false | false | false | false |
FlexSeries/FlexLib | src/main/kotlin/me/st28/flexseries/flexlib/commands/CmdFlexPlugin.kt | 1 | 3103 | /**
* Copyright 2016 Stealth2800 <http://stealthyone.com/>
* Copyright 2016 Contributors <https://github.com/FlexSeries>
*
* 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 me.st28.flexseries.flexlib.commands
import me.st28.flexseries.flexlib.command.CommandHandler
import me.st28.flexseries.flexlib.message.Message
import me.st28.flexseries.flexlib.plugin.FlexPlugin
import org.bukkit.Bukkit
import org.bukkit.command.CommandSender
object CmdFlexPlugin {
@CommandHandler(
"flexreload",
description = "Reloads a FlexPlugin or specified module",
permission = "flexlib.reload"
)
fun reload(sender: CommandSender, plugin: String, module: String?): Message {
val found = Bukkit.getPluginManager().plugins.firstOrNull { it.name.equals(plugin, true) }
?: return Message.getGlobal("error.plugin_not_found", plugin)
if (found !is FlexPlugin) {
return Message.getGlobal("error.plugin_not_flexplugin", found.name)
}
val foundModule = if (module == null) {
null
} else {
found.modules.values.firstOrNull { it.name.equals(module, true) }
}
return if (foundModule == null) {
// Reload plugin
found.reloadAll()
Message.getGlobal("notice.plugin_reloaded", found.name)
} else {
// Reload module
foundModule.reload()
Message.getGlobal("notice.module_reloaded", found.name, foundModule.name)
}
}
@CommandHandler(
"flexsave",
description = "Saves a FlexPlugin or specified module",
permission = "flexlib.save"
)
fun save(sender: CommandSender, plugin: String, module: String?): Message {
val found = Bukkit.getPluginManager().plugins.firstOrNull { it.name.equals(plugin, true) }
?: return Message.getGlobal("error.plugin_not_found", plugin)
if (found !is FlexPlugin) {
return Message.getGlobal("error.plugin_not_flexplugin", found.name)
}
val foundModule = if (module == null) {
null
} else {
found.modules.values.firstOrNull { it.name.equals(module, true) }
}
return if (foundModule == null) {
// Save plugin
found.saveAll(true)
Message.getGlobal("notice.plugin_reloaded", found.name)
} else {
// Save module
foundModule.save(true)
Message.getGlobal("notice.module_reloaded", found.name, foundModule.name)
}
}
} | apache-2.0 | cf811905112e72850be68d3015dd415b | 34.678161 | 98 | 0.638092 | 4.33986 | false | false | false | false |
iPoli/iPoli-android | app/src/test/java/io/ipoli/android/pet/usecase/ComparePetItemsUseCaseSpek.kt | 1 | 1969 | package io.ipoli.android.pet.usecase
import io.ipoli.android.pet.PetItem
import org.amshove.kluent.`should equal`
import org.amshove.kluent.shouldThrow
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
/**
* Created by Venelin Valkov <[email protected]>
* on 23.12.17.
*/
class ComparePetItemsUseCaseSpek : Spek({
describe("ComparePetItemsUseCase") {
fun executeUseCase(currentItem: PetItem?, newItem: PetItem) =
ComparePetItemsUseCase().execute(ComparePetItemsUseCase.Params(currentItem, newItem))
val newItem = PetItem.GLASSES
it("should not compare different type of items") {
val exec = { executeUseCase(PetItem.RED_HAT, newItem) }
exec shouldThrow IllegalArgumentException::class
}
it("should give no bonus difference between same items") {
val result = executeUseCase(newItem, newItem)
val expectedResult = ComparePetItemsUseCase.Result(0, 0, 0)
result.`should equal`(expectedResult)
}
it("should give bonus from new item when no current item") {
val result = executeUseCase(null, newItem)
val expectedResult = ComparePetItemsUseCase.Result(
newItem.experienceBonus,
newItem.coinBonus,
newItem.bountyBonus
)
result.`should equal`(expectedResult)
}
it("should give correct bonuses for new item") {
val currentItem = PetItem.BEARD
val result = executeUseCase(currentItem, newItem)
val expectedResult = ComparePetItemsUseCase.Result(
newItem.experienceBonus - currentItem.experienceBonus,
newItem.coinBonus - currentItem.coinBonus,
newItem.bountyBonus - currentItem.bountyBonus
)
result.`should equal`(expectedResult)
}
}
}) | gpl-3.0 | 71d029320810ca7ec3b083d3c7179f8d | 35.481481 | 97 | 0.649568 | 4.802439 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/compiler-plugins/kotlinx-serialization/common/src/org/jetbrains/kotlin/idea/compilerPlugin/kotlinxSerialization/compiler/diagnostic/JsonFormatRedundantDiagnostic.kt | 4 | 4517 | // 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.compilerPlugin.kotlinxSerialization.compiler.diagnostic
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.calls.util.getReceiverExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext
import org.jetbrains.kotlin.resolve.calls.model.DefaultValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedValueArgument
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.unpackFunctionLiteral
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlinx.serialization.compiler.diagnostic.SerializationErrors
class JsonFormatRedundantDiagnostic : CallChecker {
private val jsonFqName = FqName("kotlinx.serialization.json.Json")
private val jsonDefaultFqName = FqName("kotlinx.serialization.json.Json.Default")
private val parameterNameFrom = Name.identifier("from")
private val parameterNameBuilderAction = Name.identifier("builderAction")
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
val functionDescriptor = resolvedCall.resultingDescriptor as? SimpleFunctionDescriptor ?: return
val bindingContext = context.trace.bindingContext
if (isJsonFormatCreation(functionDescriptor)) {
if (isDefaultFormat(resolvedCall, bindingContext)) {
context.trace.report(SerializationErrors.JSON_FORMAT_REDUNDANT_DEFAULT.on(resolvedCall.call.callElement))
}
return
}
val receiverExpression = resolvedCall.getReceiverExpression() ?: return
val receiverResolvedCall = receiverExpression.getResolvedCall(bindingContext) ?: return
val receiverFunctionDescriptor = receiverResolvedCall.resultingDescriptor as? SimpleFunctionDescriptor ?: return
if (isJsonFormatCreation(receiverFunctionDescriptor) && !isDefaultFormat(receiverResolvedCall, bindingContext)) {
context.trace.report(SerializationErrors.JSON_FORMAT_REDUNDANT.on(receiverExpression.originalElement))
}
}
private fun isJsonFormatCreation(descriptor: SimpleFunctionDescriptor): Boolean {
return descriptor.importableFqName == jsonFqName
}
private fun isDefaultFormat(resolvedCall: ResolvedCall<*>, context: BindingContext): Boolean {
var defaultFrom = false
var emptyBuilder = false
resolvedCall.valueArguments.forEach { (paramDesc, arg) ->
when (paramDesc.name) {
parameterNameFrom -> defaultFrom = isDefaultFormatArgument(arg, context)
parameterNameBuilderAction -> emptyBuilder = isEmptyFunctionArgument(arg)
}
}
return defaultFrom && emptyBuilder
}
private fun isDefaultFormatArgument(arg: ResolvedValueArgument, context: BindingContext): Boolean {
if (arg is DefaultValueArgument) return true
if (arg !is ExpressionValueArgument) return false
val expression = arg.valueArgument?.getArgumentExpression() ?: return false
val fqName = context[BindingContext.EXPRESSION_TYPE_INFO, expression]?.type?.fqName ?: return false
return fqName == jsonDefaultFqName
}
private fun isEmptyFunctionArgument(arg: ResolvedValueArgument): Boolean {
if (arg !is ExpressionValueArgument) {
return false
}
val argumentExpression = arg.valueArgument?.getArgumentExpression() ?: return false
val blockExpression = if (argumentExpression is KtNamedFunction) {
// anonymous functions
argumentExpression.bodyBlockExpression ?: return true
} else {
// function literal
argumentExpression.unpackFunctionLiteral()?.bodyExpression
}
return blockExpression?.statements?.isEmpty() ?: false
}
}
| apache-2.0 | a5dc74c00cba2ca87cbafcab9381c97f | 47.053191 | 158 | 0.751826 | 5.377381 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/GrMethodReferenceResolver.kt | 8 | 2480 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightMethodBuilder
import org.jetbrains.plugins.groovy.GroovyLanguage
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.impl.GrMethodReferenceExpressionImpl
import org.jetbrains.plugins.groovy.lang.psi.impl.GrMethodReferenceExpressionImpl.Companion.CONSTRUCTOR_REFERENCE_NAME
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.unwrapClassType
import org.jetbrains.plugins.groovy.lang.resolve.impl.getAllConstructorResults
import org.jetbrains.plugins.groovy.lang.resolve.processors.MethodReferenceProcessor
internal object GrMethodReferenceResolver : GroovyResolver<GrMethodReferenceExpressionImpl> {
override fun resolve(ref: GrMethodReferenceExpressionImpl, incomplete: Boolean): Array<GroovyResolveResult> {
val name = ref.referenceName ?: return GroovyResolveResult.EMPTY_ARRAY
val type = ref.qualifier?.type ?: return GroovyResolveResult.EMPTY_ARRAY
val methods = run {
val processor = MethodReferenceProcessor(name)
type.processReceiverType(processor, ResolveState.initial(), ref)
processor.results
}
val unwrapped = unwrapClassType(type) ?: return methods.toTypedArray()
val constructors = if (name == CONSTRUCTOR_REFERENCE_NAME) {
when (unwrapped) {
is PsiClassType -> getAllConstructorResults(unwrapped, ref).toList()
is PsiArrayType -> fakeArrayConstructors(unwrapped, ref.manager)
else -> emptyList()
}
}
else {
emptyList()
}
return (methods + constructors).toTypedArray()
}
private fun fakeArrayConstructors(type: PsiArrayType, manager: PsiManager): List<GroovyResolveResult> {
return (0 until type.arrayDimensions).map { i ->
ElementResolveResult(fakeArrayConstructor(type, manager, i))
}
}
private fun fakeArrayConstructor(type: PsiArrayType, manager: PsiManager, dimensions: Int): LightMethodBuilder {
return LightMethodBuilder(manager, GroovyLanguage, "fake array constructor").apply {
setMethodReturnType(type)
if (dimensions == 0) {
addParameter("size", PsiType.INT)
}
else {
for (i in 0..dimensions) {
addParameter("size$i", PsiType.INT)
}
}
}
}
}
| apache-2.0 | 60fab3cbf71683ff462d4cc8529559c5 | 39.655738 | 120 | 0.746774 | 4.601113 | false | false | false | false |
jk1/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebBrowserUrlProvider.kt | 2 | 4222 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.builtInWebServer
import com.intellij.ide.browsers.OpenInBrowserRequest
import com.intellij.ide.browsers.WebBrowserService
import com.intellij.ide.browsers.WebBrowserUrlProvider
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.impl.http.HttpVirtualFile
import com.intellij.psi.PsiFile
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.SmartList
import com.intellij.util.Url
import com.intellij.util.Urls
import org.jetbrains.ide.BuiltInServerManager
open class BuiltInWebBrowserUrlProvider : WebBrowserUrlProvider(), DumbAware {
override fun canHandleElement(request: OpenInBrowserRequest): Boolean {
if (request.virtualFile is HttpVirtualFile) {
return true
}
// we must use base language because we serve file - not part of file, but the whole file
// handlebars, for example, contains HTML and HBS psi trees, so, regardless of context, we should not handle such file
val viewProvider = request.file.viewProvider
return viewProvider.isPhysical && request.virtualFile !is LightVirtualFile && isFileOfMyLanguage(request.file)
}
protected open fun isFileOfMyLanguage(psiFile: PsiFile): Boolean = WebBrowserService.isHtmlOrXmlFile(psiFile)
override fun getUrl(request: OpenInBrowserRequest, file: VirtualFile): Url? {
if (file is HttpVirtualFile) {
return Urls.newFromVirtualFile(file)
}
else {
return getBuiltInServerUrls(file, request.project, null, request.isAppendAccessToken).firstOrNull()
}
}
}
@JvmOverloads
fun getBuiltInServerUrls(file: VirtualFile,
project: Project,
currentAuthority: String?,
appendAccessToken: Boolean = true): List<Url> {
if (currentAuthority != null && !compareAuthority(currentAuthority)) {
return emptyList()
}
val info = WebServerPathToFileManager.getInstance(project).getPathInfo(file) ?: return emptyList()
val effectiveBuiltInServerPort = BuiltInServerOptions.getInstance().effectiveBuiltInServerPort
val path = info.path
val authority = currentAuthority ?: "localhost:$effectiveBuiltInServerPort"
val query = if (appendAccessToken) "?$TOKEN_PARAM_NAME=${acquireToken()}" else ""
val urls = SmartList(Urls.newHttpUrl(authority, "/${project.name}/$path", query))
val path2 = info.rootLessPathIfPossible
if (path2 != null) {
urls.add(Urls.newHttpUrl(authority, '/' + project.name + '/' + path2, query))
}
val defaultPort = BuiltInServerManager.getInstance().port
if (currentAuthority == null && defaultPort != effectiveBuiltInServerPort) {
val defaultAuthority = "localhost:$defaultPort"
urls.add(Urls.newHttpUrl(defaultAuthority, "/${project.name}/$path", query))
if (path2 != null) {
urls.add(Urls.newHttpUrl(defaultAuthority, "/${project.name}/$path2", query))
}
}
return urls
}
fun compareAuthority(currentAuthority: String?): Boolean {
if (currentAuthority.isNullOrEmpty()) {
return false
}
val portIndex = currentAuthority!!.indexOf(':')
if (portIndex < 0) {
return false
}
val host = currentAuthority.substring(0, portIndex)
if (!isOwnHostName(host)) {
return false
}
val port = StringUtil.parseInt(currentAuthority.substring(portIndex + 1), -1)
return port == BuiltInServerOptions.getInstance().effectiveBuiltInServerPort || port == BuiltInServerManager.getInstance().port
} | apache-2.0 | bf02c09131156fbcbf96626fdb9c66f5 | 37.743119 | 129 | 0.735433 | 4.472458 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-core/posix/src/io/ktor/client/engine/Loader.kt | 1 | 1305 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine
import io.ktor.util.*
import kotlinx.atomicfu.*
private typealias EngineFactory = HttpClientEngineFactory<HttpClientEngineConfig>
@InternalAPI
@Suppress("KDocMissingDocumentation")
/**
* Shared engines collection for.
* Use [append] to enable engine auto discover in [HttpClient()].
*/
public object engines : Iterable<EngineFactory> {
private val head = atomic<Node?>(null)
/**
* Add engine to head.
*/
public fun append(item: EngineFactory) {
while (true) {
val current = head.value
val new = Node(item, current)
if (head.compareAndSet(current, new)) break
}
}
/**
* @return unfrozen collection iterator.
*/
override fun iterator(): Iterator<EngineFactory> = object : Iterator<EngineFactory> {
var current = head.value
override fun next(): EngineFactory {
val result = current!!
current = result.next
return result.item
}
override fun hasNext(): Boolean = (null != current)
}
private class Node(
val item: EngineFactory,
val next: Node?
)
}
| apache-2.0 | 4705cb9241054d49cc6d1fd327e422fc | 24.096154 | 119 | 0.629119 | 4.484536 | false | false | false | false |
bgogetap/KotlinWeather | app/src/main/kotlin/com/cultureoftech/kotlinweather/base/MainActivity.kt | 1 | 6054 | package com.cultureoftech.kotlinweather.base
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.widget.FrameLayout
import com.cultureoftech.kotlinweather.R
import com.cultureoftech.kotlinweather.main.MainScreen
import com.cultureoftech.kotlinweather.ui.*
import com.cultureoftech.kotlinweather.utils.bindView
import java.util.*
import javax.inject.Inject
class MainActivity : BaseActivity(), UiManager.View {
@Inject lateinit var backStack: BackStack
@Inject lateinit var presenter: ActivityPresenter
@Inject lateinit var uiManager: UiManager
private var animationRunning: Boolean = false
private var currentMenuResource: Int = 0
private val container: FrameLayout by bindView(R.id.fl_container)
private val toolbar: Toolbar by bindView<Toolbar>(R.id.toolbar)
private val resultDelegates: LinkedHashSet<ActivityResultDelegate?> = LinkedHashSet()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MyApplication.component.inject(this)
presenter.takeView(this)
uiManager.takeView(this)
setSupportActionBar(toolbar)
toolbar.setNavigationOnClickListener { pop() }
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
if (backStack.size() == 0) {
push(MainScreen())
} else {
backStack.forEach { it.view = null }
val topItem: BackStackItem = backStack.peek()
backStack.forEach {
val isTop: Boolean = topItem == it
addView(it)
it.view?.visibility = if (isTop) VISIBLE else GONE
if (isTop) {
currentMenuResource = it.screen.menuResource()
}
}
}
handleBackIcon()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
if (currentMenuResource > 0) {
menuInflater.inflate(currentMenuResource, menu)
}
resultDelegates.forEach { it?.onCreateOptionsMenu(menu) }
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
resultDelegates.forEach { if (it?.onOptionsItemSelected(item) ?: false) return true}
return super.onOptionsItemSelected(item)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (permissions.size == 0) return
permissionHelper.dialogShowing = false
resultDelegates.forEach { it?.onRequestPermissionsResult(requestCode, permissions, grantResults) }
}
override fun push(screen: Screen<*>) {
if (animationRunning) return
animationRunning = true
val v: View = addLayout(screen)
if (container.childCount > 1) {
screen.animationConfiguration()
.animateIn(container, v, Runnable {
animationRunning = false
container.getChildAt(container.childCount - 2).visibility = GONE
})
} else {
animationRunning = false
}
handleBackIcon()
}
override fun pop() {
if (animationRunning) return
animationRunning = true
if (backStack.size() > 1) {
container.getChildAt(container.childCount - 2).visibility = VISIBLE
val item: BackStackItem = backStack.pop()
if (backStack.peek().view is ViewRoot) {
updateTitle((backStack.peek().view as ViewRoot).getTitle())
}
if (item.view != null) {
item.screen.animationConfiguration().animateOut(container, item.view!!, Runnable {
container.removeView(item.view)
animationRunning = false
})
}
item.screen.destroyComponent()
currentMenuResource = backStack.peek().screen.menuResource()
resetToolbarMenu()
handleBackIcon()
} else {
finish()
}
}
private fun addLayout(screen: Screen<*>): View {
val view: View = screen.view(this)
val item: BackStackItem = BackStackItem(screen, view)
backStack.push(item)
currentMenuResource = item.screen.menuResource()
resetToolbarMenu()
addView(item)
return view
}
private fun addView(backStackItem: BackStackItem) {
if (backStackItem.view == null || backStackItem.view?.context != this) {
backStackItem.view = backStackItem.screen.view(this)
}
if (backStackItem.view?.parent != null) {
(backStackItem.view?.parent as ViewGroup).removeView(backStackItem.view)
}
if (backStackItem.view is ViewRoot) {
updateTitle((backStackItem.view as ViewRoot).getTitle())
}
container.addView(backStackItem.view)
}
override fun updateTitle(title: CharSequence) {
toolbar.title = title
}
override fun setLoadingSpinner(show: Boolean) {
}
fun registerResultDelegate(delegate: ActivityResultDelegate) {
resultDelegates.add(delegate)
}
fun unregisterResultDelegate(delegate: ActivityResultDelegate) {
resultDelegates.remove(delegate)
}
fun resetToolbarMenu() {
invalidateOptionsMenu()
}
fun handleBackIcon() {
if (backStack.size() > 1) {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
} else {
supportActionBar?.setDisplayHomeAsUpEnabled(false)
}
}
override fun onBackPressed() {
pop()
}
override fun onDestroy() {
presenter.dropView(this)
uiManager.dropView(this)
super.onDestroy()
}
}
| apache-2.0 | ad865caddcbfa3bc3096713763336756 | 33.011236 | 119 | 0.634787 | 4.925956 | false | false | false | false |
chaojimiaomiao/colorful_wechat | src/main/kotlin/com/rarnu/tophighlight/market/ThemeListActivity.kt | 1 | 5092 | package com.rarnu.tophighlight.market
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.GridView
import com.rarnu.tophighlight.R
import com.rarnu.tophighlight.api.LocalApi
import com.rarnu.tophighlight.api.Theme
import com.rarnu.tophighlight.api.ThemeINI
import com.rarnu.tophighlight.api.WthApi
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread
/**
* getThemeList page=1 pageSize=2 sort=date
* theme_get_download_url id=15
* errorcode url
* http://rarnu.xyz/wth/theme/url
*/
class ThemeListActivity : BaseMarkerActivity() {
companion object {
val MENUID_PROFILE = 1;
val BASEURL = "http://rarnu.xyz/wth/theme/";
}
private var miProfile: MenuItem? = null
private var listTheme: MutableList<ThemeINI>? = null
private var gvTheme: GridView? = null
private var adapterTheme: ThemeListAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
LocalApi.ctx = this
setContentView(R.layout.activity_themelist)
actionBar.setTitle(R.string.view_themes)
gvTheme = findViewById(R.id.gvTheme) as GridView?
listTheme = arrayListOf()
adapterTheme = ThemeListAdapter(this, listTheme)
gvTheme?.adapter = adapterTheme
loadThemeList()
}
private fun loadLocalThemeList() {
//listTheme?.add(LocalTheme.themePurple)
//adapterTheme?.setList(listTheme)
}
private fun loadThemeList() {
val hTheme = object : Handler() {
override fun handleMessage(msg: Message?) {
adapterTheme?.setList(listTheme)
super.handleMessage(msg)
}
}
var wht = Environment.getExternalStorageDirectory().absolutePath
Log.e("wht", "wht: " + wht)
thread {
listTheme?.clear()
val list = WthApi.themeGetList(1, 20, "date") as List<Theme>
println("list = $list")
for(theme : Theme in list) {
Log.e("wht", "theme => $theme")
var url = WthApi.themeGetDownloadUrl(theme.id)
//val ini = WthApi.readThemeFromINI(wht + "/theme.ini")
val filename = downloadFile(BASEURL + url)
Log.e("themelist", "filename: " + filename)
val ini = WthApi.readThemeFromINI(filename)
if (ini != null) {
listTheme?.add(ini)
}
}
// TODO: download theme file and make preview
hTheme.sendEmptyMessage(0)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
miProfile = menu?.add(0, MENUID_PROFILE, 1, R.string.menu_profile)
miProfile?.setIcon(android.R.drawable.ic_menu_myplaces)
miProfile?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
MENUID_PROFILE -> {
if (LocalApi.userId == 0) {
// login / register
startActivityForResult(Intent(this, UserLoginRegisterActivity::class.java), 0)
} else {
// user profile
startActivity(Intent(this, UserProfileActivity::class.java))
}
}
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode != Activity.RESULT_OK) return
when(requestCode) {
0 -> {
// TODO: login or register callback
}
}
}
fun downloadFile(iniUrl: String) : String{
var lists = iniUrl.split("/")
var localFile = "/sdcard/" + lists.last()
val fTmp = File(localFile)
if (fTmp.exists()) {
fTmp.delete()
}
var url: URL?
var filesize = 0
try {
url = URL(iniUrl)
val con = url.openConnection() as HttpURLConnection
var ins = con.inputStream
filesize = con.contentLength
val fileOut = File(localFile + ".tmp")
val out = FileOutputStream(fileOut)
val buffer = ByteArray(1024)
var count: Int
while (true) {
count = ins.read(buffer)
if (count != -1) {
out.write(buffer, 0, count)
} else {
break
}
}
ins.close()
out.close()
fileOut.renameTo(fTmp)
} catch (e: Exception) {
Log.e("", "下载文件失败")
}
return localFile
}
} | gpl-3.0 | 429343ff1583be6e307684221ba2b758 | 30.75625 | 98 | 0.583071 | 4.276094 | false | false | false | false |
google/android-fhir | engine/src/test/java/com/google/android/fhir/sync/upload/TransactionBundleGeneratorTest.kt | 1 | 7724 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.sync.upload
import ca.uhn.fhir.context.FhirContext
import ca.uhn.fhir.context.FhirVersionEnum
import com.google.android.fhir.db.impl.dao.LocalChangeToken
import com.google.android.fhir.db.impl.dao.LocalChangeUtils
import com.google.android.fhir.db.impl.dao.toLocalChange
import com.google.android.fhir.db.impl.entities.LocalChangeEntity
import com.google.android.fhir.db.impl.entities.LocalChangeEntity.Type
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.runBlocking
import org.hl7.fhir.r4.model.Bundle
import org.hl7.fhir.r4.model.HumanName
import org.hl7.fhir.r4.model.Patient
import org.hl7.fhir.r4.model.ResourceType
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class TransactionBundleGeneratorTest {
@Test
fun `generate() should return empty list if there are no local changes`() = runBlocking {
val generator = TransactionBundleGenerator.Factory.getDefault()
val result = generator.generate(listOf(listOf(), listOf()))
assertThat(result).isEmpty()
}
@Test
fun `generate() should return single Transaction Bundle with 3 entries`() = runBlocking {
val jsonParser = FhirContext.forCached(FhirVersionEnum.R4).newJsonParser()
val changes =
listOf(
LocalChangeEntity(
id = 1,
resourceType = ResourceType.Patient.name,
resourceId = "Patient-001",
type = Type.INSERT,
payload =
jsonParser.encodeResourceToString(
Patient().apply {
id = "Patient-001"
addName(
HumanName().apply {
addGiven("John")
family = "Doe"
}
)
}
)
)
.toLocalChange()
.apply { token = LocalChangeToken(listOf(1)) },
LocalChangeEntity(
id = 2,
resourceType = ResourceType.Patient.name,
resourceId = "Patient-002",
type = Type.UPDATE,
payload =
LocalChangeUtils.diff(
jsonParser,
Patient().apply {
id = "Patient-002"
addName(
HumanName().apply {
addGiven("Jane")
family = "Doe"
}
)
},
Patient().apply {
id = "Patient-002"
addName(
HumanName().apply {
addGiven("Janet")
family = "Doe"
}
)
}
)
.toString()
)
.toLocalChange()
.apply { LocalChangeToken(listOf(2)) },
LocalChangeEntity(
id = 3,
resourceType = ResourceType.Patient.name,
resourceId = "Patient-003",
type = Type.DELETE,
payload =
jsonParser.encodeResourceToString(
Patient().apply {
id = "Patient-003"
addName(
HumanName().apply {
addGiven("John")
family = "Roe"
}
)
}
)
)
.toLocalChange()
.apply { LocalChangeToken(listOf(3)) }
)
val generator = TransactionBundleGenerator.Factory.getDefault()
val result = generator.generate(listOf(changes))
assertThat(result).hasSize(1)
val (bundle, _) = result.first()
assertThat(bundle.type).isEqualTo(Bundle.BundleType.TRANSACTION)
assertThat(bundle.entry).hasSize(3)
assertThat(bundle.entry.map { it.request.method })
.containsExactly(Bundle.HTTPVerb.PUT, Bundle.HTTPVerb.PATCH, Bundle.HTTPVerb.DELETE)
.inOrder()
}
@Test
fun `generate() should return 3 Transaction Bundle with single entry each`() = runBlocking {
val jsonParser = FhirContext.forCached(FhirVersionEnum.R4).newJsonParser()
val changes =
listOf(
LocalChangeEntity(
id = 1,
resourceType = ResourceType.Patient.name,
resourceId = "Patient-001",
type = Type.INSERT,
payload =
jsonParser.encodeResourceToString(
Patient().apply {
id = "Patient-001"
addName(
HumanName().apply {
addGiven("John")
family = "Doe"
}
)
}
)
)
.toLocalChange()
.apply { token = LocalChangeToken(listOf(1)) },
LocalChangeEntity(
id = 2,
resourceType = ResourceType.Patient.name,
resourceId = "Patient-002",
type = Type.UPDATE,
payload =
LocalChangeUtils.diff(
jsonParser,
Patient().apply {
id = "Patient-002"
addName(
HumanName().apply {
addGiven("Jane")
family = "Doe"
}
)
},
Patient().apply {
id = "Patient-002"
addName(
HumanName().apply {
addGiven("Janet")
family = "Doe"
}
)
}
)
.toString()
)
.toLocalChange()
.apply { LocalChangeToken(listOf(2)) },
LocalChangeEntity(
id = 3,
resourceType = ResourceType.Patient.name,
resourceId = "Patient-003",
type = Type.DELETE,
payload =
jsonParser.encodeResourceToString(
Patient().apply {
id = "Patient-003"
addName(
HumanName().apply {
addGiven("John")
family = "Roe"
}
)
}
)
)
.toLocalChange()
.apply { LocalChangeToken(listOf(3)) }
)
val generator = TransactionBundleGenerator.Factory.getDefault()
val result = generator.generate(changes.chunked(1))
// Exactly 3 Bundles are generated
assertThat(result).hasSize(3)
// Each Bundle is of type transaction
assertThat(result.all { it.first.type == Bundle.BundleType.TRANSACTION }).isTrue()
// Each Bundle has exactly 1 entry
assertThat(result.all { it.first.entry.size == 1 }).isTrue()
assertThat(result.map { it.first.entry.first().request.method })
.containsExactly(Bundle.HTTPVerb.PUT, Bundle.HTTPVerb.PATCH, Bundle.HTTPVerb.DELETE)
.inOrder()
}
}
| apache-2.0 | d7a4711d602a8985c71baee9e33cdda5 | 33.328889 | 94 | 0.518773 | 4.973599 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/uhabits/widgets/StackWidgetService.kt | 1 | 6625 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.widgets
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Looper
import android.util.Log
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import android.widget.RemoteViewsService.RemoteViewsFactory
import org.isoron.platform.utils.StringUtils.Companion.splitLongs
import org.isoron.uhabits.HabitsApplication
import org.isoron.uhabits.R
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.HabitNotFoundException
import org.isoron.uhabits.core.preferences.Preferences
import org.isoron.uhabits.core.utils.DateUtils.Companion.getToday
import org.isoron.uhabits.intents.IntentFactory
import org.isoron.uhabits.intents.PendingIntentFactory
import org.isoron.uhabits.utils.InterfaceUtils.dpToPixels
class StackWidgetService : RemoteViewsService() {
override fun onGetViewFactory(intent: Intent): RemoteViewsFactory {
return StackRemoteViewsFactory(this.applicationContext, intent)
}
companion object {
const val WIDGET_TYPE = "WIDGET_TYPE"
const val HABIT_IDS = "HABIT_IDS"
}
}
internal class StackRemoteViewsFactory(private val context: Context, intent: Intent) :
RemoteViewsFactory {
private val widgetId: Int = intent.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID
)
private val habitIds: LongArray
private val widgetType: StackWidgetType
override fun onCreate() {}
override fun onDestroy() {}
override fun getCount(): Int {
return habitIds.size
}
fun getDimensionsFromOptions(
ctx: Context,
options: Bundle
): WidgetDimensions {
val maxWidth = dpToPixels(
ctx,
options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH).toFloat()
).toInt()
val maxHeight = dpToPixels(
ctx,
options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT).toFloat()
).toInt()
val minWidth = dpToPixels(
ctx,
options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH).toFloat()
).toInt()
val minHeight = dpToPixels(
ctx,
options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT).toFloat()
).toInt()
return WidgetDimensions(minWidth, maxHeight, maxWidth, minHeight)
}
override fun getViewAt(position: Int): RemoteViews? {
Log.i("StackRemoteViewsFactory", "getViewAt $position started")
if (position < 0 || position >= habitIds.size) return null
val app = context.applicationContext as HabitsApplication
val prefs = app.component.preferences
val habitList = app.component.habitList
val options = AppWidgetManager.getInstance(context).getAppWidgetOptions(widgetId)
if (Looper.myLooper() == null) Looper.prepare()
val habits = habitIds.map { habitList.getById(it) ?: throw HabitNotFoundException() }
val h = habits[position]
val widget = constructWidget(h, prefs)
widget.setDimensions(getDimensionsFromOptions(context, options))
val landscapeViews = widget.landscapeRemoteViews
val portraitViews = widget.portraitRemoteViews
val factory = PendingIntentFactory(context, IntentFactory())
val intent = StackWidgetType.getIntentFillIn(factory, widgetType, h, habits, getToday())
landscapeViews.setOnClickFillInIntent(R.id.button, intent)
portraitViews.setOnClickFillInIntent(R.id.button, intent)
val remoteViews = RemoteViews(landscapeViews, portraitViews)
Log.i("StackRemoteViewsFactory", "getViewAt $position ended")
return remoteViews
}
private fun constructWidget(
habit: Habit,
prefs: Preferences
): BaseWidget {
return when (widgetType) {
StackWidgetType.CHECKMARK -> CheckmarkWidget(context, widgetId, habit, true)
StackWidgetType.FREQUENCY -> FrequencyWidget(
context,
widgetId,
habit,
prefs.firstWeekdayInt,
true
)
StackWidgetType.SCORE -> ScoreWidget(context, widgetId, habit, true)
StackWidgetType.HISTORY -> HistoryWidget(context, widgetId, habit, true)
StackWidgetType.STREAKS -> StreakWidget(context, widgetId, habit, true)
StackWidgetType.TARGET -> TargetWidget(context, widgetId, habit, true)
}
}
override fun getLoadingView(): RemoteViews {
val options = AppWidgetManager.getInstance(context).getAppWidgetOptions(widgetId)
val widget = EmptyWidget(context, widgetId)
widget.setDimensions(getDimensionsFromOptions(context, options))
val landscapeViews = widget.landscapeRemoteViews
val portraitViews = widget.portraitRemoteViews
return RemoteViews(landscapeViews, portraitViews)
}
override fun getViewTypeCount(): Int {
return 1
}
override fun getItemId(position: Int): Long {
return habitIds[position]
}
override fun hasStableIds(): Boolean {
return true
}
override fun onDataSetChanged() {
}
init {
val widgetTypeValue = intent.getIntExtra(StackWidgetService.WIDGET_TYPE, -1)
val habitIdsStr = intent.getStringExtra(StackWidgetService.HABIT_IDS)
if (widgetTypeValue < 0) throw RuntimeException("invalid widget type")
if (habitIdsStr == null) throw RuntimeException("habitIdsStr is null")
widgetType = StackWidgetType.getWidgetTypeFromValue(widgetTypeValue)
?: throw RuntimeException("unknown widget type value: $widgetTypeValue")
habitIds = splitLongs(habitIdsStr)
}
}
| gpl-3.0 | dacd2ea3fd6eafcd6c81681ecfe6946b | 39.145455 | 96 | 0.702597 | 4.824472 | false | false | false | false |
iSoron/uhabits | uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/models/HabitMatcher.kt | 1 | 1546 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.core.models
data class HabitMatcher(
val isArchivedAllowed: Boolean = false,
val isReminderRequired: Boolean = false,
val isCompletedAllowed: Boolean = true,
val isEnteredAllowed: Boolean = true,
) {
fun matches(habit: Habit): Boolean {
if (!isArchivedAllowed && habit.isArchived) return false
if (isReminderRequired && !habit.hasReminder()) return false
if (!isCompletedAllowed && habit.isCompletedToday()) return false
if (!isEnteredAllowed && habit.isEnteredToday()) return false
return true
}
companion object {
@JvmField
val WITH_ALARM = HabitMatcher(
isArchivedAllowed = true,
isReminderRequired = true,
)
}
}
| gpl-3.0 | 9b845eddf9e46b15229a0f053ad9343a | 35.785714 | 78 | 0.697735 | 4.401709 | false | false | false | false |
dahlstrom-g/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebBrowserUrlProvider.kt | 7 | 4510 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.builtInWebServer
import com.intellij.ide.browsers.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.impl.http.HttpVirtualFile
import com.intellij.psi.PsiFile
import com.intellij.util.SmartList
import com.intellij.util.Url
import com.intellij.util.Urls
import org.jetbrains.builtInWebServer.liveReload.WebServerPageConnectionService
import org.jetbrains.ide.BuiltInServerManager
open class BuiltInWebBrowserUrlProvider : WebBrowserUrlProvider(), DumbAware {
override fun canHandleElement(request: OpenInBrowserRequest): Boolean {
if (request.virtualFile is HttpVirtualFile) {
return true
}
// we must use base language because we serve file - not part of file, but the whole file
// handlebars, for example, contains HTML and HBS psi trees, so, regardless of context, we should not handle such file
return request.isPhysicalFile() && isFileOfMyLanguage(request.file)
}
protected open fun isFileOfMyLanguage(psiFile: PsiFile): Boolean = WebBrowserXmlService.getInstance().isHtmlOrXmlFile(psiFile)
override fun getUrl(request: OpenInBrowserRequest, file: VirtualFile): Url? {
if (file is HttpVirtualFile) {
return Urls.newFromVirtualFile(file)
}
else {
return getBuiltInServerUrls(file, request.project, null, request.isAppendAccessToken, request.reloadMode).firstOrNull()
}
}
}
@JvmOverloads
fun getBuiltInServerUrls(file: VirtualFile,
project: Project,
currentAuthority: String?,
appendAccessToken: Boolean = true,
reloadMode: ReloadMode? = null): List<Url> {
if (currentAuthority != null && !compareAuthority(currentAuthority)) {
return emptyList()
}
val info = WebServerPathToFileManager.getInstance(project).getPathInfo(file) ?: return emptyList()
return getBuiltInServerUrls(info, project, currentAuthority, appendAccessToken, reloadMode)
}
fun getBuiltInServerUrls(info: PathInfo,
project: Project,
currentAuthority: String? = null,
appendAccessToken: Boolean = true,
preferredReloadMode: ReloadMode? = null): SmartList<Url> {
val effectiveBuiltInServerPort = BuiltInServerOptions.getInstance().effectiveBuiltInServerPort
val path = info.path
val authority = currentAuthority ?: "localhost:$effectiveBuiltInServerPort"
val reloadMode = preferredReloadMode ?: WebBrowserManager.getInstance().webServerReloadMode
val appendReloadOnSave = reloadMode != ReloadMode.DISABLED
val queryBuilder = StringBuilder()
if (appendAccessToken || appendReloadOnSave) queryBuilder.append('?')
if (appendAccessToken) queryBuilder.append(TOKEN_PARAM_NAME).append('=').append(acquireToken())
if (appendAccessToken && appendReloadOnSave) queryBuilder.append('&')
if (appendReloadOnSave) queryBuilder.append(WebServerPageConnectionService.RELOAD_URL_PARAM).append('=').append(reloadMode.name)
val query = queryBuilder.toString()
val urls = SmartList(Urls.newHttpUrl(authority, "/${project.name}/$path", query))
val path2 = info.rootLessPathIfPossible
if (path2 != null) {
urls.add(Urls.newHttpUrl(authority, '/' + project.name + '/' + path2, query))
}
val defaultPort = BuiltInServerManager.getInstance().port
if (currentAuthority == null && defaultPort != effectiveBuiltInServerPort) {
val defaultAuthority = "localhost:$defaultPort"
urls.add(Urls.newHttpUrl(defaultAuthority, "/${project.name}/$path", query))
if (path2 != null) {
urls.add(Urls.newHttpUrl(defaultAuthority, "/${project.name}/$path2", query))
}
}
return urls
}
fun compareAuthority(currentAuthority: String?): Boolean {
if (currentAuthority.isNullOrEmpty()) {
return false
}
val portIndex = currentAuthority!!.indexOf(':')
if (portIndex < 0) {
return false
}
val host = currentAuthority.substring(0, portIndex)
if (!isOwnHostName(host)) {
return false
}
val port = StringUtil.parseInt(currentAuthority.substring(portIndex + 1), -1)
return port == BuiltInServerOptions.getInstance().effectiveBuiltInServerPort || port == BuiltInServerManager.getInstance().port
} | apache-2.0 | 3da80543b09851f895444a777f71ab52 | 40.385321 | 130 | 0.730599 | 4.574037 | false | false | false | false |
chromeos/video-decode-encode-demo | app/src/main/java/dev/hadrosaur/videodecodeencodedemo/Utils/MediaCodecUtils.kt | 1 | 15558 | /*
* Copyright (c) 2021 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 dev.hadrosaur.videodecodeencodedemo.Utils
import android.content.res.AssetFileDescriptor
import android.media.MediaCodecInfo
import android.media.MediaCodecList
import android.media.MediaExtractor
import android.media.MediaFormat
import android.media.MediaFormat.*
import android.os.Build.VERSION.SDK_INT
import dev.hadrosaur.videodecodeencodedemo.MainActivity
import dev.hadrosaur.videodecodeencodedemo.MainViewModel
/**
* Returns the first codec capable of encoding the specified MIME type, or null if no
* match was found.
*/
fun selectEncoder(mimeType: String): MediaCodecInfo? {
val numCodecs = MediaCodecList.getCodecCount()
val validCodecs = ArrayList<MediaCodecInfo>()
for (i in 0 until numCodecs) {
val codecInfo = MediaCodecList.getCodecInfoAt(i)
if (!codecInfo.isEncoder) {
continue
}
val types = codecInfo.supportedTypes
for (j in types.indices) {
if (types[j].equals(mimeType, ignoreCase = true)) {
validCodecs.add(codecInfo)
}
}
}
// Default to returning the first codec
return if (validCodecs.size > 0) {
validCodecs[0]
} else {
null
}
}
/**
* Gets the MIME type for the video stream
*/
fun getVideoTrackMimeType(videoFd: AssetFileDescriptor) : String {
val extractor = MediaExtractor()
var mimeType = ""
extractor.setDataSource(videoFd.fileDescriptor, videoFd.startOffset, videoFd.length)
// Find the video track format from the raw video file
for (i in 0 until extractor.trackCount) {
val trackFormat = extractor.getTrackFormat(i)
mimeType = trackFormat.getString(KEY_MIME) ?: ""
if (mimeType.startsWith("video/")) {
// viewModel.updateLog("Video MIME type: ${mimeType}")
break
}
}
extractor.release()
return mimeType
}
/**
* Gets the MIME type for the audio stream
*/
fun getAudioTrackMimeType(videoFd: AssetFileDescriptor) : String {
val extractor = MediaExtractor()
var mimeType = ""
extractor.setDataSource(videoFd.fileDescriptor, videoFd.startOffset, videoFd.length)
// Find the video track format from the raw video file
for (i in 0 until extractor.trackCount) {
val trackFormat = extractor.getTrackFormat(i)
mimeType = trackFormat.getString(KEY_MIME) ?: ""
if (mimeType.startsWith("audio/")) {
// viewModel.updateLog("Audio MIME type: ${mimeType}")
break
}
}
extractor.release()
return mimeType
}
/**
* Tries to get the best encoding settings for the device, using the setting from the original
* media as a guide.
*/
fun getBestVideoEncodingFormat(videoFd: AssetFileDescriptor) : MediaFormat {
val DEFAULT_BITRATE = 20000000
// Use the original decoded file to help set up the encode values
// This is not necessary but just convenient
val extractor = MediaExtractor()
var inputMediaFormat = MediaFormat()
var mimeType = ""
extractor.setDataSource(videoFd.fileDescriptor, videoFd.startOffset, videoFd.length)
// Find the video track format from the raw video file
for (i in 0 until extractor.trackCount) {
val trackFormat = extractor.getTrackFormat(i)
mimeType = trackFormat.getString(KEY_MIME) ?: ""
if (mimeType.startsWith("video/")) {
// viewModel.updateLog("Video MIME type: ${mimeType}")
inputMediaFormat = trackFormat
break
}
}
// Get the best video encoder for the given MIME type
val videoEncoderCodecInfo: MediaCodecInfo? = selectEncoder(mimeType)
if (videoEncoderCodecInfo == null) {
MainActivity.logd("WARNING: No valid video encoder codec. Encoded file may be broken.")
return MediaFormat()
}
// Start with decoder width/height
var encoderWidth = inputMediaFormat.getInteger(KEY_WIDTH)
var encoderHeight = inputMediaFormat.getInteger(KEY_HEIGHT)
// Configure encoder with the same format as the source media
val encoderFormat = createVideoFormat(
mimeType,
encoderWidth,
encoderHeight
)
encoderFormat.setInteger(
KEY_COLOR_FORMAT,
MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface
)
// Settings to copy from the original video format
val intFormatSettings = ArrayList<String>()
intFormatSettings.add(KEY_WIDTH)
intFormatSettings.add(KEY_HEIGHT)
intFormatSettings.add(KEY_BIT_RATE)
intFormatSettings.add(KEY_FRAME_RATE)
intFormatSettings.add(KEY_I_FRAME_INTERVAL)
if (SDK_INT >= 23) {
intFormatSettings.add(KEY_PRIORITY)
intFormatSettings.add(KEY_LEVEL)
}
if (SDK_INT >= 24) {
intFormatSettings.add(KEY_COLOR_STANDARD)
intFormatSettings.add(KEY_COLOR_RANGE)
intFormatSettings.add(KEY_COLOR_TRANSFER)
}
// Crop values are essential as some media decodes to larger width/height than the actual
// video. For example, 1920x1080 will decode to 1920x1088, with 8px crop offset.
// Encoding without correct crop values will show weird smearing/glitches.
intFormatSettings.add("crop-bottom")
intFormatSettings.add("crop-top")
intFormatSettings.add("crop-left")
intFormatSettings.add("crop-right")
val stringFormatSettings = ArrayList<String>()
stringFormatSettings.add(KEY_MIME)
// Copy int settings from input video format to encoder format
for (setting in intFormatSettings) {
if (inputMediaFormat.containsKey(setting)) {
encoderFormat.setInteger(
setting,
inputMediaFormat.getInteger(setting)
)
// Get the real width and height
// See: https://developer.android.com/reference/android/media/MediaCodec#accessing-raw-video-bytebuffers-on-older-devices
if (setting == KEY_WIDTH) {
encoderWidth = if (inputMediaFormat.containsKey("crop-left") && inputMediaFormat.containsKey("crop-right")) {
inputMediaFormat.getInteger("crop-right") + 1 - inputMediaFormat.getInteger("crop-left")
} else {
inputMediaFormat.getInteger(setting)
}
}
if (setting == KEY_HEIGHT) {
encoderHeight = if (inputMediaFormat.containsKey("crop-top") && inputMediaFormat.containsKey("crop-bottom")) {
inputMediaFormat.getInteger("crop-bottom") + 1 - inputMediaFormat.getInteger("crop-top")
} else {
inputMediaFormat.getInteger(setting)
}
}
}
}
// Copy string settings from input video format to encoder format
for (setting in stringFormatSettings) {
if (inputMediaFormat.containsKey(setting)) {
encoderFormat.setString(
setting,
inputMediaFormat.getString(setting)
)
}
}
// Bitrate, Framerate, and I Frame are required, try to choose sensible defaults
if (!encoderFormat.containsKey(KEY_BIT_RATE)) {
encoderFormat.setInteger(KEY_BIT_RATE, DEFAULT_BITRATE)
}
if (!encoderFormat.containsKey(KEY_FRAME_RATE)) {
encoderFormat.setFloat(KEY_FRAME_RATE, 33F)
}
if (!encoderFormat.containsKey(KEY_I_FRAME_INTERVAL)) {
encoderFormat.setInteger(KEY_I_FRAME_INTERVAL, 30)
}
// Choose the best settings best on device capabilities
val typeArray: Array<String> = videoEncoderCodecInfo.supportedTypes
if (typeArray.contains(mimeType)) {
val capabilities: MediaCodecInfo.CodecCapabilities = videoEncoderCodecInfo.getCapabilitiesForType(mimeType)
val encoderCapabilities = capabilities.encoderCapabilities
val videoCapabilities = capabilities.videoCapabilities
// Width / Height
if (!videoCapabilities.isSizeSupported(encoderWidth, encoderHeight)) {
encoderWidth = videoCapabilities.supportedWidths.upper
encoderHeight = videoCapabilities.getSupportedHeightsFor(encoderWidth).upper
}
// Framerate. If decoder does not tell us the frame rate, choose 33, 30, 25, or whatever.
if (!inputMediaFormat.containsKey(KEY_FRAME_RATE)) {
val supportedFrameRates = videoCapabilities.getSupportedFrameRatesFor(encoderWidth, encoderHeight)
when {
supportedFrameRates.contains(33.0) -> {
encoderFormat.setFloat(KEY_FRAME_RATE, 33F)
}
supportedFrameRates.contains(30.0) -> {
encoderFormat.setFloat(KEY_FRAME_RATE, 30F)
}
supportedFrameRates.contains(25.0) -> {
encoderFormat.setFloat(KEY_FRAME_RATE, 25F)
}
else -> {
encoderFormat.setFloat(KEY_FRAME_RATE, supportedFrameRates.upper.toFloat())
}
}
}
// Bitrate - Choose VBR or a default value
if (!encoderFormat.containsKey(KEY_BIT_RATE)) {
if (encoderCapabilities.isBitrateModeSupported(MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR)) {
encoderFormat.setInteger(
KEY_BITRATE_MODE,
MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR
)
} else {
val bitrateRange = videoCapabilities.bitrateRange
if (bitrateRange.contains(DEFAULT_BITRATE)) {
encoderFormat.setInteger(KEY_BIT_RATE, DEFAULT_BITRATE)
} else {
encoderFormat.setInteger(KEY_BIT_RATE, bitrateRange.upper)
}
}
}
// Profile level
if (SDK_INT >= 24) {
val profileLevels = capabilities.profileLevels
var containsProfile = false
for (profileLevel in profileLevels) {
if (inputMediaFormat.containsKey(KEY_PROFILE) && profileLevel.profile == inputMediaFormat.getInteger(KEY_PROFILE)
&& inputMediaFormat.containsKey(KEY_LEVEL) && profileLevel.level == inputMediaFormat.getInteger(KEY_LEVEL)
) {
// This encoder supports the input media profile/level, use it for the encoder
encoderFormat.setInteger(KEY_PROFILE, inputMediaFormat.getInteger(KEY_PROFILE))
encoderFormat.setInteger(KEY_LEVEL, inputMediaFormat.getInteger(KEY_LEVEL))
containsProfile = true
}
}
// If this encoder cannot encode with this level and profile, choose something basic
// TODO: Seems to be better just to let the device default. E.g. some Samsung phones don't support Main Profile 4
if (!containsProfile) {
/*
// Basically everything should support this
encoderFormat.setInteger(
MediaFormat.KEY_PROFILE,
MediaCodecInfo.CodecProfileLevel.AVCProfileMain
)
encoderFormat.setInteger(
MediaFormat.KEY_PROFILE,
MediaCodecInfo.CodecProfileLevel.AVCLevel4
)
*/
}
}
}
encoderFormat.setInteger(KEY_WIDTH, encoderWidth)
encoderFormat.setInteger(KEY_HEIGHT, encoderHeight)
extractor.release()
return encoderFormat
}
fun getBestAudioEncodingFormat(videoFd: AssetFileDescriptor) : MediaFormat {
// Use the original decoded file to help set up the encode values
// This is not necessary but just convenient
val extractor = MediaExtractor()
var inputAudioFormat = MediaFormat()
var mimeType = ""
extractor.setDataSource(videoFd.fileDescriptor, videoFd.startOffset, videoFd.length)
// Find the audio track format from the raw video file
for (i in 0 until extractor.trackCount) {
val trackFormat = extractor.getTrackFormat(i)
mimeType = trackFormat.getString(KEY_MIME) ?: ""
if (mimeType.startsWith("audio/")) {
// viewModel.updateLog("Audio MIME type: ${mimeType}")
inputAudioFormat = trackFormat
break
}
}
// The input format has a CSD-0 buffer and other information that can causes glitches in the
// encoder. Just provide the basic needed info.
// Passing in a CSD-0 buffer will cause errors in the audio stream
// If there is no sample-rate or channel count, this is probably an empty audio stream so
// using the input stream is ok
val outputAudioFormat = if (inputAudioFormat.containsKey(KEY_SAMPLE_RATE)
&& inputAudioFormat.containsKey(KEY_CHANNEL_COUNT)) {
createAudioFormat(mimeType,
inputAudioFormat.getInteger(KEY_SAMPLE_RATE),
inputAudioFormat.getInteger(KEY_CHANNEL_COUNT))
} else {
inputAudioFormat
}
if (inputAudioFormat.containsKey(KEY_BIT_RATE)) {
outputAudioFormat.setInteger(KEY_BIT_RATE, inputAudioFormat.getInteger(KEY_BIT_RATE))
} else {
outputAudioFormat.setInteger(KEY_BIT_RATE, 48000)
}
// Default encoder audio format is PCM_16BIT. Explicit reference here. If PCM_FLOAT or another
// encoding is used without the correct key here, audio will be glitchy in the output file.
// outputAudioFormat.setInteger(KEY_PCM_ENCODING, C.ENCODING_PCM_16BIT)
extractor.release()
return outputAudioFormat
}
/**
* For convenience, set up the encoder to use the same video/audio format as the original file
*
* This method should be run to save these variables in the view model for later use
*/
fun setDefaultEncoderFormats(mainActivity: MainActivity, viewModel: MainViewModel) {
// Video
val videoFd = mainActivity.resources.openRawResourceFd(viewModel.originalRawFileId)
val videoMimeType = getVideoTrackMimeType(videoFd)
viewModel.videoEncoderCodecInfo = selectEncoder(videoMimeType)
if (viewModel.videoEncoderCodecInfo == null) {
viewModel.updateLog("WARNING: No valid video encoder codec. Encoded file may be broken.")
}
viewModel.encoderVideoFormat = getBestVideoEncodingFormat(videoFd)
// Audio
val audioMimeType = getAudioTrackMimeType(videoFd)
viewModel.audioEncoderCodecInfo = selectEncoder(audioMimeType)
if (viewModel.audioEncoderCodecInfo == null) {
viewModel.updateLog("WARNING: No valid audio encoder codec. Audio in encoded file will not work")
}
viewModel.encoderAudioFormat = getBestAudioEncodingFormat(videoFd)
// Encoder debug info
// viewModel.updateLog("Video encoder: ${viewModel.videoEncoderCodecInfo?.name}, ${viewModel.encoderVideoFormat}")
// viewModel.updateLog("Audio encoder: ${viewModel.audioEncoderCodecInfo?.name}, ${viewModel.encoderAudioFormat}")
videoFd.close()
} | apache-2.0 | 074d1c7522e536ea7b3cab81438d4ef7 | 38.290404 | 133 | 0.659082 | 4.65669 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/openapi/editor/actions/TransposeAction.kt | 10 | 2295 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.editor.actions
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.EditorAction
import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler
import com.intellij.util.DocumentUtil
class TransposeAction : EditorAction(TransposeHandler()) {
private class TransposeHandler : EditorWriteActionHandler.ForEachCaret() {
override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean {
return !caret.hasSelection() && caret.offset > 0
}
override fun executeWriteAction(editor: Editor, caret: Caret, dataContext: DataContext?) {
val line = caret.logicalPosition.line
val document = editor.document
if (caret.offset < document.getLineEndOffset(line)) {
val offsetBeforeCaret = DocumentUtil.getPreviousCodePointOffset(document, caret.offset)
val offsetAfterCaret = DocumentUtil.getNextCodePointOffset(document, caret.offset)
val codepointBeforeCaret = document.charsSequence.subSequence(offsetBeforeCaret, caret.offset)
val codepointAfterCaret = document.charsSequence.subSequence(caret.offset, offsetAfterCaret)
document.replaceString(offsetBeforeCaret, offsetAfterCaret, "$codepointAfterCaret$codepointBeforeCaret")
caret.moveToOffset(offsetAfterCaret)
}
else {
// when the caret is at EOL, swap two last characters of the line and don't move caret
val offsetBeforeCaret = DocumentUtil.getPreviousCodePointOffset(document, caret.offset)
val offset2BeforeCaret = DocumentUtil.getPreviousCodePointOffset(document, offsetBeforeCaret)
if (offset2BeforeCaret >= 0) {
val codepoint2BeforeCaret = document.charsSequence.subSequence(offset2BeforeCaret, offsetBeforeCaret)
val codepointBeforeCaret = document.charsSequence.subSequence(offsetBeforeCaret, caret.offset)
document.replaceString(offset2BeforeCaret, caret.offset, "$codepointBeforeCaret$codepoint2BeforeCaret")
}
}
}
}
}
| apache-2.0 | 294e9c737a0bf5235735bbb47c7b6d99 | 56.375 | 140 | 0.77037 | 4.89339 | false | false | false | false |
mbarberot/mtg-grimoire | src/main/kotlin/org/github/mbarberot/mtg/grimoire/core/migration/MigrationRunner.kt | 1 | 1008 | package org.github.mbarberot.mtg.grimoire.core.migration
import com.github.salomonbrys.kodein.Kodein
import com.github.salomonbrys.kodein.conf.global
import com.github.salomonbrys.kodein.instance
import org.github.mbarberot.mtg.grimoire.core.migration.mtgjson.CardUpdater
import org.github.mbarberot.mtg.grimoire.core.migration.mtgjson.MTGApi
import org.github.mbarberot.mtg.grimoire.core.migration.mtgjson.MTGMigration
import org.github.mbarberot.mtg.grimoire.core.stores.VersionStore
import java.util.logging.Logger
class MigrationRunner(val di: Kodein = Kodein.global) : Runnable {
companion object {
val LOG: Logger = Logger.getLogger(MigrationRunner::class.java.name)
}
val versionStore : VersionStore = di.instance()
override fun run() {
var version = versionStore.getVersion()
version = MTGMigration(version, MTGApi(), CardUpdater(di.instance())).run()
LOG.info { "Updating version : $version" }
versionStore.updateVersion(version)
}
} | mit | 0f2dd2e63bc1ee50b89c33b517f9d138 | 36.37037 | 83 | 0.761905 | 3.9375 | false | false | false | false |
CesarValiente/KUnidirectional | store/src/main/kotlin/com/cesarvaliente/kunidirectional/store/Models.kt | 1 | 1371 | /**
* Copyright (C) 2017 Cesar Valiente & Corey Shaw
*
* https://github.com/CesarValiente
* https://github.com/coshaw
*
* 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.cesarvaliente.kunidirectional.store
import java.util.UUID
const val LOCAL_ID = "localId"
interface PositionsFactory {
fun newPosition() = System.nanoTime()
}
fun generateLocalId(): String = LOCAL_ID + "_" + UUID.randomUUID().toString().replace("-".toRegex(), "")
enum class Color {
RED, YELLOW, GREEN, BLUE, WHITE
}
data class Item(
val localId: String = generateLocalId(),
val text: String? = null,
val favorite: Boolean = false,
val color: Color = Color.WHITE,
val position: Long = object : PositionsFactory {}.newPosition()) {
fun isEmpty(): Boolean = text == null
fun isNotEmpty(): Boolean = !isEmpty()
} | apache-2.0 | ba10ebf790f287f94c7aacb067d63ff4 | 28.191489 | 104 | 0.690007 | 4.008772 | false | false | false | false |
MarkusAmshove/Kluent | native/src/main/kotlin/org/amshove/kluent/AssertionErrors.kt | 1 | 1867 | package org.amshove.kluent
/** An error that bundles multiple other [Throwable]s together */
actual class MultiAssertionError actual constructor(errors: List<Throwable>) : AssertionError(createMessage(errors)) {
companion object {
private fun createMessage(errors: List<Throwable>) = buildString {
append("The following ")
if (errors.size == 1) {
append("assertion")
} else {
append(errors.size).append(" assertions")
}
append(" failed:\n")
if (errors.size == 1) {
append(formatException(errors[0]))
stacktraces.throwableLocation(errors[0])?.let {
append("at ").append(it)
}
} else {
for ((i, err) in errors.withIndex()) {
append(formatException(err, i))
stacktraces.throwableLocation(err)?.let {
append("at ").append(it).append('\n')
}
}
}
}
private fun formatException(error: Throwable, errorIndex: Int? = null): String {
return if (errorIndex == null) {
if (error.message == null) {
""
} else {
"${error.message!!}\n"
}
} else {
"${errorIndex + 1}) ${error.message}\n"
}
}
}
}
actual fun assertionError(error: Throwable): Throwable {
val message = buildString {
append("The following assertion failed:\n")
append(error.message).append('\n')
stacktraces.throwableLocation(error)?.let {
append("at ").append(it).append('\n')
}
}
val t = AssertionError(message)
stacktraces.cleanStackTrace(t)
return t
}
| mit | b4ac319c61192f560b9479da0bcb86ac | 31.189655 | 118 | 0.498125 | 4.874674 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/utils/print/CustomPrintDocumentAdapter.kt | 1 | 2699 | /*
* 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.utils.print
import android.os.Build
import android.os.Bundle
import android.os.CancellationSignal
import android.os.ParcelFileDescriptor
import android.print.PageRange
import android.print.PrintAttributes
import android.print.PrintDocumentAdapter
import android.print.PrintDocumentInfo
import androidx.annotation.RequiresApi
import java.io.FileOutputStream
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
class CustomPrintDocumentAdapter(private val pdfWriter: IPdfWriter, private val fileName: String) :
PrintDocumentAdapter() {
override fun onLayout(
oldAttributes: PrintAttributes,
newAttributes: PrintAttributes,
cancellationSignal: CancellationSignal,
callback: PrintDocumentAdapter.LayoutResultCallback,
extras: Bundle
) {
if (cancellationSignal.isCanceled) {
callback.onLayoutCancelled()
return
}
val resolution = newAttributes.resolution ?: DEFAULT_RESOLUTION
val mediaSize = newAttributes.mediaSize ?: DEFAULT_MEDIA_SIZE
val pageCount = pdfWriter.layoutPages(resolution, mediaSize)
val pdi = PrintDocumentInfo.Builder(fileName)
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(pageCount)
.build()
callback.onLayoutFinished(pdi, true)
}
override fun onWrite(
pages: Array<PageRange>,
destination: ParcelFileDescriptor,
cancellationSignal: CancellationSignal,
callback: PrintDocumentAdapter.WriteResultCallback
) {
val outputStream = FileOutputStream(destination.fileDescriptor)
try {
outputStream.use {
pdfWriter.writePdfDocument(pages, outputStream)
}
callback.onWriteFinished(pages)
} catch (e: Exception) {
e.printStackTrace()
callback.onWriteFailed(e.localizedMessage)
}
}
companion object {
val DEFAULT_RESOLUTION = PrintAttributes.Resolution("default", "Default", 300, 300)
val DEFAULT_MEDIA_SIZE: PrintAttributes.MediaSize = PrintAttributes.MediaSize.ISO_A4
}
}
| gpl-2.0 | 8f2e6f4c1d4b513f48ba514db3991f01 | 32.7375 | 99 | 0.70804 | 4.988909 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/codepipeline/src/main/kotlin/com/kotlin/pipeline/GetPipeline.kt | 1 | 1940 | // snippet-sourcedescription:[GetPipeline.kt demonstrates how to retrieve a specific pipeline.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[AWS CodePipeline]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.pipeline
// snippet-start:[pipeline.kotlin.get_pipeline.import]
import aws.sdk.kotlin.services.codepipeline.CodePipelineClient
import aws.sdk.kotlin.services.codepipeline.model.GetPipelineRequest
import kotlin.system.exitProcess
// snippet-end:[pipeline.kotlin.get_pipeline.import]
/**
To run this Kotlin code example, ensure that you have setup your development environment,
including your credentials.
For information, see this documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<name>
Where:
name - the name of the pipeline to retrieve.
"""
if (args.size != 1) {
println(usage)
exitProcess(1)
}
val name = args[0]
getSpecificPipeline(name)
}
// snippet-start:[pipeline.kotlin.get_pipeline.main]
suspend fun getSpecificPipeline(nameVal: String?) {
val request = GetPipelineRequest {
name = nameVal
version = 1
}
CodePipelineClient { region = "us-east-1" }.use { pipelineClient ->
val response = pipelineClient.getPipeline(request)
response.pipeline?.stages?.forEach { stage ->
println("Stage name is " + stage.name.toString() + " and actions are:")
stage.actions?.forEach { action ->
println("Action name is ${action.name}")
println("Action type id is ${action.actionTypeId}")
}
}
}
}
// snippet-end:[pipeline.kotlin.get_pipeline.main]
| apache-2.0 | aa04e24a1dd62ed7aa2a54fbedcd205c | 28.793651 | 95 | 0.650515 | 4.033264 | false | false | false | false |
vhromada/Catalog | core/src/main/kotlin/com/github/vhromada/catalog/controller/ShowController.kt | 1 | 4203 | package com.github.vhromada.catalog.controller
import com.github.vhromada.catalog.common.entity.Page
import com.github.vhromada.catalog.entity.ChangeShowRequest
import com.github.vhromada.catalog.entity.Show
import com.github.vhromada.catalog.entity.ShowStatistics
import com.github.vhromada.catalog.facade.ShowFacade
import com.github.vhromada.catalog.filter.MultipleNameFilter
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestController
/**
* A class represents controller for shows.
*
* @author Vladimir Hromada
*/
@RestController("showController")
@RequestMapping("rest/shows")
class ShowController(
/**
* Facade for shows
*/
private val facade: ShowFacade
) {
/**
* Returns list of shows for filter.
*
* @param filter filter
* @return list of shows for filter
*/
@GetMapping
fun search(filter: MultipleNameFilter): Page<Show> {
return facade.search(filter = filter)
}
/**
* Returns show.
* <br></br>
* Validation errors:
*
* * Show doesn't exist in data storage
*
* @param id ID
* @return show
*/
@GetMapping("{id}")
fun get(@PathVariable("id") id: String): Show {
return facade.get(uuid = id)
}
/**
* Adds show.
* <br></br>
* Validation errors:
*
* * Czech name is null
* * Czech name is empty string
* * Original name is null
* * Original name is empty string
* * IMDB code isn't -1 or between 1 and 9999999
* * Genres are null
* * Genres contain null value
* * Genre is empty string
* * Picture doesn't exist in data storage
* * Genre doesn't exist in data storage
*
* @param request request for changing show
* @return added show
*/
@PutMapping
@ResponseStatus(HttpStatus.CREATED)
fun add(@RequestBody request: ChangeShowRequest): Show {
return facade.add(request = request)
}
/**
* Updates show.
* <br></br>
* Validation errors:
*
* * Czech name is null
* * Czech name is empty string
* * Original name is null
* * Original name is empty string
* * IMDB code isn't -1 or between 1 and 9999999
* * Genres are null
* * Genres contain null value
* * Genre is empty string
* * Picture doesn't exist in data storage
* * Genre doesn't exist in data storage
* * Show doesn't exist in data storage
*
* @param id ID
* @param request request for changing show
* @return updated show
*/
@PostMapping("{id}")
fun update(
@PathVariable("id") id: String,
@RequestBody request: ChangeShowRequest
): Show {
return facade.update(uuid = id, request = request)
}
/**
* Removes show.
* <br></br>
* Validation errors:
*
* * Show doesn't exist in data storage
*
* @param id ID
*/
@DeleteMapping("{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun remove(@PathVariable("id") id: String) {
facade.remove(uuid = id)
}
/**
* Duplicates show.
* <br></br>
* Validation errors:
*
* * Show doesn't exist in data storage
*
* @param id ID
* @return duplicated show
*/
@PostMapping("{id}/duplicate")
@ResponseStatus(HttpStatus.CREATED)
fun duplicate(@PathVariable("id") id: String): Show {
return facade.duplicate(uuid = id)
}
/**
* Returns statistics.
*
* @return statistics
*/
@GetMapping("statistics")
fun getStatistics(): ShowStatistics {
return facade.getStatistics()
}
}
| mit | 49a0cb1ee0541b034049b12ac0283a76 | 26.116129 | 61 | 0.635498 | 4.177932 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/playalong/TimingDisplayStage.kt | 2 | 4424 | package io.github.chrislo27.rhre3.editor.stage.playalong
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.math.Interpolation
import io.github.chrislo27.rhre3.playalong.InputResult
import io.github.chrislo27.rhre3.playalong.InputTiming
import io.github.chrislo27.rhre3.playalong.Playalong
import io.github.chrislo27.toolboks.ToolboksScreen
import io.github.chrislo27.toolboks.registry.AssetRegistry
import io.github.chrislo27.toolboks.ui.ColourPane
import io.github.chrislo27.toolboks.ui.Stage
import io.github.chrislo27.toolboks.ui.UIElement
class TimingDisplayStage<S : ToolboksScreen<*, *>>(parent: UIElement<S>, camera: OrthographicCamera)
: Stage<S>(parent, camera) {
companion object {
val ACE_COLOUR: Color = Color.valueOf("FFF800")
val GOOD_COLOUR: Color = Color.valueOf("6DE23B")
val BARELY_COLOUR: Color = Color.valueOf("FF7C26")
val MISS_COLOUR: Color = Color.valueOf("E82727")
}
data class Flash(val offset: Float, val timing: InputTiming, val startDuration: Float, var duration: Float = startDuration)
private val flashes: MutableList<Flash> = mutableListOf()
private val texRegionGreat: TextureRegion = TextureRegion(AssetRegistry.get<Texture>("playalong_input_timing"), 0, 0, 128, 128)
private val texRegionMiss: TextureRegion = TextureRegion(AssetRegistry.get<Texture>("playalong_input_timing"), 128, 0, 128, 128)
private val texRegionBarely: TextureRegion = TextureRegion(AssetRegistry.get<Texture>("playalong_input_timing"), 256, 0, 128, 128)
init {
fun addColourPane(color: Color, x: Float, width: Float) {
this.elements += ColourPane(this, this).apply {
this.colour.set(color)
this.location.set(screenX = 0.5f - width / 2, screenWidth = width)
}
}
val acePercentage = (Playalong.ACE_OFFSET) / Playalong.MAX_OFFSET_SEC
val goodPercentage = (Playalong.GOOD_OFFSET) / Playalong.MAX_OFFSET_SEC
val barelyPercentage = (Playalong.BARELY_OFFSET) / Playalong.MAX_OFFSET_SEC
addColourPane(MISS_COLOUR, 0f, 1f)
addColourPane(BARELY_COLOUR, barelyPercentage, barelyPercentage)
addColourPane(GOOD_COLOUR, barelyPercentage + goodPercentage, goodPercentage)
addColourPane(ACE_COLOUR, barelyPercentage + goodPercentage + acePercentage, acePercentage)
}
fun flash(input: InputResult) {
val offsetNormalized: Float = (input.offset / Playalong.MAX_OFFSET_SEC).coerceIn(-1f, 1f)
if (input.timing == InputTiming.MISS && offsetNormalized <= (Playalong.BARELY_OFFSET / Playalong.MAX_OFFSET_SEC)) return
flashes += Flash(offsetNormalized, input.timing, 0.25f)
}
override fun render(screen: S, batch: SpriteBatch, shapeRenderer: ShapeRenderer) {
super.render(screen, batch, shapeRenderer)
flashes.forEach { flash ->
batch.setColor(1f, 1f, 1f, Interpolation.pow5Out.apply(flash.duration / flash.startDuration))
// val flashWidth = 0.02f * location.realWidth
// batch.fillRect(location.realX - flashWidth / 2 + (location.realWidth / 2) * (flash.offset + 1f), location.realY, flashWidth, location.realHeight)
// batch.fillRect(location.realX - flashWidth / 2 / 3 + (location.realWidth / 2) * (flash.offset + 1f), location.realY, flashWidth / 3, location.realHeight)
val texReg: TextureRegion = when {
flash.timing == InputTiming.MISS -> texRegionMiss
flash.timing == InputTiming.ACE || flash.timing == InputTiming.GOOD -> texRegionGreat
else -> texRegionBarely
}
val squareSize = location.realHeight
batch.draw(texReg, location.realX + (location.realWidth / 2) * (flash.offset + 1f) - squareSize / 2,
location.realY, squareSize, squareSize)
}
batch.setColor(1f, 1f, 1f, 1f)
}
override fun frameUpdate(screen: S) {
super.frameUpdate(screen)
flashes.forEach {
it.duration -= Gdx.graphics.deltaTime
}
flashes.removeIf { it.duration <= 0f }
}
} | gpl-3.0 | 3b49840604677c07ed3ae50fb81a154c | 48.166667 | 167 | 0.695298 | 3.911583 | false | false | false | false |
fluidsonic/fluid-json | annotation-processor/test-cases/1/output-expected/property/serializedName/DefaultJsonCodec.kt | 1 | 2006 | package `property`.serializedName
import codecProvider.CustomCodingContext
import io.fluidsonic.json.AbstractJsonCodec
import io.fluidsonic.json.JsonCodingType
import io.fluidsonic.json.JsonDecoder
import io.fluidsonic.json.JsonEncoder
import io.fluidsonic.json.missingPropertyError
import io.fluidsonic.json.readBooleanOrNull
import io.fluidsonic.json.readByteOrNull
import io.fluidsonic.json.readCharOrNull
import io.fluidsonic.json.readDoubleOrNull
import io.fluidsonic.json.readFloatOrNull
import io.fluidsonic.json.readFromMapByElementValue
import io.fluidsonic.json.readIntOrNull
import io.fluidsonic.json.readLongOrNull
import io.fluidsonic.json.readShortOrNull
import io.fluidsonic.json.readStringOrNull
import io.fluidsonic.json.readValueOfType
import io.fluidsonic.json.readValueOfTypeOrNull
import io.fluidsonic.json.writeBooleanOrNull
import io.fluidsonic.json.writeByteOrNull
import io.fluidsonic.json.writeCharOrNull
import io.fluidsonic.json.writeDoubleOrNull
import io.fluidsonic.json.writeFloatOrNull
import io.fluidsonic.json.writeIntOrNull
import io.fluidsonic.json.writeIntoMap
import io.fluidsonic.json.writeLongOrNull
import io.fluidsonic.json.writeMapElement
import io.fluidsonic.json.writeShortOrNull
import io.fluidsonic.json.writeStringOrNull
import io.fluidsonic.json.writeValueOrNull
import kotlin.String
import kotlin.Unit
internal object DefaultJsonCodec : AbstractJsonCodec<Default, CustomCodingContext>() {
public override fun JsonDecoder<CustomCodingContext>.decode(valueType: JsonCodingType<Default>):
Default {
var _value1: String? = null
readFromMapByElementValue { key ->
when (key) {
"value1" -> _value1 = readString()
else -> skipValue()
}
}
return Default(
value1 = _value1 ?: missingPropertyError("value1")
)
}
public override fun JsonEncoder<CustomCodingContext>.encode(`value`: Default): Unit {
writeIntoMap {
writeMapElement("value1", string = value.value1)
writeMapElement("value2", string = value.value2)
}
}
}
| apache-2.0 | e59a94735734ebf110f4201edd8879f8 | 33 | 97 | 0.824028 | 4.457778 | false | false | false | false |
leafclick/intellij-community | platform/workspaceModel-core/src/ProxyBasedTypedEntityStore.kt | 1 | 48179 | @file:Suppress("UNCHECKED_CAST")
package com.intellij.workspace.api
import com.google.common.collect.BiMap
import com.google.common.collect.HashBiMap
import com.google.common.collect.Queues
import com.intellij.util.ArrayUtil
import com.intellij.util.containers.ConcurrentFactoryMap
import com.intellij.util.containers.MultiMap
import com.intellij.util.lang.JavaVersion
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.lang.reflect.*
import java.util.*
import java.util.concurrent.atomic.AtomicLong
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.HashSet
import kotlin.collections.LinkedHashMap
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
inline fun <reified M : ModifiableTypedEntity<T>, T : TypedEntity> TypedEntityStorageBuilder.addEntity(source: EntitySource, noinline initializer: M.() -> Unit): T
= addEntity(M::class.java, source, initializer)
internal interface ProxyBasedEntity : TypedEntity {
val storage: ProxyBasedEntityStorage
val id: Long
val data: EntityData
}
internal open class ProxyBasedEntityStorage(internal open val entitiesByType: Map<Class<out TypedEntity>, Set<EntityData>>,
internal open val entitiesBySource: Map<EntitySource, Set<EntityData>>,
internal open val entitiesByPersistentIdHash: Map<Int, Set<EntityData>>,
internal open val entityById: Map<Long, EntityData>,
internal open val referrers: Map<Long, List<Long>>,
internal open val persistentIdReferrers: Map<Int, Set<Long>>,
internal val metaDataRegistry: EntityMetaDataRegistry) : TypedEntityStorage {
companion object {
private val proxyClassConstructors = ConcurrentFactoryMap.createMap<Class<out TypedEntity>, Constructor<out ProxyBasedEntity>> {
//todo replace Proxy class by a generated class which stores properties in separate fields to improve performance and memory usage
val constructor = Proxy.getProxyClass(it.classLoader, it, ProxyBasedEntity::class.java).getConstructor(InvocationHandler::class.java)
constructor.isAccessible = true
constructor as Constructor<out ProxyBasedEntity>
}
@JvmStatic
internal fun <E : TypedEntity> createProxy(clazz: Class<out E>, impl: EntityImpl) =
proxyClassConstructors[clazz]!!.newInstance(impl) as E
internal fun <T1, T2> classifyByEquals(c1: Iterable<T1>, c2: Iterable<T2>, hashFunc1: (T1) -> Int, hashFunc2: (T2) -> Int, equalsFunc: (T1, T2) -> Boolean): TypedEntityStorageBuilderImpl.EqualityResult<T1, T2> {
val hashes1 = c1.groupBy(hashFunc1)
val hashes2 = c2.groupBy(hashFunc2)
val onlyIn1 = mutableListOf<T1>()
for (key in hashes1.keys - hashes2.keys) {
onlyIn1.addAll(hashes1.getValue(key))
}
val onlyIn2 = mutableListOf<T2>()
for (key in hashes2.keys - hashes1.keys) {
onlyIn2.addAll(hashes2.getValue(key))
}
val equal = mutableListOf<Pair<T1, T2>>()
for (key in hashes1.keys.intersect(hashes2.keys)) {
val l1 = hashes1.getValue(key)
val l2 = hashes2.getValue(key)
if (l1.size == 1 && l2.size == 1 && equalsFunc(l1.single(), l2.single())) {
equal.add(l1.single() to l2.single())
} else {
val ml1 = l1.toMutableList()
val ml2 = l2.toMutableList()
for (itemFrom1 in ml1) {
val index2 = ml2.indexOfFirst { equalsFunc(itemFrom1, it) }
if (index2 < 0) {
onlyIn1.add(itemFrom1)
} else {
val itemFrom2 = ml2.removeAt(index2)
equal.add(itemFrom1 to itemFrom2)
}
}
for (itemFrom2 in ml2) {
onlyIn2.add(itemFrom2)
}
}
}
return TypedEntityStorageBuilderImpl.EqualityResult(onlyIn1 = onlyIn1, onlyIn2 = onlyIn2, equal = equal)
}
}
override fun <E : TypedEntity> entities(entityClass: Class<E>): Sequence<E> {
return entitiesByType[entityClass]?.asSequence()?.map { createEntityInstance(it) as E } ?: emptySequence()
}
override fun entitiesBySource(sourceFilter: (EntitySource) -> Boolean): Map<EntitySource, Map<Class<out TypedEntity>, List<TypedEntity>>> {
return entitiesBySource.asSequence().filter { sourceFilter(it.key) && it.value.isNotEmpty() }
.associateBy({ it.key }, { (_, listOfData) ->
listOfData.groupBy({ it.unmodifiableEntityType }, { createEntityInstance(it) })
})
}
internal fun createEntityInstance(it: EntityData) =
createProxy(it.unmodifiableEntityType, EntityImpl(it, this))
override fun <E : TypedEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E? {
return entitiesByPersistentIdHash[id.hashCode()]?.asSequence()
?.map { (createEntityInstance(it) as E) }
?.find {it.persistentId() == id }
}
override fun <E : TypedEntityWithPersistentId, R : TypedEntity> referrers(id: PersistentEntityId<E>, entityClass: Class<R>): Sequence<R> {
return persistentIdReferrers[id.hashCode()]?.asSequence()?.map {
val entityData = entityById[it] ?: error("Unknown id $id")
return@map createEntityInstance(entityData).let { typedEntity ->
if (entityClass.isInstance(typedEntity)) typedEntity as R else null
}
}?.filterNotNull() ?: emptySequence()
}
override fun <E : TypedEntity, R : TypedEntity> referrers(e: E,
entityClass: KClass<R>,
property: KProperty1<R, EntityReference<E>>): Sequence<R> {
//todo: do we need this?
return entities(entityClass.java).filter { property.get(it).resolve(this) == e }
}
internal fun <R : TypedEntity> referrers(id: Long, entityClass: Class<R>, propertyName: String): Sequence<R> {
val referrers = referrers[id] ?: return emptySequence()
return referrers.asSequence().mapNotNull {
val referrer = entityById.getValue(it)
if (referrer.unmodifiableEntityType == entityClass && referrer.properties[propertyName] == id) {
createEntityInstance(referrer) as R
}
else {
null
}
}
}
fun applyDiff(diffBuilder: TypedEntityStorageDiffBuilder): TypedEntityStorage {
val builder = TypedEntityStorageBuilder.from(this) as TypedEntityStorageBuilderImpl
builder.addDiff(diffBuilder)
return builder.toStorage()
}
}
internal class TypedEntityStorageBuilderImpl(override val entitiesByType: MutableMap<Class<out TypedEntity>, MutableSet<EntityData>>,
override val entitiesBySource: MutableMap<EntitySource, MutableSet<EntityData>>,
override val entitiesByPersistentIdHash: MutableMap<Int, MutableSet<EntityData>>,
override val entityById: MutableMap<Long, EntityData>,
override val referrers: MutableMap<Long, MutableList<Long>>,
override val persistentIdReferrers: MutableMap<Int, MutableSet<Long>>,
metaDataRegistry: EntityMetaDataRegistry)
: ProxyBasedEntityStorage(entitiesByType, entitiesBySource, entitiesByPersistentIdHash, entityById, referrers, persistentIdReferrers, metaDataRegistry),
TypedEntityStorageBuilder, TypedEntityStorageDiffBuilder {
constructor(storage: ProxyBasedEntityStorage)
: this(storage.entitiesByType.mapValuesTo(HashMap()) { it.value.toMutableSet() },
storage.entitiesBySource.mapValuesTo(HashMap()) { it.value.toMutableSet() },
storage.entitiesByPersistentIdHash.mapValuesTo(HashMap()) { it.value.toMutableSet() },
storage.entityById.toMutableMap(),
storage.referrers.mapValuesTo(HashMap()) { it.value.toMutableList() },
storage.persistentIdReferrers.mapValuesTo(HashMap()) { it.value.toMutableSet() },
storage.metaDataRegistry)
private val changeLogImpl: MutableList<ChangeEntry> = mutableListOf()
override var modificationCount: Long = 0
private set
private val changeLog: List<ChangeEntry>
get() = changeLogImpl
private inline fun updateChangeLog(updater: (MutableList<ChangeEntry>) -> Unit) {
updater(changeLogImpl)
modificationCount++
}
override fun isEmpty(): Boolean = changeLog.isEmpty()
override fun <E : TypedEntity> createReference(e: E): EntityReference<E> = ProxyBasedEntityReferenceImpl((e as ProxyBasedEntity).id)
override fun <M : ModifiableTypedEntity<T>, T : TypedEntity> addEntity(clazz: Class<M>, source: EntitySource,
initializer: M.() -> Unit): T {
val data = createEntityData(source, clazz)
val entity = initializeEntityInstance(data, clazz, initializer)
// Referrers are handled by proxy method invocations from initializer
addEntity(data, entity, handleReferrers = false)
updateChangeLog { it.add(ChangeEntry.AddEntity(data)) }
return entity as T
}
private fun <M : ModifiableTypedEntity<T>, T : TypedEntity> createEntityData(source: EntitySource, clazz: Class<M>) =
createEntityDataByUnmodifiableEntityClass(source, getUnmodifiableEntityClass(clazz))
private fun <T : TypedEntity> createEntityDataByUnmodifiableEntityClass(source: EntitySource, unmodifiableEntityType: Class<out T>) =
EntityData(source, metaDataRegistry.getEntityMetaData(unmodifiableEntityType))
private fun <M : ModifiableTypedEntity<T>, T : TypedEntity> initializeEntityInstance(data: EntityData, clazz: Class<M>,
initializer: M.() -> Unit): M {
val impl = EntityImpl(data, this)
val entity = createProxy(clazz, impl)
impl.allowModifications {
entity.initializer()
}
return entity
}
internal fun addEntity(entityData: EntityData, entityInstance: TypedEntity?, handleReferrers: Boolean) {
entitiesByType.putValue(entityData.unmodifiableEntityType, entityData)
entitiesBySource.putValue(entityData.entitySource, entityData)
entityById[entityData.id] = entityData
if (TypedEntityWithPersistentId::class.java.isAssignableFrom(entityData.unmodifiableEntityType)) {
val persistentId = ((entityInstance ?: createEntityInstance(entityData)) as TypedEntityWithPersistentId).persistentId()
entitiesByPersistentIdHash.putValue(persistentId.hashCode(), entityData)
}
if (handleReferrers) {
addReferences(entityData)
}
addPersistentIdReferrers(entityData)
}
override fun <M : ModifiableTypedEntity<T>, T : TypedEntity> modifyEntity(clazz: Class<M>, e: T, change: M.() -> Unit): T {
val oldIdHash = (e as? TypedEntityWithPersistentId)?.persistentId()?.hashCode()
val oldData = (e as ProxyBasedEntity).data
val newData = oldData.createModifiableCopy()
val newImpl = EntityImpl(newData, this)
val newInstance = createProxy(clazz, newImpl)
newImpl.allowModifications {
newInstance.change()
}
// Referrers are updated in proxy method invocation
replaceEntity(e.id, newData, newInstance, oldIdHash, handleReferrers = false)
updateChangeLog { it.add(ChangeEntry.ReplaceEntity(e.id, newData)) }
return newInstance as T
}
override fun <T : TypedEntity> changeSource(e: T, newSource: EntitySource): T {
val oldData = (e as ProxyBasedEntity).data
val newData = EntityData(newSource, oldData.id, oldData.metaData, oldData.properties)
replaceEntity(e.id, newData, null, null, false)
updateChangeLog { it.add(ChangeEntry.ReplaceEntity(e.id, newData)) }
return createEntityInstance(newData) as T
}
private fun replaceEntity(id: Long, newData: EntityData, newInstance: TypedEntity?, oldIdHash: Int?, handleReferrers: Boolean,
updatePersistentIdReference: Boolean = true) {
if (id != newData.id) {
error("new and old IDs must be equal. Trying to replace entity #$id with #${newData.id}")
}
val oldData = entityById[id] ?: error("Unknown id $id")
if (oldData.entitySource == newData.entitySource) {
val bySource = entitiesBySource[oldData.entitySource]!!
bySource.removeIf { it.id == id }
bySource.add(newData)
}
else {
entitiesBySource.removeValue(oldData.entitySource, oldData)
entitiesBySource.putValue(newData.entitySource, newData)
}
val byType = entitiesByType[oldData.unmodifiableEntityType]!!
byType.removeIf { it.id == id }
byType.add(newData)
entityById[id] = newData
if (TypedEntityWithPersistentId::class.java.isAssignableFrom(oldData.unmodifiableEntityType)) {
entitiesByPersistentIdHash.removeValue(oldIdHash ?: (createEntityInstance(oldData) as TypedEntityWithPersistentId).persistentId().hashCode(), oldData)
val persistentId = ((newInstance ?: createEntityInstance(newData)) as TypedEntityWithPersistentId).persistentId()
entitiesByPersistentIdHash.putValue(persistentId.hashCode(), newData)
}
if (handleReferrers) {
removeReferences(oldData)
addReferences(newData)
}
if (updatePersistentIdReference) {
// TODO :: Improve is needed. In case of changing an irrelevant property, we scan all fields again and again
removePersistentIdReferrers(oldData)
addPersistentIdReferrers(newData)
}
updatePersistentIdInDependentEntities(oldData, newData, updatePersistentIdReference)
}
private fun addReferences(data: EntityData) {
data.collectReferences { referencesId ->
val refs = referrers.getOrPut(referencesId) { mutableListOf() }
// TODO Slow check
if (refs.contains(data.id)) error("Id ${data.id} was already in references with target id $referencesId")
refs.add(data.id)
}
}
private fun removeReferences(data: EntityData) {
data.collectReferences { referencesId ->
val refs = referrers[referencesId] ?: error("Unable to find reference target id $referencesId")
if (!refs.remove(data.id)) {
error("Id ${data.id} was not in references with target id $referencesId")
}
if (refs.isEmpty()) referrers.remove(referencesId)
}
}
private fun addPersistentIdReferrers(data: EntityData) {
data.collectPersistentIdReferences { persistentIdReference ->
val refs = persistentIdReferrers.getOrPut(persistentIdReference.hashCode()) { mutableSetOf() }
if (!refs.contains(data.id)) refs.add(data.id)
}
}
private fun updatePersistentIdInDependentEntities(oldData: EntityData, newData: EntityData, updatePersistentIdReference: Boolean) {
if(!TypedEntityWithPersistentId::class.java.isAssignableFrom(oldData.unmodifiableEntityType)
|| !TypedEntityWithPersistentId::class.java.isAssignableFrom(newData.unmodifiableEntityType)) return
val newPersistentId = newData.persistentId()
val oldPersistentId = oldData.persistentId()
if (oldPersistentId == newPersistentId) return
persistentIdReferrers[oldPersistentId.hashCode()]?.forEach { id ->
val refOldData = entityById[id]
if (refOldData == null) return
val oldIdHash = (createEntityInstance(refOldData) as? TypedEntityWithPersistentId)?.persistentId()?.hashCode()
val refNewData = refOldData.createModifiableCopy()
val newImpl = EntityImpl(refNewData, this)
val newInstance = createProxy(refNewData.unmodifiableEntityType, newImpl)
newImpl.allowModifications {
newImpl.data.replaceAllPersistentIdReferences(oldPersistentId, newPersistentId)
}
// Update persistentId reference in store only for originally replaced element. If method called
// recursively only first call should update reference.
replaceEntity(refOldData.id, refNewData, newInstance, oldIdHash, handleReferrers = false, updatePersistentIdReference = false)
updateChangeLog { it.add(ChangeEntry.ReplaceEntity(refOldData.id, refNewData)) }
}
if (updatePersistentIdReference) {
val oldRefs = persistentIdReferrers[oldPersistentId.hashCode()] ?: return
persistentIdReferrers.remove(oldPersistentId.hashCode())
val newRefs = persistentIdReferrers.getOrPut(newPersistentId.hashCode()) { mutableSetOf() }
newRefs.addAll(oldRefs)
}
}
private fun removePersistentIdReferrers(data: EntityData) {
// If removed entity which is a dependency for others we don't remove the record from the collection,
// customers code should do it manually
data.collectPersistentIdReferences { persistentIdReference ->
val hashCode = persistentIdReference.hashCode()
val refs = persistentIdReferrers[hashCode] ?: error("Unable to find reference target by hash $hashCode")
if (!refs.remove(data.id)) {
error("Id ${data.id} was not in references with target by hash $hashCode")
}
if (refs.isEmpty()) persistentIdReferrers.remove(hashCode)
}
}
override fun removeEntity(e: TypedEntity) {
val id = (e as ProxyBasedEntity).id
updateChangeLog { it.add(ChangeEntry.RemoveEntity(id)) }
removeEntity(id)
}
private fun removeEntity(id: Long) {
val toRemove = referrers[id]
while (true) {
val idToRemove = toRemove?.firstOrNull() ?: break
removeEntity(idToRemove)
}
if (referrers.containsKey(id)) {
error("Referrers still have reference target id $id even after entity removal")
}
val data = entityById.remove(id) ?: error("Unknown id $id")
entitiesByType[data.unmodifiableEntityType]?.removeIf { it.id == id }
entitiesBySource[data.entitySource]?.removeIf { it.id == id }
if (TypedEntityWithPersistentId::class.java.isAssignableFrom(data.unmodifiableEntityType)) {
//todo store hash in EntityData instead?
val persistentId = (createEntityInstance(data) as TypedEntityWithPersistentId).persistentId()
entitiesByPersistentIdHash.removeValue(persistentId.hashCode(), data)
}
removeReferences(data)
removePersistentIdReferrers(data)
}
override fun addDiff(diff: TypedEntityStorageDiffBuilder) {
val diffLog = (diff as TypedEntityStorageBuilderImpl).changeLog
updateChangeLog { it.addAll(diffLog) }
for (change in diffLog) {
when (change) {
is ChangeEntry.AddEntity -> addEntity(change.entityData, null, handleReferrers = true)
is ChangeEntry.RemoveEntity -> {
if (change.id in entityById) {
removeEntity(change.id)
}
}
is ChangeEntry.ReplaceEntity -> {
if (change.id in entityById) {
replaceEntity(change.id, change.newData, null, null, handleReferrers = true)
}
}
}
}
}
private fun EntityData.persistentId() =
(createEntityInstance(this) as TypedEntityWithPersistentId).persistentId()
private fun calcBackReferrers(referrers: Map<Long, List<Long>>): MultiMap<Long, Long> {
val map = MultiMap.create<Long, Long>()
for ((id, children) in referrers) {
for (child in children) {
map.putValue(child, id)
}
}
return map
}
override fun replaceBySource(sourceFilter: (EntitySource) -> Boolean, replaceWith: TypedEntityStorage) {
replaceWith as ProxyBasedEntityStorage
val replaceWithBackReferrers = calcBackReferrers(replaceWith.referrers)
val backReferrers = calcBackReferrers(referrers)
val replaceMap = HashBiMap.create<Long, Long>()
val emptyBiMap = HashBiMap.create<Long, Long>()
val entitiesToRemove = mutableSetOf<Long>()
val entitiesToAdd = mutableSetOf<Long>()
// TODO Cache sourceFilter result by entitySource to call it only once per entitySource
// TODO The following code assumes eligible persistent id entities to be without parents
// TODO add some support for entities with parents. Like when they're all deep equal
for ((idHash, oldEntities) in entitiesByPersistentIdHash.toList()) {
val newEntities = replaceWith.entitiesByPersistentIdHash[idHash]?.toMutableList() ?: mutableListOf()
for (oldData in oldEntities.toList()) {
if (!sourceFilter(oldData.entitySource)) continue
// Currently persistent id entities must not have any parents
if (backReferrers.containsKey(oldData.id)) continue
val persistentId = oldData.persistentId()
val newData = newEntities.firstOrNull { it.persistentId() == persistentId && sourceFilter(it.entitySource) }
if (newData != null) {
replaceMap[oldData.id] = newData.id
if (!shallowEquals(oldData, newData, emptyBiMap)) {
val replaceWithData = EntityData(
entitySource = oldData.entitySource,
metaData = oldData.metaData,
id = oldData.id,
properties = newData.properties
)
replaceEntity(oldData.id, replaceWithData, newInstance = null, oldIdHash = null, handleReferrers = true)
updateChangeLog { it.add(ChangeEntry.ReplaceEntity(oldData.id, replaceWithData)) }
}
newEntities.remove(newData)
} else {
// Remove right here?
// TODO Don't forget to check sourceFilter
entitiesToRemove.add(oldData.id)
}
}
}
for ((idHash, newEntities) in replaceWith.entitiesByPersistentIdHash.toList()) {
val oldEntities = entitiesByPersistentIdHash[idHash] ?: mutableSetOf()
for (newData in newEntities) {
if (!sourceFilter(newData.entitySource)) continue
// Currently persistent id entities must not have any parents
if (replaceWithBackReferrers.containsKey(newData.id)) continue
val persistentId = newData.persistentId()
val oldData = oldEntities.firstOrNull { it.persistentId() == persistentId && sourceFilter(it.entitySource) }
if (oldData == null) {
// Add sub-graph right here?
// TODO Don't forget to check sourceFilter
entitiesToAdd.add(newData.id)
}
}
}
// TODO References to cold entities (not having persistent id as a root)
// TODO Ref to cold entities from persistent id
// TODO test entity refs couple of persistent ids with a different path length to each
// TODO Test cold entities (not related to persistent ids)
// TODO Compare cold entities by hash, probably pre-calculate this hash
// assumes start nodes have no parents
val queue: Queue<Pair<Long, Long>> = Queues.newArrayDeque(replaceMap.toList())
while (queue.isNotEmpty()) {
val (oldId, newId) = queue.remove()
// new nodes - children
// TODO hash
val newChildren = replaceWith.referrers[newId]
?.filter { !entitiesToAdd.contains(it) && !replaceMap.containsKey(it) }
?.map { replaceWith.entityById.getValue(it) }
?: emptyList()
val oldChildren = referrers[oldId]
?.filter { !entitiesToRemove.contains(it) && !replaceMap.containsValue(it) }
?.map { entityById.getValue(it) }
?: emptyList()
val eq = classifyByEquals(
c1 = oldChildren,
c2 = newChildren,
hashFunc1 = this::shallowHashCode, hashFunc2 = this::shallowHashCode,
equalsFunc = { v1, v2 -> shallowEquals(v1, v2, replaceMap) })
for ((oldChildData, newChildData) in eq.equal) {
if (entitiesToAdd.contains(newChildData.id)) error("id=${newChildData.id} already exists in entriesToAdd")
if (entitiesToRemove.contains(oldChildData.id)) error("id=${oldChildData.id} already exists in entitiesToRemove")
queue.add(oldChildData.id to newChildData.id)
replaceMap[oldChildData.id] = newChildData.id
}
// TODO Check we won't get any persistent id nodes?
for (data in eq.onlyIn1) {
traverseNodes(this, data.id) { id ->
if (replaceMap.containsKey(id)) {
error("Trying to remove node with id=$id: it's already marked for replacement")
}
entitiesToRemove.add(id)
}
}
// TODO Check we won't get any persistent id nodes?
for (data in eq.onlyIn2) {
traverseNodes(replaceWith, data.id) { id ->
if (replaceMap.containsValue(id)) {
error("Trying to add node with id=$id: it's already marked for replacement")
}
entitiesToAdd.add(id)
}
}
}
// Process all non-persistent-id related nodes
// TODO Check for external links, sourceFilter must filter out a connected component
val destEntitiesToCompare = mutableSetOf<EntityData>()
foreachNotProcessedEntity(this, sourceFilter, replaceMap, entitiesToRemove) { data ->
destEntitiesToCompare.add(data)
}
val sourceEntitiesToCompare = mutableSetOf<EntityData>()
foreachNotProcessedEntity(replaceWith, sourceFilter, replaceMap.inverse(), entitiesToAdd) { data ->
sourceEntitiesToCompare.add(data)
}
val equalsCache = mutableMapOf<Pair<Long, Long>, Boolean>()
val eq = classifyByEquals(
destEntitiesToCompare, sourceEntitiesToCompare,
this::shallowHashCode, this::shallowHashCode
) { e1, e2 ->
deepEquals(
data1 = e1,
data2 = e2,
replaceMap = replaceMap,
storage1 = this,
storage2 = replaceWith,
backReferrers1 = backReferrers,
backReferrers2 = replaceWithBackReferrers,
equalsCache = equalsCache)
}
for (data in eq.onlyIn1) {
entitiesToRemove.add(data.id)
}
for (data in eq.onlyIn2) {
entitiesToAdd.add(data.id)
}
for ((oldChildData, newChildData) in eq.equal) {
replaceMap[oldChildData.id] = newChildData.id
}
for (idToRemove in entitiesToRemove) {
if (entityById.containsKey(idToRemove)) {
removeEntity(idToRemove)
updateChangeLog { it.add(ChangeEntry.RemoveEntity(idToRemove)) }
}
}
for (idToAdd in entitiesToAdd) {
if (!replaceMap.containsValue(idToAdd)) {
recursiveAddEntity(idToAdd, replaceWithBackReferrers, replaceWith, replaceMap)
}
}
}
private fun deepEquals(data1: EntityData,
data2: EntityData,
replaceMap: Map<Long, Long>,
storage1: ProxyBasedEntityStorage,
storage2: ProxyBasedEntityStorage,
backReferrers1: MultiMap<Long, Long>,
backReferrers2: MultiMap<Long, Long>,
equalsCache: MutableMap<Pair<Long, Long>, Boolean>): Boolean {
val cachedResult = equalsCache[data1.id to data2.id]
if (cachedResult != null) return cachedResult
if (replaceMap[data1.id] == data2.id) return true
val data1parents = backReferrers1[data1.id].map { storage1.entityById.getValue(it) }
val data2parents = backReferrers2[data2.id].map { storage2.entityById.getValue(it) }
val eq = classifyByEquals(data1parents, data2parents, this::shallowHashCode, this::shallowHashCode) { e1, e2 ->
deepEquals(e1, e2, replaceMap, storage1, storage2, backReferrers1, backReferrers2, equalsCache)
}
val result = eq.onlyIn1.isEmpty() && eq.onlyIn2.isEmpty()
equalsCache[data1.id to data2.id] = result
return result
}
private fun foreachNotProcessedEntity(storage: ProxyBasedEntityStorage,
sourceFilter: (EntitySource) -> Boolean,
replaceMap: Map<Long, Long>,
otherProcessedSet: Set<Long>,
block: (EntityData) -> Unit) {
for ((oldSource, oldEntities) in storage.entitiesBySource) {
if (sourceFilter(oldSource)) {
oldEntities.toList().forEach { data ->
if (!replaceMap.containsKey(data.id) && !otherProcessedSet.contains(data.id)) {
block(data)
}
}
}
}
}
private fun shallowHashCode(data: EntityData): Int = data.properties.entries.sortedBy { it.key }.fold(data.unmodifiableEntityType.hashCode()) { acc: Int, (key: String, value: Any?) ->
when (val kind = data.metaData.properties.getValue(key)) {
is EntityPropertyKind.EntityReference -> kind.clazz.hashCode()
is EntityPropertyKind.List -> when (val itemKind = kind.itemKind) {
is EntityPropertyKind.EntityReference -> itemKind.clazz.hashCode()
is EntityPropertyKind.List -> error("List of lists are not supported")
// TODO EntityReferences/EntityValues are not supported in sealed hierarchies
is EntityPropertyKind.SealedKotlinDataClassHierarchy -> value.hashCode()
is EntityPropertyKind.DataClass -> {
assertDataClassIsWithoutReferences(itemKind)
value.hashCode()
}
is EntityPropertyKind.EntityValue -> itemKind.clazz.hashCode()
EntityPropertyKind.FileUrl, is EntityPropertyKind.PersistentId, is EntityPropertyKind.Primitive -> value.hashCode()
}
// TODO EntityReferences/EntityValues are not supported in sealed hierarchies
is EntityPropertyKind.SealedKotlinDataClassHierarchy -> value.hashCode()
is EntityPropertyKind.DataClass -> {
assertDataClassIsWithoutReferences(kind)
value.hashCode()
}
is EntityPropertyKind.EntityValue -> kind.clazz.hashCode()
EntityPropertyKind.FileUrl, is EntityPropertyKind.PersistentId, is EntityPropertyKind.Primitive -> value.hashCode()
} * 7 + acc
}
private fun shallowEquals(data1: EntityData, data2: EntityData, replaceMap: Map<Long, Long>): Boolean {
if (data1.unmodifiableEntityType != data2.unmodifiableEntityType) return false
if (data1.properties.keys != data2.properties.keys) return false
if (data1.entitySource != data2.entitySource) return false
for (key in data1.properties.keys) {
val v1 = data1.properties.getValue(key)
val v2 = data2.properties.getValue(key)
val rc = when (val kind = data1.metaData.properties.getValue(key)) {
is EntityPropertyKind.EntityReference -> {
replaceMap[(v1 as ProxyBasedEntityReferenceImpl<*>).id] == (v2 as ProxyBasedEntityReferenceImpl<*>).id
}
is EntityPropertyKind.List -> when (val itemKind = kind.itemKind) {
is EntityPropertyKind.EntityReference -> {
val list1 = (v1 as List<ProxyBasedEntityReferenceImpl<*>>).map { replaceMap[it.id] }
val list2 = (v2 as List<ProxyBasedEntityReferenceImpl<*>>).map { it.id }
list1 == list2
}
is EntityPropertyKind.List -> error("List of lists are not supported")
// TODO EntityReferences/EntityValues are not supported in sealed hierarchies
is EntityPropertyKind.SealedKotlinDataClassHierarchy -> (v1 as List<Any?>) == (v2 as List<Any?>)
is EntityPropertyKind.DataClass -> {
assertDataClassIsWithoutReferences(itemKind)
(v1 as List<Any?>) == (v2 as List<Any?>)
}
is EntityPropertyKind.EntityValue -> {
val list1 = (v1 as List<Long>).map { replaceMap[it] }
val list2 = v2 as List<Long>
list1 == list2
}
EntityPropertyKind.FileUrl, is EntityPropertyKind.PersistentId, is EntityPropertyKind.Primitive -> (v1 as List<Any?>) == (v2 as List<Any?>)
}
// TODO EntityReferences/EntityValues are not supported in sealed hierarchies
is EntityPropertyKind.SealedKotlinDataClassHierarchy -> v1 == v2
is EntityPropertyKind.DataClass -> {
assertDataClassIsWithoutReferences(kind)
v1 == v2
}
is EntityPropertyKind.EntityValue -> if (v1 != null) replaceMap[v1 as Long] == v2 else v1 == v2
EntityPropertyKind.FileUrl, is EntityPropertyKind.PersistentId, is EntityPropertyKind.Primitive -> v1 == v2
}
if (!rc) return false
}
return true
}
private fun assertDataClassIsWithoutReferences(dataClassKind: EntityPropertyKind.DataClass) {
if (dataClassKind.hasReferences) {
TODO("DataClasses with references are not supported here yet: ${dataClassKind.dataClass}")
}
}
private fun recursiveAddEntity(id: Long, backReferrers: MultiMap<Long, Long>, storage: ProxyBasedEntityStorage, replaceMap: BiMap<Long, Long>) {
backReferrers[id].forEach { parentId ->
if (!replaceMap.containsValue(parentId)) {
recursiveAddEntity(parentId, backReferrers, storage, replaceMap)
}
}
val data = storage.entityById.getValue(id)
val newData = createEntityDataByUnmodifiableEntityClass(data.entitySource, data.unmodifiableEntityType)
replaceMap[newData.id] = id
copyEntityProperties(data, newData, replaceMap.inverse())
addEntity(newData, null, handleReferrers = true)
updateChangeLog { it.add(ChangeEntry.AddEntity(newData)) }
}
private fun copyEntityProperties(source: EntityData, dest: EntityData, replaceMap: Map<Long, Long>) {
dest.properties.clear()
source.properties.mapValuesTo(dest.properties) { (key, value) ->
when (val kind = source.metaData.properties.getValue(key)) {
is EntityPropertyKind.EntityReference -> replaceMap.getValue((value as ProxyBasedEntityReferenceImpl<*>).id)
is EntityPropertyKind.List -> when (val itemKind = kind.itemKind) {
is EntityPropertyKind.EntityReference -> (value as List<ProxyBasedEntityReferenceImpl<*>>).map { replaceMap.getValue(it.id) }
is EntityPropertyKind.List -> error("List of lists are not supported")
// TODO EntityReferences/EntityValues are not supported in sealed hierarchies
is EntityPropertyKind.SealedKotlinDataClassHierarchy -> value
is EntityPropertyKind.DataClass -> {
assertDataClassIsWithoutReferences(itemKind)
value
}
is EntityPropertyKind.EntityValue -> (value as List<Long>).map { replaceMap.getValue(it) }
EntityPropertyKind.FileUrl, is EntityPropertyKind.PersistentId, is EntityPropertyKind.Primitive -> value
}
// TODO EntityReferences/EntityValues are not supported in sealed hierarchies
is EntityPropertyKind.SealedKotlinDataClassHierarchy -> value
is EntityPropertyKind.DataClass -> {
assertDataClassIsWithoutReferences(kind)
value
}
is EntityPropertyKind.EntityValue -> (value as Long?)?.let { replaceMap.getValue(it) }
EntityPropertyKind.FileUrl, is EntityPropertyKind.PersistentId, is EntityPropertyKind.Primitive -> value
}
}
}
private fun traverseNodes(storage: ProxyBasedEntityStorage, startNode: Long, block: (Long) -> Unit) {
val queue: Queue<Long> = Queues.newArrayDeque(listOf(startNode))
while (queue.isNotEmpty()) {
val id = queue.remove()
block(id)
val referrers = storage.referrers[id]
if (referrers != null) {
queue.addAll(referrers)
}
}
}
data class EqualityResult<T1, T2>(
val onlyIn1: List<T1>,
val onlyIn2: List<T2>,
val equal: List<Pair<T1, T2>>
)
override fun collectChanges(original: TypedEntityStorage): Map<Class<*>, List<EntityChange<*>>> {
val originalImpl = original as ProxyBasedEntityStorage
//this can be optimized to avoid creation of entity instances which are thrown away and copying the results from map to list
// LinkedHashMap<Long, EntityChange<T>>
val changes = LinkedHashMap<Long, Pair<Class<*>, EntityChange<*>>>()
for (change in changeLog) {
when (change) {
is ChangeEntry.AddEntity -> {
changes[change.entityData.id] = change.entityData.unmodifiableEntityType to EntityChange.Added(createEntityInstance(change.entityData))
}
is ChangeEntry.RemoveEntity -> {
val removedData = originalImpl.entityById[change.id]
val oldChange = changes.remove(change.id)
if (oldChange?.second !is EntityChange.Added && removedData != null) {
changes[change.id] = removedData.unmodifiableEntityType to EntityChange.Removed(originalImpl.createEntityInstance(removedData))
}
}
is ChangeEntry.ReplaceEntity -> {
val oldChange = changes.remove(change.id)
if (oldChange?.second is EntityChange.Added) {
changes[change.id] = change.newData.unmodifiableEntityType to EntityChange.Added(createEntityInstance(change.newData))
}
else {
val oldData = originalImpl.entityById[change.id]
if (oldData != null) {
changes[change.id] = oldData.unmodifiableEntityType to EntityChange.Replaced(originalImpl.createEntityInstance(oldData), createEntityInstance(change.newData))
}
}
}
}
}
return changes.values.groupBy { it.first }.mapValues { list -> list.value.map { it.second } }
}
override fun resetChanges() {
updateChangeLog { changeLog -> changeLog.clear() }
}
override fun toStorage(): TypedEntityStorage = ProxyBasedEntityStorage(entitiesByType.mapValues { it.value.toSet() },
entitiesBySource.mapValues { it.value.toSet() },
entitiesByPersistentIdHash.mapValues { it.value.toSet() },
entityById.toMap(),
referrers.mapValues { it.value.toList() },
persistentIdReferrers.mapValues { it.value.toSet() },
metaDataRegistry)
sealed class ChangeEntry {
data class AddEntity(val entityData: EntityData) : ChangeEntry()
data class RemoveEntity(val id: Long) : ChangeEntry()
data class ReplaceEntity(val id: Long, val newData: EntityData) : ChangeEntry()
}
}
internal class ProxyBasedEntityReferenceImpl<E : TypedEntity>(val id: Long): EntityReference<E>() {
override fun resolve(storage: TypedEntityStorage): E = with(storage as ProxyBasedEntityStorage) {
createEntityInstance(entityById.getValue(id)) as E
}
}
internal inline class IdGenerator(val generator: AtomicLong) {
internal fun getId() = generator.getAndIncrement()
internal fun adjustId(existingId: Long) {
while (true) {
val currentGeneratorValue = generator.get()
if (currentGeneratorValue <= existingId) {
val res = generator.compareAndSet(currentGeneratorValue, existingId + 1)
if (res) break
} else break
}
}
companion object {
fun startGenerator(initialValue: Long = 1) = IdGenerator(AtomicLong(initialValue))
}
}
internal val entityDataIdGenerator = IdGenerator.startGenerator()
internal class EntityData(val entitySource: EntitySource, val id: Long, val metaData: EntityMetaData, val properties: MutableMap<String, Any?> = HashMap()) {
constructor(
entitySource: EntitySource,
metaData: EntityMetaData,
properties: MutableMap<String, Any?> = HashMap()
) : this(entitySource, entityDataIdGenerator.getId(), metaData, properties)
val unmodifiableEntityType: Class<out TypedEntity>
get() = metaData.unmodifiableEntityType
fun createModifiableCopy(): EntityData {
val propertiesCopy = properties.mapValuesTo(HashMap()) { (it.value as? List<*>)?.toMutableList() ?: it.value }
return EntityData(entitySource, id, metaData, propertiesCopy)
}
fun collectReferences(collector: (Long) -> Unit) = metaData.collectReferences(properties, collector)
fun collectPersistentIdReferences(collector: (PersistentEntityId<*>) -> Unit) = metaData.collectPersistentIdReferences(properties, collector)
fun replaceAllPersistentIdReferences(oldEntity: PersistentEntityId<*>, newEntity: PersistentEntityId<*>) =
metaData.replaceAllPersistentIdReferences(properties, oldEntity, newEntity)
override fun toString() = "${unmodifiableEntityType.simpleName}@$id"
}
internal class EntityImpl(override val data: EntityData,
override val storage: ProxyBasedEntityStorage) : InvocationHandler, ProxyBasedEntity, ReferableTypedEntity {
private val modifiable = ThreadLocal.withInitial { false }
internal inline fun allowModifications(action: () -> Unit) {
modifiable.set(true)
try {
action()
}
finally {
modifiable.remove()
}
}
override val entitySource: EntitySource
get() = data.entitySource
override val id: Long
get() = data.id
override fun <R : TypedEntity> referrers(entityClass: Class<R>, propertyName: String): Sequence<R> {
return storage.referrers(id, entityClass, propertyName)
}
override fun hasEqualProperties(e: TypedEntity): Boolean {
return e is ProxyBasedEntity && e.data.unmodifiableEntityType == data.unmodifiableEntityType && e.data.properties == data.properties
}
override fun invoke(proxy: Any, method: Method, args: Array<out Any?>?): Any? {
if (method.declaringClass == ProxyBasedEntity::class.java || method.declaringClass == ReferableTypedEntity::class.java
|| method.declaringClass == TypedEntity::class.java) {
return method.invoke(this, *(args ?: ArrayUtil.EMPTY_OBJECT_ARRAY))
}
val name = method.name
when (name) {
"equals" -> return (args?.firstOrNull() as? ProxyBasedEntity)?.id == id
"hashCode" -> return id.toInt()
"toString" -> return data.toString()
}
if (method.isDefault) {
if (JavaVersion.current().isAtLeast(9)) {
val methodHandle = MethodHandles.lookup().findSpecial(method.declaringClass, method.name,
MethodType.methodType(method.returnType, method.parameterTypes),
method.declaringClass)
return methodHandle.bindTo(proxy).invokeWithArguments(*(args ?: ArrayUtil.EMPTY_OBJECT_ARRAY))
}
else {
//this hack is needed because in Java 8 the way above won't work (see https://bugs.openjdk.java.net/browse/JDK-8130227)
val constructor = MethodHandles.Lookup::class.java.getDeclaredConstructor(Class::class.java, Int::class.java)
constructor.isAccessible = true
val lookup = constructor.newInstance(method.declaringClass, MethodHandles.Lookup.PRIVATE)
return lookup.unreflectSpecial(method, method.declaringClass).bindTo(proxy).invokeWithArguments(*(args ?: ArrayUtil.EMPTY_OBJECT_ARRAY))
}
}
if (name.startsWith("get")) {
val propertyName = name.removePrefix("get").decapitalize()
val value = data.properties[propertyName]
return when (val propertyKind = data.metaData.properties.getValue(propertyName)) {
is EntityPropertyKind.EntityValue -> (value as Long?)?.let { storage.createEntityInstance(storage.entityById.getValue(it)) }
is EntityPropertyKind.List -> when (propertyKind.itemKind) {
is EntityPropertyKind.EntityValue -> {
(value as List<Long>).map { id -> storage.createEntityInstance(storage.entityById.getValue(id)) }
}
else -> value
}
else -> value
}
}
if (name.startsWith("set")) {
if (!modifiable.get()) {
throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!")
}
val newValue = args!![0]
val propertyName = name.removePrefix("set").decapitalize()
val referrers = (storage as TypedEntityStorageBuilderImpl).referrers
when (val propertyKind = data.metaData.properties[propertyName]) {
is EntityPropertyKind.EntityValue -> {
val oldStorageValue = data.properties[propertyName]
data.properties[propertyName] = newValue?.let { it as ProxyBasedEntity }?.id
if (oldStorageValue != null) {
referrers.listRemoveValue(oldStorageValue as Long, id)
}
if (newValue != null) {
referrers.listPutValue((newValue as ProxyBasedEntity).id, id)
}
}
is EntityPropertyKind.List -> when (val itemKind = propertyKind.itemKind) {
is EntityPropertyKind.EntityValue -> {
val oldValues = data.properties[propertyName]
data.properties[propertyName] = newValue?.let { it as List<ProxyBasedEntity> }?.map { it.id }
if (oldValues != null) {
(oldValues as List<Long>).forEach { referrers.listRemoveValue(it, id) }
}
if (newValue != null) {
(newValue as List<ProxyBasedEntity>).forEach { referrers.listPutValue(it.id, id) }
}
Unit
}
is EntityPropertyKind.DataClass -> {
val oldValues = data.properties[propertyName]
data.properties[propertyName] = newValue
if (oldValues != null) {
for (oldValue in oldValues as List<*>) {
itemKind.collectReferences(oldValue) { referrers.listRemoveValue(it, id) }
}
}
if (newValue != null) {
for (value in newValue as List<*>) {
itemKind.collectReferences(newValue) { referrers.listPutValue(it, id) }
}
}
Unit
}
is EntityPropertyKind.EntityReference, is EntityPropertyKind.List -> error("List item kind is unsupported: $itemKind")
// TODO EntityReferences are unsupported in SealedKotlinDataClassHierarchy, asserted in EntityMetaDataRegistry.getPropertyKind
is EntityPropertyKind.SealedKotlinDataClassHierarchy, is EntityPropertyKind.Primitive,
is EntityPropertyKind.PersistentId, EntityPropertyKind.FileUrl -> data.properties[propertyName] = newValue
}.let { } // exhaustive when
is EntityPropertyKind.DataClass -> {
val oldValue = data.properties[propertyName]
data.properties[propertyName] = newValue
propertyKind.collectReferences(oldValue) { referrers.listRemoveValue(it, id) }
propertyKind.collectReferences(newValue) { referrers.listPutValue(it, id) }
}
else -> data.properties[propertyName] = newValue
}
return null
}
throw IllegalArgumentException("Unexpected method $method")
}
}
private fun <M : ModifiableTypedEntity<T>, T : TypedEntity> getUnmodifiableEntityClass(clazz: Class<out M>): Class<T> {
val modifiableType = clazz.genericInterfaces.filterIsInstance(ParameterizedType::class.java).find { it.rawType == ModifiableTypedEntity::class.java }
?: throw IllegalArgumentException("$clazz doesn't implement ModifiableTypedEntity")
val unmodifiableEntityClass = modifiableType.actualTypeArguments.firstOrNull() as? Class<T>
?: throw IllegalArgumentException("$clazz doesn't specify type argument for ModifiableTypedEntity")
if (!unmodifiableEntityClass.isAssignableFrom(clazz)) {
throw IllegalArgumentException("$clazz is not subclass of its unmodifiable version $unmodifiableEntityClass")
}
return unmodifiableEntityClass
}
private fun <K, V> MutableMap<K, MutableSet<V>>.putValue(k: K, v: V) {
computeIfAbsent(k) {HashSet()}.add(v)
}
private fun <K, V> MutableMap<K, MutableSet<V>>.removeValue(k: K, v: V) {
val set = get(k)
if (set != null) {
set.remove(v)
if (set.isEmpty()) {
remove(k)
}
}
}
private fun <K, V> MutableMap<K, MutableList<V>>.listPutValue(k: K, v: V) {
computeIfAbsent(k) {ArrayList()}.add(v)
}
private fun <K, V> MutableMap<K, MutableList<V>>.listRemoveValue(k: K, v: V) {
val set = get(k)
if (set != null) {
set.remove(v)
if (set.isEmpty()) {
remove(k)
}
}
} | apache-2.0 | 4fe6f50a0a95a14220f28f368c9876c6 | 43.323827 | 215 | 0.668466 | 4.668508 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/arrays/stdlib.kt | 4 | 1310 | interface ISized {
val size : Int
}
interface javaUtilIterator<T> : Iterator<T> {
fun remove() : Unit {
throw UnsupportedOperationException()
}
}
class MyIterator<T>(val array : ReadOnlyArray<T>) : javaUtilIterator<T> {
private var index = 0
override fun hasNext() : Boolean = index < array.size
override fun next() : T = array.get(index++)
}
interface ReadOnlyArray<out T> : ISized, Iterable<T> {
operator fun get(index : Int) : T
override fun iterator() : Iterator<T> = MyIterator<T>(this)
}
interface WriteOnlyArray<in T> : ISized {
operator fun set(index : Int, value : T) : Unit
operator fun set(from: Int, count: Int, value: T) {
for(i in from..from+count-1) {
set(i, value)
}
}
}
class MutableArray<T>(length: Int, init : (Int) -> T) : ReadOnlyArray<T>, WriteOnlyArray<T> {
private val array = Array<Any?>(length, init)
override fun get(index : Int) : T = array[index] as T
override fun set(index : Int, value : T) : Unit { array[index] = value }
override val size : Int
get() = array.size
}
fun box() : String {
var a = MutableArray<Int> (4, {0})
a [0] = 10
a.set(1, 2, 13)
a [3] = 40
a.iterator()
a.iterator().hasNext()
for(el in a) {
val fl = el
}
return "OK"
}
| apache-2.0 | e6d05e05b09f2f4bf4d38b1658f451a4 | 22.392857 | 93 | 0.601527 | 3.210784 | false | false | false | false |
byoutline/kickmaterial | app/src/main/java/com/byoutline/kickmaterial/features/projectlist/ProjectsListFragment.kt | 1 | 6635 | package com.byoutline.kickmaterial.features.projectlist
import android.content.res.ColorStateList
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.view.*
import com.byoutline.cachedfield.FieldState
import com.byoutline.cachedfield.FieldStateListener
import com.byoutline.kickmaterial.R
import com.byoutline.kickmaterial.databinding.FragmentProjectsBinding
import com.byoutline.kickmaterial.features.projectdetails.startProjectDetailsActivity
import com.byoutline.kickmaterial.features.search.SearchListFragment
import com.byoutline.kickmaterial.features.selectcategory.ARG_CATEGORY
import com.byoutline.kickmaterial.features.selectcategory.CategoriesListActivity
import com.byoutline.kickmaterial.model.Category
import com.byoutline.kickmaterial.model.DiscoverQuery
import com.byoutline.kickmaterial.model.Project
import com.byoutline.kickmaterial.transitions.SharedViews
import com.byoutline.kickmaterial.utils.KickMaterialFragment
import com.byoutline.kickmaterial.utils.LUtils
import com.byoutline.kickmaterial.views.EndlessScrollListener
import com.byoutline.kickmaterial.views.setEndlessScrollListener
import com.byoutline.secretsauce.activities.showFragment
import com.byoutline.secretsauce.databinding.inflateAndSetVM
import com.byoutline.secretsauce.lifecycle.lazyViewModelWithAutoLifecycle
import org.jetbrains.anko.bundleOf
import org.jetbrains.anko.sdk25.listeners.onClick
import org.jetbrains.anko.support.v4.onRefresh
import timber.log.Timber
/**
* @author Pawel Karczewski <pawel.karczewski at byoutline.com> on 2015-01-03
*/
class ProjectsListFragment : KickMaterialFragment(), ProjectClickListener, FieldStateListener, EndlessScrollListener {
private val viewModel by lazyViewModelWithAutoLifecycle(ProjectListViewModel::class)
lateinit var binding: FragmentProjectsBinding
private lateinit var category: Category
/**
* Endless scroll variables *
*/
private lateinit var layoutManager: GridLayoutManager
private lateinit var scrollListener: ProjectsListScrollListener
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = inflateAndSetVM(inflater, container, R.layout.fragment_projects, viewModel)
hostActivity?.enableToolbarAutoHide(binding.projectRecyclerView)
category = arguments!!.getParcelable(ARG_CATEGORY)
viewModel.category = category
setHasOptionsMenu(true)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpAdapters()
setUpListeners()
configureSwipeRefresh()
}
private fun configureSwipeRefresh() {
val altColor = category.colorResId
binding.swipeRefreshProjectsSrl.setColorSchemeResources(altColor, R.color.green_primary)
binding.swipeRefreshProjectsSrl.onRefresh {
// Throw away all loaded categories and start over.
val pageToRefresh = 1
viewModel.discoverField.refresh(DiscoverQuery.getDiscoverQuery(category, pageToRefresh))
}
}
private fun setUpListeners() {
binding.showCategoriesFab.onClick {
CategoriesListActivity.launch(activity!!, category, binding.showCategoriesFab)
}
scrollListener = ProjectsListScrollListener(context!!, { hostActivity }, binding)
binding.projectRecyclerView.addOnScrollListener(scrollListener)
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putFloat(INSTANCE_STATE_SUMMARY_SCROLLED, scrollListener.summaryScrolled)
super.onSaveInstanceState(outState)
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
scrollListener.summaryScrolled = savedInstanceState?.getFloat(INSTANCE_STATE_SUMMARY_SCROLLED) ?: 0f
super.onViewStateRestored(savedInstanceState)
}
override fun onResume() {
super.onResume()
restoreDefaultScreenLook()
viewModel.discoverField.addStateListener(this)
Timber.d("items will be refreshed ${viewModel.category}")
viewModel.loadCurrentPage()
binding.showCategoriesFab.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(context!!, category.colorResId))
}
override fun onPause() {
viewModel.discoverField.removeStateListener(this)
super.onPause()
}
private fun setUpAdapters() {
layoutManager = GridLayoutManager(activity, 2)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int
= if (viewModel.items[position].type == ProjectItemViewModel.NORMAL_ITEM) 1 else 2
}
binding.projectRecyclerView.setEndlessScrollListener(this)
binding.projectRecyclerView.layoutManager = layoutManager
}
private fun restoreDefaultScreenLook() {
hostActivity?.showToolbar(true, false)
LUtils.setStatusBarColor(activity!!, ContextCompat.getColor(context!!, R.color.status_bar_color))
}
override fun getFragmentToolbarName() = category.nameResId
override fun showBackButtonInToolbar() = false
override fun projectClicked(project: Project, views: SharedViews) {
views.add(binding.showCategoriesFab)
activity?.startProjectDetailsActivity(project, views)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater?) {
val searchView = SearchListFragment.getSearchView(activity!!, menu)
searchView.isIconified = true
searchView.setOnSearchClickListener { _ -> activity?.showFragment(SearchListFragment(), true) }
}
override fun fieldStateChanged(newState: FieldState) {
binding.swipeRefreshProjectsSrl.isRefreshing = newState == FieldState.CURRENTLY_LOADING
}
override val lastVisibleItemPosition: Int
get() = layoutManager.findLastVisibleItemPosition()
override fun loadMoreData() = viewModel.loadMoreData()
@Synchronized override fun hasMoreDataAndNotLoading() = viewModel.hasMoreDataAndNotLoading()
companion object {
const val PREFS_SHOW_HEADER = "PREFS_SHOW_HEADER"
private const val INSTANCE_STATE_SUMMARY_SCROLLED = "INSTANCE_STATE_SUMMARY_SCROLLED"
fun newInstance(category: Category?): ProjectsListFragment {
return ProjectsListFragment().apply {
arguments = bundleOf(ARG_CATEGORY to category)
}
}
}
}
| apache-2.0 | d2f0a4057d0234e5f93a40da483f606e | 40.21118 | 133 | 0.755539 | 5.076511 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/net/auth/AuthHelper.kt | 1 | 3836 | package au.com.codeka.warworlds.client.net.auth
import android.app.Activity
import android.content.Context
import au.com.codeka.warworlds.client.App
import au.com.codeka.warworlds.common.Log
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
import com.google.common.util.concurrent.Futures
import java.util.concurrent.Callable
import java.util.concurrent.Future
import java.util.concurrent.FutureTask
const val SERVER_CLIENT_ID =
"809181406384-obrefe4qb0hmaektbesqsc25rop0u72f.apps.googleusercontent.com"
const val SIGN_IN_COMPLETE_RESULT_CODE = 9746
class AuthHelper(private val appContext: Context) {
private lateinit var client: GoogleSignInClient
private val awaitingSignInCompleteLock = Object()
private var awaitingSignInComplete = false
/**
* The current [GoogleSignInAccount], or null if not signed in. This can also be null before
* [silentSignIn] has completed. If you need to know whether [silentSignIn] has completed (and
* the account could still be null), use [futureAccount].
*/
var account: GoogleSignInAccount? = null
private set
companion object {
val log = Log("AuthHelper")
}
/** Returns a future that will only return after [silentSignIn] has completed. */
fun futureAccount(): Future<GoogleSignInAccount?> {
if (awaitingSignInComplete) {
return Futures.immediateFuture(account)
}
return App.taskRunner.backgroundExecutor.submit(Callable {
while (!awaitingSignInComplete) {
synchronized(awaitingSignInCompleteLock) {
awaitingSignInCompleteLock.wait(100)
}
}
account
})
}
val isSignedIn: Boolean
get() = account != null
/**
* Attempt to do a 'silent' sign-in. This should be called as early in app start-up time as
* possible.
*/
fun silentSignIn(activity: Activity) {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(SERVER_CLIENT_ID)
.requestEmail()
.build()
client = GoogleSignIn.getClient(appContext, gso)
client.silentSignIn().addOnCompleteListener(activity) { task -> handleSignInResult(task) }
}
/**
* Perform an explicit sign-in. This is after the user has clicked a "sign in" button and they
* expect to see some UI.
*/
fun explicitSignIn(activity: Activity): Future<GoogleSignInAccount?> {
awaitingSignInComplete = false
activity.startActivityForResult(client.signInIntent, SIGN_IN_COMPLETE_RESULT_CODE)
return futureAccount()
}
/**
* Performs a sign out. This will block until actually signed out, so only call this on a
* background thread.
*/
fun signOut() {
Tasks.await(client.signOut())
}
/**
* Handle a sign-in result. This is called from the activity's onActivityResult when you get
* a result code of [SIGN_IN_COMPLETE_RESULT_CODE].
*/
fun handleSignInResult(task: Task<GoogleSignInAccount>) {
try {
val acct = task.getResult(ApiException::class.java)
account = acct
log.info("Authenticated as: ${acct.email} : ${acct.displayName}")
App.eventBus.publish(AuthAccountUpdate(acct))
} catch (e: ApiException) {
log.warning("Authentication failed code: ${e.statusCode}")
account = null
App.eventBus.publish(AuthAccountUpdate(null))
}
synchronized(awaitingSignInCompleteLock) {
if (!awaitingSignInComplete) {
awaitingSignInComplete = true
awaitingSignInCompleteLock.notifyAll()
}
}
}
}
| mit | 854125d628dbafb9c2a47f20380ad5fb | 32.356522 | 96 | 0.724713 | 4.129171 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/camera/tasks/ResolveTakenPictureAsyncTask.kt | 2 | 8314 | package abi44_0_0.expo.modules.camera.tasks
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.util.Base64
import androidx.exifinterface.media.ExifInterface
import abi44_0_0.expo.modules.camera.CameraViewHelper.getExifData
import abi44_0_0.expo.modules.camera.CameraViewHelper.addExifData
import abi44_0_0.expo.modules.camera.utils.FileSystemUtils
import abi44_0_0.expo.modules.core.Promise
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.lang.Exception
private const val DIRECTORY_NOT_FOUND_MSG = "Documents directory of the app could not be found."
private const val UNKNOWN_IO_EXCEPTION_MSG = "An unknown I/O exception has occurred."
private const val UNKNOWN_EXCEPTION_MSG = "An unknown exception has occurred."
private const val ERROR_TAG = "E_TAKING_PICTURE_FAILED"
private const val DIRECTORY_NAME = "Camera"
private const val EXTENSION = ".jpg"
private const val SKIP_PROCESSING_KEY = "skipProcessing"
private const val FAST_MODE_KEY = "fastMode"
private const val QUALITY_KEY = "quality"
private const val BASE64_KEY = "base64"
private const val HEIGHT_KEY = "height"
private const val WIDTH_KEY = "width"
private const val EXIF_KEY = "exif"
private const val DATA_KEY = "data"
private const val URI_KEY = "uri"
private const val ID_KEY = "id"
private const val DEFAULT_QUALITY = 1
class ResolveTakenPictureAsyncTask(
private var promise: Promise,
private var options: Map<String, Any>,
private val directory: File,
private var pictureSavedDelegate: PictureSavedDelegate
) : AsyncTask<Void?, Void?, Bundle?>() {
private var imageData: ByteArray? = null
private var bitmap: Bitmap? = null
constructor(imageData: ByteArray?, promise: Promise, options: Map<String, Any>, directory: File, delegate: PictureSavedDelegate) : this(
promise, options, directory, delegate
) {
this.imageData = imageData
}
constructor(bitmap: Bitmap?, promise: Promise, options: Map<String, Any>, directory: File, delegate: PictureSavedDelegate) : this(
promise, options, directory, delegate
) {
this.bitmap = bitmap
}
private val quality: Int
get() = options[QUALITY_KEY]?.let {
val requestedQuality = (it as Number).toDouble()
(requestedQuality * 100).toInt()
} ?: DEFAULT_QUALITY * 100
override fun doInBackground(vararg params: Void?): Bundle? {
// handle SkipProcessing
if (imageData != null && isOptionEnabled(SKIP_PROCESSING_KEY)) {
return handleSkipProcessing()
}
if (bitmap == null) {
bitmap = imageData?.let { BitmapFactory.decodeByteArray(imageData, 0, it.size) }
}
try {
ByteArrayInputStream(imageData).use { inputStream ->
val response = Bundle()
val exifInterface = ExifInterface(inputStream)
// Get orientation of the image from mImageData via inputStream
val orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
// Rotate the bitmap to the proper orientation if needed
if (orientation != ExifInterface.ORIENTATION_UNDEFINED) {
bitmap = bitmap?.let {
rotateBitmap(it, getImageRotation(orientation))
}
}
// Write Exif data to the response if requested
if (isOptionEnabled(EXIF_KEY)) {
val exifData = getExifData(exifInterface)
response.putBundle(EXIF_KEY, exifData)
}
// Upon rotating, write the image's dimensions to the response
response.apply {
putInt(WIDTH_KEY, bitmap!!.width)
putInt(HEIGHT_KEY, bitmap!!.height)
}
// Cache compressed image in imageStream
ByteArrayOutputStream().use { imageStream ->
bitmap!!.compress(Bitmap.CompressFormat.JPEG, quality, imageStream)
// Write compressed image to file in cache directory
val filePath = writeStreamToFile(imageStream)
// Save Exif data to the image if requested
if (isOptionEnabled(EXIF_KEY)) {
val exifFromFile = ExifInterface(filePath!!)
addExifData(exifFromFile, exifInterface)
}
val imageFile = File(filePath)
val fileUri = Uri.fromFile(imageFile).toString()
response.putString(URI_KEY, fileUri)
// Write base64-encoded image to the response if requested
if (isOptionEnabled(BASE64_KEY)) {
response.putString(BASE64_KEY, Base64.encodeToString(imageStream.toByteArray(), Base64.NO_WRAP))
}
}
return response
}
} catch (e: Exception) {
when (e) {
is Resources.NotFoundException -> promise.reject(ERROR_TAG, DIRECTORY_NOT_FOUND_MSG, e)
is IOException -> promise.reject(ERROR_TAG, UNKNOWN_IO_EXCEPTION_MSG, e)
else -> promise.reject(ERROR_TAG, UNKNOWN_EXCEPTION_MSG, e)
}
e.printStackTrace()
}
// An exception had to occur, promise has already been rejected. Do not try to resolve it again.
return null
}
private fun handleSkipProcessing(): Bundle? {
try {
// save byte array (it's already a JPEG)
ByteArrayOutputStream().use { imageStream ->
imageStream.write(imageData)
// write compressed image to file in cache directory
val filePath = writeStreamToFile(imageStream)
val imageFile = File(filePath)
// handle image uri
val fileUri = Uri.fromFile(imageFile).toString()
// read exif information
val exifInterface = ExifInterface(filePath!!)
return Bundle().apply {
putString(URI_KEY, fileUri)
putInt(WIDTH_KEY, exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, -1))
putInt(HEIGHT_KEY, exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, -1))
// handle exif request
if (isOptionEnabled(EXIF_KEY)) {
val exifData = getExifData(exifInterface)
putBundle(EXIF_KEY, exifData)
}
// handle base64
if (isOptionEnabled(BASE64_KEY)) {
putString(BASE64_KEY, Base64.encodeToString(imageData, Base64.NO_WRAP))
}
}
}
} catch (e: Exception) {
if (e is IOException) {
promise.reject(ERROR_TAG, UNKNOWN_IO_EXCEPTION_MSG, e)
} else {
promise.reject(ERROR_TAG, UNKNOWN_EXCEPTION_MSG, e)
}
e.printStackTrace()
}
// error occurred
return null
}
override fun onPostExecute(response: Bundle?) {
super.onPostExecute(response)
// If the response is not null everything went well and we can resolve the promise.
if (response != null) {
if (isOptionEnabled(FAST_MODE_KEY)) {
val wrapper = Bundle()
wrapper.putInt(ID_KEY, (options[ID_KEY] as Double).toInt())
wrapper.putBundle(DATA_KEY, response)
pictureSavedDelegate.onPictureSaved(wrapper)
} else {
promise.resolve(response)
}
}
}
// Write stream to file in cache directory
@Throws(Exception::class)
private fun writeStreamToFile(inputStream: ByteArrayOutputStream): String? {
try {
val outputPath = FileSystemUtils.generateOutputPath(directory, DIRECTORY_NAME, EXTENSION)
FileOutputStream(outputPath).use { outputStream ->
inputStream.writeTo(outputStream)
}
return outputPath
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
private fun rotateBitmap(source: Bitmap, angle: Int): Bitmap {
val matrix = Matrix()
matrix.postRotate(angle.toFloat())
return Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true)
}
// Get rotation degrees from Exif orientation enum
private fun getImageRotation(orientation: Int) = when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> 90
ExifInterface.ORIENTATION_ROTATE_180 -> 180
ExifInterface.ORIENTATION_ROTATE_270 -> 270
else -> 0
}
private fun isOptionEnabled(key: String) = options[key] != null && (options[key] as Boolean)
}
| bsd-3-clause | 9e3a7160c450ea411204d84bce704c1a | 34.991342 | 138 | 0.679937 | 4.424694 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/gradle/testRunConfigurations/preferredConfigurations/src/test/kotlin/MyKotlinTest.kt | 13 | 378 | import org.junit.Test
class <lineMarker descr="Run Test" settings=":test --tests \"MyKotlinTest\"">MyKotlinTest</lineMarker> {
@Test
fun <lineMarker descr="Run Test" settings=":test --tests \"MyKotlinTest.testA\"">testA</lineMarker>() {
}
@Test
fun <lineMarker descr="Run Test" settings=":test --tests \"MyKotlinTest.testB\"">testB</lineMarker>() {
}
} | apache-2.0 | b63752e97e044998a70de25aebfd4621 | 33.454545 | 107 | 0.666667 | 3.896907 | false | true | false | false |
smmribeiro/intellij-community | plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MavenSetupProjectTest.kt | 1 | 4013 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.importing
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.NonBlockingReadActionImpl
import com.intellij.openapi.externalSystem.importing.ExternalSystemSetupProjectTest
import com.intellij.openapi.externalSystem.importing.ExternalSystemSetupProjectTestCase
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.PlatformTestUtil
import junit.framework.TestCase
import com.intellij.maven.testFramework.MavenImportingTestCase
import com.intellij.maven.testFramework.xml.MavenBuildFileBuilder
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent
import org.jetbrains.idea.maven.project.actions.AddFileAsMavenProjectAction
import org.jetbrains.idea.maven.project.actions.AddManagedFilesAction
import org.jetbrains.idea.maven.project.importing.MavenImportingManager
import org.jetbrains.idea.maven.utils.MavenUtil.SYSTEM_ID
import org.junit.Test
class MavenSetupProjectTest : ExternalSystemSetupProjectTest, MavenImportingTestCase() {
override fun getSystemId(): ProjectSystemId = SYSTEM_ID
@Test
fun `test settings are not reset`() {
val projectInfo = generateProject("A")
val linkedProjectInfo = generateProject("L")
waitForImport {
openProjectFrom(projectInfo.projectFile)
}.use {
assertModules(it, projectInfo)
MavenWorkspaceSettingsComponent.getInstance(it).settings.getGeneralSettings().isWorkOffline = true
waitForImport {
attachProject(it, linkedProjectInfo.projectFile)
}
assertModules(it, projectInfo, linkedProjectInfo)
TestCase.assertTrue(MavenWorkspaceSettingsComponent.getInstance(it).settings.getGeneralSettings().isWorkOffline)
}
}
override fun generateProject(id: String): ExternalSystemSetupProjectTestCase.ProjectInfo {
val name = "${System.currentTimeMillis()}-$id"
createProjectSubFile("$name-external-module/pom.xml", MavenBuildFileBuilder("$name-external-module").generate())
createProjectSubFile("$name-project/$name-module/pom.xml", MavenBuildFileBuilder("$name-module").generate())
val buildScript = MavenBuildFileBuilder("$name-project")
.withPomPackaging()
.withModule("$name-module")
.withModule("../$name-external-module")
.generate()
val projectFile = createProjectSubFile("$name-project/pom.xml", buildScript)
return ExternalSystemSetupProjectTestCase.ProjectInfo(projectFile, "$name-project", "$name-module", "$name-external-module")
}
override fun attachProject(project: Project, projectFile: VirtualFile): Project {
AddManagedFilesAction().perform(project, selectedFile = projectFile)
waitForImportCompletion(project)
return project
}
override fun attachProjectFromScript(project: Project, projectFile: VirtualFile): Project {
AddFileAsMavenProjectAction().perform(project, selectedFile = projectFile)
waitForImportCompletion(project)
return project
}
override fun waitForImport(action: () -> Project): Project {
val p = action()
waitForImportCompletion(p)
return p
}
private fun waitForImportCompletion(project: Project) {
NonBlockingReadActionImpl.waitForAsyncTaskCompletion()
val projectManager = MavenProjectsManager.getInstance(project)
projectManager.initForTests()
if (isNewImportingProcess) {
val promise = MavenImportingManager.getInstance(project).getImportFinishPromise()
PlatformTestUtil.waitForPromise(promise)
}
else {
ApplicationManager.getApplication().invokeAndWait {
projectManager.waitForResolvingCompletion()
projectManager.performScheduledImportInTests()
}
}
}
} | apache-2.0 | e8b0335fcab7850e099a4e8c2614f77a | 43.6 | 140 | 0.786693 | 4.923926 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/resolve/partialBodyResolve/IfNullElvisReturn.kt | 13 | 232 | fun foo() {
for (i in 1..10) {
val x = take()
if (x == null) {
print(1)
val v = f() ?: return
}
<caret>x.hashCode()
}
}
fun take(): Any? = null
fun f(): String? = null | apache-2.0 | 331f2cd4619850c37498c6eb9a9e26db | 16.923077 | 33 | 0.383621 | 3.222222 | false | false | false | false |
vanniktech/lint-rules | lint-rules-android-lint/src/main/java/com/vanniktech/lintrules/android/WrongTestMethodNameDetector.kt | 1 | 2258 | @file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final.
package com.vanniktech.lintrules.android
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.LintFix
import com.android.tools.lint.detector.api.Scope.JAVA_FILE
import com.android.tools.lint.detector.api.Scope.TEST_SOURCES
import com.android.tools.lint.detector.api.Severity.WARNING
import org.jetbrains.uast.UAnnotated
import org.jetbrains.uast.UMethod
import java.util.EnumSet
import java.util.Locale
val ISSUE_WRONG_TEST_METHOD_NAME = Issue.create(
"WrongTestMethodName",
"Flags test methods that start with test.",
"The @Test annotation already states that this is a test hence the test prefix is not necessary.",
CORRECTNESS, PRIORITY, WARNING,
Implementation(WrongTestMethodNameDetector::class.java, EnumSet.of(JAVA_FILE, TEST_SOURCES), EnumSet.of(JAVA_FILE, TEST_SOURCES)),
)
class WrongTestMethodNameDetector : Detector(), Detector.UastScanner {
override fun getApplicableUastTypes() = listOf(UMethod::class.java)
override fun createUastHandler(context: JavaContext) = WrongTestMethodNameVisitor(context)
class WrongTestMethodNameVisitor(private val context: JavaContext) : UElementHandler() {
override fun visitMethod(node: UMethod) {
context.evaluator.getAllAnnotations(node as UAnnotated, true)
.mapNotNull { it.qualifiedName?.split(".")?.lastOrNull() }
.filter { it == "Test" }
.filter { node.name.startsWith("test", ignoreCase = true) }
.forEach { _ ->
val fix = LintFix.create()
.name("Remove test prefix")
.replace()
.text(node.name)
.with(node.name.replace("test", "", ignoreCase = true).decapitalize(Locale.ROOT))
.autoFix()
.build()
context.report(ISSUE_WRONG_TEST_METHOD_NAME, node, context.getNameLocation(node), "Test method starts with test", fix)
}
}
}
}
| apache-2.0 | 34872b0468f9ba8286f5ab1408e17fde | 43.27451 | 132 | 0.735164 | 4.010657 | false | true | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt | 1 | 2957 | package info.nightscout.androidaps.plugins.general.automation
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.general.automation.actions.Action
import info.nightscout.androidaps.plugins.general.automation.actions.ActionDummy
import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerDummy
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import org.json.JSONArray
import org.json.JSONObject
import java.util.*
import javax.inject.Inject
class AutomationEvent(private val injector: HasAndroidInjector) {
@Inject lateinit var aapsLogger: AAPSLogger
var title: String? = null
var isEnabled = true
var systemAction: Boolean = false // true = generated by AAPS, false = entered by user
var readOnly: Boolean = false // removing, editing disabled
var autoRemove: Boolean = false // auto-remove once used
var trigger: Trigger = TriggerConnector(injector)
val actions: MutableList<Action> = ArrayList()
var lastRun: Long = 0
init {
injector.androidInjector().inject(this)
}
fun getPreconditions(): TriggerConnector {
val trigger = TriggerConnector(injector, TriggerConnector.Type.AND)
for (action in actions) {
action.precondition?.let { trigger.list.add(it) }
}
return trigger
}
fun addAction(action: Action) = actions.add(action)
fun toJSON(): String {
val array = JSONArray()
for (a in actions) array.put(a.toJSON())
return JSONObject()
.put("title", title)
.put("enabled", isEnabled)
.put("systemAction", systemAction)
.put("readOnly", readOnly)
.put("autoRemove", autoRemove)
.put("trigger", trigger.toJSON())
.put("actions", array)
.toString()
}
fun fromJSON(data: String?): AutomationEvent {
val d = JSONObject(data)
title = d.optString("title", "")
isEnabled = d.optBoolean("enabled", true)
systemAction = d.optBoolean("systemAction", false)
readOnly = d.optBoolean("readOnly", false)
autoRemove = d.optBoolean("autoRemove", false)
trigger = TriggerDummy(injector).instantiate(JSONObject(d.getString("trigger")))
?: TriggerConnector(injector)
val array = d.getJSONArray("actions")
actions.clear()
for (i in 0 until array.length()) {
ActionDummy(injector).instantiate(JSONObject(array.getString(i)))?.let {
actions.add(it)
}
}
return this
}
fun shouldRun(): Boolean {
return lastRun <= DateUtil.now() - T.mins(5).msecs()
}
} | agpl-3.0 | 7f3ca908d8c1c1ab099d79bb940610c2 | 35.073171 | 90 | 0.673318 | 4.500761 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/entity/Entity.kt | 4 | 619 | // 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.tools.projectWizard.core.entity
import org.jetbrains.kotlin.tools.projectWizard.core.safeAs
interface Entity {
val path: String
}
abstract class EntityBase: Entity {
final override fun equals(other: Any?): Boolean = other.safeAs<Entity>()?.path == path
final override fun hashCode(): Int = path.hashCode()
final override fun toString(): String = path
}
abstract class EntityWithValue<out T : Any> : EntityBase()
| apache-2.0 | b0f7a4a6138fe13b21473e6f5dec501d | 40.266667 | 158 | 0.751212 | 4.182432 | false | false | false | false |
3sidedcube/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/viewcontrollers/stack/topbar/button/ButtonSpan.kt | 1 | 1440 | package com.reactnativenavigation.viewcontrollers.stack.topbar.button
import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.text.TextPaint
import android.text.style.MetricAffectingSpan
import com.reactnativenavigation.options.ButtonOptions
import com.reactnativenavigation.options.parsers.TypefaceLoader
import com.reactnativenavigation.utils.UiUtils
class ButtonSpan(
private val context: Context,
private val button: ButtonOptions,
private val typefaceLoader: TypefaceLoader = TypefaceLoader(context)
) : MetricAffectingSpan() {
val fontSize: Float?
get() {
return if (button.fontSize.hasValue()) UiUtils.dpToPx(context, button.fontSize.get().toFloat()) else null
}
override fun updateDrawState(drawState: TextPaint) = apply(drawState)
override fun updateMeasureState(paint: TextPaint) = apply(paint)
fun apply(paint: Paint) {
with(button.font) {
val typeface = getTypeface(typefaceLoader, Typeface.DEFAULT)
val fakeStyle = (paint.typeface?.style ?: 0) and (typeface?.style?.inv() ?: 1)
if (fakeStyle and Typeface.BOLD != 0) paint.isFakeBoldText = true
if (fakeStyle and Typeface.ITALIC != 0) paint.textSkewX = -0.25f
fontSize?.let { paint.textSize = it }
paint.typeface = typeface
}
}
}
| mit | 2ace0006eaf6beba9be1c336e20f3ff5 | 37.918919 | 117 | 0.711111 | 4.430769 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/JavaToJKTreeBuilder.kt | 1 | 50451 | // 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.nj2k
import com.intellij.codeInsight.AnnotationTargetUtil
import com.intellij.codeInsight.daemon.impl.quickfix.AddTypeArgumentsFix
import com.intellij.lang.jvm.JvmModifier
import com.intellij.psi.*
import com.intellij.psi.JavaTokenType.SUPER_KEYWORD
import com.intellij.psi.JavaTokenType.THIS_KEYWORD
import com.intellij.psi.impl.source.tree.ChildRole
import com.intellij.psi.impl.source.tree.CompositeElement
import com.intellij.psi.impl.source.tree.java.PsiClassObjectAccessExpressionImpl
import com.intellij.psi.impl.source.tree.java.PsiLabeledStatementImpl
import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl
import com.intellij.psi.impl.source.tree.java.PsiNewExpressionImpl
import com.intellij.psi.infos.MethodCandidateInfo
import com.intellij.psi.javadoc.PsiDocComment
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.elements.KtLightField
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.idea.caches.lightClasses.KtLightClassForDecompiledDeclaration
import org.jetbrains.kotlin.idea.j2k.content
import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName
import org.jetbrains.kotlin.j2k.ReferenceSearcher
import org.jetbrains.kotlin.j2k.ast.Nullability
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.nj2k.symbols.*
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.tree.JKLiteralExpression.LiteralType.*
import org.jetbrains.kotlin.nj2k.types.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration
import org.jetbrains.kotlin.resolve.QualifiedExpressionResolver
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class JavaToJKTreeBuilder constructor(
private val symbolProvider: JKSymbolProvider,
private val typeFactory: JKTypeFactory,
converterServices: NewJavaToKotlinServices,
private val importStorage: JKImportStorage,
private val bodyFilter: ((PsiElement) -> Boolean)?,
) {
private fun todoExpression(): JKExpression = JKCallExpressionImpl(
symbolProvider.provideMethodSymbol("kotlin.TODO"),
JKArgumentList(
JKArgumentImpl(
JKLiteralExpression(
"\"${QualifiedExpressionResolver.ROOT_PREFIX_FOR_IDE_RESOLUTION_MODE}\"",
STRING,
)
)
),
)
private fun PsiType?.toJK(): JKType {
if (this == null) return JKNoType
return typeFactory.fromPsiType(this)
}
private val expressionTreeMapper = ExpressionTreeMapper()
private val referenceSearcher: ReferenceSearcher = converterServices.oldServices.referenceSearcher
private val declarationMapper = DeclarationMapper(expressionTreeMapper, bodyFilter == null)
private val formattingCollector = FormattingCollector()
// we don't want to capture comments of previous declaration/statement
private fun PsiElement.takeLeadingCommentsNeeded() =
this !is PsiMember && this !is PsiStatement
private fun <T : JKFormattingOwner> T.withFormattingFrom(
psi: PsiElement?,
assignLineBreaks: Boolean = false,
takeTrailingComments: Boolean = true,
takeLeadingComments: Boolean = psi?.takeLeadingCommentsNeeded() ?: false
): T = with(formattingCollector) {
takeFormattingFrom(this@withFormattingFrom, psi, assignLineBreaks, takeTrailingComments, takeLeadingComments)
this@withFormattingFrom
}
private fun <O : JKFormattingOwner> O.withLineBreaksFrom(psi: PsiElement?) = with(formattingCollector) {
takeLineBreaksFrom(this@withLineBreaksFrom, psi)
this@withLineBreaksFrom
}
private fun <O : JKFormattingOwner> O.withLeadingCommentsWithParent(psi: PsiElement?) = with(formattingCollector) {
if (psi == null) return@with this@withLeadingCommentsWithParent
[email protected] += psi.leadingCommentsWithParent()
return this@withLeadingCommentsWithParent
}
private fun PsiJavaFile.toJK(): JKFile =
JKFile(
packageStatement?.toJK() ?: JKPackageDeclaration(JKNameIdentifier("")),
importList.toJK(saveImports = false),
with(declarationMapper) { classes.map { it.toJK() } }
)
private fun PsiImportList?.toJK(saveImports: Boolean): JKImportList =
JKImportList(this?.allImportStatements?.mapNotNull { it.toJK(saveImports) }.orEmpty()).also { importList ->
val innerComments = this?.collectDescendantsOfType<PsiComment>()?.map { comment ->
JKComment(comment.text)
}.orEmpty()
importList.trailingComments += innerComments
}
private fun PsiPackageStatement.toJK(): JKPackageDeclaration =
JKPackageDeclaration(JKNameIdentifier(packageName))
.also {
it.withFormattingFrom(this)
symbolProvider.provideUniverseSymbol(this, it)
}
private fun PsiImportStatementBase.toJK(saveImports: Boolean): JKImportStatement? {
val target = when (this) {
is PsiImportStaticStatement -> resolveTargetClass()
else -> resolve()
}
val rawName = (importReference?.canonicalText ?: return null) + if (isOnDemand) ".*" else ""
// We will save only unresolved imports and print all static calls with fqNames
// to avoid name clashes in future
if (!saveImports) {
return if (target == null)
JKImportStatement(JKNameIdentifier(rawName))
else null
}
fun KtLightClassForDecompiledDeclaration.fqName(): FqName =
kotlinOrigin?.fqName ?: FqName(qualifiedName.orEmpty())
val name =
target.safeAs<KtLightElement<*, *>>()?.kotlinOrigin?.getKotlinFqName()?.asString()
?: target.safeAs<KtLightClass>()?.containingFile?.safeAs<KtFile>()?.packageFqName?.asString()?.let { "$it.*" }
?: target.safeAs<KtLightClassForFacade>()?.fqName?.parent()?.asString()?.let { "$it.*" }
?: target.safeAs<KtLightClassForDecompiledDeclaration>()?.fqName()?.parent()?.asString()?.let { "$it.*" }
?: rawName
return JKImportStatement(JKNameIdentifier(name)).also {
it.withFormattingFrom(this)
}
}
private fun PsiIdentifier?.toJK(): JKNameIdentifier = this?.let {
JKNameIdentifier(it.text).also { identifier ->
identifier.withFormattingFrom(this)
}
} ?: JKNameIdentifier("")
private inner class ExpressionTreeMapper {
fun PsiExpression?.toJK(): JKExpression = when (this) {
null -> JKStubExpression()
is PsiBinaryExpression -> toJK()
is PsiPrefixExpression -> toJK()
is PsiPostfixExpression -> toJK()
is PsiLiteralExpression -> toJK()
is PsiMethodCallExpression -> toJK()
is PsiReferenceExpression -> toJK()
is PsiNewExpression -> toJK()
is PsiArrayAccessExpression -> toJK()
is PsiTypeCastExpression -> toJK()
is PsiParenthesizedExpression -> toJK()
is PsiAssignmentExpression -> toJK()
is PsiInstanceOfExpression -> toJK()
is PsiThisExpression ->
JKThisExpression(
qualifier?.referenceName?.let { JKLabelText(JKNameIdentifier(it)) } ?: JKLabelEmpty(),
type.toJK()
)
is PsiSuperExpression ->
JKSuperExpression(
qualifier?.referenceName?.let { JKLabelText(JKNameIdentifier(it)) } ?: JKLabelEmpty(),
type.toJK()
)
is PsiConditionalExpression -> JKIfElseExpression(
condition.toJK(),
thenExpression.toJK(),
elseExpression.toJK(),
type.toJK()
)
is PsiPolyadicExpression -> {
val token = JKOperatorToken.fromElementType(operationTokenType)
val type = type?.toJK() ?: typeFactory.types.nullableAny
val jkOperands = operands.map { it.toJK().withLineBreaksFrom(it).parenthesizeIfBinaryExpression() }
jkOperands.reduce { acc, operand ->
JKBinaryExpression(acc, operand, JKKtOperatorImpl(token, type))
}.let { folded ->
if (jkOperands.any { it.containsNewLine() }) folded.parenthesize()
else folded
}
}
is PsiArrayInitializerExpression -> toJK()
is PsiLambdaExpression -> toJK()
is PsiClassObjectAccessExpressionImpl -> toJK()
else -> throwCanNotConvertError()
}.also {
if (this != null) {
(it as PsiOwner).psi = this
it.withFormattingFrom(this)
}
}
fun PsiClassObjectAccessExpressionImpl.toJK(): JKClassLiteralExpression {
val type = operand.type.toJK().updateNullabilityRecursively(Nullability.NotNull)
return JKClassLiteralExpression(
JKTypeElement(type),
when (type) {
is JKJavaPrimitiveType -> JKClassLiteralExpression.ClassLiteralType.JAVA_PRIMITIVE_CLASS
is JKJavaVoidType -> JKClassLiteralExpression.ClassLiteralType.JAVA_VOID_TYPE
else -> JKClassLiteralExpression.ClassLiteralType.JAVA_CLASS
}
).also {
it.withFormattingFrom(this)
}
}
fun PsiInstanceOfExpression.toJK(): JKIsExpression =
JKIsExpression(operand.toJK(), JKTypeElement(checkType?.type?.toJK() ?: JKNoType))
.also {
it.withFormattingFrom(this)
}
fun PsiAssignmentExpression.toJK(): JKJavaAssignmentExpression {
return JKJavaAssignmentExpression(
lExpression.toJK(),
rExpression.toJK(),
createOperator(operationSign.tokenType, type)
).also {
it.withFormattingFrom(this)
}
}
fun PsiBinaryExpression.toJK(): JKExpression {
val token = when (operationSign.tokenType) {
JavaTokenType.EQEQ, JavaTokenType.NE ->
when {
canKeepEqEq(lOperand, rOperand) -> JKOperatorToken.fromElementType(operationSign.tokenType)
operationSign.tokenType == JavaTokenType.EQEQ -> JKOperatorToken.fromElementType(KtTokens.EQEQEQ)
else -> JKOperatorToken.fromElementType(KtTokens.EXCLEQEQEQ)
}
else -> JKOperatorToken.fromElementType(operationSign.tokenType)
}
return JKBinaryExpression(
lOperand.toJK().withLineBreaksFrom(lOperand),
rOperand.toJK().withLineBreaksFrom(rOperand),
JKKtOperatorImpl(
token,
type?.toJK() ?: typeFactory.types.nullableAny
)
).also {
it.withFormattingFrom(this)
}
}
fun PsiLiteralExpression.toJK(): JKLiteralExpression {
require(this is PsiLiteralExpressionImpl)
return when (literalElementType) {
JavaTokenType.NULL_KEYWORD -> JKLiteralExpression("null", NULL)
JavaTokenType.TRUE_KEYWORD -> JKLiteralExpression("true", BOOLEAN)
JavaTokenType.FALSE_KEYWORD -> JKLiteralExpression("false", BOOLEAN)
JavaTokenType.STRING_LITERAL -> JKLiteralExpression(text, STRING)
JavaTokenType.CHARACTER_LITERAL -> JKLiteralExpression(text, CHAR)
JavaTokenType.INTEGER_LITERAL -> JKLiteralExpression(text, INT)
JavaTokenType.LONG_LITERAL -> JKLiteralExpression(text, LONG)
JavaTokenType.FLOAT_LITERAL -> JKLiteralExpression(text, FLOAT)
JavaTokenType.DOUBLE_LITERAL -> JKLiteralExpression(text, DOUBLE)
else -> throwCanNotConvertError("Unknown literal element type: $literalElementType")
}.also {
it.withFormattingFrom(this)
}
}
private fun createOperator(elementType: IElementType, type: PsiType?) =
JKKtOperatorImpl(
JKOperatorToken.fromElementType(elementType),
type?.toJK() ?: typeFactory.types.nullableAny
)
fun PsiPrefixExpression.toJK(): JKExpression = when (operationSign.tokenType) {
JavaTokenType.TILDE -> operand.toJK().callOn(symbolProvider.provideMethodSymbol("kotlin.Int.inv"))
else -> JKPrefixExpression(operand.toJK(), createOperator(operationSign.tokenType, type))
}.also {
it.withFormattingFrom(this)
}
fun PsiPostfixExpression.toJK(): JKExpression =
JKPostfixExpression(operand.toJK(), createOperator(operationSign.tokenType, type)).also {
it.withFormattingFrom(this)
}
fun PsiLambdaExpression.toJK(): JKExpression {
return JKLambdaExpression(
body.let {
when (it) {
is PsiExpression -> JKExpressionStatement(it.toJK())
is PsiCodeBlock -> JKBlockStatement(with(declarationMapper) { it.toJK() })
else -> JKBlockStatement(JKBodyStub)
}
},
with(declarationMapper) { parameterList.parameters.map { it.toJK() } },
functionalType()
).also {
it.withFormattingFrom(this)
}
}
private fun PsiMethodCallExpression.getExplicitTypeArguments(): PsiReferenceParameterList {
if (typeArguments.isNotEmpty()) return typeArgumentList
val resolveResult = resolveMethodGenerics()
if (resolveResult is MethodCandidateInfo && resolveResult.isApplicable) {
val method = resolveResult.element
if (method.isConstructor || !method.hasTypeParameters()) return typeArgumentList
}
return AddTypeArgumentsFix.addTypeArguments(this, null, false)
?.safeAs<PsiMethodCallExpression>()
?.typeArgumentList
?: typeArgumentList
}
//TODO mostly copied from old j2k, refactor
fun PsiMethodCallExpression.toJK(): JKExpression {
val arguments = argumentList
val typeArguments = getExplicitTypeArguments().toJK()
val qualifier = methodExpression.qualifierExpression?.toJK()?.withLineBreaksFrom(methodExpression.qualifierExpression)
val target = methodExpression.resolve()
val symbol = target?.let {
symbolProvider.provideDirectSymbol(it)
} ?: JKUnresolvedMethod(methodExpression, typeFactory)
return when {
methodExpression.referenceNameElement is PsiKeyword -> {
val callee = when ((methodExpression.referenceNameElement as PsiKeyword).tokenType) {
SUPER_KEYWORD -> JKSuperExpression(JKLabelEmpty(), JKNoType)
THIS_KEYWORD -> JKThisExpression(JKLabelEmpty(), JKNoType)
else -> throwCanNotConvertError("unknown keyword in callee position")
}
val calleeSymbol = when {
symbol is JKMethodSymbol -> symbol
target is KtLightMethod -> KtClassImplicitConstructorSymbol(target, typeFactory)
else -> throwCanNotConvertError("Expected constructor call, found ${target?.javaClass?.name}")
}
JKDelegationConstructorCall(calleeSymbol, callee, arguments.toJK())
}
target is KtLightMethod -> {
when (val origin = target.kotlinOrigin) {
is KtNamedFunction -> {
if (origin.isExtensionDeclaration()) {
val receiver = arguments.expressions.firstOrNull()?.toJK()?.parenthesizeIfBinaryExpression()
origin.fqName?.also { importStorage.addImport(it) }
JKCallExpressionImpl(
symbolProvider.provideDirectSymbol(origin) as JKMethodSymbol,
arguments.expressions.drop(1).map { it.toJK() }.toArgumentList(),
typeArguments
).qualified(receiver)
} else {
origin.fqName?.also { importStorage.addImport(it) }
JKCallExpressionImpl(
symbolProvider.provideDirectSymbol(origin) as JKMethodSymbol,
arguments.toJK(),
typeArguments
).qualified(qualifier)
}
}
is KtProperty, is KtPropertyAccessor, is KtParameter -> {
origin.getKotlinFqName()?.also { importStorage.addImport(it) }
val property =
if (origin is KtPropertyAccessor) origin.parent as KtProperty
else origin as KtNamedDeclaration
val parameterCount = target.parameterList.parameters.size
val propertyAccessExpression =
JKFieldAccessExpression(symbolProvider.provideDirectSymbol(property) as JKFieldSymbol)
val isExtension = property.isExtensionDeclaration()
val isTopLevel = origin.getStrictParentOfType<KtClassOrObject>() == null
val propertyAccess = if (isTopLevel) {
if (isExtension) JKQualifiedExpression(
arguments.expressions.first().toJK(),
propertyAccessExpression
)
else propertyAccessExpression
} else propertyAccessExpression.qualified(qualifier)
when (if (isExtension) parameterCount - 1 else parameterCount) {
0 /* getter */ ->
propertyAccess
1 /* setter */ -> {
val argument = (arguments.expressions[if (isExtension) 1 else 0]).toJK()
JKJavaAssignmentExpression(
propertyAccess,
argument,
createOperator(JavaTokenType.EQ, type) //TODO correct type
)
}
else -> throwCanNotConvertError("expected getter or setter call")
}
}
else -> {
JKCallExpressionImpl(
JKMultiverseMethodSymbol(target, typeFactory),
arguments.toJK(),
typeArguments
).qualified(qualifier)
}
}
}
symbol is JKMethodSymbol ->
JKCallExpressionImpl(symbol, arguments.toJK(), typeArguments)
.qualified(qualifier)
symbol is JKFieldSymbol ->
JKFieldAccessExpression(symbol).qualified(qualifier)
else -> throwCanNotConvertError("unexpected symbol ${symbol::class}")
}.also {
it.withFormattingFrom(this)
}
}
fun PsiFunctionalExpression.functionalType(): JKTypeElement =
functionalInterfaceType
?.takeUnless { type ->
type.safeAs<PsiClassType>()?.parameters?.any { it is PsiCapturedWildcardType } == true
}?.takeUnless { type ->
type.isKotlinFunctionalType
}?.toJK()
?.asTypeElement() ?: JKTypeElement(JKNoType)
fun PsiMethodReferenceExpression.toJK(): JKMethodReferenceExpression {
val symbol = symbolProvider.provideSymbolForReference<JKSymbol>(this).let { symbol ->
when {
symbol.isUnresolved && isConstructor -> JKUnresolvedClassSymbol(qualifier?.text ?: text, typeFactory)
symbol.isUnresolved && !isConstructor -> JKUnresolvedMethod(referenceName ?: text, typeFactory)
else -> symbol
}
}
return JKMethodReferenceExpression(
methodReferenceQualifier(),
symbol,
functionalType(),
isConstructor
)
}
fun PsiMethodReferenceExpression.methodReferenceQualifier(): JKExpression {
val qualifierType = qualifierType
if (qualifierType != null) return JKTypeQualifierExpression(typeFactory.fromPsiType(qualifierType.type))
return qualifierExpression?.toJK() ?: JKStubExpression()
}
fun PsiReferenceExpression.toJK(): JKExpression {
if (this is PsiMethodReferenceExpression) return toJK()
val target = resolve()
if (target is KtLightClassForFacade
|| target is KtLightClassForDecompiledDeclaration
) return JKStubExpression()
if (target is KtLightField
&& target.name == "INSTANCE"
&& target.containingClass.kotlinOrigin is KtObjectDeclaration
) {
return qualifierExpression?.toJK() ?: JKStubExpression()
}
val symbol = symbolProvider.provideSymbolForReference<JKSymbol>(this)
return when (symbol) {
is JKClassSymbol -> JKClassAccessExpression(symbol)
is JKFieldSymbol -> JKFieldAccessExpression(symbol)
is JKPackageSymbol -> JKPackageAccessExpression(symbol)
is JKMethodSymbol -> JKMethodAccessExpression(symbol)
is JKTypeParameterSymbol -> JKTypeQualifierExpression(JKTypeParameterType(symbol))
else -> throwCanNotConvertError("unexpected symbol ${symbol::class}")
}.qualified(qualifierExpression?.toJK()).also {
it.withFormattingFrom(this)
}
}
fun PsiArrayInitializerExpression.toJK(): JKExpression {
return JKJavaNewArray(
initializers.map { it.toJK().withLineBreaksFrom(it) },
JKTypeElement(type?.toJK().safeAs<JKJavaArrayType>()?.type ?: JKContextType)
).also {
it.withFormattingFrom(this)
}
}
fun PsiNewExpression.toJK(): JKExpression {
require(this is PsiNewExpressionImpl)
val newExpression =
if (findChildByRole(ChildRole.LBRACKET) != null) {
arrayInitializer?.toJK() ?: run {
val dimensions = mutableListOf<JKExpression>()
var child = firstChild
while (child != null) {
if (child.node.elementType == JavaTokenType.LBRACKET) {
child = child.getNextSiblingIgnoringWhitespaceAndComments()
if (child.node.elementType == JavaTokenType.RBRACKET) {
dimensions += JKStubExpression()
} else {
child.safeAs<PsiExpression>()?.toJK()?.also { dimensions += it }
}
}
child = child.nextSibling
}
JKJavaNewEmptyArray(
dimensions,
JKTypeElement(generateSequence(type?.toJK()) { it.safeAs<JKJavaArrayType>()?.type }.last())
).also {
it.psi = this
}
}
} else {
val classSymbol =
classOrAnonymousClassReference?.resolve()?.let {
symbolProvider.provideDirectSymbol(it) as JKClassSymbol
} ?: JKUnresolvedClassSymbol(
classOrAnonymousClassReference?.referenceName ?: throwCanNotConvertError(),
typeFactory
)
val typeArgumentList =
this.typeArgumentList.toJK()
.takeIf { it.typeArguments.isNotEmpty() }
?: classOrAnonymousClassReference
?.typeParameters
?.let { typeParameters ->
JKTypeArgumentList(typeParameters.map { JKTypeElement(it.toJK()) })
} ?: JKTypeArgumentList()
JKNewExpression(
classSymbol,
argumentList?.toJK() ?: JKArgumentList(),
typeArgumentList,
with(declarationMapper) { anonymousClass?.createClassBody() } ?: JKClassBody(),
anonymousClass != null
)
}
return newExpression.qualified(qualifier?.toJK())
}
fun PsiReferenceParameterList.toJK(): JKTypeArgumentList =
JKTypeArgumentList(typeArguments.map { JKTypeElement(it.toJK()) })
.also {
it.withFormattingFrom(this)
}
fun PsiArrayAccessExpression.toJK(): JKExpression =
arrayExpression.toJK()
.callOn(
symbolProvider.provideMethodSymbol("kotlin.Array.get"),
arguments = listOf(indexExpression?.toJK() ?: JKStubExpression())
).also {
it.withFormattingFrom(this)
}
fun PsiTypeCastExpression.toJK(): JKExpression {
return JKTypeCastExpression(
operand?.toJK() ?: throwCanNotConvertError(),
(castType?.type?.toJK() ?: JKNoType).asTypeElement()
).also {
it.withFormattingFrom(this)
}
}
fun PsiParenthesizedExpression.toJK(): JKExpression {
return JKParenthesizedExpression(expression.toJK())
.also {
it.withFormattingFrom(this)
}
}
fun PsiExpressionList.toJK(): JKArgumentList {
val jkExpressions = expressions.map { it.toJK().withLineBreaksFrom(it) }
return ((parent as? PsiCall)?.resolveMethod()
?.let { method ->
val lastExpressionType = expressions.lastOrNull()?.type
if (jkExpressions.size == method.parameterList.parameters.size
&& method.parameterList.parameters.getOrNull(jkExpressions.lastIndex)?.isVarArgs == true
&& lastExpressionType is PsiArrayType
) {
val staredExpression =
JKPrefixExpression(
jkExpressions.last(),
JKKtSpreadOperator(lastExpressionType.toJK())
).withFormattingFrom(jkExpressions.last())
staredExpression.expression.also {
it.hasLeadingLineBreak = false
it.hasTrailingLineBreak = false
}
jkExpressions.dropLast(1) + staredExpression
} else jkExpressions
} ?: jkExpressions)
.toArgumentList()
.also {
it.withFormattingFrom(this)
}
}
}
private inner class DeclarationMapper(val expressionTreeMapper: ExpressionTreeMapper, var withBody: Boolean) {
fun <R> withBodyGeneration(
elementToCheck: PsiElement,
trueBranch: DeclarationMapper.() -> R,
elseBranch: DeclarationMapper.() -> R = trueBranch
): R = when {
withBody -> trueBranch()
bodyFilter?.invoke(elementToCheck) == true -> {
withBody = true
trueBranch().also { withBody = false }
}
else -> elseBranch()
}
fun PsiTypeParameterList.toJK(): JKTypeParameterList =
JKTypeParameterList(typeParameters.map { it.toJK() })
.also {
it.withFormattingFrom(this)
}
fun PsiTypeParameter.toJK(): JKTypeParameter =
JKTypeParameter(
nameIdentifier.toJK(),
extendsListTypes.map { JKTypeElement(it.toJK()) }
).also {
symbolProvider.provideUniverseSymbol(this, it)
it.withFormattingFrom(this)
}
fun PsiClass.toJK(): JKClass =
JKClass(
nameIdentifier.toJK(),
inheritanceInfo(),
classKind(),
typeParameterList?.toJK() ?: JKTypeParameterList(),
createClassBody(),
annotationList(this),
otherModifiers(),
visibility(),
modality()
).also { klass ->
klass.psi = this
symbolProvider.provideUniverseSymbol(this, klass)
klass.withFormattingFrom(this)
}
fun PsiClass.inheritanceInfo(): JKInheritanceInfo {
val implTypes = implementsList?.referencedTypes?.map { JKTypeElement(it.toJK()) }.orEmpty()
val extensionType = extendsList?.referencedTypes?.map { JKTypeElement(it.toJK()) }.orEmpty()
return JKInheritanceInfo(extensionType, implTypes)
.also {
if (implementsList != null) {
it.withFormattingFrom(implementsList!!)
}
}
}
fun PsiClass.createClassBody() =
JKClassBody(
children.mapNotNull {
when (it) {
is PsiEnumConstant -> it.toJK()
is PsiClass -> it.toJK()
is PsiAnnotationMethod -> it.toJK()
is PsiMethod -> it.toJK()
is PsiField -> it.toJK()
is PsiClassInitializer -> it.toJK()
else -> null
}
}
).also {
it.leftBrace.withFormattingFrom(
lBrace,
takeLeadingComments = false
) // do not capture comments which belongs to following declarations
it.rightBrace.withFormattingFrom(rBrace)
it.declarations.lastOrNull()?.let { lastMember ->
lastMember.withLeadingCommentsWithParent(lastMember.psi)
}
}
fun PsiClassInitializer.toJK(): JKDeclaration = when {
hasModifier(JvmModifier.STATIC) -> JKJavaStaticInitDeclaration(body.toJK())
else -> JKKtInitDeclaration(body.toJK())
}.also {
it.withFormattingFrom(this)
}
fun PsiEnumConstant.toJK(): JKEnumConstant =
JKEnumConstant(
nameIdentifier.toJK(),
with(expressionTreeMapper) { argumentList?.toJK() ?: JKArgumentList() },
initializingClass?.createClassBody() ?: JKClassBody(),
JKTypeElement(
containingClass?.let { klass ->
JKClassType(
symbolProvider.provideDirectSymbol(klass) as JKClassSymbol,
emptyList()
)
} ?: JKNoType
)
).also {
symbolProvider.provideUniverseSymbol(this, it)
it.psi = this
it.withFormattingFrom(this)
}
fun PsiMember.modality() =
modality { ast, psi -> ast.withFormattingFrom(psi) }
fun PsiMember.otherModifiers() =
modifierList?.children?.mapNotNull { child ->
if (child !is PsiKeyword) return@mapNotNull null
when (child.text) {
PsiModifier.NATIVE -> OtherModifier.NATIVE
PsiModifier.STATIC -> OtherModifier.STATIC
PsiModifier.STRICTFP -> OtherModifier.STRICTFP
PsiModifier.SYNCHRONIZED -> OtherModifier.SYNCHRONIZED
PsiModifier.TRANSIENT -> OtherModifier.TRANSIENT
PsiModifier.VOLATILE -> OtherModifier.VOLATILE
else -> null
}?.let {
JKOtherModifierElement(it).withFormattingFrom(child)
}
}.orEmpty()
private fun PsiMember.visibility(): JKVisibilityModifierElement =
visibility(referenceSearcher) { ast, psi -> ast.withFormattingFrom(psi) }
fun PsiField.toJK(): JKField = JKField(
JKTypeElement(type.toJK(), typeElement.annotationList()).withFormattingFrom(typeElement),
nameIdentifier.toJK(),
with(expressionTreeMapper) {
withBodyGeneration(
this@toJK,
trueBranch = { initializer.toJK() },
elseBranch = { todoExpression() }
)
},
annotationList(this),
otherModifiers(),
visibility(),
modality(),
JKMutabilityModifierElement(Mutability.UNKNOWN)
).also {
symbolProvider.provideUniverseSymbol(this, it)
it.psi = this
it.withFormattingFrom(this)
}
fun <T : PsiModifierListOwner> T.annotationList(docCommentOwner: PsiDocCommentOwner?): JKAnnotationList {
val deprecatedAnnotation = docCommentOwner?.docComment?.deprecatedAnnotation()
val plainAnnotations = annotations.mapNotNull { annotation ->
when {
annotation !is PsiAnnotation -> null
annotation.qualifiedName == DEPRECATED_ANNOTATION_FQ_NAME && deprecatedAnnotation != null -> null
AnnotationTargetUtil.isTypeAnnotation(annotation) -> null
else -> annotation.toJK()
}
}
return JKAnnotationList(plainAnnotations + listOfNotNull(deprecatedAnnotation))
}
fun PsiTypeElement?.annotationList(): JKAnnotationList {
return JKAnnotationList(this?.applicableAnnotations?.map { it.toJK() }.orEmpty())
}
fun PsiAnnotation.toJK(): JKAnnotation = JKAnnotation(
symbolProvider.provideSymbolForReference<JKSymbol>(
nameReferenceElement ?: throwCanNotConvertError()
).safeAs() ?: JKUnresolvedClassSymbol(nameReferenceElement?.text ?: throwCanNotConvertError(), typeFactory),
parameterList.attributes.map { parameter ->
if (parameter.nameIdentifier != null) {
JKAnnotationNameParameter(
parameter.value?.toJK() ?: JKStubExpression(),
JKNameIdentifier(parameter.name ?: throwCanNotConvertError())
)
} else {
JKAnnotationParameterImpl(
parameter.value?.toJK() ?: JKStubExpression()
)
}
}
).also {
it.withFormattingFrom(this)
}
fun PsiDocComment.deprecatedAnnotation(): JKAnnotation? =
findTagByName("deprecated")?.let { tag ->
JKAnnotation(
symbolProvider.provideClassSymbol("kotlin.Deprecated"),
listOf(
JKAnnotationParameterImpl(stringLiteral(tag.content(), typeFactory))
)
)
}
private fun PsiAnnotationMemberValue.toJK(): JKAnnotationMemberValue =
when (this) {
is PsiExpression -> with(expressionTreeMapper) { toJK() }
is PsiAnnotation -> toJK()
is PsiArrayInitializerMemberValue ->
JKKtAnnotationArrayInitializerExpression(initializers.map { it.toJK() })
else -> throwCanNotConvertError()
}.also {
it.withFormattingFrom(this)
}
fun PsiAnnotationMethod.toJK(): JKJavaAnnotationMethod =
JKJavaAnnotationMethod(
JKTypeElement(
returnType?.toJK()
?: JKJavaVoidType.takeIf { isConstructor }
?: JKNoType),
nameIdentifier.toJK(),
defaultValue?.toJK() ?: JKStubExpression(),
otherModifiers(),
visibility(),
modality()
).also {
it.psi = this
symbolProvider.provideUniverseSymbol(this, it)
it.withFormattingFrom(this)
}
fun PsiMethod.toJK(): JKMethod {
return JKMethodImpl(
JKTypeElement(
returnType?.toJK()
?: JKJavaVoidType.takeIf { isConstructor }
?: JKNoType,
returnTypeElement.annotationList()),
nameIdentifier.toJK(),
parameterList.parameters.map { it.toJK().withLineBreaksFrom(it) },
withBodyGeneration(this, trueBranch = { body?.toJK() ?: JKBodyStub }),
typeParameterList?.toJK() ?: JKTypeParameterList(),
annotationList(this),
throwsList.referencedTypes.map { JKTypeElement(it.toJK()) },
otherModifiers(),
visibility(),
modality()
).also { jkMethod ->
jkMethod.psi = this
symbolProvider.provideUniverseSymbol(this, jkMethod)
parameterList.node
?.safeAs<CompositeElement>()
?.also {
jkMethod.leftParen.withFormattingFrom(it.findChildByRoleAsPsiElement(ChildRole.LPARENTH))
jkMethod.rightParen.withFormattingFrom(it.findChildByRoleAsPsiElement(ChildRole.RPARENTH))
}
}.withFormattingFrom(this)
}
fun PsiParameter.toJK(): JKParameter {
val rawType = type.toJK()
val type =
if (isVarArgs && rawType is JKJavaArrayType) JKTypeElement(rawType.type, typeElement.annotationList())
else rawType.asTypeElement(typeElement.annotationList())
return JKParameter(
type,
nameIdentifier.toJK(),
isVarArgs,
annotationList = annotationList(null)
).also {
symbolProvider.provideUniverseSymbol(this, it)
it.psi = this
it.withFormattingFrom(this)
}
}
fun PsiCodeBlock.toJK(): JKBlock = JKBlockImpl(
if (withBody) statements.map { it.toJK() } else listOf(todoExpression().asStatement())
).withFormattingFrom(this).also {
it.leftBrace.withFormattingFrom(lBrace)
it.rightBrace.withFormattingFrom(rBrace)
}
fun PsiLocalVariable.toJK(): JKLocalVariable {
return JKLocalVariable(
JKTypeElement(type.toJK(), typeElement.annotationList()).withFormattingFrom(typeElement),
nameIdentifier.toJK(),
with(expressionTreeMapper) { initializer.toJK() },
JKMutabilityModifierElement(
if (hasModifierProperty(PsiModifier.FINAL)) Mutability.IMMUTABLE
else Mutability.UNKNOWN
),
annotationList(null)
).also { i ->
symbolProvider.provideUniverseSymbol(this, i)
i.psi = this
}.also {
it.withFormattingFrom(this)
}
}
fun PsiStatement?.asJKStatementsList() = when (this) {
null -> emptyList()
is PsiExpressionListStatement -> expressionList.expressions.map { expression ->
JKExpressionStatement(with(expressionTreeMapper) { expression.toJK() })
}
else -> listOf(toJK())
}
fun PsiStatement?.toJK(): JKStatement {
return when (this) {
null -> JKExpressionStatement(JKStubExpression())
is PsiExpressionStatement -> JKExpressionStatement(with(expressionTreeMapper) { expression.toJK() })
is PsiReturnStatement -> JKReturnStatement(with(expressionTreeMapper) { returnValue.toJK() })
is PsiDeclarationStatement ->
JKDeclarationStatement(declaredElements.mapNotNull {
when (it) {
is PsiClass -> it.toJK()
is PsiLocalVariable -> it.toJK()
else -> null
}
})
is PsiAssertStatement ->
JKJavaAssertStatement(
with(expressionTreeMapper) { assertCondition.toJK() },
with(expressionTreeMapper) { assertDescription?.toJK() } ?: JKStubExpression())
is PsiIfStatement ->
with(expressionTreeMapper) {
JKIfElseStatement(condition.toJK(), thenBranch.toJK(), elseBranch.toJK())
}
is PsiForStatement -> JKJavaForLoopStatement(
initialization.asJKStatementsList(),
with(expressionTreeMapper) { condition.toJK() },
update.asJKStatementsList(),
body.toJK()
)
is PsiForeachStatement ->
JKForInStatement(
iterationParameter.toJK(),
with(expressionTreeMapper) { iteratedValue?.toJK() ?: JKStubExpression() },
body?.toJK() ?: blockStatement()
)
is PsiBlockStatement -> JKBlockStatement(codeBlock.toJK())
is PsiWhileStatement -> JKWhileStatement(with(expressionTreeMapper) { condition.toJK() }, body.toJK())
is PsiDoWhileStatement -> JKDoWhileStatement(body.toJK(), with(expressionTreeMapper) { condition.toJK() })
is PsiSwitchStatement -> {
val cases = mutableListOf<JKJavaSwitchCase>()
for (statement in body?.statements.orEmpty()) {
when (statement) {
is PsiSwitchLabelStatement ->
cases += when {
statement.isDefaultCase -> JKJavaDefaultSwitchCase(emptyList())
else -> JKJavaLabelSwitchCase(
with(expressionTreeMapper) { statement.caseValue.toJK() },
emptyList()
)
}.withFormattingFrom(statement)
else ->
cases.lastOrNull()?.also { it.statements = it.statements + statement.toJK() } ?: run {
cases += JKJavaLabelSwitchCase(
JKStubExpression(),
listOf(statement.toJK())
)
}
}
}
JKJavaSwitchStatement(with(expressionTreeMapper) { expression.toJK() }, cases)
}
is PsiBreakStatement ->
JKBreakStatement(labelIdentifier?.let { JKLabelText(JKNameIdentifier(it.text)) } ?: JKLabelEmpty())
is PsiContinueStatement -> {
val label = labelIdentifier?.let {
JKLabelText(JKNameIdentifier(it.text))
} ?: JKLabelEmpty()
JKContinueStatement(label)
}
is PsiLabeledStatement -> {
val (labels, statement) = collectLabels()
JKLabeledExpression(statement.toJK(), labels.map { JKNameIdentifier(it.text) }).asStatement()
}
is PsiEmptyStatement -> JKEmptyStatement()
is PsiThrowStatement ->
JKJavaThrowStatement(with(expressionTreeMapper) { exception.toJK() })
is PsiTryStatement ->
JKJavaTryStatement(
resourceList?.toList()?.map { (it as PsiResourceListElement).toJK() }.orEmpty(),
tryBlock?.toJK() ?: JKBodyStub,
finallyBlock?.toJK() ?: JKBodyStub,
catchSections.map { it.toJK() }
)
is PsiSynchronizedStatement ->
JKJavaSynchronizedStatement(
with(expressionTreeMapper) { lockExpression?.toJK() } ?: JKStubExpression(),
body?.toJK() ?: JKBodyStub
)
else -> throwCanNotConvertError()
}.also {
if (this != null) {
(it as PsiOwner).psi = this
it.withFormattingFrom(this)
}
}
}
fun PsiResourceListElement.toJK(): JKJavaResourceElement =
when (this) {
is PsiResourceVariable -> JKJavaResourceDeclaration((this as PsiLocalVariable).toJK())
is PsiResourceExpression -> JKJavaResourceExpression(with(expressionTreeMapper) { [email protected]() })
else -> throwCanNotConvertError()
}
fun PsiCatchSection.toJK(): JKJavaTryCatchSection =
JKJavaTryCatchSection(
parameter?.toJK() ?: throwCanNotConvertError(),
catchBlock?.toJK() ?: JKBodyStub
).also {
it.psi = this
it.withFormattingFrom(this)
}
}
fun PsiLabeledStatement.collectLabels(): Pair<List<PsiIdentifier>, PsiStatement> =
generateSequence(emptyList<PsiIdentifier>() to this as PsiStatement) { (labels, statement) ->
if (statement !is PsiLabeledStatementImpl) return@generateSequence null
(labels + statement.labelIdentifier) to (statement.statement ?: throwCanNotConvertError())
}.last()
fun buildTree(psi: PsiElement, saveImports: Boolean): JKTreeRoot? =
when (psi) {
is PsiJavaFile -> psi.toJK()
is PsiExpression -> with(expressionTreeMapper) { psi.toJK() }
is PsiStatement -> with(declarationMapper) { psi.toJK() }
is PsiClass -> with(declarationMapper) { psi.toJK() }
is PsiField -> with(declarationMapper) { psi.toJK() }
is PsiMethod -> with(declarationMapper) { psi.toJK() }
is PsiAnnotation -> with(declarationMapper) { psi.toJK() }
is PsiImportList -> psi.toJK(saveImports)
is PsiImportStatementBase -> psi.toJK(saveImports)
is PsiJavaCodeReferenceElement ->
if (psi.parent is PsiReferenceList) {
val factory = JavaPsiFacade.getInstance(psi.project).elementFactory
val type = factory.createType(psi)
JKTypeElement(type.toJK().updateNullabilityRecursively(Nullability.NotNull))
} else null
else -> null
}?.let { JKTreeRoot(it) }
private fun PsiElement.throwCanNotConvertError(message: String? = null): Nothing {
throw KotlinExceptionWithAttachments("Cannot convert the following Java element ${this::class}" + message?.let { " due to `$it`" })
.also {
try {
it.withAttachment("elementText", text)
} catch (e: Exception) {
it.withAttachment("elementText.error", e.message)
}
}
.also {
try {
it.withAttachment("file", containingFile?.text)
} catch (e: Exception) {
it.withAttachment("file.error", e.message)
}
}
}
companion object {
private const val DEPRECATED_ANNOTATION_FQ_NAME = "java.lang.Deprecated"
}
}
| apache-2.0 | ca6e705bc1633db6c79ca204481d1f49 | 45.327824 | 158 | 0.54992 | 6.175909 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinProjectConfigurator.kt | 1 | 3092 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.configuration
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ExternalLibraryDescriptor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.versions.LibraryJarDescriptor
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.compat.toNewPlatform
enum class ConfigureKotlinStatus {
/** Kotlin is correctly configured using this configurator. */
CONFIGURED,
/** The configurator is not applicable to the current project type. */
NON_APPLICABLE,
/** The configurator is applicable to the current project type and can configure Kotlin automatically. */
CAN_BE_CONFIGURED,
/**
* The configurator is applicable to the current project type and Kotlin is not configured,
* but the state of the project doesn't allow to configure Kotlin automatically.
*/
BROKEN
}
interface KotlinProjectConfigurator {
fun getStatus(moduleSourceRootGroup: ModuleSourceRootGroup): ConfigureKotlinStatus
@JvmSuppressWildcards
fun configure(project: Project, excludeModules: Collection<Module>)
val presentableText: String
val name: String
/*
We have to provide default for newer 'targetPlatform.get()' through delegation to deprecated 'getTargetPlatform()',
not the vice versa, to preserve binary compatibility with old inheritors which override only signature of 'getTargetPlatform'
New clients are encouraged to override both methods
*/
@JvmDefault
val targetPlatform: TargetPlatform
get() = @Suppress("DEPRECATION_ERROR") getTargetPlatform().toNewPlatform()
@Suppress("DEPRECATION_ERROR")
@Deprecated(
message = "This accessor is deprecated and will be removed soon, use API from 'org.jetbrains.kotlin.platform.*' packages instead",
replaceWith = ReplaceWith("targetPlatform"),
level = DeprecationLevel.ERROR
)
fun getTargetPlatform(): org.jetbrains.kotlin.resolve.TargetPlatform
fun updateLanguageVersion(
module: Module,
languageVersion: String?,
apiVersion: String?,
requiredStdlibVersion: ApiVersion,
forTests: Boolean
)
fun changeGeneralFeatureConfiguration(
module: Module,
feature: LanguageFeature,
state: LanguageFeature.State,
forTests: Boolean
)
fun addLibraryDependency(
module: Module,
element: PsiElement,
library: ExternalLibraryDescriptor,
libraryJarDescriptors: List<LibraryJarDescriptor>
)
companion object {
val EP_NAME = ExtensionPointName.create<KotlinProjectConfigurator>("org.jetbrains.kotlin.projectConfigurator")
}
}
| apache-2.0 | 203a24a0b43e48bb549e62ceb3f31d38 | 34.54023 | 158 | 0.743208 | 5.276451 | false | true | false | false |
siosio/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/api/PackageSearchApiClient.kt | 1 | 4274 | package com.jetbrains.packagesearch.intellij.plugin.api
import com.jetbrains.packagesearch.api.v2.ApiPackagesResponse
import com.jetbrains.packagesearch.api.v2.ApiRepositoriesResponse
import com.jetbrains.packagesearch.api.v2.ApiStandardPackage
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment
import com.jetbrains.packagesearch.intellij.plugin.api.http.ApiResult
import com.jetbrains.packagesearch.intellij.plugin.api.http.requestString
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import org.apache.commons.httpclient.util.URIUtil
internal object ServerURLs {
const val base = "https://package-search.services.jetbrains.com/api"
}
private val pluginEnvironment = PluginEnvironment()
@Suppress("unused") // Used in SearchClient but the lazy throws off the IDE code analysis
private val contentType by lazy {
@Suppress("MayBeConst") // False positive
object {
val standard = "application/vnd.jetbrains.packagesearch.standard.v2+json"
}
}
private val emptyStandardV2PackagesWithRepos: ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> = ApiPackagesResponse(
packages = emptyList(),
repositories = emptyList()
)
internal class PackageSearchApiClient(
private val baseUrl: String,
private val timeoutInSeconds: Int = 10,
private val headers: List<Pair<String, String>> = listOf(
Pair("JB-Plugin-Version", pluginEnvironment.pluginVersion),
Pair("JB-IDE-Version", pluginEnvironment.ideVersion)
)
) {
private val maxRequestResultsCount = 25
private val maxMavenCoordinatesParts = 3
private val serializer = Json {
ignoreUnknownKeys = true
encodeDefaults = false
}
@Suppress("BlockingMethodInNonBlockingContext")
suspend fun packagesByQuery(
searchQuery: String,
onlyStable: Boolean = false,
onlyMpp: Boolean = false,
repositoryIds: List<String>
): ApiResult<ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion>> {
if (searchQuery.isEmpty()) {
return ApiResult.Success(emptyStandardV2PackagesWithRepos)
}
val joinedRepositoryIds = repositoryIds.joinToString(",") { URIUtil.encodeQuery(it) }
val requestUrl = buildString {
append(baseUrl)
append("/package?query=")
append(URIUtil.encodeQuery(searchQuery))
append("&onlyStable=")
append(onlyStable.toString())
append("&onlyMpp=")
append(onlyMpp.toString())
if (repositoryIds.isNotEmpty()) {
append("&repositoryIds=")
append(joinedRepositoryIds)
}
}
return requestString(requestUrl, contentType.standard, timeoutInSeconds, headers)
.mapSuccess { serializer.decodeFromString(it) }
}
suspend fun packagesByRange(range: List<String>): ApiResult<ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion>> {
if (range.isEmpty()) {
return ApiResult.Success(emptyStandardV2PackagesWithRepos)
}
if (range.size > maxRequestResultsCount) {
return argumentError(PackageSearchBundle.message("packagesearch.search.client.error.too.many.requests.for.range"))
}
if (range.any { it.split(":").size >= maxMavenCoordinatesParts }) {
return argumentError(PackageSearchBundle.message("packagesearch.search.client.error.no.versions.for.range"))
}
val joinedRange = range.joinToString(",") { URIUtil.encodeQuery(it) }
val requestUrl = "$baseUrl/package?range=$joinedRange"
return requestString(requestUrl, contentType.standard, timeoutInSeconds, headers)
.mapSuccess { serializer.decodeFromString(it) }
}
private fun <T : Any> argumentError(message: String) = ApiResult.Failure<T>(IllegalArgumentException(message))
suspend fun repositories(): ApiResult<ApiRepositoriesResponse> =
requestString("$baseUrl/repositories", contentType.standard, timeoutInSeconds, headers)
.mapSuccess { serializer.decodeFromString(it) }
}
| apache-2.0 | 61826ee714e01a526ff1c803086da91e | 39.704762 | 147 | 0.716191 | 4.912644 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/drawerheaderview/DrawerHeaderWidget.kt | 1 | 2285 | package io.github.feelfreelinux.wykopmobilny.ui.widgets.drawerheaderview
import android.content.Context
import android.util.AttributeSet
import android.view.View
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.ui.modules.profile.ProfileActivity
import io.github.feelfreelinux.wykopmobilny.utils.getActivityContext
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.loadImage
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserCredentials
import kotlinx.android.synthetic.main.drawer_header_view_layout.view.*
class DrawerHeaderWidget @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : androidx.constraintlayout.widget.ConstraintLayout(context, attrs, defStyleAttr) {
companion object {
// @TODO Put this in memory
private const val PLACEHOLDER_IMAGE_URL = "https://i.imgur.com/aSm6pSJ.jpg"
}
init {
View.inflate(context, R.layout.drawer_header_view_layout, this)
}
var hashTagsNotificationsCount: Int
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
set(value) {
nav_notifications_tag.text = value.toString()
}
var notificationCount: Int
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
set(value) {
nav_notifications.text = value.toString()
}
fun showDrawerHeader(isUserAuthorized: Boolean, credentials: UserCredentials?) {
if (isUserAuthorized) {
isVisible = true
nav_profile_image.loadImage(credentials!!.avatarUrl)
nav_profile_image.setOnClickListener {
val context = getActivityContext()!!
context.startActivity(ProfileActivity.createIntent(context, credentials.login))
}
if (credentials.backgroundUrl != null) {
backgroundImage.loadImage(credentials.backgroundUrl)
} else {
backgroundImage.loadImage(PLACEHOLDER_IMAGE_URL)
}
} else {
isVisible = false
}
}
} | mit | e26e625bf7a7a44ded0e769fa6c2bc0e | 39.821429 | 123 | 0.697593 | 4.770355 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.