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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
VerifAPS/verifaps-lib | lang/src/main/kotlin/edu/kit/iti/formal/automation/experimental/java.kt | 1 | 15264 | package edu.kit.iti.formal.automation.experimental
import edu.kit.iti.formal.automation.datatypes.*
import edu.kit.iti.formal.automation.datatypes.values.RecordValue
import edu.kit.iti.formal.automation.datatypes.values.TimeData
import edu.kit.iti.formal.automation.datatypes.values.Value
import edu.kit.iti.formal.automation.operators.Operator
import edu.kit.iti.formal.automation.operators.Operators
import edu.kit.iti.formal.automation.scope.Scope
import edu.kit.iti.formal.automation.st.ast.*
import edu.kit.iti.formal.automation.st.util.AstVisitor
import edu.kit.iti.formal.automation.st.util.AstVisitorWithScope
import edu.kit.iti.formal.util.CodeWriter
import java.io.StringWriter
/**
*
* @author Alexander Weigl
* @version 1 (15.02.19)
*/
class JavaExportVisitor(val packageName: String, val rootClass: String) {
val sw = StringWriter()
val cw = CodeWriter(sw)
fun export(pous: PouElements): String {
cw.write("package $packageName;\n")
cw.write("// Header").nl()
cw.cblock("public class $rootClass {", "}")
{
val predicate: (PouElement) -> Boolean = { it is GlobalVariableListDeclaration }
pous.filter(predicate)
.map { it as HasScope }
//TODO Make them static!
.forEach { it.scope.accept(JavaExportVisitorImpl()) }
pous.filter { it !is GlobalVariableListDeclaration }
.forEach { it.accept(JavaExportVisitorImpl()) }
cw.nl().cblock("public static void main(String[] args) {", "}") {
pous.filter { it is ProgramDeclaration }
.forEach {
cw.nl().write("${it.name}.call();")
}
}
}
return sw.toString()
}
fun iecToJavaType(dt: AnyDt): String = when (dt) {
INT -> "short"
SINT -> "byte"
LINT -> "long"
DINT -> "int"
UINT -> "short"
USINT -> "byte"
ULINT -> "long"
UDINT -> "int"
AnyBit.BOOL -> "boolean"
is FunctionBlockDataType -> dt.functionBlock.name
is ClassDataType.ClassDt -> dt.clazz.name
is ClassDataType.InterfaceDt -> dt.clazz.name
is TimeType -> "long"
is EnumerateType -> dt.name
else -> throw IllegalStateException("$dt")
}
private inner class JavaExportVisitorImpl : AstVisitor<Unit>() {
override fun defaultVisit(obj: Any) {}
override fun visit(localScope: Scope) {
localScope.variables.forEach {
cw.nl().write(variableDecl(it))
}
}
override fun visit(programDeclaration: ProgramDeclaration) {
val name = programDeclaration.name
cw.nl().cblock("public static class $name {", "}") {
visit(programDeclaration.scope)
cw.cblock("public void call() {", "}") {
programDeclaration.stBody?.also { translateSt(it, programDeclaration.scope) }
}
}
cw.nl().write("static $name $name = new $name();").nl()
}
override fun visit(functionDeclaration: FunctionDeclaration) {
val rt = iecToJavaType(functionDeclaration.returnType.obj!!)
val inp = functionDeclaration.scope.filter { it.isInput }
.joinToString(", ") { iecToJavaType(it.dataType!!) + " " + it.name }
val initOut = functionDeclaration.returnType
cw.nl().cblock("public $rt ${functionDeclaration.name}($inp) {", "}") {
functionDeclaration.scope.filter { !it.isInput }
.forEach {
cw.write(variableDecl(it)).nl()
}
functionDeclaration.stBody?.also { translateSt(it, functionDeclaration.scope) }
cw.nl().write("return ${functionDeclaration.name};")
}
}
override fun visit(functionBlockDeclaration: FunctionBlockDeclaration) {
cw.nl().cblock("public static class ${functionBlockDeclaration.name} {", "}") {
val scope = functionBlockDeclaration.scope.sortedBy { it.name }
visit(functionBlockDeclaration.scope) //vars are global
val ctorArgs = scope.joinToString { iecToJavaType(it.dataType!!) + " " + it.name }
cw.nl().cblock("public ${functionBlockDeclaration.name}($ctorArgs) {", "}") {
scope.forEach {
val name = it.name
cw.nl().write("this.$name = $name;")
}
}
cw.nl().cblock("public void call() {", "}") {
functionBlockDeclaration.stBody?.also { translateSt(it, functionBlockDeclaration.scope) }
}
}
}
override fun visit(clazz: ClassDeclaration) {
cw.cblock("public static class ${clazz.name} {", "}") {
visit(clazz.scope)
clazz.methods.forEach { it.accept(this@JavaExportVisitorImpl) }
}
}
override fun visit(interfaceDeclaration: InterfaceDeclaration) {
cw.nl().cblock("public interface ${interfaceDeclaration.name} {", "}") {
interfaceDeclaration.methods.forEach { it.accept(this@JavaExportVisitorImpl) }
}
}
override fun visit(method: MethodDeclaration) {
val rt = iecToJavaType(method.returnType.obj!!)
val inp = method.scope.filter { it.isInput }
.joinToString(", ") { iecToJavaType(it.dataType!!) + " " + it.name }
val initOut = method.returnType
cw.cblock("public $rt ${method.name}($inp) {", "}") {
method.scope.filter { !it.isInput }
.forEach {
cw.write(variableDecl(it)).nl()
}
method.stBody?.also { translateSt(it, method.scope) }
cw.nl().write("return ${method.name};")
}
}
override fun visit(enumerationTypeDeclaration: EnumerationTypeDeclaration) {
cw.nl().cblock("public enum ${enumerationTypeDeclaration.name} {", "}") {
val v = enumerationTypeDeclaration.allowedValues
.joinToString(", ", "", ";") { it.text.toUpperCase() }
cw.write(v)
}
cw.nl()
}
}
private fun translateValue(x: Value<*, *>): String {
val (dt, v) = x
if (dt is EnumerateType) return "${dt.name}.$v"
return when (v) {
is RecordValue -> {
val dt = dt as RecordType
val args = v.fieldValues.keys.sorted().joinToString {
val a = v.fieldValues[it]!!
"(${iecToJavaType(a.dataType)}) " + translateValue(a)
}
"new ${dt.name}($args)"
}
is TimeData -> v.milliseconds.toString() + "/* milliseconds */"
else -> v.toString();
}
}
private fun variableDecl(vd: VariableDeclaration): String {
val dt = iecToJavaType(vd.dataType!!)
return vd.initValue?.let {
val init = translateValue(it)
"$dt ${vd.name} = $init;"
} ?: "$dt ${vd.name};"
}
private fun translateSt(list: StatementList, scope: Scope) {
list.accept(JavaExportStmtImpl(scope))
}
private inner class JavaExportStmtImpl(val scope: Scope) : AstVisitor<Unit>() {
override fun defaultVisit(obj: Any) {
cw.write("// Unsupported statement ${obj.javaClass}").nl()
}
override fun visit(ifStatement: IfStatement) {
cw.nl()
ifStatement.conditionalBranches.forEach {
val cond = translateExpr(it.condition)
cw.cblock("if($cond) {", "}") {
it.statements.accept(this@JavaExportStmtImpl)
}
}
if (ifStatement.elseBranch.isNotEmpty()) {
cw.cblock("else {", "}") {
ifStatement.elseBranch.accept(this@JavaExportStmtImpl)
}
}
}
override fun visit(assignmentStatement: AssignmentStatement) {
val lhs = translateExpr(assignmentStatement.location)
val rhs = translateExpr(assignmentStatement.expression)
val cast = try {
val expdt = assignmentStatement.location.dataType(scope)
val gotdt = assignmentStatement.location.dataType(scope)
/*if (gotdt == expdt) ""
else*/ "(${iecToJavaType(expdt)})"
} catch (e: Exception) {
"/* no cast found ${e.message}*/"
}
cw.nl().write("$lhs = $cast $rhs;")
}
override fun visit(caseStatement: CaseStatement) {
cw.nl()
val expr = translateExpr(caseStatement.expression)
cw.cblock("switch($expr) {", "}") {
caseStatement.cases.forEach { it.accept(this@JavaExportStmtImpl) }
caseStatement.elseCase?.let {
nl().cblock("default: {", "}") {
it.accept(this@JavaExportStmtImpl)
}
}
}
}
override fun visit(aCase: Case) {
aCase.conditions.forEach { it.accept(this) }
cw.increaseIndent().nl()
aCase.statements.accept(this)
cw.nl().write("break;").decreaseIndent().nl()
}
override fun visit(range: CaseCondition.Range) {
(range.range.startValue..range.range.stopValue).forEach {
cw.nl().write("case $it:")
}
}
override fun visit(integerCondition: CaseCondition.IntegerCondition) {
cw.nl().write("case ${translateExpr(integerCondition.value)}:")
}
override fun visit(enumeration: CaseCondition.Enumeration) {
val n = (enumeration.start).value.toUpperCase()
cw.nl().write("case $n:")
}
override fun visit(exitStatement: ExitStatement) {
cw.nl().write("break;")
}
override fun visit(commentStatement: CommentStatement) {
cw.nl().write("// ${commentStatement.comment}")
}
override fun visit(returnStatement: ReturnStatement) {
cw.nl().write("return;")
}
override fun visit(invocation: InvocationStatement) {
val c = translateExpr(invocation.callee)
invocation.inputParameters.forEach {
val sr = invocation.callee.copy(sub = SymbolicReference(it.name))
val t = AssignmentStatement(sr, it.expression)
t.accept(this)
}
cw.nl().write("$c.call();").nl()
invocation.outputParameters.forEach {
val sr = it.expression as SymbolicReference
val t = AssignmentStatement(sr,
invocation.callee.copy(sub=SymbolicReference(it.name)))
t.accept(this)
}
}
override fun visit(forStatement: ForStatement) {
val start = translateExpr(forStatement.start)
val stop = translateExpr(forStatement.stop)
val step = forStatement.step?.let { translateExpr(it) } ?: "0"
val v = forStatement.variable
cw.cblock("for(int $v=$start; $v<=$stop; $v+=$step) {", "}") {
forStatement.statements.accept(this@JavaExportStmtImpl)
}
}
override fun visit(whileStatement: WhileStatement) {
val cond = translateExpr(whileStatement.condition)
cw.cblock("while($cond) {", "}") {
whileStatement.statements.accept(this@JavaExportStmtImpl)
}
}
override fun visit(repeatStatement: RepeatStatement) {
val cond = translateExpr(repeatStatement.condition)
cw.cblock("do {", "} while(($cond);") {
repeatStatement.statements.accept(this@JavaExportStmtImpl)
}
}
override fun visit(statements: StatementList) {
statements.forEach { it.accept(this) }
}
}
private fun translateExpr(expression: Expression): String {
return expression.accept(JavaExportExprImpl)
}
object JavaExportExprImpl : AstVisitorWithScope<String>() {
override fun defaultVisit(obj: Any) = "/* Unsupported construct: $obj */"
override fun visit(unaryExpression: UnaryExpression): String {
return translateOp(unaryExpression.operator) +
"(" + unaryExpression.expression.accept(this) + ")"
}
private fun translateOp(operator: Operator): String {
return when (operator) {
Operators.ADD -> "+"
Operators.AND -> "&&"
Operators.MINUS -> "-"
Operators.DIV -> "/"
Operators.EQUALS -> "=="
Operators.NOT_EQUALS -> "!="
Operators.LESS_EQUALS -> "<="
Operators.LESS_THAN -> "<"
Operators.GREATER_EQUALS -> ">="
Operators.GREATER_THAN -> ">"
Operators.MULT -> "*"
Operators.OR -> "||"
Operators.POWER -> throw java.lang.IllegalStateException("power not supported yet")
Operators.SUB -> "-"
Operators.NOT -> "!"
else -> operator.toString()
}
}
override fun visit(symbolicReference: SymbolicReference): String {
val array = (if (symbolicReference.isArrayAccess)
"[" + symbolicReference.subscripts?.accept(this) + "]"
else "")
val sub = symbolicReference.sub?.let { "." + it.accept(this) } ?: ""
return symbolicReference.identifier + array + sub
}
override fun visit(binaryExpression: BinaryExpression): String {
return ("(" + binaryExpression.leftExpr.accept(this) + " " +
translateOp(binaryExpression.operator) + " " +
binaryExpression.rightExpr.accept(this) + ")")
}
override fun visit(expressions: ExpressionList): String {
return expressions.joinToString(", ") { it.accept(this) }
}
override fun visit(invocation: Invocation): String {
return invocation.callee.accept(this) + "(" +
invocation.parameters.joinToString(", ") { it.expression.accept(this) } + ")"
}
override fun visit(literal: Literal): String {
val td = literal.asValue()?.value
return when (literal) {
is TimeLit -> {
val a: TimeData = td as TimeData
a.milliseconds.toString()
}
is EnumLit -> {
literal.dataType.identifier!! + "." + literal.value.toUpperCase()
}
else -> td?.toString() ?: ""
}
}
}
} | gpl-3.0 | 7a4ad01eb70b3b075826cb7195c95a7e | 37.258145 | 109 | 0.539177 | 4.703852 | false | false | false | false |
jayrave/falkon | falkon-mapper/src/test/kotlin/com/jayrave/falkon/mapper/testLib/ImmovableSingleRowSource.kt | 1 | 1873 | package com.jayrave.falkon.mapper.testLib
import com.jayrave.falkon.engine.Source
import java.util.*
/**
* A [Source] that can hold only one row at a time and always points at the row & throws on
* attempts to move around
*/
internal class ImmovableSingleRowSource(map: Map<String, Any?>) : Source {
override val canBacktrack: Boolean = false
override var isClosed: Boolean = false
private set
// `Source` contract demands user facing index map to be 1-based
private val columnNameToUserFacingIndexMap: Map<String, Int>
private val values: List<Any?>
init {
values = ArrayList(map.size)
columnNameToUserFacingIndexMap = HashMap()
map.forEach { entry ->
val index = values.size
values.add(index, entry.value)
columnNameToUserFacingIndexMap[entry.key] = index + 1 // columnIndex is 1-based
}
}
override fun moveToNext() = false
override fun moveToPrevious() = false
override fun getColumnIndex(columnName: String) = columnNameToUserFacingIndexMap[columnName]!!
override fun getShort(columnIndex: Int) = getValue(columnIndex) as Short
override fun getInt(columnIndex: Int) = getValue(columnIndex) as Int
override fun getLong(columnIndex: Int) = getValue(columnIndex) as Long
override fun getFloat(columnIndex: Int) = getValue(columnIndex) as Float
override fun getDouble(columnIndex: Int) = getValue(columnIndex) as Double
override fun getString(columnIndex: Int) = getValue(columnIndex) as String
override fun getBlob(columnIndex: Int) = getValue(columnIndex) as ByteArray
override fun isNull(columnIndex: Int) = getValue(columnIndex) == null
override fun close() { isClosed = true }
private fun getValue(columnIndex: Int): Any? {
return values[columnIndex - 1] // user facing index is 1-based
}
} | apache-2.0 | 3dea90e882a2020dbe8d1b73bb1ef8a6 | 40.644444 | 98 | 0.707955 | 4.470167 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/main/tut08/cameraRelative.kt | 2 | 7228 | package main.tut08
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL2ES3.GL_COLOR
import com.jogamp.opengl.GL2ES3.GL_DEPTH
import com.jogamp.opengl.GL3
import glNext.*
import glm.*
import glm.mat.Mat4
import glm.quat.Quat
import glm.vec._3.Vec3
import glm.vec._4.Vec4
import main.framework.Framework
import main.framework.component.Mesh
import uno.glm.MatrixStack
import uno.glsl.programOf
/**
* Created by GBarbieri on 10.03.2017.
*/
fun main(args: Array<String>) {
CameraRelative_().setup("Tutorial 08 - Camera Relative")
}
class CameraRelative_ : Framework() {
object OffsetRelative {
val MODEL = 0
val WORLD = 1
val CAMERA = 2
val MAX = 3
}
var theProgram = 0
var modelToCameraMatrixUnif = 0
var cameraToClipMatrixUnif = 0
var baseColorUnif = 0
lateinit var ship: Mesh
lateinit var plane: Mesh
val frustumScale = calcFrustumScale(20.0f)
fun calcFrustumScale(fovDeg: Float) = 1.0f / glm.tan(fovDeg.rad / 2.0f)
val cameraToClipMatrix = Mat4(0.0f)
val camTarget = Vec3(0.0f, 10.0f, 0.0f)
var orientation = Quat(1.0f, 0.0f, 0.0f, 0.0f)
//In spherical coordinates.
val sphereCamRelPos = Vec3(90.0f, 0.0f, 66.0f)
var offset = OffsetRelative.MODEL
public override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
ship = Mesh(gl, javaClass, "tut08/Ship.xml")
plane = Mesh(gl, javaClass, "tut08/UnitPlane.xml")
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
glFrontFace(GL_CW)
glEnable(GL_DEPTH_TEST)
glDepthMask(true)
glDepthFunc(GL_LEQUAL)
glDepthRangef(0.0f, 1.0f)
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut08", "pos-color-local-transform.vert", "color-mult-uniform.frag")
modelToCameraMatrixUnif = glGetUniformLocation(theProgram, "modelToCameraMatrix")
cameraToClipMatrixUnif = glGetUniformLocation(theProgram, "cameraToClipMatrix")
baseColorUnif = glGetUniformLocation(theProgram, "baseColor")
val zNear = 1.0f
val zFar = 600.0f
cameraToClipMatrix[0].x = frustumScale
cameraToClipMatrix[1].y = frustumScale
cameraToClipMatrix[2].z = (zFar + zNear) / (zNear - zFar)
cameraToClipMatrix[2].w = -1.0f
cameraToClipMatrix[3].z = 2f * zFar * zNear / (zNear - zFar)
glUseProgram(theProgram)
glUniformMatrix4f(cameraToClipMatrixUnif, cameraToClipMatrix)
glUseProgram()
}
public override fun display(gl: GL3) = with(gl) {
glClearBufferf(GL_COLOR, 0)
glClearBufferf(GL_DEPTH)
val currMatrix = MatrixStack()
val camPos = resolveCamPosition()
currMatrix setMatrix calcLookAtMatrix(camPos, camTarget, Vec3(0.0f, 1.0f, 0.0f))
glUseProgram(theProgram)
currMatrix.apply {
scale(100.0f, 1.0f, 100.0f)
glUniform4f(baseColorUnif, 0.2f, 0.5f, 0.2f, 1.0f)
glUniformMatrix4f(modelToCameraMatrixUnif, top())
plane.render(gl)
} run {
translate(camTarget)
applyMatrix(orientation.toMat4())
rotateX(-90.0f)
glUniform4f(baseColorUnif, 1.0f)
glUniformMatrix4f(modelToCameraMatrixUnif, top())
ship.render(gl, "tint")
}
glUseProgram()
}
fun resolveCamPosition(): Vec3 {
val phi = sphereCamRelPos.x.rad
val theta = (sphereCamRelPos.y + 90.0f).rad
val dirToCamera = Vec3(theta.sin * phi.cos, theta.cos, theta.sin * phi.sin)
return dirToCamera * sphereCamRelPos.z + camTarget
}
fun calcLookAtMatrix(cameraPt: Vec3, lookPt: Vec3, upPt: Vec3): Mat4 {
val lookDir = (lookPt - cameraPt).normalize()
val upDir = upPt.normalize()
val rightDir = (lookDir cross upDir).normalize()
val perpUpDir = rightDir cross lookDir
val rotationMat = Mat4(1.0f)
rotationMat[0] = Vec4(rightDir, 0.0f)
rotationMat[1] = Vec4(perpUpDir, 0.0f)
rotationMat[2] = Vec4(-lookDir, 0.0f)
rotationMat.transpose_()
val translMat = Mat4(1.0f)
translMat[3] = Vec4(-cameraPt, 1.0f)
return rotationMat * translMat
}
public override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
cameraToClipMatrix[0].x = frustumScale * (h / w.f)
cameraToClipMatrix[1].y = frustumScale
glUseProgram(theProgram)
glUniformMatrix4f(cameraToClipMatrixUnif, cameraToClipMatrix)
glUseProgram()
glViewport(w, h)
}
public override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
plane.dispose(gl)
ship.dispose(gl)
}
override fun keyPressed(e: KeyEvent) {
val smallAngleIncrement = 9.0f
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_W -> offsetOrientation(Vec3(1.0f, 0.0f, 0.0f), +smallAngleIncrement)
KeyEvent.VK_S -> offsetOrientation(Vec3(1.0f, 0.0f, 0.0f), -smallAngleIncrement)
KeyEvent.VK_A -> offsetOrientation(Vec3(0.0f, 0.0f, 1.0f), +smallAngleIncrement)
KeyEvent.VK_D -> offsetOrientation(Vec3(0.0f, 0.0f, 1.0f), -smallAngleIncrement)
KeyEvent.VK_Q -> offsetOrientation(Vec3(0.0f, 1.0f, 0.0f), +smallAngleIncrement)
KeyEvent.VK_E -> offsetOrientation(Vec3(0.0f, 1.0f, 0.0f), -smallAngleIncrement)
KeyEvent.VK_SPACE -> {
offset = (++offset) % OffsetRelative.MAX
when (offset) {
OffsetRelative.MODEL -> println("MODEL_RELATIVE")
OffsetRelative.WORLD -> println("WORLD_RELATIVE")
OffsetRelative.CAMERA -> println("CAMERA_RELATIVE")
}
}
KeyEvent.VK_I -> sphereCamRelPos.y -= if (e.isShiftDown) 1.125f else 11.25f
KeyEvent.VK_K -> sphereCamRelPos.y += if (e.isShiftDown) 1.125f else 11.25f
KeyEvent.VK_J -> sphereCamRelPos.x -= if (e.isShiftDown) 1.125f else 11.25f
KeyEvent.VK_L -> sphereCamRelPos.x += if (e.isShiftDown) 1.125f else 11.25f
}
sphereCamRelPos.y = glm.clamp(sphereCamRelPos.y, -78.75f, 10.0f)
}
fun offsetOrientation(axis: Vec3, angDeg: Float) {
axis.normalize()
axis times_ glm.sin(angDeg.rad / 2.0f)
val scalar = glm.cos(angDeg.rad / 2.0f)
val offsetQuat = Quat(scalar, axis)
when (offset) {
OffsetRelative.MODEL -> orientation times_ offsetQuat
OffsetRelative.WORLD -> orientation = offsetQuat * orientation
OffsetRelative.CAMERA -> {
val camPos = resolveCamPosition()
val camMat = calcLookAtMatrix(camPos, camTarget, Vec3(0.0f, 1.0f, 0.0f))
val viewQuat = camMat.toQuat()
val invViewQuat = viewQuat.conjugate()
val worldQuat = invViewQuat * offsetQuat * viewQuat
orientation = worldQuat * orientation
}
}
orientation.normalize_()
}
} | mit | 75711e326854e559dcfdc4d6d3937baa | 27.128405 | 115 | 0.61497 | 3.729618 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/ui/order/fragment/NormalTestItemFragment.kt | 1 | 6805 | package com.fuyoul.sanwenseller.ui.order.fragment
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import com.csl.refresh.SmartRefreshLayout
import com.fuyoul.sanwenseller.R
import com.fuyoul.sanwenseller.base.BaseAdapter
import com.fuyoul.sanwenseller.base.BaseFragment
import com.fuyoul.sanwenseller.base.BaseViewHolder
import com.fuyoul.sanwenseller.bean.AdapterMultiItem
import com.fuyoul.sanwenseller.bean.MultBaseBean
import com.fuyoul.sanwenseller.bean.others.AppointMentItemBean
import com.fuyoul.sanwenseller.configs.Code
import com.fuyoul.sanwenseller.configs.Data
import com.fuyoul.sanwenseller.configs.Key
import com.fuyoul.sanwenseller.helper.MsgDialogHelper
import com.fuyoul.sanwenseller.structure.model.AppointMentM
import com.fuyoul.sanwenseller.structure.presenter.AppointMentP
import com.fuyoul.sanwenseller.structure.view.AppointMentV
import com.fuyoul.sanwenseller.ui.web.WebViewActivity
import com.fuyoul.sanwenseller.ui.order.AppointMentInfoActivity
import com.fuyoul.sanwenseller.utils.GlideUtils
import kotlinx.android.synthetic.main.normaltestitem.*
/**
* @author: chen
* @CreatDate: 2017\10\30 0030
* @Desc:
*/
class NormalTestItemFragment : BaseFragment<AppointMentM, AppointMentV, AppointMentP>() {
private var allDayState = 0//全天接单状态
private var TYPE = Data.TODAY
private var adapter: ThisAdapter? = null
override fun setLayoutRes(): Int = R.layout.normaltestitem
override fun init(view: View?, savedInstanceState: Bundle?) {
TYPE = arguments.getInt(Key.appointmentTypeKey, Data.TODAY)
val manager = GridLayoutManager(context, 4)
normalTestList.layoutManager = manager
normalTestList.adapter = initViewImpl().getAdapter()
getPresenter().getData(context, TYPE)
}
override fun setListener() {
normalTestRefreshLayout.setOnRefreshListener {
getPresenter().getData(context, TYPE)
}
stateView.setOnClickListener {
getPresenter().changeAllDayState(context, TYPE, if (allDayState == Data.BUSY) Data.FREE else Data.BUSY)
}
allDayStateRule.setOnClickListener {
WebViewActivity.startWebView(context, "时间安排协议", "http://www.baidu.com")
}
}
override fun getPresenter(): AppointMentP = AppointMentP(initViewImpl())
override fun initViewImpl(): AppointMentV = object : AppointMentV() {
override fun setItemState(position: Int) {
(getAdapter().datas[position] as AppointMentItemBean).canOrder = !(getAdapter().datas[position] as AppointMentItemBean).canOrder
getAdapter().notifyItemRangeChanged(position, 1)
}
override fun setAllDaySatate(state: Int, isRefreshData: Boolean) {
allDayState = state
if (allDayState == Data.BUSY) {//如果设置了全天不接单
stateView.setImageResource(R.mipmap.ic_my_yyb_jdshut)
allDayStateInfo.text = "全天不接单"
initViewImpl().getAdapter().datas.forEach {
(it as AppointMentItemBean).isBusy = true
}
} else {
allDayStateInfo.text = "全天接单"
initViewImpl().getAdapter().datas.forEach {
(it as AppointMentItemBean).isBusy = false
}
stateView.setImageResource(R.mipmap.ic_my_yyb_jdopen)
}
if (isRefreshData) {
Log.e("csl", "-----刷新数据------$isRefreshData--")
initViewImpl().getAdapter().notifyItemRangeChanged(0, initViewImpl().getAdapter().datas.size)
}
}
override fun getAdapter(): ThisAdapter {
if (adapter == null) {
adapter = ThisAdapter()
}
return adapter!!
}
}
inner class ThisAdapter : BaseAdapter(context) {
override fun getSmartRefreshLayout(): SmartRefreshLayout {
normalTestRefreshLayout.isEnableLoadmore = false
return normalTestRefreshLayout
}
override fun convert(holder: BaseViewHolder, position: Int, datas: List<MultBaseBean>) {
val item = datas[position] as AppointMentItemBean
val time = holder.itemView.findViewById<TextView>(R.id.time)
val state = holder.itemView.findViewById<TextView>(R.id.state)
val infoLayout = holder.itemView.findViewById<RelativeLayout>(R.id.infoLayout)
time.text = item.time
if (item.isSelect) {//如果被预约了,无论全天是否可接单都显示
infoLayout.visibility = View.VISIBLE
GlideUtils.loadCircleImg(context, item.avatar, holder.itemView.findViewById(R.id.avatar), R.drawable.nim_avatar_default, R.drawable.nim_avatar_default)
state.text = "已约"
infoLayout.setOnClickListener {
AppointMentInfoActivity.start(context, item.orderId)
}
time.setTextColor(resources.getColor(R.color.color_333333))
state.setTextColor(resources.getColor(R.color.color_FF627B))
} else {
infoLayout.visibility = View.GONE
if (item.isBusy || !item.canOrder) {//如果全天不可接单或者某个时间点不接单
state.text = "不可约"
time.setTextColor(resources.getColor(R.color.color_888888))
state.setTextColor(resources.getColor(R.color.color_888888))
} else {
state.text = "可约"
time.setTextColor(resources.getColor(R.color.color_333333))
state.setTextColor(resources.getColor(R.color.color_3CC5BC))
}
}
}
override fun addMultiType(multiItems: ArrayList<AdapterMultiItem>) {
multiItems.add(AdapterMultiItem(Code.VIEWTYPE_APPOINTMENT, R.layout.apointmentitem))
}
override fun onItemClicked(view: View, position: Int) {
val item = datas[position] as AppointMentItemBean
if (!item.isBusy && !item.isSelect) {//
getPresenter().changeItemState(context, TYPE, position)
} else {
MsgDialogHelper.showSingleDialog(context, true, "温馨提示", "当前状态不可修改接单状态", "我知道了", null)
}
}
override fun onEmpryLayou(view: View, layoutResId: Int) {
}
override fun getRecyclerView(): RecyclerView = normalTestList
}
} | apache-2.0 | 685dece92c628ab011689b490c1325b6 | 34.923913 | 167 | 0.6532 | 4.637895 | false | false | false | false |
sandjelkovic/configurator | src/main/java/com/saanx/configurator/config/ApplicationConfiguration.kt | 1 | 2033 | package com.saanx.configurator.config
import com.saanx.configurator.data.entity.Slot
import com.saanx.configurator.data.handlers.ConfigurationEventHandler
import com.saanx.configurator.data.handlers.ConfigurationKtEventHandler
import com.saanx.configurator.data.repository.UserRepository
import com.saanx.configurator.processor.ConfigurationProcessor
import com.saanx.configurator.processor.SlotProcessor
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.rest.core.config.RepositoryRestConfiguration
import org.springframework.data.rest.core.mapping.RepositoryDetectionStrategy.RepositoryDetectionStrategies.ANNOTATED
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter
import org.springframework.hateoas.Resource
import org.springframework.hateoas.ResourceProcessor
/**
* @author sandjelkovic
* @date 22.7.17.
*/
@Configuration
open class ApplicationConfiguration {
@Bean
open fun repositoryRestConfigurer(): RepositoryRestConfigurer {
return object : RepositoryRestConfigurerAdapter() {
override fun configureRepositoryRestConfiguration(config: RepositoryRestConfiguration?) {
if (config != null) {
config.repositoryDetectionStrategy = ANNOTATED;
config.setReturnBodyForPutAndPost(true)
}
}
}
}
@Bean
open fun slotProcessor(): ResourceProcessor<Resource<Slot>> = SlotProcessor()
@Bean
open fun configurationProcessor(): ResourceProcessor<Resource<com.saanx.configurator.data.entity.Configuration>> = ConfigurationProcessor()
@Bean
open fun configurationKtEventHandler(userRepository: UserRepository) = ConfigurationKtEventHandler(userRepository)
@Bean
open fun configurationEventHandler(userRepository: UserRepository) = ConfigurationEventHandler(userRepository)
}
| apache-2.0 | 356c18e8c3d0375d93c0926add634936 | 41.354167 | 143 | 0.791933 | 4.8753 | false | true | false | false |
nfrankel/kaadin | kaadin-core/src/test/kotlin/ch/frankel/kaadin/grid/GridRendererTest.kt | 1 | 1721 | /*
* Copyright 2016 Nicolas Fränkel
*
* 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 ch.frankel.kaadin.grid
import ch.frankel.kaadin.*
import com.vaadin.ui.renderers.ButtonRenderer
import com.vaadin.ui.renderers.TextRenderer
import org.assertj.core.api.Assertions.assertThat
import org.testng.annotations.Test
@Test(dependsOnGroups = ["baseGrid"])
class GridRendererTest {
@Test
fun `column should add button renderer`() {
val layout = horizontalLayout {
grid(dataSource = GridTestData.container) {
column("string").buttonRenderer()
}
}
val grid = layout.getGrid()
assertThat(grid.getStringColumn().renderer)
.isNotNull
.isInstanceOf(ButtonRenderer::class.java)
}
@Test
fun `column should add custom renderer`() {
val layout = horizontalLayout {
grid(dataSource = GridTestData.container) {
column("string").renderer(TextRenderer())
}
}
val grid = layout.getGrid()
assertThat(grid.getStringColumn().renderer)
.isNotNull
.isInstanceOf(TextRenderer::class.java)
}
} | apache-2.0 | 112031b7aed97e971a737b004018c55b | 32.096154 | 75 | 0.662209 | 4.562334 | false | true | false | false |
cloverrose/KlickModel | src/test/kotlin/com/github/cloverrose/klickmodel/parsers/YandexRelPredChallengeParser.kt | 1 | 1163 | package com.github.cloverrose.klickmodel.parsers
import java.io.File
import com.github.cloverrose.klickmodel.domain.SearchSession
import com.github.cloverrose.klickmodel.domain.SearchResult
object YandexRelPredChallengeParser: Parser() {
override fun parse(sessionsFilename: String, sessionsMax: Int): List<SearchSession> {
val sessionFile = File(sessionsFilename)
val sessions: List<SearchSession> = sessionFile.useLines { it.map { it.trim().split("\t") }.groupBy { it[0] }.map {
val queryOrClicks: Map<String, List<List<String>>> = it.value.groupBy { it[2] }
val queryEntry = queryOrClicks["Q"]!!.first()
val clickEntries: List<List<String>> = queryOrClicks.getOrElse("C") { emptyList() }
val resultIds: List<String> = queryEntry.subList(5, queryEntry.size)
val clickIds: List<String> = clickEntries.map { it[3] }
val results: List<SearchResult> = resultIds.map { id -> SearchResult(id, id in clickIds) }
val session: SearchSession = SearchSession(queryEntry[3], results)
session
}}.take(sessionsMax)
return sessions
}
}
| gpl-3.0 | b065852d1d0a316aeab04d94b9b0da69 | 47.458333 | 123 | 0.674119 | 3.915825 | false | false | false | false |
koesie10/AdventOfCode-Solutions-Kotlin | 2016/src/main/kotlin/com/koenv/adventofcode/Day1.kt | 1 | 2996 | package com.koenv.adventofcode
object Day1 {
fun getBlocksAway(input: String): Int {
var heading: Int = 0 // heading North, positive is clockwise
// store our coordinates
var x: Int = 0
var y: Int = 0
input.split(",").map(String::trim).forEach {
heading = getNewHeading(heading, it[0])
val blocks = it.substring(1).toInt()
val (xDiff, yDiff) = getXYDiff(heading, blocks)
x += xDiff
y += yDiff
}
// the total distance is away is just the total x + total y distance
return Math.abs(x) + Math.abs(y)
}
fun getFirstLocationVisitedTwice(input: String): Int {
var heading: Int = 0 // heading North, positive is clockwise
// store our coordinates
var x: Int = 0
var y: Int = 0
val visitedLocations = mutableListOf<Pair<Int, Int>>()
input.split(",").map(String::trim).forEach {
heading = getNewHeading(heading, it[0])
val blocks = it.substring(1).toInt()
var (xDiff, yDiff) = getXYDiff(heading, blocks)
while (Math.abs(xDiff) > 0) {
val sign = Integer.signum(xDiff)
xDiff -= sign
x += sign
val location = x to y
if (location in visitedLocations) {
// the total distance is away is just the total x + total y distance
return Math.abs(x) + Math.abs(y)
}
visitedLocations.add(x to y)
}
while (Math.abs(yDiff) > 0) {
val sign = Integer.signum(yDiff)
yDiff -= sign
y += sign
val location = x to y
if (location in visitedLocations) {
// the total distance is away is just the total x + total y distance
return Math.abs(x) + Math.abs(y)
}
visitedLocations.add(x to y)
}
}
throw IllegalStateException("There were no locations that were visited twice")
}
fun getNewHeading(oldHeading: Int, direction: Char): Int {
var newHeading = oldHeading
newHeading += when (direction) {
'R' -> 90
'L' -> -90
else -> throw IllegalStateException("Direction is $direction")
}
// make sure we are in the range -360 to 360
newHeading = newHeading.mod(360)
// and we don't want negative headings
if (newHeading < 0) {
newHeading += 360
}
return newHeading
}
fun getXYDiff(heading: Int, blocks: Int): Pair<Int, Int> {
when (heading) {
0 -> return 0 to -blocks
90 -> return blocks to 0
180 -> return 0 to blocks
270 -> return -blocks to 0
else -> throw IllegalStateException("Heading is $heading")
}
}
} | mit | 94af8a83b1fe12d22a74697ff7a38c57 | 28.097087 | 88 | 0.514352 | 4.491754 | false | false | false | false |
world-federation-of-advertisers/common-jvm | src/main/kotlin/org/wfanet/measurement/common/grpc/LoggingServerInterceptor.kt | 1 | 4215 | // Copyright 2020 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.common.grpc
import com.google.protobuf.Message
import io.grpc.BindableService
import io.grpc.ForwardingServerCall.SimpleForwardingServerCall
import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener
import io.grpc.Metadata
import io.grpc.ServerCall
import io.grpc.ServerCallHandler
import io.grpc.ServerInterceptor
import io.grpc.ServerInterceptors
import io.grpc.ServerServiceDefinition
import io.grpc.Status
import java.util.concurrent.atomic.AtomicLong
import java.util.logging.Level
import java.util.logging.Logger
import org.wfanet.measurement.common.truncateByteFields
/** Logs all gRPC requests and responses. */
object LoggingServerInterceptor : ServerInterceptor {
private val logger: Logger = Logger.getLogger(this::class.java.name)
private const val BYTES_TO_LOG = 100
private val threadName: String
get() = Thread.currentThread().name
private val requestCounter = AtomicLong()
override fun <ReqT, RespT> interceptCall(
call: ServerCall<ReqT, RespT>,
headers: Metadata?,
next: ServerCallHandler<ReqT, RespT>
): ServerCall.Listener<ReqT> {
val requestId = requestCounter.incrementAndGet()
val serviceName = call.methodDescriptor.serviceName
val methodName = call.methodDescriptor.bareMethodName
val interceptedCall =
object : SimpleForwardingServerCall<ReqT, RespT>(call) {
override fun sendMessage(message: RespT) {
val messageToLog = (message as Message).truncateByteFields(BYTES_TO_LOG)
logger.logp(
Level.INFO,
serviceName,
methodName,
"[$threadName] gRPC $requestId response: $messageToLog"
)
super.sendMessage(message)
}
override fun close(status: Status, trailers: Metadata) {
if (!status.isOk) {
val message =
listOfNotNull(
"[$threadName]",
"gRPC $requestId error:",
status.code.name,
status.description,
)
.joinToString(" ")
logger.logp(Level.INFO, serviceName, methodName, message, status.cause)
}
super.close(status, trailers)
}
}
val originalListener = next.startCall(interceptedCall, headers)
return object : SimpleForwardingServerCallListener<ReqT>(originalListener) {
override fun onMessage(message: ReqT) {
val messageToLog = (message as Message).truncateByteFields(BYTES_TO_LOG)
logger.logp(
Level.INFO,
serviceName,
methodName,
"[$threadName] gRPC $requestId request: $headers $messageToLog"
)
super.onMessage(message)
}
override fun onComplete() {
logger.logp(Level.INFO, serviceName, methodName, "[$threadName] gRPC $requestId complete")
}
}
}
}
/** Psuedo-constructor for backwards-compatibility. */
@Deprecated("Use singleton object", ReplaceWith("LoggingServerInterceptor"))
fun LoggingServerInterceptor() = LoggingServerInterceptor
/** Logs all gRPC requests and responses. */
fun BindableService.withVerboseLogging(enabled: Boolean = true): ServerServiceDefinition {
if (!enabled) return this.bindService()
return ServerInterceptors.interceptForward(this, LoggingServerInterceptor)
}
/** Logs all gRPC requests and responses. */
fun ServerServiceDefinition.withVerboseLogging(enabled: Boolean = true): ServerServiceDefinition {
if (!enabled) return this
return ServerInterceptors.interceptForward(this, LoggingServerInterceptor)
}
| apache-2.0 | 0631b7c3125a09d96cfd801aed3c92d5 | 36.972973 | 98 | 0.708185 | 4.688543 | false | false | false | false |
world-federation-of-advertisers/common-jvm | src/main/kotlin/org/wfanet/measurement/gcloud/spanner/Structs.kt | 1 | 4969 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.gcloud.spanner
import com.google.cloud.ByteArray
import com.google.cloud.Date
import com.google.cloud.Timestamp
import com.google.cloud.spanner.Struct
import com.google.cloud.spanner.StructReader
import com.google.protobuf.Message
import com.google.protobuf.ProtocolMessageEnum
import org.wfanet.measurement.common.identity.ExternalId
import org.wfanet.measurement.common.identity.InternalId
/** Sets the value that should be bound to the specified column. */
@JvmName("setBoolean")
fun Struct.Builder.set(columnValuePair: Pair<String, Boolean>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).to(value)
}
/** Sets the value that should be bound to the specified column. */
@JvmName("setBooleanBoxed")
fun Struct.Builder.set(columnValuePair: Pair<String, Boolean?>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).to(value)
}
/** Sets the value that should be bound to the specified column. */
@JvmName("setLong")
fun Struct.Builder.set(columnValuePair: Pair<String, Long>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).to(value)
}
/** Sets the value that should be bound to the specified column. */
@JvmName("setLongBoxed")
fun Struct.Builder.set(columnValuePair: Pair<String, Long?>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).to(value)
}
/** Sets the value that should be bound to the specified column. */
@JvmName("setDouble")
fun Struct.Builder.set(columnValuePair: Pair<String, Double>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).to(value)
}
/** Sets the value that should be bound to the specified column. */
@JvmName("setDoubleBoxed")
fun Struct.Builder.set(columnValuePair: Pair<String, Double?>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).to(value)
}
/** Sets the value that should be bound to the specified column. */
@JvmName("setString")
fun Struct.Builder.set(columnValuePair: Pair<String, String?>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).to(value)
}
/** Sets the value that should be bound to the specified column. */
@JvmName("setTimestamp")
fun Struct.Builder.set(columnValuePair: Pair<String, Timestamp?>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).to(value)
}
/** Sets the value that should be bound to the specified column. */
@JvmName("setDate")
fun Struct.Builder.set(columnValuePair: Pair<String, Date?>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).to(value)
}
/** Sets the value that should be bound to the specified column. */
@JvmName("setBytes")
fun Struct.Builder.set(columnValuePair: Pair<String, ByteArray?>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).to(value)
}
/** Sets the value that should be bound to the specified column. */
@JvmName("setProtoEnum")
fun Struct.Builder.set(columnValuePair: Pair<String, ProtocolMessageEnum>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).toProtoEnum(value)
}
/** Sets the value that should be bound to the specified column. */
@JvmName("setProtoMessageBytes")
fun Struct.Builder.set(columnValuePair: Pair<String, Message?>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).toProtoBytes(value)
}
/** Sets the JSON value that should be bound to the specified string column. */
fun Struct.Builder.setJson(columnValuePair: Pair<String, Message?>): Struct.Builder {
val (columnName, value) = columnValuePair
return set(columnName).toProtoJson(value)
}
/**
* Returns an [InternalId] with the value of a non-`NULL` column with type [Type.int64()]
* [com.google.cloud.spanner.Type.int64].
*/
fun StructReader.getInternalId(columnName: String) = InternalId(getLong(columnName))
/**
* Returns an [ExternalId] with the value of a non-`NULL` column with type [Type.int64()]
* [com.google.cloud.spanner.Type.int64].
*/
fun StructReader.getExternalId(columnName: String) = ExternalId(getLong(columnName))
/** Builds a [Struct]. */
inline fun struct(bind: Struct.Builder.() -> Unit): Struct = Struct.newBuilder().apply(bind).build()
| apache-2.0 | ee80cf173578b25fe661335b1c5a9fb4 | 37.223077 | 100 | 0.753069 | 3.924961 | false | false | false | false |
idanarye/nisui | cli/src/main/kotlin/nisui/cli/EntryPoint.kt | 1 | 3056 | package nisui.cli
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.PrintStream
import java.io.UnsupportedEncodingException
import java.nio.charset.StandardCharsets
import java.util.Arrays
import java.util.List
import picocli.CommandLine
import nisui.cli.print_formats.*
import nisui.core.NisuiFactory
@CommandLine.Command
public class EntryPoint(val nisuiFactory: NisuiFactory) {
@CommandLine.Option(names = ["-h", "--help"], usageHelp = true, description = ["Show this help message and exit."])
var helpRequested: Boolean = false
@CommandLine.Option(names = ["--format"], description = ["The format to print the results in."])
var format: String = ""
fun run(in_: InputStream?, out_: PrintStream, vararg args: String) {
val commandLine = CommandLine(this)
val mainCommand = StartGuiSubcommand(nisuiFactory)
mainCommand.register(commandLine)
ExperimentSubcommand(nisuiFactory).register(commandLine)
DataPointSubcommand(nisuiFactory).register(commandLine)
ExperimentResultSubcommand(nisuiFactory).register(commandLine)
RunSubcommand(nisuiFactory).register(commandLine)
QueriesSubcommand(nisuiFactory).register(commandLine)
val subCommands = commandLine.parseArgs(*args).asCommandLineList()
if (helpRequested) {
commandLine.usage(out_)
return
}
var ranSomething = false
for ((i, subCommand) in subCommands.withIndex()) {
val obj = subCommand.getCommand<Any>()
if (obj is CommandGroup) {
val commandGroup: CommandGroup = obj
if (
commandGroup.helpRequested
|| i == subCommands.size - 1
|| subCommands.get(i + 1).parent != subCommand
) {
subCommand.usage(out_)
return
}
commandGroup.printFormatCreator = when (format) {
"" -> ({ PrintTabular<Any>() })
"csv" -> ({ PrintCSV<Any>() })
else -> {
throw Exception("Unknown format $format")
}
}
}
if (obj is SubCommand) {
val subCmd: SubCommand = obj
if (subCmd.helpRequested) {
subCommand.usage(out_)
return
}
ranSomething = true
subCmd.run(in_, out_)
}
}
if (!ranSomething) {
mainCommand.run(in_, out_)
}
}
fun run(vararg args: String) {
run(System.`in`, System.`out`, *args)
}
fun runGetOutput(vararg args: String): String {
val baos = ByteArrayOutputStream()
return PrintStream(baos, true, "utf-8").use { ps ->
run(null, ps, *args)
ps.flush()
String(baos.toByteArray(), StandardCharsets.UTF_8)
}
}
}
| mit | 1f1f95f59c661ebfdcf4a09336dff96d | 31.860215 | 119 | 0.565445 | 4.827804 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/support/GradleApiMetadata.kt | 4 | 3419 | /*
* 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.support
import org.gradle.api.internal.file.pattern.PatternMatcher
import org.gradle.api.internal.file.pattern.PatternMatcherFactory
import org.gradle.kotlin.dsl.codegen.ParameterNamesSupplier
import java.io.File
import java.util.Properties
import java.util.jar.JarFile
const val gradleApiMetadataModuleName = "gradle-api-metadata"
data class GradleApiMetadata(
val includes: List<String>,
val excludes: List<String>,
val parameterNamesSupplier: ParameterNamesSupplier
) {
val spec = apiSpecFor(includes, excludes)
}
fun gradleApiMetadataFrom(gradleApiMetadataJar: File, gradleApiJars: Collection<File>): GradleApiMetadata =
apiDeclarationFrom(gradleApiMetadataJar).let { (includes, excludes) ->
GradleApiMetadata(includes, excludes, parameterNamesSupplierFor(parameterNamesFrom(gradleApiJars)))
}
private
fun apiDeclarationFrom(gradleApiMetadataJar: File): Pair<List<String>, List<String>> =
JarFile(gradleApiMetadataJar).use { jar ->
val apiDeclaration = jar.loadProperties(gradleApiDeclarationPropertiesName)
apiDeclaration.getProperty("includes").split(":") to apiDeclaration.getProperty("excludes").split(":")
}
private
fun parameterNamesFrom(gradleApiJars: Collection<File>): List<Properties> =
gradleApiJars.mapNotNull { gradleApiJar ->
JarFile(gradleApiJar).use { jar ->
jar.loadPropertiesOrNull(parameterNamesResourceNameFor(gradleApiJar))
}
}
private
fun JarFile.loadPropertiesOrNull(name: String): Properties? =
getJarEntry(name)?.let { entry ->
getInputStream(entry)?.use { input ->
Properties().also { it.load(input) }
}
}
private
fun JarFile.loadProperties(name: String): Properties =
loadPropertiesOrNull(name)!!
private
const val gradleApiDeclarationPropertiesName = "gradle-api-declaration.properties"
private
fun parameterNamesResourceNameFor(jar: File) =
"${jar.name.split(Regex("\\d")).first()}parameter-names.properties"
private
fun parameterNamesSupplierFor(parameterNames: List<Properties>): ParameterNamesSupplier =
{ key: String ->
parameterNames.asSequence()
.mapNotNull { it.getProperty(key, null) }
.firstOrNull()
?.split(",")
}
private
fun apiSpecFor(includes: List<String>, excludes: List<String>): PatternMatcher =
when {
includes.isEmpty() && excludes.isEmpty() -> PatternMatcher.MATCH_ALL
includes.isEmpty() -> patternSpecFor(excludes).negate()
excludes.isEmpty() -> patternSpecFor(includes)
else -> patternSpecFor(includes).and(patternSpecFor(excludes).negate())
}
private
fun patternSpecFor(patterns: List<String>) =
PatternMatcherFactory.getPatternsMatcher(true, true, patterns)
| apache-2.0 | 23a9efcccd7e9cc4d6b91a09e049f2b1 | 30.953271 | 110 | 0.731793 | 4.360969 | false | false | false | false |
jksiezni/xpra-client | xpra-client-android/src/main/java/com/github/jksiezni/xpra/view/WorkspaceView.kt | 1 | 5196 | /*
* Copyright (C) 2020 Jakub Ksiezniak
*
* 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 2 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.jksiezni.xpra.view
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.widget.FrameLayout
import android.widget.Scroller
import androidx.core.math.MathUtils
import androidx.core.view.GestureDetectorCompat
import androidx.core.view.children
/**
*
*/
class WorkspaceView : FrameLayout {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
private val overflingDistance = ViewConfiguration.get(context).scaledOverflingDistance
override fun shouldDelayChildPressedState(): Boolean {
return true
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
return ev.pointerCount >= 2
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent?): Boolean {
return gestureDetector.onTouchEvent(event) || super.onTouchEvent(event)
}
override fun scrollBy(x: Int, y: Int) {
val r = getScrollRange()
val tx = MathUtils.clamp(scrollX + x, r.left, r.right - width)
val ty = MathUtils.clamp(scrollY + y, r.top, r.bottom - height)
super.scrollTo(tx, ty)
}
private fun getScrollRange(): Rect {
val temp = Rect()
return children.fold(Rect()) { acc, view ->
view.getDrawingRect(temp)
acc.apply { union(temp) }
}
}
override fun computeScroll() {
if (scroller.computeScrollOffset()) {
val oldX: Int = scrollX
val oldY: Int = scrollY
val x: Int = scroller.currX
val y: Int = scroller.currY
if (oldX != x || oldY != y) {
val range = getScrollRange()
overScrollBy(x - oldX, y - oldY, oldX, oldY, range.width(), range.height(),
overflingDistance, overflingDistance, false)
onScrollChanged(scrollX, scrollY, oldX, oldY)
}
if (!awakenScrollBars()) {
// Keep on drawing until the animation has finished.
postInvalidateOnAnimation()
}
}
}
override fun onOverScrolled(scrollX: Int, scrollY: Int, clampedX: Boolean, clampedY: Boolean) {
scrollTo(scrollX, scrollY)
awakenScrollBars()
}
override fun onViewRemoved(child: View?) {
super.onViewRemoved(child)
val range = getScrollRange()
val viewport = Rect().apply { getDrawingRect(this) }
var dx = 0
var dy = 0
if (range.right < viewport.right) {
dx = range.right - viewport.right
}
if (range.bottom < viewport.bottom) {
dy = range.bottom - viewport.bottom
}
smoothScrollBy(dx, dy)
}
fun smoothScrollBy(dx: Int, dy: Int) {
scroller.startScroll(scrollX, scrollY, dx, dy)
postInvalidateOnAnimation()
}
private val scroller = Scroller(context)
private val gestureDetector: GestureDetectorCompat = GestureDetectorCompat(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean {
return true
}
override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean {
scroller.forceFinished(true)
scrollBy(distanceX.toInt(), distanceY.toInt())
return true
}
override fun onFling(e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean {
val bounds = getScrollRange()
scroller.forceFinished(true)
scroller.fling(scrollX, scrollY, -velocityX.toInt(), -velocityY.toInt(),
bounds.left, bounds.right-width,
bounds.top, bounds.bottom-height)
postInvalidateOnAnimation()
return true
}
})
}
| gpl-3.0 | 2f052f6d24c9d6f726bfd568465912b2 | 35.083333 | 143 | 0.647614 | 4.549912 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/customer/WCCustomerMapper.kt | 2 | 3572 | package org.wordpress.android.fluxc.model.customer
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.network.rest.wpcom.wc.customer.dto.CustomerDTO
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class WCCustomerMapper @Inject constructor() {
@Suppress("ComplexMethod")
fun mapToModel(site: SiteModel, dto: CustomerDTO): WCCustomerModel {
return WCCustomerModel().apply {
localSiteId = site.id
avatarUrl = dto.avatarUrl ?: ""
dateCreated = dto.dateCreated ?: ""
dateCreatedGmt = dto.dateCreatedGmt ?: ""
dateModified = dto.dateModified ?: ""
dateModifiedGmt = dto.dateModifiedGmt ?: ""
email = dto.email ?: ""
firstName = dto.firstName ?: ""
remoteCustomerId = dto.id ?: 0
isPayingCustomer = dto.isPayingCustomer
lastName = dto.lastName ?: ""
role = dto.role ?: ""
username = dto.username ?: ""
billingAddress1 = dto.billing?.address1 ?: ""
billingAddress2 = dto.billing?.address2 ?: ""
billingCompany = dto.billing?.company ?: ""
billingCountry = dto.billing?.country ?: ""
billingCity = dto.billing?.city ?: ""
billingEmail = dto.billing?.email ?: ""
billingFirstName = dto.billing?.firstName ?: ""
billingLastName = dto.billing?.lastName ?: ""
billingPhone = dto.billing?.phone ?: ""
billingPostcode = dto.billing?.postcode ?: ""
billingState = dto.billing?.state ?: ""
shippingAddress1 = dto.billing?.address1 ?: ""
shippingAddress2 = dto.billing?.address2 ?: ""
shippingCity = dto.billing?.city ?: ""
shippingCompany = dto.billing?.company ?: ""
shippingCountry = dto.billing?.country ?: ""
shippingFirstName = dto.billing?.firstName ?: ""
shippingLastName = dto.billing?.lastName ?: ""
shippingPostcode = dto.billing?.postcode ?: ""
shippingState = dto.billing?.state ?: ""
}
}
fun mapToDTO(model: WCCustomerModel): CustomerDTO {
val billing = CustomerDTO.Billing(
firstName = model.billingFirstName,
lastName = model.billingLastName,
company = model.billingCompany,
address1 = model.billingAddress1,
address2 = model.billingAddress2,
city = model.billingCity,
state = model.billingState,
postcode = model.billingPostcode,
country = model.billingCountry,
email = model.billingEmail,
phone = model.billingPhone
)
val shipping = CustomerDTO.Shipping(
firstName = model.billingFirstName,
lastName = model.billingLastName,
company = model.billingCompany,
address1 = model.billingAddress1,
address2 = model.billingAddress2,
city = model.billingCity,
state = model.billingState,
postcode = model.billingPostcode,
country = model.billingCountry
)
return CustomerDTO(
email = model.email,
firstName = model.firstName,
lastName = model.lastName,
username = model.username,
billing = billing,
shipping = shipping
)
}
}
| gpl-2.0 | 2047a3fe9b0d3f057f70b0483290818e | 41.023529 | 81 | 0.56495 | 5.110157 | false | false | false | false |
linuxyz/FirstExamples | src/main/kotlin/task-genericfun.kt | 1 | 852 | /**
* Created by sysop on 6/29/2017.
*/
package com.ytzb.kotlin
import kotlin.collections.*
fun <C, T:MutableCollection<C>> Collection<C>.partitionTo(left:T, right:T, pf:(C)->Boolean): Pair<T,T> {
for (ele in this) {
if (pf(ele)) {
left.add(ele)
} else {
right.add(ele)
}
}
return Pair(left, right)
}
fun partitionWordsAndLines() {
val (words, lines) = listOf("a", "a b", "c", "d e").
partitionTo(ArrayList<String>(), ArrayList()) { s -> !s.contains(" ") }
words == listOf("a", "c")
lines == listOf("a b", "d e")
}
fun partitionLettersAndOtherSymbols() {
val (letters, other) = setOf('a', '%', 'r', '}').
partitionTo(HashSet<Char>(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z'}
letters == setOf('a', 'r')
other == setOf('%', '}')
}
| gpl-2.0 | 3d008d9582aded86d2d26c77a1ae0585 | 26.483871 | 104 | 0.521127 | 3.227273 | false | false | false | false |
devmil/muzei-bingimageoftheday | app/src/main/java/de/devmil/muzei/bingimageoftheday/BingImageMetadata.kt | 1 | 1850 | /*
* Copyright 2014 Devmil Solutions
*
* 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 de.devmil.muzei.bingimageoftheday
import android.net.Uri
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by devmil on 17.02.14.
* This class represents one Bing image containing all data that this app needs
*/
class BingImageMetadata(uri: Uri, copyright: String, startDateString: String) {
var uri: Uri? = uri
var copyright: String? = copyright
var startDate: Date? = null
private fun parseStartDate(startDateString: String): Date {
val df = SimpleDateFormat("yyyyMMddHHmm", Locale.US)
df.timeZone = TimeZone.getTimeZone("GMT")
var result: Date? = null
try {
result = df.parse(startDateString)
} catch (e: ParseException) {
}
val localTime = Calendar.getInstance()
if (result == null)
return localTime.time
localTime.timeInMillis = result.time
return localTime.time
}
val copyrightOrEmpty: String
get() {
if (copyright == null)
return ""
return copyright!!
}
init {
startDate = parseStartDate(startDateString)
}
}
| apache-2.0 | 6d937a957d7ae71923c046421885ed85 | 27.365079 | 79 | 0.643243 | 4.501217 | false | true | false | false |
alygin/intellij-rust | toml/src/main/kotlin/org/toml/ide/TomlHighlighter.kt | 2 | 1848 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.toml.ide
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
import gnu.trove.THashMap
import org.toml.lang.core.lexer.TomlLexer
import org.toml.lang.core.psi.TomlTypes
class TomlHighlighter : SyntaxHighlighterBase() {
override fun getHighlightingLexer(): Lexer =
TomlLexer()
override fun getTokenHighlights(tokenType: IElementType?): Array<out TextAttributesKey> =
pack(tokenType?.let { tokenMap[it] })
private val tokenMap: Map<IElementType, TextAttributesKey> = makeTokenMap()
}
private fun makeTokenMap(): Map<IElementType, TextAttributesKey> {
val result = THashMap<IElementType, TextAttributesKey>()
result[TomlTypes.KEY] =
TextAttributesKey.createTextAttributesKey("TOML_KEY", DefaultLanguageHighlighterColors.KEYWORD)
result[TomlTypes.COMMENT] =
TextAttributesKey.createTextAttributesKey("TOML_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT)
result[TomlTypes.STRING] =
TextAttributesKey.createTextAttributesKey("TOML_STRING", DefaultLanguageHighlighterColors.STRING)
result[TomlTypes.NUMBER] =
TextAttributesKey.createTextAttributesKey("TOML_NUMBER", DefaultLanguageHighlighterColors.NUMBER)
result[TomlTypes.BOOLEAN] =
TextAttributesKey.createTextAttributesKey("TOML_BOOLEAN", DefaultLanguageHighlighterColors.PREDEFINED_SYMBOL)
result[TomlTypes.DATE] =
TextAttributesKey.createTextAttributesKey("TOML_DATE", DefaultLanguageHighlighterColors.PREDEFINED_SYMBOL)
return result
}
| mit | ab711660aaeb6971b7f577ee1d935ebc | 34.538462 | 117 | 0.78355 | 5.220339 | false | false | false | false |
italoag/qksms | presentation/src/main/java/com/moez/QKSMS/feature/conversationinfo/ConversationInfoAdapter.kt | 3 | 5991 | package com.moez.QKSMS.feature.conversationinfo
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.moez.QKSMS.common.base.QkAdapter
import com.moez.QKSMS.common.base.QkViewHolder
import com.moez.QKSMS.common.util.Colors
import com.moez.QKSMS.common.util.extensions.setTint
import com.moez.QKSMS.common.util.extensions.setVisible
import com.moez.QKSMS.extensions.isVideo
import com.moez.QKSMS.feature.conversationinfo.ConversationInfoItem.*
import com.moez.QKSMS.util.GlideApp
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.conversation_info_settings.*
import kotlinx.android.synthetic.main.conversation_media_list_item.*
import kotlinx.android.synthetic.main.conversation_recipient_list_item.*
import javax.inject.Inject
class ConversationInfoAdapter @Inject constructor(
private val context: Context,
private val colors: Colors
) : QkAdapter<ConversationInfoItem>() {
val recipientClicks: Subject<Long> = PublishSubject.create()
val recipientLongClicks: Subject<Long> = PublishSubject.create()
val themeClicks: Subject<Long> = PublishSubject.create()
val nameClicks: Subject<Unit> = PublishSubject.create()
val notificationClicks: Subject<Unit> = PublishSubject.create()
val archiveClicks: Subject<Unit> = PublishSubject.create()
val blockClicks: Subject<Unit> = PublishSubject.create()
val deleteClicks: Subject<Unit> = PublishSubject.create()
val mediaClicks: Subject<Long> = PublishSubject.create()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val inflater = LayoutInflater.from(parent.context)
return when (viewType) {
0 -> QkViewHolder(inflater.inflate(R.layout.conversation_recipient_list_item, parent, false)).apply {
itemView.setOnClickListener {
val item = getItem(adapterPosition) as? ConversationInfoRecipient
item?.value?.id?.run(recipientClicks::onNext)
}
itemView.setOnLongClickListener {
val item = getItem(adapterPosition) as? ConversationInfoRecipient
item?.value?.id?.run(recipientLongClicks::onNext)
true
}
theme.setOnClickListener {
val item = getItem(adapterPosition) as? ConversationInfoRecipient
item?.value?.id?.run(themeClicks::onNext)
}
}
1 -> QkViewHolder(inflater.inflate(R.layout.conversation_info_settings, parent, false)).apply {
groupName.clicks().subscribe(nameClicks)
notifications.clicks().subscribe(notificationClicks)
archive.clicks().subscribe(archiveClicks)
block.clicks().subscribe(blockClicks)
delete.clicks().subscribe(deleteClicks)
}
2 -> QkViewHolder(inflater.inflate(R.layout.conversation_media_list_item, parent, false)).apply {
itemView.setOnClickListener {
val item = getItem(adapterPosition) as? ConversationInfoMedia
item?.value?.id?.run(mediaClicks::onNext)
}
}
else -> throw IllegalStateException()
}
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
when (val item = getItem(position)) {
is ConversationInfoRecipient -> {
val recipient = item.value
holder.avatar.setRecipient(recipient)
holder.name.text = recipient.contact?.name ?: recipient.address
holder.address.text = recipient.address
holder.address.setVisible(recipient.contact != null)
holder.add.setVisible(recipient.contact == null)
val theme = colors.theme(recipient)
holder.theme.setTint(theme.theme)
}
is ConversationInfoSettings -> {
holder.groupName.isVisible = item.recipients.size > 1
holder.groupName.summary = item.name
holder.notifications.isEnabled = !item.blocked
holder.archive.isEnabled = !item.blocked
holder.archive.title = context.getString(when (item.archived) {
true -> R.string.info_unarchive
false -> R.string.info_archive
})
holder.block.title = context.getString(when (item.blocked) {
true -> R.string.info_unblock
false -> R.string.info_block
})
}
is ConversationInfoMedia -> {
val part = item.value
GlideApp.with(context)
.load(part.getUri())
.fitCenter()
.into(holder.thumbnail)
holder.video.isVisible = part.isVideo()
}
}
}
override fun getItemViewType(position: Int): Int {
return when (data[position]) {
is ConversationInfoRecipient -> 0
is ConversationInfoSettings -> 1
is ConversationInfoMedia -> 2
}
}
override fun areItemsTheSame(old: ConversationInfoItem, new: ConversationInfoItem): Boolean {
return when {
old is ConversationInfoRecipient && new is ConversationInfoRecipient -> {
old.value.id == new.value.id
}
old is ConversationInfoSettings && new is ConversationInfoSettings -> {
true
}
old is ConversationInfoMedia && new is ConversationInfoMedia -> {
old.value.id == new.value.id
}
else -> false
}
}
}
| gpl-3.0 | 1522e57f71c65fe64cf085fec6e85285 | 38.156863 | 113 | 0.621098 | 4.988343 | false | false | false | false |
pyamsoft/zaptorch | app/src/main/java/com/pyamsoft/zaptorch/main/MainActivity.kt | 1 | 5719 | /*
* Copyright 2020 Peter Kenji Yamanaka
*
* 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.pyamsoft.zaptorch.main
import android.os.Bundle
import androidx.activity.viewModels
import androidx.compose.foundation.layout.padding
import androidx.compose.material.SnackbarHostState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import coil.ImageLoader
import com.google.accompanist.insets.ProvideWindowInsets
import com.pyamsoft.pydroid.arch.asFactory
import com.pyamsoft.pydroid.core.requireNotNull
import com.pyamsoft.pydroid.inject.Injector
import com.pyamsoft.pydroid.ui.changelog.ChangeLogActivity
import com.pyamsoft.pydroid.ui.changelog.buildChangeLog
import com.pyamsoft.pydroid.ui.navigator.Navigator
import com.pyamsoft.pydroid.util.stableLayoutHideNavigation
import com.pyamsoft.zaptorch.BuildConfig
import com.pyamsoft.zaptorch.R
import com.pyamsoft.zaptorch.ZapTorchComponent
import com.pyamsoft.zaptorch.ZapTorchTheme
import com.pyamsoft.zaptorch.ZapTorchViewModelFactory
import com.pyamsoft.zaptorch.databinding.ActivityMainBinding
import javax.inject.Inject
class MainActivity : ChangeLogActivity() {
override val versionName: String = BuildConfig.VERSION_NAME
override val applicationIcon: Int = R.mipmap.ic_launcher
override val changelog = buildChangeLog { feature("Convert to Jetpack Compose") }
private var viewBinding: ActivityMainBinding? = null
@JvmField @Inject internal var imageLoader: ImageLoader? = null
@JvmField @Inject internal var navigator: Navigator<Unit>? = null
@JvmField @Inject internal var toolbarFactory: ZapTorchViewModelFactory? = null
@JvmField @Inject internal var factory: MainViewModel.Factory? = null
private val viewModel by viewModels<MainViewModel> { factory.requireNotNull().asFactory(this) }
private val toolbarViewModel by
viewModels<ToolbarViewModel> { toolbarFactory.requireNotNull().create(this) }
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.Theme_ZapTorch)
super.onCreate(savedInstanceState)
stableLayoutHideNavigation()
// NOTE(Peter):
// Not full Compose yet
// Compose has an issue handling Fragments.
//
// We need an AndroidView to handle a Fragment, but a Fragment outlives the Activity via the
// FragmentManager keeping state. The Compose render does not, so when an activity dies from
// configuration change, the Fragment is headless somewhere in the great beyond. This leads to
// memory leaks and other issues like Disposable hooks not being called on DisposeEffect blocks.
// To avoid these growing pains, we use an Activity layout file and then host the ComposeViews
// from it that are then used to render Activity level views. Fragment transactions happen as
// normal and then Fragments host ComposeViews too.
val binding = ActivityMainBinding.inflate(layoutInflater).apply { viewBinding = this }
setContentView(binding.root)
Injector.obtainFromApplication<ZapTorchComponent>(this)
.plusMainComponent()
.create(
this,
binding.mainFragmentContainerView.id,
)
.inject(this)
// Toolbar respects window insets and hosts Toolbar composable
binding.mainComposeToolbar.setContent {
val state by viewModel.compose()
val theme = state.theme
ZapTorchTheme(
theme = theme,
) {
ProvideWindowInsets {
MainAppBar(
onHeightMeasured = { toolbarViewModel.handleSetTopBarHeight(it) },
)
}
}
}
// Snackbar respects window offsets and hosts snackbar composables
// Because these are not in a nice Scaffold, we cannot take advantage of Coordinator style
// actions (a FAB will not move out of the way for example)
binding.mainComposeSnackbar.setContent {
val state by viewModel.compose()
val snackbarHostState = remember { SnackbarHostState() }
val theme = state.theme
ZapTorchTheme(
theme = theme,
) {
ProvideWindowInsets {
MainBottomAction(
modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp),
state = state,
imageLoader = imageLoader.requireNotNull(),
onClickAccessibilitySettings = { AccessibilityRequestDialog.show(this) },
onClickHowTo = { HowToDialog.show(this) },
onHeightMeasured = { toolbarViewModel.handleSetBottomSpaceHeight(it) },
)
RatingScreen(
snackbarHostState = snackbarHostState,
)
VersionScreen(
snackbarHostState = snackbarHostState,
)
}
}
}
viewModel.handleSyncDarkTheme(this)
navigator.requireNotNull().restore(savedInstanceState)
}
override fun onDestroy() {
super.onDestroy()
viewBinding?.apply {
this.mainComposeSnackbar.disposeComposition()
this.mainComposeToolbar.disposeComposition()
}
toolbarFactory = null
factory = null
navigator = null
viewBinding = null
imageLoader = null
}
}
| apache-2.0 | 40d8d6b6c1eafff4bb4bac049a85d115 | 35.426752 | 100 | 0.726176 | 4.757903 | false | false | false | false |
mttkay/RxJava | language-adaptors/rxjava-kotlin/src/test/kotlin/rx/lang/kotlin/ExtensionTests.kt | 1 | 9759 | /**
* Copyright 2013 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 rx.lang.kotlin
import rx.Observable
import org.junit.Test
import org.mockito.Mockito.*
import org.mockito.Matchers.*
import org.junit.Assert.*
import rx.Notification
import kotlin.concurrent.thread
import rx.Subscriber
/**
* This class contains tests using the extension functions provided by the language adaptor.
*/
public class ExtensionTests : KotlinTests() {
[Test]
public fun testCreate() {
{(subscriber: Subscriber<in String>) ->
subscriber.onNext("Hello")
subscriber.onCompleted()
}.asObservable().subscribe { result ->
a!!.received(result)
}
verify(a, times(1))!!.received("Hello")
}
[Test]
public fun testFilter() {
listOf(1, 2, 3).asObservable().filter { it!! >= 2 }!!.subscribe(received())
verify(a, times(0))!!.received(1);
verify(a, times(1))!!.received(2);
verify(a, times(1))!!.received(3);
}
[Test]
public fun testLast() {
assertEquals("three", listOf("one", "two", "three").asObservable().toBlocking()!!.last())
}
[Test]
public fun testLastWithPredicate() {
assertEquals("two", listOf("one", "two", "three").asObservable().toBlocking()!!.last { x -> x!!.length == 3 })
}
[Test]
public fun testMap1() {
1.asObservable().map { v -> "hello_$v" }!!.subscribe((received()))
verify(a, times(1))!!.received("hello_1")
}
[Test]
public fun testMap2() {
listOf(1, 2, 3).asObservable().map { v -> "hello_$v" }!!.subscribe((received()))
verify(a, times(1))!!.received("hello_1")
verify(a, times(1))!!.received("hello_2")
verify(a, times(1))!!.received("hello_3")
}
[Test]
public fun testMaterialize() {
listOf(1, 2, 3).asObservable().materialize()!!.subscribe((received()))
verify(a, times(4))!!.received(any(javaClass<Notification<Int>>()))
verify(a, times(0))!!.error(any(javaClass<Exception>()))
}
[Test]
public fun testMergeDelayError() {
Triple(listOf(1, 2, 3).asObservable(),
Triple(6.asObservable(),
NullPointerException().asObservable<Int>(),
7.asObservable()
).merge(),
listOf(4, 5).asObservable()
).mergeDelayError().subscribe(received(), { e -> a!!.error(e) })
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(1))!!.received(3)
verify(a, times(1))!!.received(4)
verify(a, times(1))!!.received(5)
verify(a, times(1))!!.received(6)
verify(a, times(0))!!.received(7)
verify(a, times(1))!!.error(any(javaClass<NullPointerException>()))
}
[Test]
public fun testMerge() {
Triple(listOf(1, 2, 3).asObservable(),
Triple(6.asObservable(),
NullPointerException().asObservable<Int>(),
7.asObservable()
).merge(),
listOf(4, 5).asObservable()
).merge().subscribe(received(), { e -> a!!.error(e) })
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(1))!!.received(3)
verify(a, times(0))!!.received(4)
verify(a, times(0))!!.received(5)
verify(a, times(1))!!.received(6)
verify(a, times(0))!!.received(7)
verify(a, times(1))!!.error(any(javaClass<NullPointerException>()))
}
[Test]
public fun testScriptWithMaterialize() {
TestFactory().observable.materialize()!!.subscribe((received()))
verify(a, times(2))!!.received(any(javaClass<Notification<Int>>()))
}
[Test]
public fun testScriptWithMerge() {
val factory = TestFactory()
(factory.observable to factory.observable).merge().subscribe((received()))
verify(a, times(1))!!.received("hello_1")
verify(a, times(1))!!.received("hello_2")
}
[Test]
public fun testFromWithIterable() {
assertEquals(5, listOf(1, 2, 3, 4, 5).asObservable().count()!!.toBlocking()!!.single())
}
[Test]
public fun testStartWith() {
val list = listOf(10, 11, 12, 13, 14)
val startList = listOf(1, 2, 3, 4, 5)
assertEquals(6, list.asObservable().startWith(0)!!.count()!!.toBlocking()!!.single())
assertEquals(10, list.asObservable().startWith(startList)!!.count()!!.toBlocking()!!.single())
}
[Test]
public fun testScriptWithOnNext() {
TestFactory().observable.subscribe((received()))
verify(a, times(1))!!.received("hello_1")
}
[Test]
public fun testSkipTake() {
Triple(1, 2, 3).asObservable().skip(1)!!.take(1)!!.subscribe(received())
verify(a, times(0))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(0))!!.received(3)
}
[Test]
public fun testSkip() {
Triple(1, 2, 3).asObservable().skip(2)!!.subscribe(received())
verify(a, times(0))!!.received(1)
verify(a, times(0))!!.received(2)
verify(a, times(1))!!.received(3)
}
[Test]
public fun testTake() {
Triple(1, 2, 3).asObservable().take(2)!!.subscribe(received())
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(0))!!.received(3)
}
[Test]
public fun testTakeLast() {
TestFactory().observable.takeLast(1)!!.subscribe((received()))
verify(a, times(1))!!.received("hello_1")
}
[Test]
public fun testTakeWhile() {
Triple(1, 2, 3).asObservable().takeWhile { x -> x!! < 3 }!!.subscribe(received())
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(0))!!.received(3)
}
[Test]
public fun testTakeWhileWithIndex() {
Triple(1, 2, 3).asObservable().takeWhileWithIndex { x, i -> i!! < 2 }!!.subscribe(received())
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(0))!!.received(3)
}
[Test]
public fun testToSortedList() {
TestFactory().numbers.toSortedList()!!.subscribe(received())
verify(a, times(1))!!.received(listOf(1, 2, 3, 4, 5))
}
[Test]
public fun testForEach() {
asyncObservable.asObservable().toBlocking()!!.forEach(received())
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(1))!!.received(3)
}
[Test(expected = javaClass<RuntimeException>())]
public fun testForEachWithError() {
asyncObservable.asObservable().toBlocking()!!.forEach { throw RuntimeException("err") }
fail("we expect an exception to be thrown")
}
[Test]
public fun testLastOrDefault() {
assertEquals("two", ("one" to"two").asObservable().toBlocking()!!.lastOrDefault("default") { x -> x!!.length == 3 })
assertEquals("default", ("one" to"two").asObservable().toBlocking()!!.lastOrDefault("default") { x -> x!!.length > 3 })
}
[Test]
public fun testDefer() {
{ (1 to 2).asObservable() }.defer().subscribe(received())
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
}
[Test]
public fun testAll() {
Triple(1, 2, 3).asObservable().all { x -> x!! > 0 }!!.subscribe(received())
verify(a, times(1))!!.received(true)
}
[Test]
public fun testZip() {
val o1 = Triple(1, 2, 3).asObservable()
val o2 = Triple(4, 5, 6).asObservable()
val o3 = Triple(7, 8, 9).asObservable()
val values = Observable.zip(o1, o2, o3) { a, b, c -> listOf(a, b, c) }!!.toList()!!.toBlocking()!!.single()!!
assertEquals(listOf(1, 4, 7), values[0])
assertEquals(listOf(2, 5, 8), values[1])
assertEquals(listOf(3, 6, 9), values[2])
}
val funOnSubscribe: (Int, Subscriber<in String>) -> Unit = { counter, subscriber ->
subscriber.onNext("hello_$counter")
subscriber.onCompleted()
}
val asyncObservable: (Subscriber<in Int>) -> Unit = { subscriber ->
thread {
Thread.sleep(50)
subscriber.onNext(1)
subscriber.onNext(2)
subscriber.onNext(3)
subscriber.onCompleted()
}
}
/**
* Copied from (funKTionale)[https://github.com/MarioAriasC/funKTionale/blob/master/src/main/kotlin/org/funktionale/partials/namespace.kt]
*/
public fun <P1, P2, R> Function2<P1, P2, R>.partially1(p1: P1): (P2) -> R {
return {(p2: P2) -> this(p1, p2) }
}
inner public class TestFactory() {
var counter = 1
val numbers: Observable<Int>
get(){
return listOf(1, 3, 2, 5, 4).asObservable()
}
val onSubscribe: (Subscriber<in String>) -> Unit
get(){
return funOnSubscribe.partially1(counter++)
}
val observable: Observable<String>
get(){
return onSubscribe.asObservable()
}
}
} | apache-2.0 | 8d0a55f2d6e2e60696a1368a7033a5a6 | 31.861953 | 142 | 0.57055 | 3.920852 | false | true | false | false |
abreslav/androidVNC | androidVNC/src/com/example/adsl/ListenerHelpers.kt | 1 | 22654 | package com.example.adsl
import android.view.ContextMenu
import android.view.ViewGroup
import android.content.Context
import android.widget.*
import android.app.AlertDialog
import android.widget.LinearLayout.LayoutParams
import android.view.View
fun android.app.SearchManager.onDismiss(l: () -> Unit) {
setOnDismissListener(l)
}
fun android.app.SearchManager.onCancel(l: () -> Unit) {
setOnCancelListener(l)
}
fun android.app.AlertDialog.Builder.onCancel(l: (android.content.DialogInterface?) -> Unit) {
setOnCancelListener(l)
}
fun android.app.AlertDialog.Builder.onKey(l: (android.content.DialogInterface?, Int, android.view.KeyEvent?) -> Boolean) {
setOnKeyListener(l)
}
class __BuilderOnItemSelectedListener {
var _onItemSelected: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit = { p0, p1, p2, p3 -> }
fun onItemSelected(f : (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit) { _onItemSelected = f }
var _onNothingSelected: (p0: android.widget.AdapterView<*>?) -> Unit = { p0 -> }
fun onNothingSelected(f : (p0: android.widget.AdapterView<*>?) -> Unit) { _onNothingSelected = f }
}
fun android.app.AlertDialog.Builder.onItemSelected(init: __BuilderOnItemSelectedListener.() -> Unit) {
val wrapper = __BuilderOnItemSelectedListener()
wrapper.init()
val listener = object: android.widget.AdapterView.OnItemSelectedListener {
override fun onItemSelected(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long): Unit {
return wrapper._onItemSelected(p0!!, p1!!, p2, p3)
}
override fun onNothingSelected(p0: android.widget.AdapterView<*>?): Unit {
return wrapper._onNothingSelected(p0!!)
}
}
setOnItemSelectedListener(listener)
}
fun android.app.Dialog.onCancel(l: (android.content.DialogInterface?) -> Unit) {
setOnCancelListener(l)
}
fun android.app.Dialog.onDismiss(l: (android.content.DialogInterface?) -> Unit) {
setOnDismissListener(l)
}
fun android.app.Dialog.onShow(l: (android.content.DialogInterface?) -> Unit) {
setOnShowListener(l)
}
fun android.app.Dialog.onKey(l: (android.content.DialogInterface?, Int, android.view.KeyEvent?) -> Boolean) {
setOnKeyListener(l)
}
fun android.preference.Preference.onPreferenceChange(l: (android.preference.Preference?, Any?) -> Boolean) {
setOnPreferenceChangeListener(l)
}
fun android.preference.Preference.onPreferenceClick(l: (android.preference.Preference?) -> Boolean) {
setOnPreferenceClickListener(l)
}
fun android.os.CancellationSignal.onCancel(l: () -> Unit) {
setOnCancelListener(l)
}
fun android.graphics.SurfaceTexture.onFrameAvailable(l: (android.graphics.SurfaceTexture?) -> Unit) {
setOnFrameAvailableListener(l)
}
fun android.speech.tts.TextToSpeech.onUtteranceCompleted(l: (String?) -> Unit) {
setOnUtteranceCompletedListener(l)
}
class __TextToSpeechUtteranceProgressListener {
var _onStart: (p0: String?) -> Unit = { p0 -> }
fun onStart(f : (p0: String?) -> Unit) { _onStart = f }
var _onDone: (p0: String?) -> Unit = { p0 -> }
fun onDone(f : (p0: String?) -> Unit) { _onDone = f }
var _onError: (p0: String?) -> Unit = { p0 -> }
fun onError(f : (p0: String?) -> Unit) { _onError = f }
}
fun android.speech.tts.TextToSpeech.onUtteranceProgress(init: __TextToSpeechUtteranceProgressListener.() -> Unit) {
val wrapper = __TextToSpeechUtteranceProgressListener()
wrapper.init()
val listener = object: android.speech.tts.UtteranceProgressListener() {
override fun onStart(p0: String?): Unit {
return wrapper._onStart(p0!!)
}
override fun onDone(p0: String?): Unit {
return wrapper._onDone(p0!!)
}
override fun onError(p0: String?): Unit {
return wrapper._onError(p0!!)
}
}
setOnUtteranceProgressListener(listener)
}
fun android.drm.DrmManagerClient.onInfo(l: (android.drm.DrmManagerClient?, android.drm.DrmInfoEvent?) -> Unit) {
setOnInfoListener(l)
}
fun android.drm.DrmManagerClient.onEvent(l: (android.drm.DrmManagerClient?, android.drm.DrmEvent?) -> Unit) {
setOnEventListener(l)
}
fun android.drm.DrmManagerClient.onError(l: (android.drm.DrmManagerClient?, android.drm.DrmErrorEvent?) -> Unit) {
setOnErrorListener(l)
}
fun android.media.SoundPool.onLoadComplete(l: (android.media.SoundPool?, Int, Int) -> Unit) {
setOnLoadCompleteListener(l)
}
fun android.media.MediaRecorder.onError(l: (android.media.MediaRecorder?, Int, Int) -> Unit) {
setOnErrorListener(l)
}
fun android.media.MediaRecorder.onInfo(l: (android.media.MediaRecorder?, Int, Int) -> Unit) {
setOnInfoListener(l)
}
fun android.media.MediaPlayer.onPrepared(l: (android.media.MediaPlayer?) -> Unit) {
setOnPreparedListener(l)
}
fun android.media.MediaPlayer.onCompletion(l: (android.media.MediaPlayer?) -> Unit) {
setOnCompletionListener(l)
}
fun android.media.MediaPlayer.onBufferingUpdate(l: (android.media.MediaPlayer?, Int) -> Unit) {
setOnBufferingUpdateListener(l)
}
fun android.media.MediaPlayer.onSeekComplete(l: (android.media.MediaPlayer?) -> Unit) {
setOnSeekCompleteListener(l)
}
fun android.media.MediaPlayer.onVideoSizeChanged(l: (android.media.MediaPlayer?, Int, Int) -> Unit) {
setOnVideoSizeChangedListener(l)
}
fun android.media.MediaPlayer.onTimedText(l: (android.media.MediaPlayer?, android.media.TimedText?) -> Unit) {
setOnTimedTextListener(l)
}
fun android.media.MediaPlayer.onError(l: (android.media.MediaPlayer?, Int, Int) -> Boolean) {
setOnErrorListener(l)
}
fun android.media.MediaPlayer.onInfo(l: (android.media.MediaPlayer?, Int, Int) -> Boolean) {
setOnInfoListener(l)
}
fun android.view.MenuItem.onMenuItemClick(l: (android.view.MenuItem?) -> Boolean) {
setOnMenuItemClickListener(l)
}
class __MenuItemOnActionExpandListener {
var _onMenuItemActionExpand: (p0: android.view.MenuItem?) -> Boolean = { p0 -> false }
fun onMenuItemActionExpand(f : (p0: android.view.MenuItem?) -> Boolean) { _onMenuItemActionExpand = f }
var _onMenuItemActionCollapse: (p0: android.view.MenuItem?) -> Boolean = { p0 -> false }
fun onMenuItemActionCollapse(f : (p0: android.view.MenuItem?) -> Boolean) { _onMenuItemActionCollapse = f }
}
fun android.view.MenuItem.onActionExpand(init: __MenuItemOnActionExpandListener.() -> Unit) {
val wrapper = __MenuItemOnActionExpandListener()
wrapper.init()
val listener = object: android.view.MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(p0: android.view.MenuItem?): Boolean {
return wrapper._onMenuItemActionExpand(p0!!)
}
override fun onMenuItemActionCollapse(p0: android.view.MenuItem?): Boolean {
return wrapper._onMenuItemActionCollapse(p0!!)
}
}
setOnActionExpandListener(listener)
}
fun android.view.View.onFocusChange(l: (android.view.View?, Boolean) -> Unit) {
setOnFocusChangeListener(l)
}
fun android.view.View.onClick(l: (android.view.View?) -> Unit) {
setOnClickListener(l)
}
fun android.view.View.onLongClick(l: (android.view.View?) -> Boolean) {
setOnLongClickListener(l)
}
fun android.view.View.onCreateContextMenu(l: (android.view.ContextMenu?, android.view.View?, android.view.ContextMenu.ContextMenuInfo?) -> Unit) {
setOnCreateContextMenuListener(l)
}
fun android.view.View.onKey(l: (android.view.View?, Int, android.view.KeyEvent?) -> Boolean) {
setOnKeyListener(l)
}
fun android.view.View.onTouch(l: (android.view.View?, android.view.MotionEvent?) -> Boolean) {
setOnTouchListener(l)
}
fun android.view.View.onGenericMotion(l: (android.view.View?, android.view.MotionEvent?) -> Boolean) {
setOnGenericMotionListener(l)
}
fun android.view.View.onHover(l: (android.view.View?, android.view.MotionEvent?) -> Boolean) {
setOnHoverListener(l)
}
fun android.view.View.onDrag(l: (android.view.View?, android.view.DragEvent?) -> Boolean) {
setOnDragListener(l)
}
fun android.view.View.onSystemUiVisibilityChange(l: (Int) -> Unit) {
setOnSystemUiVisibilityChangeListener(l)
}
class __GestureDetectorOnDoubleTapListener {
var _onSingleTapConfirmed: (p0: android.view.MotionEvent?) -> Boolean = { p0 -> false }
fun onSingleTapConfirmed(f : (p0: android.view.MotionEvent?) -> Boolean) { _onSingleTapConfirmed = f }
var _onDoubleTap: (p0: android.view.MotionEvent?) -> Boolean = { p0 -> false }
fun onDoubleTap(f : (p0: android.view.MotionEvent?) -> Boolean) { _onDoubleTap = f }
var _onDoubleTapEvent: (p0: android.view.MotionEvent?) -> Boolean = { p0 -> false }
fun onDoubleTapEvent(f : (p0: android.view.MotionEvent?) -> Boolean) { _onDoubleTapEvent = f }
}
fun android.view.GestureDetector.onDoubleTap(init: __GestureDetectorOnDoubleTapListener.() -> Unit) {
val wrapper = __GestureDetectorOnDoubleTapListener()
wrapper.init()
val listener = object: android.view.GestureDetector.OnDoubleTapListener {
override fun onSingleTapConfirmed(p0: android.view.MotionEvent?): Boolean {
return wrapper._onSingleTapConfirmed(p0!!)
}
override fun onDoubleTap(p0: android.view.MotionEvent?): Boolean {
return wrapper._onDoubleTap(p0!!)
}
override fun onDoubleTapEvent(p0: android.view.MotionEvent?): Boolean {
return wrapper._onDoubleTapEvent(p0!!)
}
}
setOnDoubleTapListener(listener)
}
fun android.widget.PopupMenu.onMenuItemClick(l: (android.view.MenuItem?) -> Boolean) {
setOnMenuItemClickListener(l)
}
fun android.widget.PopupMenu.onDismiss(l: (android.widget.PopupMenu?) -> Unit) {
setOnDismissListener(l)
}
fun android.widget.ListPopupWindow.onItemClick(l: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit) {
setOnItemClickListener(l)
}
class __ListPopupWindowOnItemSelectedListener {
var _onItemSelected: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit = { p0, p1, p2, p3 -> }
fun onItemSelected(f : (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit) { _onItemSelected = f }
var _onNothingSelected: (p0: android.widget.AdapterView<*>?) -> Unit = { p0 -> }
fun onNothingSelected(f : (p0: android.widget.AdapterView<*>?) -> Unit) { _onNothingSelected = f }
}
fun android.widget.ListPopupWindow.onItemSelected(init: __ListPopupWindowOnItemSelectedListener.() -> Unit) {
val wrapper = __ListPopupWindowOnItemSelectedListener()
wrapper.init()
val listener = object: android.widget.AdapterView.OnItemSelectedListener {
override fun onItemSelected(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long): Unit {
return wrapper._onItemSelected(p0!!, p1!!, p2, p3)
}
override fun onNothingSelected(p0: android.widget.AdapterView<*>?): Unit {
return wrapper._onNothingSelected(p0!!)
}
}
setOnItemSelectedListener(listener)
}
fun android.widget.ListPopupWindow.onDismiss(l: () -> Unit) {
setOnDismissListener(l)
}
class __ZoomButtonsControllerOnZoomListener {
var _onVisibilityChanged: (p0: Boolean) -> Unit = { p0 -> }
fun onVisibilityChanged(f : (p0: Boolean) -> Unit) { _onVisibilityChanged = f }
var _onZoom: (p0: Boolean) -> Unit = { p0 -> }
fun onZoom(f : (p0: Boolean) -> Unit) { _onZoom = f }
}
fun android.widget.ZoomButtonsController.onZoom(init: __ZoomButtonsControllerOnZoomListener.() -> Unit) {
val wrapper = __ZoomButtonsControllerOnZoomListener()
wrapper.init()
val listener = object: android.widget.ZoomButtonsController.OnZoomListener {
override fun onVisibilityChanged(p0: Boolean): Unit {
return wrapper._onVisibilityChanged(p0)
}
override fun onZoom(p0: Boolean): Unit {
return wrapper._onZoom(p0)
}
}
setOnZoomListener(listener)
}
fun android.widget.PopupWindow.onDismiss(l: () -> Unit) {
setOnDismissListener(l)
}
fun android.widget.ShareActionProvider.onShareTargetSelected(l: (android.widget.ShareActionProvider?, android.content.Intent?) -> Boolean) {
setOnShareTargetSelectedListener(l)
}
class __KeyboardViewOnKeyboardActionListener {
var _onPress: (p0: Int) -> Unit = { p0 -> }
fun onPress(f : (p0: Int) -> Unit) { _onPress = f }
var _onRelease: (p0: Int) -> Unit = { p0 -> }
fun onRelease(f : (p0: Int) -> Unit) { _onRelease = f }
var _onKey: (p0: Int, p1: IntArray?) -> Unit = { p0, p1 -> }
fun onKey(f : (p0: Int, p1: IntArray?) -> Unit) { _onKey = f }
var _onText: (p0: CharSequence?) -> Unit = { p0 -> }
fun onText(f : (p0: CharSequence?) -> Unit) { _onText = f }
var _swipeLeft: () -> Unit = { -> }
fun swipeLeft(f : () -> Unit) { _swipeLeft = f }
var _swipeRight: () -> Unit = { -> }
fun swipeRight(f : () -> Unit) { _swipeRight = f }
var _swipeDown: () -> Unit = { -> }
fun swipeDown(f : () -> Unit) { _swipeDown = f }
var _swipeUp: () -> Unit = { -> }
fun swipeUp(f : () -> Unit) { _swipeUp = f }
}
fun android.view.ViewStub.onInflate(l: (android.view.ViewStub?, android.view.View?) -> Unit) {
setOnInflateListener(l)
}
class __ViewGroupOnHierarchyChangeListener {
var _onChildViewAdded: (p0: android.view.View?, p1: android.view.View?) -> Unit = { p0, p1 -> }
fun onChildViewAdded(f : (p0: android.view.View?, p1: android.view.View?) -> Unit) { _onChildViewAdded = f }
var _onChildViewRemoved: (p0: android.view.View?, p1: android.view.View?) -> Unit = { p0, p1 -> }
fun onChildViewRemoved(f : (p0: android.view.View?, p1: android.view.View?) -> Unit) { _onChildViewRemoved = f }
}
fun android.widget.TextView.onEditorAction(l: (android.widget.TextView?, Int, android.view.KeyEvent?) -> Boolean) {
setOnEditorActionListener(l)
}
fun android.app.FragmentBreadCrumbs.onBreadCrumbClick(l: (android.app.FragmentManager.BackStackEntry?, Int) -> Boolean) {
setOnBreadCrumbClickListener(l)
}
fun android.widget.SlidingDrawer.onDrawerOpen(l: () -> Unit) {
setOnDrawerOpenListener(l)
}
fun android.widget.SlidingDrawer.onDrawerClose(l: () -> Unit) {
setOnDrawerCloseListener(l)
}
class __SlidingDrawerOnDrawerScrollListener {
var _onScrollStarted: () -> Unit = { -> }
fun onScrollStarted(f : () -> Unit) { _onScrollStarted = f }
var _onScrollEnded: () -> Unit = { -> }
fun onScrollEnded(f : () -> Unit) { _onScrollEnded = f }
}
fun android.widget.AdapterView<out android.widget.Adapter?>.onItemClick(l: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit) {
setOnItemClickListener(l)
}
fun android.widget.AdapterView<out android.widget.Adapter?>.onItemLongClick(l: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Boolean) {
setOnItemLongClickListener(l)
}
class __AdapterViewOnItemSelectedListener {
var _onItemSelected: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit = { p0, p1, p2, p3 -> }
fun onItemSelected(f : (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit) { _onItemSelected = f }
var _onNothingSelected: (p0: android.widget.AdapterView<*>?) -> Unit = { p0 -> }
fun onNothingSelected(f : (p0: android.widget.AdapterView<*>?) -> Unit) { _onNothingSelected = f }
}
fun android.widget.AdapterView<out android.widget.Adapter?>.onClick(l: (android.view.View?) -> Unit) {
setOnClickListener(l)
}
fun android.widget.VideoView.onPrepared(l: (android.media.MediaPlayer?) -> Unit) {
setOnPreparedListener(l)
}
fun android.widget.VideoView.onCompletion(l: (android.media.MediaPlayer?) -> Unit) {
setOnCompletionListener(l)
}
fun android.widget.VideoView.onError(l: (android.media.MediaPlayer?, Int, Int) -> Boolean) {
setOnErrorListener(l)
}
fun android.widget.Chronometer.onChronometerTick(l: (android.widget.Chronometer?) -> Unit) {
setOnChronometerTickListener(l)
}
fun android.widget.CalendarView.onDateChange(l: (android.widget.CalendarView?, Int, Int, Int) -> Unit) {
setOnDateChangeListener(l)
}
fun android.widget.TimePicker.onTimeChanged(l: (android.widget.TimePicker?, Int, Int) -> Unit) {
setOnTimeChangedListener(l)
}
fun android.widget.TabHost.onTabChanged(l: (String?) -> Unit) {
setOnTabChangedListener(l)
}
class __AbsListViewOnScrollListener {
var _onScrollStateChanged: (p0: android.widget.AbsListView?, p1: Int) -> Unit = { p0, p1 -> }
fun onScrollStateChanged(f : (p0: android.widget.AbsListView?, p1: Int) -> Unit) { _onScrollStateChanged = f }
var _onScroll: (p0: android.widget.AbsListView?, p1: Int, p2: Int, p3: Int) -> Unit = { p0, p1, p2, p3 -> }
fun onScroll(f : (p0: android.widget.AbsListView?, p1: Int, p2: Int, p3: Int) -> Unit) { _onScroll = f }
}
class __TableLayoutOnHierarchyChangeListener {
var _onChildViewAdded: (p0: android.view.View?, p1: android.view.View?) -> Unit = { p0, p1 -> }
fun onChildViewAdded(f : (p0: android.view.View?, p1: android.view.View?) -> Unit) { _onChildViewAdded = f }
var _onChildViewRemoved: (p0: android.view.View?, p1: android.view.View?) -> Unit = { p0, p1 -> }
fun onChildViewRemoved(f : (p0: android.view.View?, p1: android.view.View?) -> Unit) { _onChildViewRemoved = f }
}
class __TableRowOnHierarchyChangeListener {
var _onChildViewAdded: (p0: android.view.View?, p1: android.view.View?) -> Unit = { p0, p1 -> }
fun onChildViewAdded(f : (p0: android.view.View?, p1: android.view.View?) -> Unit) { _onChildViewAdded = f }
var _onChildViewRemoved: (p0: android.view.View?, p1: android.view.View?) -> Unit = { p0, p1 -> }
fun onChildViewRemoved(f : (p0: android.view.View?, p1: android.view.View?) -> Unit) { _onChildViewRemoved = f }
}
fun android.widget.NumberPicker.onValueChanged(l: (android.widget.NumberPicker?, Int, Int) -> Unit) {
setOnValueChangedListener(l)
}
fun android.widget.NumberPicker.onScroll(l: (android.widget.NumberPicker?, Int) -> Unit) {
setOnScrollListener(l)
}
class __RadioGroupOnHierarchyChangeListener {
var _onChildViewAdded: (p0: android.view.View?, p1: android.view.View?) -> Unit = { p0, p1 -> }
fun onChildViewAdded(f : (p0: android.view.View?, p1: android.view.View?) -> Unit) { _onChildViewAdded = f }
var _onChildViewRemoved: (p0: android.view.View?, p1: android.view.View?) -> Unit = { p0, p1 -> }
fun onChildViewRemoved(f : (p0: android.view.View?, p1: android.view.View?) -> Unit) { _onChildViewRemoved = f }
}
fun android.widget.RadioGroup.onCheckedChange(l: (android.widget.RadioGroup?, Int) -> Unit) {
setOnCheckedChangeListener(l)
}
fun android.widget.ZoomControls.onZoomInClick(l: (android.view.View?) -> Unit) {
setOnZoomInClickListener(l)
}
fun android.widget.ZoomControls.onZoomOutClick(l: (android.view.View?) -> Unit) {
setOnZoomOutClickListener(l)
}
class __SearchViewOnQueryTextListener {
var _onQueryTextSubmit: (p0: String?) -> Boolean = { p0 -> false }
fun onQueryTextSubmit(f : (p0: String?) -> Boolean) { _onQueryTextSubmit = f }
var _onQueryTextChange: (p0: String?) -> Boolean = { p0 -> false }
fun onQueryTextChange(f : (p0: String?) -> Boolean) { _onQueryTextChange = f }
}
fun android.widget.SearchView.onClose(l: () -> Boolean) {
setOnCloseListener(l)
}
fun android.widget.SearchView.onQueryTextFocusChange(l: (android.view.View?, Boolean) -> Unit) {
setOnQueryTextFocusChangeListener(l)
}
class __SearchViewOnSuggestionListener {
var _onSuggestionSelect: (p0: Int) -> Boolean = { p0 -> false }
fun onSuggestionSelect(f : (p0: Int) -> Boolean) { _onSuggestionSelect = f }
var _onSuggestionClick: (p0: Int) -> Boolean = { p0 -> false }
fun onSuggestionClick(f : (p0: Int) -> Boolean) { _onSuggestionClick = f }
}
fun android.widget.SearchView.onSearchClick(l: (android.view.View?) -> Unit) {
setOnSearchClickListener(l)
}
fun android.widget.CompoundButton.onCheckedChange(l: (android.widget.CompoundButton?, Boolean) -> Unit) {
setOnCheckedChangeListener(l)
}
fun android.widget.AutoCompleteTextView.onClick(l: (android.view.View?) -> Unit) {
setOnClickListener(l)
}
fun android.widget.AutoCompleteTextView.onItemClick(l: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit) {
setOnItemClickListener(l)
}
class __AutoCompleteTextViewOnItemSelectedListener {
var _onItemSelected: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit = { p0, p1, p2, p3 -> }
fun onItemSelected(f : (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit) { _onItemSelected = f }
var _onNothingSelected: (p0: android.widget.AdapterView<*>?) -> Unit = { p0 -> }
fun onNothingSelected(f : (p0: android.widget.AdapterView<*>?) -> Unit) { _onNothingSelected = f }
}
class __SeekBarOnSeekBarChangeListener {
var _onProgressChanged: (p0: android.widget.SeekBar?, p1: Int, p2: Boolean) -> Unit = { p0, p1, p2 -> }
fun onProgressChanged(f : (p0: android.widget.SeekBar?, p1: Int, p2: Boolean) -> Unit) { _onProgressChanged = f }
var _onStartTrackingTouch: (p0: android.widget.SeekBar?) -> Unit = { p0 -> }
fun onStartTrackingTouch(f : (p0: android.widget.SeekBar?) -> Unit) { _onStartTrackingTouch = f }
var _onStopTrackingTouch: (p0: android.widget.SeekBar?) -> Unit = { p0 -> }
fun onStopTrackingTouch(f : (p0: android.widget.SeekBar?) -> Unit) { _onStopTrackingTouch = f }
}
fun android.widget.RatingBar.onRatingBarChange(l: (android.widget.RatingBar?, Float, Boolean) -> Unit) {
setOnRatingBarChangeListener(l)
}
fun android.widget.Spinner.onItemClick(l: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit) {
setOnItemClickListener(l)
}
fun android.widget.ExpandableListView.onItemClick(l: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit) {
setOnItemClickListener(l)
}
fun android.widget.ExpandableListView.onGroupCollapse(l: (Int) -> Unit) {
setOnGroupCollapseListener(l)
}
fun android.widget.ExpandableListView.onGroupExpand(l: (Int) -> Unit) {
setOnGroupExpandListener(l)
}
fun android.widget.ExpandableListView.onGroupClick(l: (android.widget.ExpandableListView?, android.view.View?, Int, Long) -> Boolean) {
setOnGroupClickListener(l)
}
fun android.widget.ExpandableListView.onChildClick(l: (android.widget.ExpandableListView?, android.view.View?, Int, Int, Long) -> Boolean) {
setOnChildClickListener(l)
}
| gpl-2.0 | 1f9f8e1c9f4d96916e4eaa0e028e09d5 | 39.965642 | 156 | 0.690695 | 3.617116 | false | false | false | false |
vilnius/tvarkau-vilniu | app/src/main/java/lt/vilnius/tvarkau/fragments/MultipleProblemsMapFragment.kt | 1 | 4835 | package lt.vilnius.tvarkau.fragments
import android.location.Location
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.Marker
import kotlinx.android.synthetic.main.fragment_map_fragment.*
import kotlinx.android.synthetic.main.loading_indicator.*
import lt.vilnius.tvarkau.R
import lt.vilnius.tvarkau.activity.ActivityConstants
import lt.vilnius.tvarkau.entity.Problem
import lt.vilnius.tvarkau.entity.ReportEntity
import lt.vilnius.tvarkau.extensions.gone
import lt.vilnius.tvarkau.extensions.visible
import lt.vilnius.tvarkau.fragments.interactors.MultipleReportsMapInteractor
import lt.vilnius.tvarkau.fragments.presenters.MultipleReportsMapPresenter
import lt.vilnius.tvarkau.fragments.presenters.MultipleReportsMapPresenterImpl
import lt.vilnius.tvarkau.fragments.views.MultipleProblemsMapView
import javax.inject.Inject
@Screen(
titleRes = R.string.title_problems_map,
trackingScreenName = ActivityConstants.SCREEN_ALL_REPORTS_MAP
)
class MultipleProblemsMapFragment : BaseMapFragment(),
MultipleProblemsMapView,
GoogleMap.OnInfoWindowClickListener,
GoogleMap.OnInfoWindowCloseListener {
@Inject
internal lateinit var interactor: MultipleReportsMapInteractor
private val presenter: MultipleReportsMapPresenter by lazy {
MultipleReportsMapPresenterImpl(
interactor,
uiScheduler,
connectivityProvider,
this
)
}
private var zoomedToMyLocation = false
private var toast: Snackbar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
savedInstanceState?.let {
zoomedToMyLocation = it.getBoolean(EXTRA_ZOOMED_TO_MY_LOCATION)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.report_filter, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_action_filter -> {
navigationManager.navigateToReportsMapFilter()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun addMarkers(reports: List<Problem>) {
populateMarkers(reports)
}
override fun showError() {
Toast.makeText(context, R.string.error_no_problems_in_list, Toast.LENGTH_SHORT).show()
}
override fun showNetworkError() {
toast = Snackbar.make(map_container, R.string.no_connection, Snackbar.LENGTH_INDEFINITE)
.setActionTextColor(ContextCompat.getColor(context!!, R.color.snackbar_action_text))
.setAction(R.string.try_again) {
presenter.onAttach()
}.apply { show() }
}
override fun showProgress() {
loading_indicator.visible()
map_container.gone()
}
override fun hideProgress() {
loading_indicator.gone()
map_container.visible()
}
override fun onInfoWindowClick(marker: Marker) {
navigationManager.navigateToReportDetailsActivity(marker.tag as ReportEntity)
}
override fun onInfoWindowClose(marker: Marker) {
val problem = marker.tag as Problem
activity!!.setTitle(R.string.title_problems_map)
marker.setIcon(getMarkerIcon(problem))
}
override fun onMapLoaded() {
super.onMapLoaded()
googleMap?.setOnInfoWindowClickListener(this)
googleMap?.setOnInfoWindowCloseListener(this)
presenter.onAttach()
}
override fun onLocationInsideCity(location: Location) {
if (!zoomedToMyLocation) {
zoomedToMyLocation = true
zoomToMyLocation(googleMap!!, location)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(EXTRA_ZOOMED_TO_MY_LOCATION, zoomedToMyLocation)
}
override fun onDestroyView() {
toast?.dismiss()
presenter.onDetach()
googleMap?.setOnInfoWindowCloseListener(null)
googleMap?.setOnInfoWindowClickListener(null)
super.onDestroyView()
}
companion object {
private const val EXTRA_ZOOMED_TO_MY_LOCATION = "zoomed_to_my_location"
fun newInstance() = MultipleProblemsMapFragment()
}
}
| mit | 571143fea96006577ac71f1d7c567282 | 31.233333 | 96 | 0.707963 | 4.712476 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/pages/PageFragment.kt | 1 | 2267 | /*
* Copyright (c) 2022 Brayan Oliveira <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.pages
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import com.ichi2.anki.R
import com.ichi2.anki.pages.PagesActivity.Companion.HOST_NAME
import com.ichi2.themes.Themes
import timber.log.Timber
/**
* Base class for displaying Anki HTML pages
*/
abstract class PageFragment : Fragment() {
@get:StringRes
/** Title string resource of the page */
abstract val title: Int
abstract val pageName: String
abstract var webViewClient: PageWebViewClient
abstract var webChromeClient: PageChromeClient
lateinit var webView: WebView
val port
get() = (requireActivity() as PagesActivity).port
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.page_fragment, container, false)
webView = view.findViewById<WebView>(R.id.pagesWebview).apply {
settings.javaScriptEnabled = true
webViewClient = [email protected]
webChromeClient = [email protected]
}
val nightMode = if (Themes.currentTheme.isNightMode) "#night" else ""
val url = "http://$HOST_NAME:$port/$pageName.html$nightMode"
Timber.i("Loading $url")
webView.loadUrl(url)
return view
}
}
| gpl-3.0 | 2734e164c13b62b12919d082eac106a8 | 33.348485 | 83 | 0.716365 | 4.277358 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/model/ClassTime.kt | 1 | 10588 | /*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.model
import android.app.Activity
import android.content.Context
import android.database.Cursor
import android.os.Parcel
import android.os.Parcelable
import co.timetableapp.R
import co.timetableapp.TimetableApplication
import co.timetableapp.data.TimetableDbHelper
import co.timetableapp.data.handler.DataNotFoundException
import co.timetableapp.data.schema.ClassTimesSchema
import co.timetableapp.model.home.HomeItem
import co.timetableapp.model.home.HomeItemProperties
import co.timetableapp.ui.home.HomeDataHelper
import co.timetableapp.util.PrefUtils
import org.threeten.bp.DayOfWeek
import org.threeten.bp.LocalTime
/**
* A collection of data relating to a time that the class takes place.
*
* Data about when the class takes place can be organized into `ClassTime` objects. Each of these
* has properties for a day of the week, which weeks it takes place, and of course, start and end
* times.
*
* So each `ClassTime` only includes data for one occurrence of the class (e.g. 12:00 to 13:00 on
* Mondays on Week 2s).
*
* Note that a `ClassTime` is linked to a [ClassDetail] and not a [Class] so that we know the times
* for each different class detail (e.g. when the student gets taught by teacher A and when they
* get taught by teacher B).
*
* @property classDetailId the id of the associated [ClassDetail]
* @property day the day of the week (Monday to Sunday) that the class takes place
* @property weekNumber the number of a week rotation when the class takes place
* @property startTime the time the class starts
* @property endTime the time the class ends
*/
data class ClassTime(
override val id: Int,
override val timetableId: Int,
val classDetailId: Int,
val day: DayOfWeek,
val weekNumber: Int,
val startTime: LocalTime,
val endTime: LocalTime
) : TimetableItem, HomeItem, Comparable<ClassTime> {
init {
if (startTime.isAfter(endTime)) {
throw IllegalArgumentException("the start time cannot be after the end time")
}
}
companion object {
/**
* Constructs a [ClassTime] using column values from the cursor provided
*
* @param cursor a query of the class times table
* @see [ClassTimesSchema]
*/
@JvmStatic
fun from(cursor: Cursor): ClassTime {
val dayOfWeek =
DayOfWeek.of(cursor.getInt(cursor.getColumnIndex(ClassTimesSchema.COL_DAY)))
val startTime = LocalTime.of(
cursor.getInt(cursor.getColumnIndex(ClassTimesSchema.COL_START_TIME_HRS)),
cursor.getInt(cursor.getColumnIndex(ClassTimesSchema.COL_START_TIME_MINS)))
val endTime = LocalTime.of(
cursor.getInt(cursor.getColumnIndex(ClassTimesSchema.COL_END_TIME_HRS)),
cursor.getInt(cursor.getColumnIndex(ClassTimesSchema.COL_END_TIME_MINS)))
return ClassTime(
cursor.getInt(cursor.getColumnIndex(ClassTimesSchema._ID)),
cursor.getInt(cursor.getColumnIndex(ClassTimesSchema.COL_TIMETABLE_ID)),
cursor.getInt(cursor.getColumnIndex(ClassTimesSchema.COL_CLASS_DETAIL_ID)),
dayOfWeek,
cursor.getInt(cursor.getColumnIndex(ClassTimesSchema.COL_WEEK_NUMBER)),
startTime,
endTime)
}
/**
* Creates a [ClassTime] from the [classTimeId] and corresponding data in the database.
*
* @throws DataNotFoundException if the database query returns no results
* @see from
*/
@JvmStatic
@Throws(DataNotFoundException::class)
fun create(context: Context, classTimeId: Int): ClassTime {
val db = TimetableDbHelper.getInstance(context).readableDatabase
val cursor = db.query(
ClassTimesSchema.TABLE_NAME,
null,
"${ClassTimesSchema._ID}=?",
arrayOf(classTimeId.toString()),
null, null, null)
if (cursor.count == 0) {
cursor.close()
throw DataNotFoundException(this::class.java, classTimeId)
}
cursor.moveToFirst()
val classTime = ClassTime.from(cursor)
cursor.close()
return classTime
}
@Suppress("unused")
@JvmField
val CREATOR: Parcelable.Creator<ClassTime> = object : Parcelable.Creator<ClassTime> {
override fun createFromParcel(source: Parcel): ClassTime = ClassTime(source)
override fun newArray(size: Int): Array<ClassTime?> = arrayOfNulls(size)
}
/**
* @return the string to be displayed indicating the week rotation (e.g. Week 1, Week C).
*/
@JvmOverloads
@JvmStatic
fun getWeekText(activity: Activity, weekNumber: Int, fullText: Boolean = true): String {
val timetable = (activity.application as TimetableApplication).currentTimetable!!
if (timetable.hasFixedScheduling()) {
return ""
} else {
val weekChar = if (PrefUtils.isWeekRotationShownWithNumbers(activity)) {
weekNumber.toString()
} else {
when(weekNumber) {
1 -> "A"
2 -> "B"
3 -> "C"
4 -> "D"
else -> throw IllegalArgumentException("invalid week number '$weekNumber'")
}
}
return if (fullText) activity.getString(R.string.week_item, weekChar) else weekChar
}
}
}
/**
* @return the string to be displayed indicating the week rotation (e.g. Week 1, Week C).
*
* @see Companion.getWeekText
*/
fun getWeekText(activity: Activity) = Companion.getWeekText(activity, weekNumber)
override fun getHomeItemProperties(activity: Activity) = HomeClassProperties(activity, this)
override fun compareTo(other: ClassTime): Int {
// Sort by day, then by time
val dayComparison = day.compareTo(other.day)
return if (dayComparison != 0) {
dayComparison
} else {
startTime.compareTo(other.startTime)
}
}
private constructor(source: Parcel) : this(
source.readInt(),
source.readInt(),
source.readInt(),
source.readSerializable() as DayOfWeek,
source.readInt(),
source.readSerializable() as LocalTime,
source.readSerializable() as LocalTime
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel?, flags: Int) {
dest?.writeInt(id)
dest?.writeInt(timetableId)
dest?.writeInt(classDetailId)
dest?.writeSerializable(day)
dest?.writeInt(weekNumber)
dest?.writeSerializable(startTime)
dest?.writeSerializable(endTime)
}
/**
* Defines a sorting order for [class times][ClassTime] so that they are sorted by start time,
* then end time, then days, then week numbers.
*/
class TimeComparator : Comparator<ClassTime> {
override fun compare(o1: ClassTime?, o2: ClassTime?): Int {
val startTimeComparison = o1!!.startTime.compareTo(o2!!.startTime)
if (startTimeComparison != 0) {
return startTimeComparison
}
val endTimeComparison = o1.endTime.compareTo(o2.endTime)
if (endTimeComparison != 0) {
return endTimeComparison
}
val dayComparison = o1.day.compareTo(o2.day)
if (dayComparison != 0) {
return dayComparison
}
return o1.weekNumber - o2.weekNumber
}
}
class HomeClassProperties(
private val activity: Activity,
private val classTime: ClassTime
) : HomeItemProperties {
private val mClassDetail = ClassDetail.create(activity, classTime.classDetailId)
private val mClass: Class
private val mSubject: Subject
private val mDataHelper by lazy { HomeDataHelper(activity) }
init {
mClass = Class.create(activity, mClassDetail.classId)
mSubject = Subject.create(activity, mClass.subjectId)
}
override val title by lazy { mClass.makeName(mSubject) }
override val subtitle by lazy {
val classDetailBuilder = StringBuilder()
mClassDetail.formatLocationName()?.let {
classDetailBuilder.append(it)
}
if (mClassDetail.hasTeacher()) {
classDetailBuilder.append(" \u2022 ").append(mClassDetail.teacher)
}
if (classDetailBuilder.isEmpty()) {
null
} else {
classDetailBuilder.toString()
}
}
override val time = with(classTime) { "$startTime\n$endTime" }
override val extraText: String?
get() {
val classDetail = ClassDetail.create(activity, classTime.classDetailId)
val cls = Class.create(activity, classDetail.classId)
val classAssignments =
mDataHelper.getAssignmentsToday().filter { it.classId == cls.id }
val numberDue = classAssignments.size
if (numberDue == 0) {
return null
}
return activity.resources.getQuantityString(
R.plurals.class_card_assignment_text,
numberDue,
numberDue)
}
override val color = Color(mSubject.colorId)
}
}
| apache-2.0 | 239b3d26b86b5c4afcd6ad57d996346a | 35.38488 | 99 | 0.606536 | 4.775823 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/FieldEditText.kt | 1 | 9969 | /****************************************************************************************
* Copyright (c) 2015 Timothy Rae <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki
import android.content.ClipboardManager
import android.content.Context
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.LocaleList
import android.os.Parcelable
import android.text.InputType
import android.util.AttributeSet
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.widget.EditText
import androidx.annotation.RequiresApi
import androidx.annotation.VisibleForTesting
import androidx.core.view.ContentInfoCompat
import androidx.core.view.OnReceiveContentListener
import androidx.core.view.ViewCompat
import androidx.core.view.inputmethod.EditorInfoCompat
import androidx.core.view.inputmethod.InputConnectionCompat
import com.ichi2.anki.servicelayer.NoteService
import com.ichi2.themes.Themes.getColorFromAttr
import com.ichi2.ui.FixedEditText
import com.ichi2.utils.ClipboardUtil.IMAGE_MIME_TYPES
import com.ichi2.utils.ClipboardUtil.getImageUri
import com.ichi2.utils.ClipboardUtil.getPlainText
import com.ichi2.utils.ClipboardUtil.hasImage
import com.ichi2.utils.KotlinCleanup
import kotlinx.parcelize.Parcelize
import timber.log.Timber
import java.util.*
import kotlin.math.max
import kotlin.math.min
class FieldEditText : FixedEditText, NoteService.NoteField {
override var ord = 0
private var mOrigBackground: Drawable? = null
private var mSelectionChangeListener: TextSelectionListener? = null
private var mImageListener: ImagePasteListener? = null
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
var clipboard: ClipboardManager? = null
constructor(context: Context?) : super(context!!)
constructor(context: Context?, attr: AttributeSet?) : super(context!!, attr)
constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(context!!, attrs, defStyle)
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (shouldDisableExtendedTextUi()) {
Timber.i("Disabling Extended Text UI")
this.imeOptions = this.imeOptions or EditorInfo.IME_FLAG_NO_EXTRACT_UI
}
}
@KotlinCleanup("Remove try-catch")
private fun shouldDisableExtendedTextUi(): Boolean {
return try {
val sp = AnkiDroidApp.getSharedPrefs(this.context)
sp.getBoolean("disableExtendedTextUi", false)
} catch (e: Exception) {
Timber.e(e, "Failed to get extended UI preference")
false
}
}
@KotlinCleanup("Simplify")
override val fieldText: String?
get() {
val text = text ?: return null
return text.toString()
}
fun init() {
try {
clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
} catch (e: Exception) {
Timber.w(e)
}
minimumWidth = 400
mOrigBackground = background
// Fixes bug where new instances of this object have wrong colors, probably
// from some reuse mechanic in Android.
setDefaultStyle()
}
fun setImagePasteListener(imageListener: ImagePasteListener?) {
mImageListener = imageListener
}
@KotlinCleanup("add extension method to iterate clip items")
override fun onCreateInputConnection(editorInfo: EditorInfo): InputConnection? {
val inputConnection = super.onCreateInputConnection(editorInfo) ?: return null
EditorInfoCompat.setContentMimeTypes(editorInfo, IMAGE_MIME_TYPES)
ViewCompat.setOnReceiveContentListener(
this, IMAGE_MIME_TYPES,
object : OnReceiveContentListener {
override fun onReceiveContent(view: View, payload: ContentInfoCompat): ContentInfoCompat? {
val pair = payload.partition { item -> item.uri != null }
val uriContent = pair.first
val remaining = pair.second
if (mImageListener == null || uriContent == null) {
return remaining
}
val clip = uriContent.clip
val description = clip.description
if (!hasImage(description)) {
return remaining
}
for (i in 0 until clip.itemCount) {
val uri = clip.getItemAt(i).uri
try {
onImagePaste(uri)
} catch (e: Exception) {
Timber.w(e)
CrashReportService.sendExceptionReport(e, "NoteEditor::onImage")
return remaining
}
}
return remaining
}
}
)
return InputConnectionCompat.createWrapper(this, inputConnection, editorInfo)
}
override fun onSelectionChanged(selStart: Int, selEnd: Int) {
if (mSelectionChangeListener != null) {
try {
mSelectionChangeListener!!.onSelectionChanged(selStart, selEnd)
} catch (e: Exception) {
Timber.w(e, "mSelectionChangeListener")
}
}
super.onSelectionChanged(selStart, selEnd)
}
@RequiresApi(api = Build.VERSION_CODES.N)
fun setHintLocale(locale: Locale) {
Timber.d("Setting hint locale to '%s'", locale)
imeHintLocales = LocaleList(locale)
}
/**
* Modify the style of this view to represent a duplicate field.
*/
fun setDupeStyle() {
setBackgroundColor(getColorFromAttr(context, R.attr.duplicateColor))
}
/**
* Restore the default style of this view.
*/
fun setDefaultStyle() {
background = mOrigBackground
}
fun setSelectionChangeListener(listener: TextSelectionListener?) {
mSelectionChangeListener = listener
}
fun setContent(content: String?, replaceNewLine: Boolean) {
val text = if (content == null) {
""
} else if (replaceNewLine) {
content.replace("<br(\\s*/*)>".toRegex(), NEW_LINE)
} else {
content
}
setText(text)
}
override fun onSaveInstanceState(): Parcelable? {
val state = super.onSaveInstanceState()
return SavedState(state, ord)
}
override fun onTextContextMenuItem(id: Int): Boolean {
// This handles both CTRL+V and "Paste"
if (id == android.R.id.paste) {
if (hasImage(clipboard)) {
return onImagePaste(getImageUri(clipboard))
}
return pastePlainText()
}
return super.onTextContextMenuItem(id)
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
fun pastePlainText(): Boolean {
getPlainText(clipboard, context)?.let { pasted ->
val start = min(selectionStart, selectionEnd)
val end = max(selectionStart, selectionEnd)
setText(
text!!.substring(0, start) + pasted + text!!.substring(end)
)
setSelection(start + pasted.length)
return true
}
return false
}
private fun onImagePaste(imageUri: Uri?): Boolean {
return if (imageUri == null) {
false
} else mImageListener!!.onImagePaste(this, imageUri)
}
override fun onRestoreInstanceState(state: Parcelable) {
if (state !is SavedState) {
super.onRestoreInstanceState(state)
return
}
super.onRestoreInstanceState(state.superState)
ord = state.ord
}
fun setCapitalize(value: Boolean) {
val inputType = this.inputType
this.inputType = if (value) {
inputType or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
} else {
inputType and InputType.TYPE_TEXT_FLAG_CAP_SENTENCES.inv()
}
}
val isCapitalized: Boolean
get() = this.inputType and InputType.TYPE_TEXT_FLAG_CAP_SENTENCES == InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
@Parcelize
internal class SavedState(val state: Parcelable?, val ord: Int) : BaseSavedState(state)
interface TextSelectionListener {
fun onSelectionChanged(selStart: Int, selEnd: Int)
}
@KotlinCleanup("non-null")
fun interface ImagePasteListener {
fun onImagePaste(editText: EditText?, uri: Uri?): Boolean
}
companion object {
val NEW_LINE: String = System.getProperty("line.separator")!!
}
}
| gpl-3.0 | 52726a30d188a5dc4c9a11f9e4b8ca8e | 36.197761 | 115 | 0.599759 | 5.13866 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/ui/AppCompatPreferenceActivity.kt | 1 | 10713 | // noinspection MissingCopyrightHeader #8659
/*
* Copyright (C) 2014 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.
*/
@file:Suppress("DEPRECATION") // TODO Tracked in https://github.com/ankidroid/Anki-Android/issues/5019
package com.ichi2.ui
import android.content.*
import android.content.res.Configuration
import android.os.Bundle
import android.preference.PreferenceActivity
import android.view.*
import androidx.annotation.LayoutRes
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.widget.Toolbar
import com.ichi2.anki.AnkiDroidApp
import com.ichi2.anki.CollectionHelper
import com.ichi2.anki.receiver.SdCardReceiver
import com.ichi2.libanki.Collection
import com.ichi2.libanki.Deck
import com.ichi2.utils.HashUtil
import com.ichi2.utils.KotlinCleanup
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import timber.log.Timber
import java.util.*
/**
* A [android.preference.PreferenceActivity] which implements and proxies the necessary calls
* to be used with AppCompat.
*
* This technique can be used with an [android.app.Activity] class, not just
* [android.preference.PreferenceActivity].
*/
abstract class AppCompatPreferenceActivity<PreferenceHack : AppCompatPreferenceActivity<PreferenceHack>.AbstractPreferenceHack> :
PreferenceActivity(),
CoroutineScope by MainScope(),
SharedPreferences.OnSharedPreferenceChangeListener {
private var mDelegate: AppCompatDelegate? = null
fun isColInitialized() = ::col.isInitialized
protected var prefChanged = false
lateinit var unmountReceiver: BroadcastReceiver
protected lateinit var col: Collection
private set
protected lateinit var pref: PreferenceHack
protected lateinit var deck: Deck
abstract inner class AbstractPreferenceHack : SharedPreferences {
val mValues: MutableMap<String, String> = HashUtil.HashMapInit(30) // At most as many as in cacheValues
val mSummaries: MutableMap<String, String?> = HashMap()
protected val listeners: MutableList<SharedPreferences.OnSharedPreferenceChangeListener> = LinkedList()
@KotlinCleanup("scope function")
abstract fun cacheValues()
abstract inner class Editor : SharedPreferences.Editor {
protected var update = ContentValues()
override fun clear(): SharedPreferences.Editor {
Timber.d("clear()")
update = ContentValues()
return this
}
override fun putBoolean(key: String, value: Boolean): SharedPreferences.Editor {
update.put(key, value)
return this
}
override fun putFloat(key: String, value: Float): SharedPreferences.Editor {
update.put(key, value)
return this
}
override fun putInt(key: String, value: Int): SharedPreferences.Editor {
update.put(key, value)
return this
}
override fun putLong(key: String, value: Long): SharedPreferences.Editor {
update.put(key, value)
return this
}
override fun putString(key: String, value: String?): SharedPreferences.Editor {
update.put(key, value)
return this
}
override fun remove(key: String): SharedPreferences.Editor {
Timber.d("Editor.remove(key=%s)", key)
update.remove(key)
return this
}
override fun apply() {
commit()
}
// @Override On Android 1.5 this is not Override
override fun putStringSet(arg0: String, arg1: Set<String>?): SharedPreferences.Editor? {
// TODO Auto-generated method stub
return null
}
@Suppress("unused")
@KotlinCleanup("maybe remove this")
val deckPreferenceHack: AbstractPreferenceHack
get() = this@AbstractPreferenceHack
}
override fun contains(key: String): Boolean {
return mValues.containsKey(key)
}
override fun getAll(): Map<String, *> {
return mValues
}
override fun getBoolean(key: String, defValue: Boolean): Boolean {
return java.lang.Boolean.parseBoolean(this.getString(key, java.lang.Boolean.toString(defValue)))
}
override fun getFloat(key: String, defValue: Float): Float {
return this.getString(key, defValue.toString())!!.toFloat()
}
override fun getInt(key: String, defValue: Int): Int {
return this.getString(key, defValue.toString())!!.toInt()
}
override fun getLong(key: String, defValue: Long): Long {
return this.getString(key, defValue.toString())!!.toLong()
}
override fun getString(key: String, defValue: String?): String? {
Timber.d("getString(key=%s, defValue=%s)", key, defValue)
return if (!mValues.containsKey(key)) {
defValue
} else mValues[key]
}
override fun registerOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) {
listeners.add(listener)
}
override fun unregisterOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) {
listeners.remove(listener)
}
// @Override On Android 1.5 this is not Override
override fun getStringSet(arg0: String, arg1: Set<String>?): Set<String>? {
// TODO Auto-generated method stub
return null
}
init {
cacheValues()
}
}
@Deprecated("Deprecated in Java")
override fun onCreate(savedInstanceState: Bundle?) {
delegate.installViewFactory()
delegate.onCreate(savedInstanceState)
super.onCreate(savedInstanceState)
val col = CollectionHelper.instance.getCol(this)
if (col != null) {
this.col = col
} else {
finish()
}
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(AnkiDroidApp.updateContextWithLanguage(base))
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
delegate.onPostCreate(savedInstanceState)
}
val supportActionBar: ActionBar?
get() = delegate.supportActionBar
fun setSupportActionBar(toolbar: Toolbar?) {
delegate.setSupportActionBar(toolbar)
}
override fun getMenuInflater(): MenuInflater {
return delegate.menuInflater
}
override fun setContentView(@LayoutRes layoutResID: Int) {
delegate.setContentView(layoutResID)
}
override fun setContentView(view: View) {
delegate.setContentView(view)
}
override fun setContentView(view: View, params: ViewGroup.LayoutParams) {
delegate.setContentView(view, params)
}
override fun addContentView(view: View, params: ViewGroup.LayoutParams) {
delegate.addContentView(view, params)
}
override fun onPostResume() {
super.onPostResume()
delegate.onPostResume()
}
override fun onTitleChanged(title: CharSequence, color: Int) {
super.onTitleChanged(title, color)
delegate.setTitle(title)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
delegate.onConfigurationChanged(newConfig)
}
@Deprecated("Deprecated in Java")
override fun onStop() {
super.onStop()
delegate.onStop()
}
@Deprecated("Deprecated in Java")
override fun onDestroy() {
super.onDestroy()
delegate.onDestroy()
unregisterReceiver(unmountReceiver)
cancel() // cancel all the Coroutines started from Activity's Scope
}
override fun invalidateOptionsMenu() {
delegate.invalidateOptionsMenu()
}
protected abstract fun updateSummaries()
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String?) {
// update values on changed preference
prefChanged = true
updateSummaries()
}
private val delegate: AppCompatDelegate
get() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null)
}
return mDelegate!! // safe as mDelegate is only initialized here, before being returned
}
/**
* Call exactly once, during creation
* to ensure that if the SD card is ejected
* this activity finish.
*/
/**
* finish when sd card is ejected
*/
fun registerExternalStorageListener() {
unmountReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == SdCardReceiver.MEDIA_EJECT) {
finish()
}
}
}
val iFilter = IntentFilter()
iFilter.addAction(SdCardReceiver.MEDIA_EJECT)
registerReceiver(unmountReceiver, iFilter)
}
protected abstract fun closeWithResult()
@Deprecated("Deprecated in Java")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
closeWithResult()
return true
}
return false
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0) {
Timber.i("DeckOptions - onBackPressed()")
closeWithResult()
return true
}
return super.onKeyDown(keyCode, event)
}
override fun getSharedPreferences(name: String, mode: Int): SharedPreferences {
Timber.d("getSharedPreferences(name=%s)", name)
return pref
}
}
| gpl-3.0 | 5a5e280c0dc68d337e1613086791d259 | 32.478125 | 129 | 0.647064 | 5.195441 | false | false | false | false |
rock3r/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/coroutines/GlobalCoroutineUsage.kt | 1 | 2170 | package io.gitlab.arturbosch.detekt.rules.coroutines
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getCalleeExpressionIfAny
/**
* Report usages of `GlobalScope.launch` and `GlobalScope.async`. It is highly discouraged by the Kotlin documentation:
*
* > Global scope is used to launch top-level coroutines which are operating on the whole application lifetime and are
* > not cancelled prematurely.
*
* > Application code usually should use an application-defined CoroutineScope. Using async or launch on the instance
* > of GlobalScope is highly discouraged.
*
* See https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/
*
* <noncompliant>
* fun foo() {
* GlobalScope.launch { delay(1_000L) }
* }
* </noncompliant>
*
* <compliant>
* val scope = CoroutineScope(Dispatchers.Default)
*
* fun foo() {
* scope.launch { delay(1_000L) }
* }
*
* fun onDestroy() {
* scope.cancel()
* }
* </compliant>
*/
class GlobalCoroutineUsage(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
javaClass.simpleName,
Severity.Defect,
"Usage of GlobalScope instance is highly discouraged",
Debt.TEN_MINS
)
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
if (expression.receiverExpression.text == "GlobalScope" &&
expression.getCalleeExpressionIfAny()?.text in listOf("launch", "async")) {
report(CodeSmell(issue, Entity.from(expression), MESSAGE))
}
super.visitDotQualifiedExpression(expression)
}
companion object {
private const val MESSAGE =
"This use of GlobalScope should be replaced by `CoroutineScope` or `coroutineScope`."
}
}
| apache-2.0 | 5641eb5425673b3f161f1082f25ccc15 | 33.444444 | 119 | 0.722581 | 4.238281 | false | true | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/notifications/QuestSelectionHintController.kt | 1 | 2037 | package de.westnordost.streetcomplete.data.notifications
import android.content.SharedPreferences
import de.westnordost.streetcomplete.ApplicationConstants.QUEST_COUNT_AT_WHICH_TO_SHOW_QUEST_SELECTION_HINT
import de.westnordost.streetcomplete.Prefs
import de.westnordost.streetcomplete.data.quest.Quest
import de.westnordost.streetcomplete.data.quest.QuestKey
import de.westnordost.streetcomplete.data.quest.VisibleQuestsSource
import de.westnordost.streetcomplete.data.notifications.QuestSelectionHintState.*
import java.util.concurrent.CopyOnWriteArrayList
import javax.inject.Inject
import javax.inject.Singleton
@Singleton class QuestSelectionHintController @Inject constructor(
private val visibleQuestsSource: VisibleQuestsSource,
private val prefs: SharedPreferences
) {
interface Listener {
fun onQuestSelectionHintStateChanged()
}
private val listeners: MutableList<Listener> = CopyOnWriteArrayList()
var state: QuestSelectionHintState
set(value) {
prefs.edit().putString(Prefs.QUEST_SELECTION_HINT_STATE, value.toString()).apply()
listeners.forEach { it.onQuestSelectionHintStateChanged() }
}
get() {
val str = prefs.getString(Prefs.QUEST_SELECTION_HINT_STATE, null)
return if (str == null) NOT_SHOWN else QuestSelectionHintState.valueOf(str)
}
init {
visibleQuestsSource.addListener(object : VisibleQuestsSource.Listener {
override fun onUpdatedVisibleQuests(added: Collection<Quest>, removed: Collection<QuestKey>) {
if (state == NOT_SHOWN && added.size >= QUEST_COUNT_AT_WHICH_TO_SHOW_QUEST_SELECTION_HINT) {
state = SHOULD_SHOW
}
}
override fun onVisibleQuestsInvalidated() {}
})
}
fun addListener(listener: Listener) {
listeners.add(listener)
}
fun removeListener(listener: Listener) {
listeners.remove(listener)
}
}
enum class QuestSelectionHintState {
NOT_SHOWN, SHOULD_SHOW, SHOWN
}
| gpl-3.0 | ec9818c1defea3f34ee9cd0a713980f7 | 35.375 | 108 | 0.728522 | 4.587838 | false | false | false | false |
udevbe/westmalle | compositor/src/main/kotlin/org/westford/compositor/protocol/WlCompositor.kt | 3 | 4406 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.protocol
import org.freedesktop.wayland.server.*
import org.westford.compositor.core.*
import java.util.*
import javax.annotation.Nonnegative
import javax.inject.Inject
import javax.inject.Singleton
@Singleton class WlCompositor @Inject internal constructor(display: Display,
private val wlSurfaceFactory: WlSurfaceFactory,
private val wlRegionFactory: WlRegionFactory,
private val finiteRegionFactory: org.westford.compositor.core.FiniteRegionFactory,
private val surfaceFactory: org.westford.compositor.core.SurfaceFactory,
private val compositor: Compositor,
private val scene: Scene,
private val renderer: Renderer) : Global<WlCompositorResource>(display,
WlCompositorResource::class.java,
WlCompositorRequestsV4.VERSION), WlCompositorRequestsV4, ProtocolObject<WlCompositorResource> {
override val resources: MutableSet<WlCompositorResource> = Collections.newSetFromMap(WeakHashMap<WlCompositorResource, Boolean>())
override fun onBindClient(client: Client,
version: Int,
id: Int): WlCompositorResource = add(client,
version,
id)
override fun createSurface(compositorResource: WlCompositorResource,
id: Int) {
val surface = this.surfaceFactory.create()
val wlSurface = this.wlSurfaceFactory.create(surface)
val wlSurfaceResource = wlSurface.add(compositorResource.client,
compositorResource.version,
id)
//TODO we might want to move view creation to role object
surface.createView(wlSurfaceResource,
Point.ZERO)
surface.siblings.add(Sibling(wlSurfaceResource))
//TODO unit test destroy handler
wlSurfaceResource.register {
this.scene.removeAllViews(wlSurfaceResource)
surface.markDestroyed()
this.renderer.onDestroy(wlSurfaceResource)
this.compositor.requestRender()
}
}
override fun createRegion(resource: WlCompositorResource,
id: Int) {
this.wlRegionFactory.create(this.finiteRegionFactory.create()).add(resource.client,
resource.version,
id)
}
override fun create(client: Client,
@Nonnegative version: Int,
id: Int): WlCompositorResource = WlCompositorResource(client,
version,
id,
this)
}
| agpl-3.0 | b81da690233c2bf6f997bf3417d784f8 | 53.395062 | 217 | 0.51044 | 6.479412 | false | false | false | false |
WijayaPrinting/wp-javafx | openpss-client-javafx/src/com/hendraanggrian/openpss/ui/price/EditOffsetPriceDialog.kt | 1 | 2720 | package com.hendraanggrian.openpss.ui.price
import com.hendraanggrian.openpss.FxComponent
import com.hendraanggrian.openpss.R2
import com.hendraanggrian.openpss.api.OpenPSSApi
import com.hendraanggrian.openpss.schema.OffsetPrice
import javafx.beans.property.ReadOnlyDoubleWrapper
import javafx.beans.property.ReadOnlyIntegerWrapper
import javafx.beans.value.ObservableValue
import kotlinx.coroutines.CoroutineScope
import ktfx.cells.textFieldCellFactory
import ktfx.coroutines.onEditCommit
import ktfx.text.buildStringConverter
@Suppress("UNCHECKED_CAST")
class EditOffsetPriceDialog(
component: FxComponent
) : EditPriceDialog<OffsetPrice>(component, R2.string.offset_print_price) {
init {
getString(R2.string.min_qty)<Int> {
minWidth = 128.0
style = "-fx-alignment: center-right;"
setCellValueFactory { ReadOnlyIntegerWrapper(it.value.minQty) as ObservableValue<Int> }
textFieldCellFactory(buildStringConverter {
fromString { it.toIntOrNull() ?: 0 }
})
onEditCommit { cell ->
val offset = cell.rowValue
OpenPSSApi.editOffsetPrice(offset.apply { minQty = cell.newValue })
}
}
getString(R2.string.min_price)<Double> {
minWidth = 128.0
style = "-fx-alignment: center-right;"
setCellValueFactory { ReadOnlyDoubleWrapper(it.value.minPrice) as ObservableValue<Double> }
textFieldCellFactory(buildStringConverter {
fromString { it.toDoubleOrNull() ?: 0.0 }
})
onEditCommit { cell ->
val offset = cell.rowValue
OpenPSSApi.editOffsetPrice(offset.apply { minPrice = cell.newValue })
}
}
getString(R2.string.excess_price)<Double> {
minWidth = 128.0
style = "-fx-alignment: center-right;"
setCellValueFactory { ReadOnlyDoubleWrapper(it.value.excessPrice) as ObservableValue<Double> }
textFieldCellFactory(buildStringConverter {
fromString { it.toDoubleOrNull() ?: 0.0 }
})
onEditCommit { cell ->
val offset = cell.rowValue
OpenPSSApi.editOffsetPrice(offset.apply { excessPrice = cell.newValue })
}
}
}
override suspend fun CoroutineScope.refresh(): List<OffsetPrice> = OpenPSSApi.getOffsetPrices()
override suspend fun CoroutineScope.add(name: String): OffsetPrice? =
OpenPSSApi.addOffsetPrice(OffsetPrice.new(name))
override suspend fun CoroutineScope.delete(selected: OffsetPrice): Boolean =
OpenPSSApi.deleteOffsetPrice(selected.id)
}
| apache-2.0 | bb847a9dfe41ded08634ad1518bf2023 | 39 | 106 | 0.661029 | 4.556114 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/effect/firework/LanternFireworkEffectBuilder.kt | 1 | 2746 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.effect.firework
import org.lanternpowered.api.effect.firework.FireworkEffect
import org.lanternpowered.api.effect.firework.FireworkEffectBuilder
import org.lanternpowered.api.effect.firework.FireworkShape
import org.lanternpowered.api.effect.firework.FireworkShapes
import org.lanternpowered.api.effect.firework.flickers
import org.lanternpowered.api.effect.firework.hasTrail
import org.lanternpowered.api.util.Color
import org.lanternpowered.api.util.collections.toImmutableList
class LanternFireworkEffectBuilder : FireworkEffectBuilder {
private var trail: Boolean = false
private var flicker: Boolean = false
private val colors: MutableList<Color> = mutableListOf()
private val fades: MutableList<Color> = mutableListOf()
private var shape: FireworkShape? = null
init {
reset()
}
override fun trail(trail: Boolean): FireworkEffectBuilder = apply { this.trail = trail }
override fun flicker(flicker: Boolean): FireworkEffectBuilder = apply { this.flicker = flicker }
override fun shape(shape: FireworkShape): FireworkEffectBuilder = apply { this.shape = shape }
override fun color(color: Color): FireworkEffectBuilder = apply { this.colors.add(color) }
override fun colors(vararg colors: Color): FireworkEffectBuilder = apply { this.colors.addAll(colors) }
override fun colors(colors: Iterable<Color>): FireworkEffectBuilder = apply { this.colors.addAll(colors) }
override fun fade(color: Color): FireworkEffectBuilder = apply { this.fades.add(color) }
override fun fades(vararg colors: Color): FireworkEffectBuilder = apply { this.fades.addAll(colors) }
override fun fades(colors: Iterable<Color>): FireworkEffectBuilder = apply { this.fades.addAll(colors) }
override fun build(): FireworkEffect {
return LanternFireworkEffect(this.flicker, this.trail, this.colors.toImmutableList(), this.fades.toImmutableList(), this.shape!!)
}
override fun from(value: FireworkEffect): FireworkEffectBuilder = apply {
trail(value.hasTrail)
colors(value.colors)
fades(value.fadeColors)
shape(value.shape)
flicker(value.flickers)
}
override fun reset(): FireworkEffectBuilder = apply {
this.trail = false
this.flicker = false
this.colors.clear()
this.fades.clear()
this.shape = FireworkShapes.BALL.get()
}
}
| mit | 9923f67d2128c63248a1d6ec1807a41c | 42.587302 | 137 | 0.735251 | 4.050147 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/reporting/deploy/postgres/writers/SetMeasurementFailure.kt | 1 | 3639 | // Copyright 2022 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.reporting.deploy.postgres.writers
import org.wfanet.measurement.common.db.r2dbc.boundStatement
import org.wfanet.measurement.internal.reporting.Measurement
import org.wfanet.measurement.internal.reporting.Report
import org.wfanet.measurement.internal.reporting.SetMeasurementFailureRequest
import org.wfanet.measurement.internal.reporting.measurement
import org.wfanet.measurement.reporting.deploy.postgres.readers.MeasurementReader
import org.wfanet.measurement.reporting.service.internal.MeasurementNotFoundException
import org.wfanet.measurement.reporting.service.internal.MeasurementStateInvalidException
/**
* Update a [Measurement] to be in a failure state along with any dependent [Report].
*
* Throws the following on [execute]:
* * [MeasurementNotFoundException] Measurement not found.
* * [MeasurementStateInvalidException] Measurement does not have PENDING state.
*/
class SetMeasurementFailure(private val request: SetMeasurementFailureRequest) :
PostgresWriter<Measurement>() {
override suspend fun TransactionScope.runTransaction(): Measurement {
val measurementResult =
MeasurementReader()
.readMeasurementByReferenceIds(
transactionContext,
measurementConsumerReferenceId = request.measurementConsumerReferenceId,
measurementReferenceId = request.measurementReferenceId
)
?: throw MeasurementNotFoundException()
if (measurementResult.measurement.state != Measurement.State.PENDING) {
throw MeasurementStateInvalidException()
}
val updateMeasurementStatement =
boundStatement(
"""
UPDATE Measurements
SET State = $1, Failure = $2
WHERE MeasurementConsumerReferenceId = $3 AND MeasurementReferenceId = $4
"""
) {
bind("$1", Measurement.State.FAILED_VALUE)
bind("$2", request.failure)
bind("$3", request.measurementConsumerReferenceId)
bind("$4", request.measurementReferenceId)
}
val updateReportStatement =
boundStatement(
"""
UPDATE Reports
SET State = $1
FROM (
SELECT
ReportId
FROM ReportMeasurements
WHERE MeasurementConsumerReferenceId = $2 AND MeasurementReferenceId = $3
) AS ReportMeasurements
WHERE Reports.ReportId = ReportMeasurements.ReportId
"""
) {
bind("$1", Report.State.FAILED_VALUE)
bind("$2", request.measurementConsumerReferenceId)
bind("$3", request.measurementReferenceId)
}
transactionContext.run {
val numRowsUpdated = executeStatement(updateMeasurementStatement).numRowsUpdated
if (numRowsUpdated == 0L) {
return@run
}
executeStatement(updateReportStatement)
}
return measurement {
measurementConsumerReferenceId = request.measurementConsumerReferenceId
measurementReferenceId = request.measurementReferenceId
state = Measurement.State.FAILED
failure = request.failure
}
}
}
| apache-2.0 | 820bee9edccfa39990afe7c46c664985 | 36.515464 | 89 | 0.730695 | 5.054167 | false | false | false | false |
prt2121/json2pojo | src/main/kotlin/com/prt2121/pojo/PojoApplication.kt | 1 | 614 | package com.prt2121.pojo
import javafx.application.Application
import javafx.fxml.FXMLLoader
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.stage.Stage
class PojoApplication : Application() {
override fun start(primaryStage: Stage) {
val root = FXMLLoader.load<Parent>(javaClass.getResource("/json2pojo.fxml"))
val scene = Scene(root, 640.0, 520.0)
primaryStage.isResizable = false
primaryStage.title = "json2pojo"
primaryStage.scene = scene
primaryStage.show()
}
}
fun main(args: Array<String>) {
Application.launch(PojoApplication::class.java, * arrayOf())
} | apache-2.0 | 9c2e2b38bb6fcbd7faf6d07af7935c03 | 25.73913 | 80 | 0.747557 | 3.861635 | false | false | false | false |
oubowu/AndroidExerciseProgram | ExerciseProgram/app/src/main/java/com/oubowu/exerciseprogram/kotlin/LoginActivity.kt | 1 | 2537 | package com.oubowu.exerciseprogram.kotlin
import android.app.Activity
import android.text.TextUtils
import android.view.View
import android.widget.*
import butterknife.Bind
import com.oubowu.exerciseprogram.BaseActivity
import com.oubowu.exerciseprogram.R
import com.socks.library.KLog
import kotlin.concurrent.thread
// 为指定类添加方法(拓展)
// 这是个非常实用的方法,像OC一样,kotlin也可以给某个类添加一些方法,比如代码中,我们给Activity类添加了一个toast方法,
// 这样所有的Activity子类都可以拥有了toast方法。相信所有做Java的朋友都遇到过Java不能多继承的问题,虽然这给Java开发带来了很大的好处,
// 但是在某些情况下不能多继承确实很麻烦,用kotlin的这个特性就能轻松解决这种问题了。
fun Activity.toast(msg: CharSequence) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
}
/**
* A login screen that offers login via email/password.
*/
class LoginActivity : BaseActivity() {
// 伴随对象
private companion object {
val TAG = LoginActivity::class.java.simpleName
}
var progressBar: ProgressBar? = null
var email: AutoCompleteTextView? = null
var password: EditText? = null
var button: Button? = null
override fun provideLayoutId(): Int {
return R.layout.activity_login
}
override fun initView() {
KLog.e(LoginActivity.TAG)
progressBar = getViewById(R.id.login_progress)
email = getViewById(R.id.email)
password = getViewById(R.id.password)
button = getViewById(R.id.email_sign_in_button)
button?.setOnClickListener { view: View ->
progressBar?.visibility = View.VISIBLE
val account: String? = email!!.getText().toString().trim()
val pwd: String? = password!!.getText().toString().trim()
thread {
Thread.sleep(2000)
runOnUiThread {
if (TextUtils.isEmpty(account) || TextUtils.isEmpty(pwd)) {
toast("email or password can't be null")
} else if (account.equals("ou") && pwd.equals("123")) {
toast("login success")
} else {
toast("email or passeord is incorrect, please try again")
}
progressBar?.visibility = View.GONE
}
}
}
}
override fun initData() {
}
}
| apache-2.0 | ac60f8be3784a14b2840168636132ca1 | 26.9125 | 81 | 0.62472 | 3.856649 | false | false | false | false |
NextFaze/dev-fun | demo/src/main/java/com/nextfaze/devfun/demo/test/InjectablesSingletonScoped.kt | 1 | 2404 | package com.nextfaze.devfun.demo.test
import android.app.Activity
import android.content.Context
import androidx.appcompat.app.AlertDialog
import com.nextfaze.devfun.function.DeveloperFunction
import dagger.Module
import dagger.Provides
import javax.inject.Inject
import javax.inject.Singleton
@Module
class SingletonScopedTestModule {
@Provides
@Singleton
fun scoped() = InjectableSingletonScopedViaProvides()
@Provides
@Singleton
fun scopedWithArgs(context: Context) = InjectableSingletonScopedViaProvidesWithArgs(context)
}
@TestCat
class InjectableSingletonScopedViaProvides {
@DeveloperFunction
fun validateSelf(activity: Activity, self: InjectableSingletonScopedViaProvides): AlertDialog =
AlertDialog.Builder(activity)
.setMessage(
"""this=$this($activity)
|self=$self
|this===self: ${this === self}""".trimMargin()
)
.show()
}
@TestCat
class InjectableSingletonScopedViaProvidesWithArgs @Inject constructor(private val context: Context) {
@DeveloperFunction
fun validateSelf(activity: Activity, self: InjectableSingletonScopedViaProvidesWithArgs): AlertDialog =
AlertDialog.Builder(activity)
.setMessage(
"""this=$this($context)
|self=$self
|this===self: ${this === self}""".trimMargin()
)
.show()
}
@Singleton
@TestCat
class InjectableSingletonScopedViaAnnotation @Inject constructor() {
@DeveloperFunction
fun validateSelf(activity: Activity, self: InjectableSingletonScopedViaAnnotation): AlertDialog =
AlertDialog.Builder(activity)
.setMessage(
"""this=$this($activity)
|self=$self
|this===self: ${this === self}""".trimMargin()
)
.show()
}
@Singleton
@TestCat
class InjectableSingletonScopedViaAnnotationWithArgs @Inject constructor(private val context: Context) {
@DeveloperFunction
fun validateSelf(activity: Activity, self: InjectableSingletonScopedViaAnnotationWithArgs): AlertDialog =
AlertDialog.Builder(activity)
.setMessage(
"""this=$this($context)
|self=$self
|this===self: ${this === self}""".trimMargin()
)
.show()
}
| apache-2.0 | 63b07b35944c4d77c3568d36fd77e497 | 31.053333 | 109 | 0.646839 | 5.029289 | false | true | false | false |
nemerosa/ontrack | ontrack-extension-general/src/test/java/net/nemerosa/ontrack/extension/general/AutoPromotionPropertyMutationProviderIT.kt | 1 | 5735 | package net.nemerosa.ontrack.extension.general
import net.nemerosa.ontrack.graphql.AbstractQLKTITJUnit4Support
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class AutoPromotionPropertyMutationProviderIT : AbstractQLKTITJUnit4Support() {
@Test
fun `Setting auto promotion by ID`() {
asAdmin {
project {
branch {
val vs1 = validationStamp()
val vs2 = validationStamp()
val other = promotionLevel()
val pl = promotionLevel()
run("""
mutation {
setPromotionLevelAutoPromotionPropertyById(input: {
id: ${pl.id},
validationStamps: ["${vs1.name}", "${vs2.name}"],
promotionLevels: ["${other.name}"]
}) {
errors {
message
}
}
}
""").let { data ->
assertNoUserError(data, "setPromotionLevelAutoPromotionPropertyById")
assertNotNull(getProperty(pl, AutoPromotionPropertyType::class.java)) { property ->
assertEquals("", property.include)
assertEquals("", property.exclude)
assertEquals(
setOf(vs1.name, vs2.name),
property.validationStamps.map { it.name }.toSet()
)
assertEquals(
setOf(other.name),
property.promotionLevels.map { it.name }.toSet()
)
}
}
}
}
}
}
@Test
fun `Setting auto promotion by name`() {
asAdmin {
project {
branch {
val vs1 = validationStamp()
val vs2 = validationStamp()
val other = promotionLevel()
val pl = promotionLevel()
run("""
mutation {
setPromotionLevelAutoPromotionProperty(input: {
project: "${pl.project.name}",
branch: "${pl.branch.name}",
promotion: "${pl.name}",
validationStamps: ["${vs1.name}", "${vs2.name}"],
promotionLevels: ["${other.name}"]
}) {
errors {
message
}
}
}
""").let { data ->
assertNoUserError(data, "setPromotionLevelAutoPromotionProperty")
assertNotNull(getProperty(pl, AutoPromotionPropertyType::class.java)) { property ->
assertEquals("", property.include)
assertEquals("", property.exclude)
assertEquals(
setOf(vs1.name, vs2.name),
property.validationStamps.map { it.name }.toSet()
)
assertEquals(
setOf(other.name),
property.promotionLevels.map { it.name }.toSet()
)
}
}
}
}
}
}
@Test
fun `Setting auto promotion with exclude and include by name`() {
asAdmin {
project {
branch {
val other = promotionLevel()
val pl = promotionLevel()
run("""
mutation {
setPromotionLevelAutoPromotionProperty(input: {
project: "${pl.project.name}",
branch: "${pl.branch.name}",
promotion: "${pl.name}",
promotionLevels: ["${other.name}"],
include: "acceptance-.*",
exclude: "acceptance-long-.*"
}) {
errors {
message
}
}
}
""").let { data ->
assertNoUserError(data, "setPromotionLevelAutoPromotionProperty")
assertNotNull(getProperty(pl, AutoPromotionPropertyType::class.java)) { property ->
assertEquals("acceptance-.*", property.include)
assertEquals("acceptance-long-.*", property.exclude)
assertEquals(
emptySet(),
property.validationStamps.map { it.name }.toSet()
)
assertEquals(
setOf(other.name),
property.promotionLevels.map { it.name }.toSet()
)
}
}
}
}
}
}
} | mit | eab5ddff6b971c949297b1ae755b54b0 | 40.266187 | 107 | 0.365126 | 7.277919 | false | false | false | false |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/optimizations/Devirtualization.kt | 1 | 91426 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.optimizations
import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext
import org.jetbrains.kotlin.backend.common.descriptors.explicitParameters
import org.jetbrains.kotlin.backend.common.ir.ir2stringWhole
import org.jetbrains.kotlin.backend.common.pop
import org.jetbrains.kotlin.backend.common.push
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.common.lower.irBlock
import org.jetbrains.kotlin.backend.konan.*
import org.jetbrains.kotlin.backend.konan.util.IntArrayList
import org.jetbrains.kotlin.backend.konan.util.LongArrayList
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrVariableImpl
import org.jetbrains.kotlin.ir.descriptors.IrTemporaryVariableDescriptorImpl
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrReturnableBlockSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrVariableSymbolImpl
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.classifierOrFail
import org.jetbrains.kotlin.ir.types.impl.originalKotlinType
import org.jetbrains.kotlin.ir.types.toKotlinType
import org.jetbrains.kotlin.ir.util.irCall
import org.jetbrains.kotlin.ir.util.explicitParameters
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.name.Name
import java.util.*
import kotlin.collections.ArrayList
inline fun BitSet.forEachBit(block: (Int) -> Unit) {
var i = -1
while (true) {
i = nextSetBit(i + 1)
if (i < 0) break
block(i)
}
}
// Devirtualization analysis is performed using Variable Type Analysis algorithm.
// See http://web.cs.ucla.edu/~palsberg/tba/papers/sundaresan-et-al-oopsla00.pdf for details.
internal object Devirtualization {
private val TAKE_NAMES = false // Take fqNames for all functions and types (for debug purposes).
private inline fun takeName(block: () -> String) = if (TAKE_NAMES) block() else null
fun computeRootSet(context: Context, moduleDFG: ModuleDFG, externalModulesDFG: ExternalModulesDFG)
: List<DataFlowIR.FunctionSymbol> {
fun DataFlowIR.FunctionSymbol.resolved(): DataFlowIR.FunctionSymbol {
if (this is DataFlowIR.FunctionSymbol.External)
return externalModulesDFG.publicFunctions[this.hash] ?: this
return this
}
val entryPoint = context.ir.symbols.entryPoint?.owner
val exportedFunctions =
if (entryPoint != null)
listOf(moduleDFG.symbolTable.mapFunction(entryPoint).resolved())
else {
// In a library every public function and every function accessible via virtual call belongs to the rootset.
moduleDFG.symbolTable.functionMap.values.filter {
it is DataFlowIR.FunctionSymbol.Public
|| (it as? DataFlowIR.FunctionSymbol.External)?.isExported == true
} +
moduleDFG.symbolTable.classMap.values
.filterIsInstance<DataFlowIR.Type.Declared>()
.flatMap { it.vtable + it.itable.values }
.filterIsInstance<DataFlowIR.FunctionSymbol.Declared>()
.filter { moduleDFG.functions.containsKey(it) }
}
// TODO: Are globals initializers always called whether they are actually reachable from roots or not?
val globalInitializers =
moduleDFG.symbolTable.functionMap.values.filter { it.isGlobalInitializer } +
externalModulesDFG.functionDFGs.keys.filter { it.isGlobalInitializer }
val explicitlyExportedFunctions =
moduleDFG.symbolTable.functionMap.values.filter { it.explicitlyExported } +
externalModulesDFG.functionDFGs.keys.filter { it.explicitlyExported }
// Conservatively assume each associated object could be called.
// Note: for constructors there is additional parameter (<this>) and its type will be added
// to instantiating classes since all objects are final types.
val associatedObjects = mutableListOf<DataFlowIR.FunctionSymbol>()
context.irModule!!.acceptChildrenVoid(object: IrElementVisitorVoid {
override fun visitElement(element: IrElement) {
element.acceptChildrenVoid(this)
}
override fun visitClass(declaration: IrClass) {
context.getLayoutBuilder(declaration).associatedObjects.values.forEach {
assert (it.kind == ClassKind.OBJECT) { "An object expected but was ${it.dump()}" }
associatedObjects += moduleDFG.symbolTable.mapFunction(it.constructors.single())
}
super.visitClass(declaration)
}
})
return (exportedFunctions + globalInitializers + explicitlyExportedFunctions + associatedObjects).distinct()
}
fun BitSet.format(allTypes: Array<DataFlowIR.Type.Declared>): String {
return allTypes.withIndex().filter { this[it.index] }.joinToString { it.value.toString() }
}
private val VIRTUAL_TYPE_ID = 0 // Id of [DataFlowIR.Type.Virtual].
internal class DevirtualizationAnalysis(val context: Context,
val moduleDFG: ModuleDFG,
val externalModulesDFG: ExternalModulesDFG) {
private val entryPoint = context.ir.symbols.entryPoint?.owner
private val symbolTable = moduleDFG.symbolTable
sealed class Node(val id: Int) {
var directCastEdges: MutableList<CastEdge>? = null
var reversedCastEdges: MutableList<CastEdge>? = null
val types = BitSet()
var priority = -1
var multiNodeStart = -1
var multiNodeEnd = -1
val multiNodeSize get() = multiNodeEnd - multiNodeStart
fun addCastEdge(edge: CastEdge) {
if (directCastEdges == null) directCastEdges = ArrayList(1)
directCastEdges!!.add(edge)
if (edge.node.reversedCastEdges == null) edge.node.reversedCastEdges = ArrayList(1)
edge.node.reversedCastEdges!!.add(CastEdge(this, edge.suitableTypes))
}
abstract fun toString(allTypes: Array<DataFlowIR.Type.Declared>): String
class Source(id: Int, typeId: Int, nameBuilder: () -> String): Node(id) {
val name = takeName(nameBuilder)
init {
types.set(typeId)
}
override fun toString(allTypes: Array<DataFlowIR.Type.Declared>): String {
return "Source(name='$name', types='${types.format(allTypes)}')"
}
}
class Ordinary(id: Int, nameBuilder: () -> String) : Node(id) {
val name = takeName(nameBuilder)
override fun toString(allTypes: Array<DataFlowIR.Type.Declared>): String {
return "Ordinary(name='$name', types='${types.format(allTypes)}')"
}
}
class CastEdge(val node: Node, val suitableTypes: BitSet)
}
class Function(val symbol: DataFlowIR.FunctionSymbol, val parameters: Array<Node>, val returns: Node, val throws: Node)
inner class ConstraintGraph {
private var nodesCount = 0
val nodes = mutableListOf<Node>()
val voidNode = addNode { Node.Ordinary(it, { "Void" }) }
val virtualNode = addNode { Node.Source(it, VIRTUAL_TYPE_ID, { "Virtual" }) }
val arrayItemField = DataFlowIR.Field(null,
symbolTable.mapClassReferenceType(context.irBuiltIns.anyClass.owner), 1, "Array\$Item")
val functions = mutableMapOf<DataFlowIR.FunctionSymbol, Function>()
val externalFunctions = mutableMapOf<Pair<DataFlowIR.FunctionSymbol, DataFlowIR.Type>, Node>()
val fields = mutableMapOf<DataFlowIR.Field, Node>() // Do not distinguish receivers.
val virtualCallSiteReceivers = mutableMapOf<DataFlowIR.Node.VirtualCall, Node>()
private fun nextId(): Int = nodesCount++
fun addNode(nodeBuilder: (Int) -> Node) = nodeBuilder(nextId()).also { nodes.add(it) }
}
private val constraintGraph = ConstraintGraph()
private fun DataFlowIR.Type.resolved(): DataFlowIR.Type.Declared {
if (this is DataFlowIR.Type.Declared) return this
val hash = (this as DataFlowIR.Type.External).hash
return externalModulesDFG.publicTypes[hash] ?: error("Unable to resolve exported type $this")
}
private fun DataFlowIR.FunctionSymbol.resolved(): DataFlowIR.FunctionSymbol {
if (this is DataFlowIR.FunctionSymbol.External)
return externalModulesDFG.publicFunctions[this.hash] ?: this
return this
}
private inline fun forEachBitInBoth(first: BitSet, second: BitSet, block: (Int) -> Unit) {
if (first.cardinality() < second.cardinality())
first.forEachBit {
if (second[it])
block(it)
}
else second.forEachBit {
if (first[it])
block(it)
}
}
private inline fun IntArray.forEachEdge(v: Int, block: (Int) -> Unit) {
for (i in this[v] until this[v + 1])
block(this[i])
}
inner class TypeHierarchy(val allTypes: Array<DataFlowIR.Type.Declared>) {
private val typesSubTypes = Array(allTypes.size) { mutableListOf<DataFlowIR.Type.Declared>() }
private val allInheritors = Array(allTypes.size) { BitSet() }
init {
val visited = BitSet()
fun processType(type: DataFlowIR.Type.Declared) {
if (visited[type.index]) return
visited.set(type.index)
type.superTypes
.map { it.resolved() }
.forEach { superType ->
val subTypes = typesSubTypes[superType.index]
subTypes += type
processType(superType)
}
}
allTypes.forEach { processType(it) }
}
fun inheritorsOf(type: DataFlowIR.Type.Declared): BitSet {
val typeId = type.index
val inheritors = allInheritors[typeId]
if (!inheritors.isEmpty || type == DataFlowIR.Type.Virtual) return inheritors
inheritors.set(typeId)
for (subType in typesSubTypes[typeId])
inheritors.or(inheritorsOf(subType))
return inheritors
}
}
private fun DataFlowIR.Type.Declared.calleeAt(callSite: DataFlowIR.Node.VirtualCall) = when (callSite) {
is DataFlowIR.Node.VtableCall ->
vtable[callSite.calleeVtableIndex]
is DataFlowIR.Node.ItableCall ->
itable[callSite.calleeHash]!!
else -> error("Unreachable")
}
fun BitSet.copy() = BitSet(this.size()).apply { this.or(this@copy) }
fun logPathToType(reversedEdges: IntArray, node: Node, type: Int) {
val nodes = constraintGraph.nodes
val visited = BitSet()
val prev = mutableMapOf<Node, Node>()
var front = mutableListOf<Node>()
front.add(node)
visited.set(node.id)
lateinit var source: Node.Source
bfs@while (front.isNotEmpty()) {
val prevFront = front
front = mutableListOf()
for (from in prevFront) {
var endBfs = false
reversedEdges.forEachEdge(from.id) { toId ->
val to = nodes[toId]
if (!visited[toId] && to.types[type]) {
visited.set(toId)
prev[to] = from
front.add(to)
if (to is Node.Source) {
source = to
endBfs = true
return@forEachEdge
}
}
}
if (endBfs) break@bfs
val reversedCastEdges = from.reversedCastEdges
if (reversedCastEdges != null)
for (castEdge in reversedCastEdges) {
val to = castEdge.node
if (!visited[to.id] && castEdge.suitableTypes[type] && to.types[type]) {
visited.set(to.id)
prev[to] = from
front.add(to)
if (to is Node.Source) {
source = to
break@bfs
}
}
}
}
}
try {
var cur: Node = source
do {
context.log { " #${cur.id}" }
cur = prev[cur]!!
} while (cur != node)
} catch (t: Throwable) {
context.log { "Unable to print path" }
}
}
private inner class Condensation(val multiNodes: IntArray, val topologicalOrder: IntArray) {
inline fun forEachNode(node: Node, block: (Node) -> Unit) {
for (i in node.multiNodeStart until node.multiNodeEnd)
block(constraintGraph.nodes[multiNodes[i]])
}
}
private inner class CondensationBuilder(val directEdges: IntArray, val reversedEdges: IntArray) {
val nodes = constraintGraph.nodes
val nodesCount = nodes.size
val visited = BitSet(nodesCount)
var index = 0
val multiNodes = IntArray(nodesCount)
fun build(): Condensation {
// First phase.
val order = IntArray(nodesCount)
for (node in nodes) {
if (!visited[node.id])
findOrder(node, order)
}
// Second phase.
visited.clear()
index = 0
var multiNodesCount = 0
val multiNodesRepresentatives = IntArray(nodesCount)
for (i in order.size - 1 downTo 0) {
val nodeIndex = order[i]
if (visited[nodeIndex]) continue
multiNodesRepresentatives[multiNodesCount++] = nodeIndex
val start = index
paint(nodes[nodeIndex])
val end = index
for (multiNodeIndex in start until end) {
val node = nodes[multiNodes[multiNodeIndex]]
node.multiNodeStart = start
node.multiNodeEnd = end
}
}
// Topsort the built condensation.
visited.clear()
index = 0
val multiNodesOrder = IntArray(multiNodesCount)
for (v in multiNodesRepresentatives) {
if (!visited[v])
findMultiNodesOrder(nodes[v], multiNodesOrder)
}
multiNodesOrder.reverse()
return Condensation(multiNodes, multiNodesOrder)
}
private fun findOrder(node: Node, order: IntArray) {
visited.set(node.id)
directEdges.forEachEdge(node.id) {
if (!visited[it])
findOrder(nodes[it], order)
}
order[index++] = node.id
}
private fun paint(node: Node) {
visited.set(node.id)
multiNodes[index++] = node.id
reversedEdges.forEachEdge(node.id) {
if (!visited[it])
paint(nodes[it])
}
}
private fun findMultiNodesOrder(multiNode: Node, order: IntArray) {
visited.set(multiNode.id)
for (v in multiNode.multiNodeStart until multiNode.multiNodeEnd) {
val node = nodes[multiNodes[v]]
directEdges.forEachEdge(node.id) {
val nextMultiNode = multiNodes[nodes[it].multiNodeStart]
if (!visited[nextMultiNode])
findMultiNodesOrder(nodes[nextMultiNode], order)
}
}
order[index++] = multiNode.id
}
}
private fun DataFlowIR.Node.VirtualCall.debugString() =
irCallSite?.let { ir2stringWhole(it).trimEnd() } ?: this.toString()
fun analyze(): AnalysisResult {
val functions = moduleDFG.functions + externalModulesDFG.functionDFGs
assert(DataFlowIR.Type.Virtual !in symbolTable.classMap.values) {
"DataFlowIR.Type.Virtual cannot be in symbolTable.classMap"
}
val allDeclaredTypes = listOf(DataFlowIR.Type.Virtual) +
symbolTable.classMap.values.filterIsInstance<DataFlowIR.Type.Declared>() +
symbolTable.primitiveMap.values.filterIsInstance<DataFlowIR.Type.Declared>() +
externalModulesDFG.allTypes
val allTypes = Array<DataFlowIR.Type.Declared>(allDeclaredTypes.size) { DataFlowIR.Type.Virtual }
for (type in allDeclaredTypes)
allTypes[type.index] = type
val typeHierarchy = TypeHierarchy(allTypes)
val rootSet = computeRootSet(context, moduleDFG, externalModulesDFG)
val nodesMap = mutableMapOf<DataFlowIR.Node, Node>()
val (instantiatingClasses, directEdges, reversedEdges) = buildConstraintGraph(nodesMap, functions, typeHierarchy, rootSet)
context.logMultiple {
+"FULL CONSTRAINT GRAPH"
constraintGraph.nodes.forEach {
+" NODE #${it.id}"
directEdges.forEachEdge(it.id) { +" EDGE: #${it}z" }
it.directCastEdges?.forEach {
+" CAST EDGE: #${it.node.id}z casted to ${it.suitableTypes.format(allTypes)}"
}
allTypes.forEachIndexed { index, type ->
if (it.types[index])
+" TYPE: $type"
}
}
+""
}
constraintGraph.nodes.forEach {
if (it is Node.Source) {
assert(reversedEdges[it.id] == reversedEdges[it.id + 1]) { "A source node #${it.id} has incoming edges" }
assert(it.reversedCastEdges?.isEmpty() ?: true) { "A source node #${it.id} has incoming edges" }
}
}
context.logMultiple {
val edgesCount = constraintGraph.nodes.sumBy {
(directEdges[it.id + 1] - directEdges[it.id]) + (it.directCastEdges?.size ?: 0)
}
+"CONSTRAINT GRAPH: ${constraintGraph.nodes.size} nodes, $edgesCount edges"
+""
}
val condensation = CondensationBuilder(directEdges, reversedEdges).build()
val topologicalOrder = condensation.topologicalOrder.map { constraintGraph.nodes[it] }
context.logMultiple {
+"CONDENSATION"
topologicalOrder.forEachIndexed { index, multiNode ->
+" MULTI-NODE #$index"
condensation.forEachNode(multiNode) { +" #${it.id}: ${it.toString(allTypes)}" }
}
+""
}
topologicalOrder.forEachIndexed { index, multiNode ->
condensation.forEachNode(multiNode) { node -> node.priority = index }
}
val badEdges = mutableListOf<Pair<Node, Node.CastEdge>>()
for (node in constraintGraph.nodes) {
node.directCastEdges
?.filter { it.node.priority < node.priority } // Contradicts topological order.
?.forEach { badEdges += node to it }
}
badEdges.sortBy { it.second.node.priority } // Heuristic.
// First phase - greedy phase.
var iterations = 0
val maxNumberOfIterations = 2
do {
++iterations
// Handle all 'right-directed' edges.
// TODO: this is pessimistic handling of [DataFlowIR.Type.Virtual], think how to do it better.
for (multiNode in topologicalOrder) {
if (multiNode.multiNodeSize == 1 && multiNode is Node.Source)
continue // A source has no incoming edges.
val types = BitSet()
condensation.forEachNode(multiNode) { node ->
reversedEdges.forEachEdge(node.id) {
types.or(constraintGraph.nodes[it].types)
}
node.reversedCastEdges
?.filter { it.node.priority < node.priority } // Doesn't contradict topological order.
?.forEach {
val sourceTypes = it.node.types.copy()
sourceTypes.and(it.suitableTypes)
types.or(sourceTypes)
}
}
condensation.forEachNode(multiNode) { node -> node.types.or(types) }
}
if (iterations >= maxNumberOfIterations) break
var end = true
for ((sourceNode, edge) in badEdges) {
val distNode = edge.node
val missingTypes = sourceNode.types.copy().apply { andNot(distNode.types) }
missingTypes.and(edge.suitableTypes)
if (!missingTypes.isEmpty) {
end = false
distNode.types.or(missingTypes)
}
}
} while (!end)
// Second phase - do BFS.
val nodesCount = constraintGraph.nodes.size
val marked = BitSet(nodesCount)
var front = IntArray(nodesCount)
var prevFront = IntArray(nodesCount)
var frontSize = 0
val tempBitSet = BitSet()
for ((sourceNode, edge) in badEdges) {
val distNode = edge.node
tempBitSet.clear()
tempBitSet.or(sourceNode.types)
tempBitSet.andNot(distNode.types)
tempBitSet.and(edge.suitableTypes)
distNode.types.or(tempBitSet)
if (!marked[distNode.id] && !tempBitSet.isEmpty) {
marked.set(distNode.id)
front[frontSize++] = distNode.id
}
}
while (frontSize > 0) {
val prevFrontSize = frontSize
frontSize = 0
val temp = front
front = prevFront
prevFront = temp
for (i in 0 until prevFrontSize) {
marked[prevFront[i]] = false
val node = constraintGraph.nodes[prevFront[i]]
directEdges.forEachEdge(node.id) { distNodeId ->
val distNode = constraintGraph.nodes[distNodeId]
if (marked[distNode.id])
distNode.types.or(node.types)
else {
tempBitSet.clear()
tempBitSet.or(node.types)
tempBitSet.andNot(distNode.types)
distNode.types.or(node.types)
if (!marked[distNode.id] && !tempBitSet.isEmpty) {
marked.set(distNode.id)
front[frontSize++] = distNode.id
}
}
}
node.directCastEdges?.forEach { edge ->
val distNode = edge.node
tempBitSet.clear()
tempBitSet.or(node.types)
tempBitSet.andNot(distNode.types)
tempBitSet.and(edge.suitableTypes)
distNode.types.or(tempBitSet)
if (!marked[distNode.id] && !tempBitSet.isEmpty) {
marked.set(distNode.id)
front[frontSize++] = distNode.id
}
}
}
}
context.logMultiple {
topologicalOrder.forEachIndexed { index, multiNode ->
+"Types of multi-node #$index"
condensation.forEachNode(multiNode) { node ->
+" Node #${node.id}"
allTypes.asSequence()
.withIndex()
.filter { node.types[it.index] }.toList()
.forEach { +" ${it.value}" }
}
}
+""
}
val result = mutableMapOf<DataFlowIR.Node.VirtualCall, Pair<DevirtualizedCallSite, DataFlowIR.FunctionSymbol>>()
val nothing = symbolTable.classMap[context.ir.symbols.nothing.owner]
for (function in functions.values) {
if (!constraintGraph.functions.containsKey(function.symbol)) continue
function.body.forEachNonScopeNode { node ->
val virtualCall = node as? DataFlowIR.Node.VirtualCall ?: return@forEachNonScopeNode
assert(nodesMap[virtualCall] != null) { "Node for virtual call $virtualCall has not been built" }
val receiverNode = constraintGraph.virtualCallSiteReceivers[virtualCall]
?: error("virtualCallSiteReceivers were not built for virtual call $virtualCall")
if (receiverNode.types[VIRTUAL_TYPE_ID]) {
context.logMultiple {
+"Unable to devirtualize callsite ${virtualCall.debugString()}"
+" receiver is Virtual"
logPathToType(reversedEdges, receiverNode, VIRTUAL_TYPE_ID)
+""
}
return@forEachNonScopeNode
}
context.log { "Devirtualized callsite ${virtualCall.debugString()}" }
val receiverType = virtualCall.receiverType.resolved()
val possibleReceivers = mutableListOf<DataFlowIR.Type.Declared>()
forEachBitInBoth(receiverNode.types, typeHierarchy.inheritorsOf(receiverType)) {
val type = allTypes[it]
assert(instantiatingClasses[it]) { "Non-instantiating class $type" }
if (type != nothing) {
context.logMultiple {
+"Path to type $type"
logPathToType(reversedEdges, receiverNode, it)
}
possibleReceivers.add(type)
}
}
context.log { "" }
result[virtualCall] = DevirtualizedCallSite(virtualCall.callee.resolved(),
possibleReceivers.map { possibleReceiverType ->
val callee = possibleReceiverType.calleeAt(virtualCall)
if (callee is DataFlowIR.FunctionSymbol.Declared && callee.symbolTableIndex < 0)
error("Function ${possibleReceiverType}.$callee cannot be called virtually," +
" but actually is at call site: ${virtualCall.debugString()}")
DevirtualizedCallee(possibleReceiverType, callee)
}) to function.symbol
}
}
context.logMultiple {
+"Devirtualized from current module:"
result.forEach { virtualCall, devirtualizedCallSite ->
if (virtualCall.irCallSite != null) {
+"DEVIRTUALIZED"
+"FUNCTION: ${devirtualizedCallSite.second}"
+"CALL SITE: ${virtualCall.debugString()}"
+"POSSIBLE RECEIVERS:"
devirtualizedCallSite.first.possibleCallees.forEach { +" TYPE: ${it.receiverType}" }
devirtualizedCallSite.first.possibleCallees.forEach { +" FUN: ${it.callee}" }
+""
}
}
+"Devirtualized from external modules:"
result.forEach { virtualCall, devirtualizedCallSite ->
if (virtualCall.irCallSite == null) {
+"DEVIRTUALIZED"
+"FUNCTION: ${devirtualizedCallSite.second}"
+"CALL SITE: ${virtualCall.debugString()}"
+"POSSIBLE RECEIVERS:"
devirtualizedCallSite.first.possibleCallees.forEach { +" TYPE: ${it.receiverType}" }
devirtualizedCallSite.first.possibleCallees.forEach { +" FUN: ${it.callee}" }
+""
}
}
}
return AnalysisResult(result.asSequence().associateBy({ it.key }, { it.value.first }), typeHierarchy)
}
// Both [directEdges] and [reversedEdges] are the array representation of a graph:
// for each node v the edges of that node are stored in edges[edges[v] until edges[v + 1]].
private data class ConstraintGraphBuildResult(val instantiatingClasses: BitSet,
val directEdges: IntArray, val reversedEdges: IntArray)
// Here we're dividing the build process onto two phases:
// 1. build bag of edges and direct edges array;
// 2. build reversed edges array from the direct edges array.
// This is to lower memory usage (all of these edges structures are more or less equal by size),
// and by that we're only holding references to two out of three of them.
private fun buildConstraintGraph(nodesMap: MutableMap<DataFlowIR.Node, Node>,
functions: Map<DataFlowIR.FunctionSymbol, DataFlowIR.Function>,
typeHierarchy: TypeHierarchy,
rootSet: List<DataFlowIR.FunctionSymbol>
): ConstraintGraphBuildResult {
val precursor = buildConstraintGraphPrecursor(nodesMap, functions, typeHierarchy, rootSet)
return ConstraintGraphBuildResult(precursor.instantiatingClasses, precursor.directEdges,
buildReversedEdges(precursor.directEdges, precursor.reversedEdgesCount))
}
private class ConstraintGraphPrecursor(val instantiatingClasses: BitSet,
val directEdges: IntArray, val reversedEdgesCount: IntArrayList)
private fun buildReversedEdges(directEdges: IntArray, reversedEdgesCount: IntArrayList): IntArray {
val numberOfNodes = constraintGraph.nodes.size
var edgesArraySize = numberOfNodes + 1
for (v in 0 until numberOfNodes)
edgesArraySize += reversedEdgesCount[v]
val reversedEdges = IntArray(edgesArraySize)
var index = numberOfNodes + 1
for (v in 0..numberOfNodes) {
reversedEdges[v] = index
index += reversedEdgesCount[v]
reversedEdgesCount[v] = 0
}
for (from in 0 until numberOfNodes) {
directEdges.forEachEdge(from) { to ->
reversedEdges[reversedEdges[to] + (reversedEdgesCount[to]++)] = from
}
}
return reversedEdges
}
private fun buildConstraintGraphPrecursor(nodesMap: MutableMap<DataFlowIR.Node, Node>,
functions: Map<DataFlowIR.FunctionSymbol, DataFlowIR.Function>,
typeHierarchy: TypeHierarchy,
rootSet: List<DataFlowIR.FunctionSymbol>
): ConstraintGraphPrecursor {
val constraintGraphBuilder = ConstraintGraphBuilder(nodesMap, functions, typeHierarchy, rootSet, true)
constraintGraphBuilder.build()
val bagOfEdges = constraintGraphBuilder.bagOfEdges
val directEdgesCount = constraintGraphBuilder.directEdgesCount
val reversedEdgesCount = constraintGraphBuilder.reversedEdgesCount
val numberOfNodes = constraintGraph.nodes.size
// numberOfNodes + 1 for convenience.
directEdgesCount.reserve(numberOfNodes + 1)
reversedEdgesCount.reserve(numberOfNodes + 1)
var edgesArraySize = numberOfNodes + 1
for (v in 0 until numberOfNodes)
edgesArraySize += directEdgesCount[v]
val directEdges = IntArray(edgesArraySize)
var index = numberOfNodes + 1
for (v in 0..numberOfNodes) {
directEdges[v] = index
index += directEdgesCount[v]
directEdgesCount[v] = 0
}
for (bucket in bagOfEdges)
if (bucket != null)
for (edge in bucket) {
val from = edge.toInt()
val to = (edge shr 32).toInt()
directEdges[directEdges[from] + (directEdgesCount[from]++)] = to
}
return ConstraintGraphPrecursor(constraintGraphBuilder.instantiatingClasses, directEdges, reversedEdgesCount)
}
private class ConstraintGraphVirtualCall(val caller: Function, val virtualCall: DataFlowIR.Node.VirtualCall,
val arguments: List<Node>, val returnsNode: Node)
private inner class ConstraintGraphBuilder(val functionNodesMap: MutableMap<DataFlowIR.Node, Node>,
val functions: Map<DataFlowIR.FunctionSymbol, DataFlowIR.Function>,
val typeHierarchy: TypeHierarchy,
val rootSet: List<DataFlowIR.FunctionSymbol>,
val useTypes: Boolean) {
private val allTypes = typeHierarchy.allTypes
private val variables = mutableMapOf<DataFlowIR.Node.Variable, Node>()
private val typesVirtualCallSites = Array(allTypes.size) { mutableListOf<ConstraintGraphVirtualCall>() }
private val suitableTypes = arrayOfNulls<BitSet?>(allTypes.size)
private val concreteClasses = arrayOfNulls<Node?>(allTypes.size)
private val virtualTypeFilter = BitSet().apply { set(VIRTUAL_TYPE_ID) }
val instantiatingClasses = BitSet()
private val preliminaryNumberOfNodes =
allTypes.size + // A possible source node for each type.
functions.size * 2 + // <returns> and <throws> nodes for each function.
functions.values.sumBy {
it.body.allScopes.sumBy { it.nodes.size } // A node for each DataFlowIR.Node.
} +
functions.values
.sumBy { function ->
function.body.allScopes.sumBy {
it.nodes.count { node ->
// A cast if types are different.
node is DataFlowIR.Node.Call
&& node.returnType.resolved() != node.callee.returnParameter.type.resolved()
}
}
}
private fun isPrime(x: Int): Boolean {
if (x <= 3) return true
if (x % 2 == 0) return false
var r = 3
while (r * r <= x) {
if (x % r == 0) return false
r += 2
}
return true
}
private fun makePrime(p: Int): Int {
var x = p
while (true) {
if (isPrime(x)) return x
++x
}
}
// A heuristic: the number of edges in the data flow graph
// for any reasonable program is linear in number of nodes.
val bagOfEdges = arrayOfNulls<LongArrayList>(makePrime(preliminaryNumberOfNodes * 5))
val directEdgesCount = IntArrayList()
val reversedEdgesCount = IntArrayList()
@OptIn(ExperimentalUnsignedTypes::class)
private fun addEdge(from: Node, to: Node) {
val fromId = from.id
val toId = to.id
val value = fromId.toLong() or (toId.toLong() shl 32)
// This is 64-bit extension of a hashing method from Knuth's "The Art of Computer Programming".
// The magic constant is the closest prime to 2^64 * phi, where phi is the golden ratio.
val bucketIdx = ((value.toULong() * 11400714819323198393UL) % bagOfEdges.size.toUInt()).toInt()
val bucket = bagOfEdges[bucketIdx] ?: LongArrayList().also { bagOfEdges[bucketIdx] = it }
for (x in bucket)
if (x == value) return
bucket.add(value)
directEdgesCount.reserve(fromId + 1)
directEdgesCount[fromId]++
reversedEdgesCount.reserve(toId + 1)
reversedEdgesCount[toId]++
}
private fun concreteType(type: DataFlowIR.Type.Declared): Int {
assert(!(type.isAbstract && type.isFinal)) { "Incorrect type: $type" }
return if (type.isAbstract)
VIRTUAL_TYPE_ID
else {
if (!instantiatingClasses[type.index])
error("Type $type is not instantiated")
type.index
}
}
private fun ordinaryNode(nameBuilder: () -> String) =
constraintGraph.addNode { Node.Ordinary(it, nameBuilder) }
private fun sourceNode(typeId: Int, nameBuilder: () -> String) =
constraintGraph.addNode { Node.Source(it, typeId, nameBuilder) }
private fun concreteClass(type: DataFlowIR.Type.Declared) =
concreteClasses[type.index]
?: sourceNode(concreteType(type)) { "Class\$$type" }.also { concreteClasses[type.index] = it}
private fun fieldNode(field: DataFlowIR.Field) =
constraintGraph.fields.getOrPut(field) {
val fieldNode = ordinaryNode { "Field\$$field" }
if (entryPoint == null) {
// TODO: This is conservative.
val fieldType = field.type.resolved()
// Some user of our library might place some value into the field.
if (fieldType.isFinal)
addEdge(concreteClass(fieldType), fieldNode)
else
addEdge(constraintGraph.virtualNode, fieldNode)
}
fieldNode
}
private var stack = mutableListOf<DataFlowIR.FunctionSymbol>()
fun build() {
// Rapid Type Analysis: find all instantiations and conservatively estimate call graph.
// Add all final parameters of the roots.
for (root in rootSet) {
root.parameters
.map { it.type.resolved() }
.filter { it.isFinal }
.forEach { addInstantiatingClass(it) }
}
if (entryPoint == null) {
// For library assume all public non-abstract classes could be instantiated.
// Note: for constructors there is additional parameter (<this>) and for associated objects
// its type will be added to instantiating classes since all objects are final types.
symbolTable.classMap.values
.filterIsInstance<DataFlowIR.Type.Public>()
.filter { !it.isAbstract }
.forEach { addInstantiatingClass(it) }
} else {
// String arguments are implicitly put into the <args> array parameter of <main>.
addInstantiatingClass(symbolTable.mapType(context.irBuiltIns.stringType).resolved())
addEdge(concreteClass(symbolTable.mapType(context.irBuiltIns.stringType).resolved()),
fieldNode(constraintGraph.arrayItemField))
}
rootSet.forEach { createFunctionConstraintGraph(it, true) }
while (stack.isNotEmpty()) {
val symbol = stack.pop()
val function = functions[symbol] ?: continue
val body = function.body
val functionConstraintGraph = constraintGraph.functions[symbol]!!
body.forEachNonScopeNode { dfgNodeToConstraintNode(functionConstraintGraph, it) }
addEdge(functionNodesMap[body.returns]!!, functionConstraintGraph.returns)
addEdge(functionNodesMap[body.throws]!!, functionConstraintGraph.throws)
context.logMultiple {
+"CONSTRAINT GRAPH FOR $symbol"
val ids = function.body.allScopes.flatMap { it.nodes }.withIndex().associateBy({ it.value }, { it.index })
function.body.forEachNonScopeNode { node ->
+"FT NODE #${ids[node]}"
+DataFlowIR.Function.nodeToString(node, ids)
val constraintNode = functionNodesMap[node] ?: variables[node] ?: return@forEachNonScopeNode
+" CG NODE #${constraintNode.id}: ${constraintNode.toString(allTypes)}"
}
+"Returns: #${ids[function.body.returns]}"
+""
}
}
suitableTypes.forEach {
it?.and(instantiatingClasses)
it?.set(VIRTUAL_TYPE_ID)
}
if (entryPoint == null) {
for (list in typesVirtualCallSites)
for (virtualCall in list) {
val returnType = virtualCall.virtualCall.returnType.resolved()
val totalIncomingEdgesToReturnsNode =
if (virtualCall.returnsNode.id >= reversedEdgesCount.size)
0
else reversedEdgesCount[virtualCall.returnsNode.id]
if (returnType.isFinal && totalIncomingEdgesToReturnsNode == 0) {
// If we are in a library and facing final return type with no possible callees -
// this type still can be returned by some user of this library, so propagate it explicitly.
addEdge(concreteClass(returnType), virtualCall.returnsNode)
}
}
}
}
private fun createFunctionConstraintGraph(symbol: DataFlowIR.FunctionSymbol, isRoot: Boolean): Function? {
if (symbol is DataFlowIR.FunctionSymbol.External) return null
constraintGraph.functions[symbol]?.let { return it }
val parameters = Array(symbol.parameters.size) { ordinaryNode { "Param#$it\$$symbol" } }
if (isRoot) {
// Exported function from the current module.
symbol.parameters.forEachIndexed { index, type ->
val resolvedType = type.type.resolved()
val node = if (!resolvedType.isFinal)
constraintGraph.virtualNode // TODO: OBJC-INTEROP-GENERATED-CLASSES
else
concreteClass(resolvedType)
addEdge(node, parameters[index])
}
}
val returnsNode = ordinaryNode { "Returns\$$symbol" }
val throwsNode = ordinaryNode { "Throws\$$symbol" }
val functionConstraintGraph = Function(symbol, parameters, returnsNode, throwsNode)
constraintGraph.functions[symbol] = functionConstraintGraph
stack.push(symbol)
return functionConstraintGraph
}
private fun addInstantiatingClass(type: DataFlowIR.Type.Declared) {
if (instantiatingClasses[type.index]) return
instantiatingClasses.set(type.index)
context.log { "Adding instantiating class: $type" }
checkSupertypes(type, type, BitSet())
}
private fun processVirtualCall(virtualCall: ConstraintGraphVirtualCall,
receiverType: DataFlowIR.Type.Declared) {
context.logMultiple {
+"Processing virtual call: ${virtualCall.virtualCall.callee}"
+"Receiver type: $receiverType"
}
val callee = receiverType.calleeAt(virtualCall.virtualCall)
addEdge(doCall(virtualCall.caller, callee, virtualCall.arguments,
callee.returnParameter.type.resolved()), virtualCall.returnsNode)
}
private fun checkSupertypes(type: DataFlowIR.Type.Declared,
inheritor: DataFlowIR.Type.Declared,
seenTypes: BitSet) {
seenTypes.set(type.index)
context.logMultiple {
+"Checking supertype $type of $inheritor"
typesVirtualCallSites[type.index].let {
if (it.isEmpty())
+"None virtual call sites encountered yet"
else {
+"Virtual call sites:"
it.forEach { +" ${it.virtualCall.callee}" }
}
}
+""
}
typesVirtualCallSites[type.index].let { virtualCallSites ->
var index = 0
while (index < virtualCallSites.size) {
processVirtualCall(virtualCallSites[index], inheritor)
++index
}
}
for (superType in type.superTypes) {
val resolvedSuperType = superType.resolved()
if (!seenTypes[resolvedSuperType.index])
checkSupertypes(resolvedSuperType, inheritor, seenTypes)
}
}
private fun createCastEdge(node: Node, type: DataFlowIR.Type.Declared): Node.CastEdge {
if (suitableTypes[type.index] == null)
suitableTypes[type.index] = typeHierarchy.inheritorsOf(type).copy()
return Node.CastEdge(node, suitableTypes[type.index]!!)
}
private fun doCast(function: Function, node: Node, type: DataFlowIR.Type.Declared): Node {
val castNode = ordinaryNode { "Cast\$${function.symbol}" }
val castEdge = createCastEdge(castNode, type)
node.addCastEdge(castEdge)
return castNode
}
private fun castIfNeeded(function: Function, node: Node,
nodeType: DataFlowIR.Type.Declared, type: DataFlowIR.Type.Declared) =
if (!useTypes || type == nodeType)
node
else doCast(function, node, type)
private fun edgeToConstraintNode(function: Function,
edge: DataFlowIR.Edge): Node {
val result = dfgNodeToConstraintNode(function, edge.node)
val castToType = edge.castToType?.resolved() ?: return result
return doCast(function, result, castToType)
}
fun doCall(caller: Function, callee: Function, arguments: List<Node>, returnType: DataFlowIR.Type.Declared): Node {
assert(callee.parameters.size == arguments.size) {
"Function ${callee.symbol} takes ${callee.parameters.size} but caller ${caller.symbol}" +
" provided ${arguments.size}"
}
callee.parameters.forEachIndexed { index, parameter ->
addEdge(arguments[index], parameter)
}
return castIfNeeded(caller, callee.returns, callee.symbol.returnParameter.type.resolved(), returnType)
}
fun doCall(caller: Function, callee: DataFlowIR.FunctionSymbol,
arguments: List<Node>, returnType: DataFlowIR.Type.Declared): Node {
val resolvedCallee = callee.resolved()
val calleeConstraintGraph = createFunctionConstraintGraph(resolvedCallee, false)
return if (calleeConstraintGraph == null) {
constraintGraph.externalFunctions.getOrPut(resolvedCallee to returnType) {
val fictitiousReturnNode = ordinaryNode { "External$resolvedCallee" }
if (returnType.isFinal) {
addInstantiatingClass(returnType)
addEdge(concreteClass(returnType), fictitiousReturnNode)
} else {
addEdge(constraintGraph.virtualNode, fictitiousReturnNode)
// TODO: Unconservative way - when we can use it?
// TODO: OBJC-INTEROP-GENERATED-CLASSES
// typeHierarchy.inheritorsOf(returnType)
// .filterNot { it.isAbstract }
// .filter { instantiatingClasses.containsKey(it) }
// .forEach { concreteClass(it).addEdge(fictitiousReturnNode) }
}
fictitiousReturnNode
}
} else {
addEdge(calleeConstraintGraph.throws, caller.throws)
doCall(caller, calleeConstraintGraph, arguments, returnType)
}
}
/**
* Takes a function DFG's node and creates a constraint graph node corresponding to it.
* Also creates all necessary edges.
*/
private fun dfgNodeToConstraintNode(function: Function, node: DataFlowIR.Node): Node {
fun edgeToConstraintNode(edge: DataFlowIR.Edge): Node =
edgeToConstraintNode(function, edge)
fun doCall(callee: DataFlowIR.FunctionSymbol, arguments: List<Node>,
returnType: DataFlowIR.Type.Declared) =
doCall(function, callee, arguments, returnType)
fun readField(field: DataFlowIR.Field, actualType: DataFlowIR.Type.Declared): Node {
val fieldNode = fieldNode(field)
val expectedType = field.type.resolved()
return if (!useTypes || actualType == expectedType)
fieldNode
else
doCast(function, fieldNode, actualType)
}
fun writeField(field: DataFlowIR.Field, actualType: DataFlowIR.Type.Declared, value: Node) {
val fieldNode = fieldNode(field)
val expectedType = field.type.resolved()
val castedValue = if (!useTypes || actualType == expectedType)
value
else
doCast(function, value, actualType)
addEdge(castedValue, fieldNode)
}
if (node is DataFlowIR.Node.Variable && node.kind != DataFlowIR.VariableKind.Temporary) {
var variableNode = variables[node]
if (variableNode == null) {
variableNode = ordinaryNode { "Variable\$${function.symbol}" }
variables[node] = variableNode
for (value in node.values) {
addEdge(edgeToConstraintNode(value), variableNode)
}
if (node.kind == DataFlowIR.VariableKind.CatchParameter)
function.throws.addCastEdge(createCastEdge(variableNode, node.type.resolved()))
}
return variableNode
}
return functionNodesMap.getOrPut(node) {
when (node) {
is DataFlowIR.Node.Const -> {
val type = node.type.resolved()
addInstantiatingClass(type)
sourceNode(concreteType(type)) { "Const\$${function.symbol}" }
}
DataFlowIR.Node.Null -> constraintGraph.voidNode
is DataFlowIR.Node.Parameter ->
function.parameters[node.index]
is DataFlowIR.Node.StaticCall -> {
val arguments = node.arguments.map(::edgeToConstraintNode)
doCall(node.callee, arguments, node.returnType.resolved())
}
is DataFlowIR.Node.NewObject -> {
val returnType = node.constructedType.resolved()
addInstantiatingClass(returnType)
val instanceNode = concreteClass(returnType)
val arguments = listOf(instanceNode) + node.arguments.map(::edgeToConstraintNode)
doCall(node.callee, arguments, returnType)
instanceNode
}
is DataFlowIR.Node.VirtualCall -> {
val callee = node.callee
val receiverType = node.receiverType.resolved()
context.logMultiple {
+"Virtual call"
+"Caller: ${function.symbol}"
+"Callee: $callee"
+"Receiver type: $receiverType"
+"Possible callees:"
forEachBitInBoth(typeHierarchy.inheritorsOf(receiverType), instantiatingClasses) {
+allTypes[it].calleeAt(node).toString()
}
+""
}
val returnType = node.returnType.resolved()
val arguments = node.arguments.map(::edgeToConstraintNode)
val receiverNode = arguments[0]
if (receiverType == DataFlowIR.Type.Virtual)
addEdge(constraintGraph.virtualNode, receiverNode)
if (entryPoint == null && returnType.isFinal) {
// If we are in a library and facing final return type then
// this type can be returned by some user of this library, so propagate it explicitly.
addInstantiatingClass(returnType)
}
val returnsNode = ordinaryNode { "VirtualCallReturns\$${function.symbol}" }
if (receiverType != DataFlowIR.Type.Virtual)
typesVirtualCallSites[receiverType.index].add(
ConstraintGraphVirtualCall(function, node, arguments, returnsNode))
forEachBitInBoth(typeHierarchy.inheritorsOf(receiverType), instantiatingClasses) {
val actualCallee = allTypes[it].calleeAt(node)
addEdge(doCall(actualCallee, arguments, actualCallee.returnParameter.type.resolved()), returnsNode)
}
// Add cast to [Virtual] edge from receiver to returns, if return type is not final.
// With this we're reflecting the fact that unknown function can return anything.
if (!returnType.isFinal && entryPoint == null) {
receiverNode.addCastEdge(Node.CastEdge(returnsNode, virtualTypeFilter))
}
// And throw anything.
receiverNode.addCastEdge(Node.CastEdge(function.throws, virtualTypeFilter))
constraintGraph.virtualCallSiteReceivers[node] = receiverNode
castIfNeeded(function, returnsNode, node.callee.returnParameter.type.resolved(), returnType)
}
is DataFlowIR.Node.Singleton -> {
val type = node.type.resolved()
addInstantiatingClass(type)
val instanceNode = concreteClass(type)
node.constructor?.let { doCall(it, listOf(instanceNode), type) }
instanceNode
}
is DataFlowIR.Node.AllocInstance -> {
val type = node.type.resolved()
addInstantiatingClass(type)
concreteClass(type)
}
is DataFlowIR.Node.FunctionReference -> {
concreteClass(node.type.resolved())
}
is DataFlowIR.Node.FieldRead -> {
val type = node.field.type.resolved()
if (entryPoint == null && type.isFinal)
addInstantiatingClass(type)
readField(node.field, type)
}
is DataFlowIR.Node.FieldWrite -> {
val type = node.field.type.resolved()
if (entryPoint == null && type.isFinal)
addInstantiatingClass(type)
writeField(node.field, type, edgeToConstraintNode(node.value))
constraintGraph.voidNode
}
is DataFlowIR.Node.ArrayRead ->
readField(constraintGraph.arrayItemField, node.type.resolved())
is DataFlowIR.Node.ArrayWrite -> {
writeField(constraintGraph.arrayItemField, node.type.resolved(), edgeToConstraintNode(node.value))
constraintGraph.voidNode
}
is DataFlowIR.Node.Variable ->
node.values.map { edgeToConstraintNode(it) }.let { values ->
ordinaryNode { "TempVar\$${function.symbol}" }.also { node ->
values.forEach { addEdge(it, node) }
}
}
else -> error("Unreachable")
}
}
}
}
}
class DevirtualizedCallee(val receiverType: DataFlowIR.Type, val callee: DataFlowIR.FunctionSymbol)
class DevirtualizedCallSite(val callee: DataFlowIR.FunctionSymbol, val possibleCallees: List<DevirtualizedCallee>)
class AnalysisResult(val devirtualizedCallSites: Map<DataFlowIR.Node.VirtualCall, DevirtualizedCallSite>,
val typeHierarchy: DevirtualizationAnalysis.TypeHierarchy)
fun run(irModule: IrModuleFragment, context: Context, moduleDFG: ModuleDFG, externalModulesDFG: ExternalModulesDFG)
: AnalysisResult {
val devirtualizationAnalysisResult = DevirtualizationAnalysis(context, moduleDFG, externalModulesDFG).analyze()
val devirtualizedCallSites =
devirtualizationAnalysisResult.devirtualizedCallSites
.asSequence()
.filter { it.key.irCallSite != null }
.associate { it.key.irCallSite!! to it.value }
devirtualize(irModule, context, externalModulesDFG, devirtualizedCallSites)
removeRedundantCoercions(irModule, context)
return devirtualizationAnalysisResult
}
/**
* TODO: JVM inliner crashed on attempt inline this function from transform.kt with:
* j.l.IllegalStateException: Couldn't obtain compiled function body for
* public inline fun <reified T : org.jetbrains.kotlin.ir.IrElement> kotlin.collections.MutableList<T>.transform...
*/
private inline fun <reified T : IrElement> MutableList<T>.transform(transformation: (T) -> IrElement) {
forEachIndexed { i, item ->
set(i, transformation(item) as T)
}
}
private fun IrExpression.isBoxOrUnboxCall() =
(this is IrCall && symbol.owner.origin == DECLARATION_ORIGIN_INLINE_CLASS_SPECIAL_FUNCTION)
private fun devirtualize(irModule: IrModuleFragment, context: Context, externalModulesDFG: ExternalModulesDFG,
devirtualizedCallSites: Map<IrCall, DevirtualizedCallSite>) {
val symbols = context.ir.symbols
val nativePtrEqualityOperatorSymbol = symbols.areEqualByValue[PrimitiveBinaryType.POINTER]!!
val optimize = context.shouldOptimize()
fun DataFlowIR.Type.resolved(): DataFlowIR.Type.Declared {
if (this is DataFlowIR.Type.Declared) return this
val hash = (this as DataFlowIR.Type.External).hash
return externalModulesDFG.publicTypes[hash] ?: error("Unable to resolve exported type $hash")
}
fun DataFlowIR.FunctionSymbol.resolved(): DataFlowIR.FunctionSymbol {
if (this is DataFlowIR.FunctionSymbol.External)
return externalModulesDFG.publicFunctions[this.hash] ?: this
return this
}
fun IrBuilderWithScope.irCoerce(value: IrExpression, coercion: IrFunctionSymbol?) =
if (coercion == null)
value
else irCall(coercion).apply {
addArguments(listOf(coercion.descriptor.explicitParameters.single() to value))
}
fun IrBuilderWithScope.irCoerce(value: IrExpression, coercion: DataFlowIR.FunctionSymbol.Declared?) =
if (coercion == null)
value
else irCall(coercion.irFunction!!).apply {
putValueArgument(0, value)
}
class PossiblyCoercedValue(val value: IrVariable, val coercion: IrFunctionSymbol?) {
fun getFullValue(irBuilder: IrBuilderWithScope) = irBuilder.run {
irCoerce(irGet(value), coercion)
}
}
fun <T : IrElement> IrStatementsBuilder<T>.irTemporary(value: IrExpression, tempName: String, type: IrType): IrVariable {
val originalKotlinType = type.originalKotlinType ?: type.toKotlinType()
val descriptor = IrTemporaryVariableDescriptorImpl(scope.scopeOwner, Name.identifier(tempName), originalKotlinType, false)
val temporary = IrVariableImpl(
value.startOffset, value.endOffset, IrDeclarationOrigin.IR_TEMPORARY_VARIABLE, IrVariableSymbolImpl(descriptor),
descriptor.name, type, isVar = false, isConst = false, isLateinit = false
).apply {
this.initializer = value
}
+temporary
return temporary
}
fun <T : IrElement> IrStatementsBuilder<T>.irSplitCoercion(expression: IrExpression, tempName: String, actualType: IrType) =
if (!expression.isBoxOrUnboxCall())
PossiblyCoercedValue(irTemporary(expression, tempName, actualType), null)
else {
val coercion = expression as IrCall
PossiblyCoercedValue(
irTemporary(coercion.getValueArgument(0)!!, tempName,
coercion.symbol.owner.explicitParameters.single().type)
, coercion.symbol)
}
fun getTypeConversion(actualType: DataFlowIR.FunctionParameter,
targetType: DataFlowIR.FunctionParameter): DataFlowIR.FunctionSymbol.Declared? {
if (actualType.boxFunction == null && targetType.boxFunction == null) return null
if (actualType.boxFunction != null && targetType.boxFunction != null) {
assert (actualType.type.resolved() == targetType.type.resolved())
{ "Inconsistent types: ${actualType.type} and ${targetType.type}" }
return null
}
if (actualType.boxFunction == null)
return targetType.unboxFunction!!.resolved() as DataFlowIR.FunctionSymbol.Declared
return actualType.boxFunction.resolved() as DataFlowIR.FunctionSymbol.Declared
}
fun IrCallImpl.putArgument(index: Int, value: IrExpression) {
var receiversCount = 0
val callee = symbol.owner
if (callee.dispatchReceiverParameter != null)
++receiversCount
if (callee.extensionReceiverParameter != null)
++receiversCount
if (index >= receiversCount)
putValueArgument(index - receiversCount, value)
else {
if (callee.dispatchReceiverParameter != null && index == 0)
dispatchReceiver = value
else
extensionReceiver = value
}
}
fun IrBuilderWithScope.irDevirtualizedCall(callSite: IrCall,
actualType: IrType,
devirtualizedCallee: DevirtualizedCallee,
arguments: List<IrExpression>): IrCall {
val actualCallee = devirtualizedCallee.callee.irFunction as IrSimpleFunction
val call = IrCallImpl(
callSite.startOffset, callSite.endOffset,
actualType,
actualCallee.symbol,
actualCallee.typeParameters.size,
actualCallee.valueParameters.size,
callSite.origin,
actualCallee.parentAsClass.symbol
)
if (actualCallee.explicitParameters.size == arguments.size) {
arguments.forEachIndexed { index, argument -> call.putArgument(index, argument) }
return call
}
assert(actualCallee.isSuspend && actualCallee.explicitParameters.size == arguments.size - 1) {
"Incorrect number of arguments: expected [${actualCallee.explicitParameters.size}] but was [${arguments.size - 1}]\n" +
actualCallee.dump()
}
val continuation = arguments.last()
for (index in 0..arguments.size - 2)
call.putArgument(index, arguments[index])
return irCall(context.ir.symbols.coroutineLaunchpad, actualType).apply {
putValueArgument(0, call)
putValueArgument(1, continuation)
}
}
fun IrBuilderWithScope.irDevirtualizedCall(callee: IrCall, actualType: IrType,
devirtualizedCallee: DevirtualizedCallee,
arguments: List<PossiblyCoercedValue>): IrExpression {
val actualCallee = devirtualizedCallee.callee as DataFlowIR.FunctionSymbol.Declared
return actualCallee.bridgeTarget.let { bridgeTarget ->
if (bridgeTarget == null)
irDevirtualizedCall(callee, actualType,
devirtualizedCallee,
arguments.map { it.getFullValue(this@irDevirtualizedCall) })
else {
val callResult = irDevirtualizedCall(callee, actualType,
DevirtualizedCallee(devirtualizedCallee.receiverType, bridgeTarget),
arguments.mapIndexed { index, value ->
val coercion = getTypeConversion(actualCallee.parameters[index], bridgeTarget.parameters[index])
val fullValue = value.getFullValue(this@irDevirtualizedCall)
coercion?.let { irCoerce(fullValue, coercion) } ?: fullValue
})
val returnCoercion = getTypeConversion(bridgeTarget.returnParameter, actualCallee.returnParameter)
irCoerce(callResult, returnCoercion)
}
}
}
irModule.transformChildrenVoid(object: IrElementTransformerVoidWithContext() {
override fun visitCall(expression: IrCall): IrExpression {
expression.transformChildrenVoid(this)
val devirtualizedCallSite = devirtualizedCallSites[expression]
val possibleCallees = devirtualizedCallSite?.possibleCallees
if (possibleCallees == null
|| possibleCallees.any { it.callee is DataFlowIR.FunctionSymbol.External }
|| possibleCallees.any { it.receiverType is DataFlowIR.Type.External })
return expression
val callee = expression.symbol.owner
val owner = callee.parentAsClass
// TODO: Think how to evaluate different unfold factors (in terms of both execution speed and code size).
val classMaxUnfoldFactor = 3
val interfaceMaxUnfoldFactor = 3
val maxUnfoldFactor = if (owner.isInterface) interfaceMaxUnfoldFactor else classMaxUnfoldFactor
if (possibleCallees.size > maxUnfoldFactor) {
// Callsite too complicated to devirtualize.
return expression
}
val startOffset = expression.startOffset
val endOffset = expression.endOffset
val function = expression.symbol.owner
val type = if (callee.isSuspend)
context.irBuiltIns.anyNType
else function.returnType
val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset)
irBuilder.run {
val dispatchReceiver = expression.dispatchReceiver!!
return when {
possibleCallees.isEmpty() -> irBlock(expression) {
val throwExpr = irCall(symbols.throwInvalidReceiverTypeException.owner).apply {
putValueArgument(0,
irCall(symbols.kClassImplConstructor.owner, listOf(dispatchReceiver.type)).apply {
putValueArgument(0,
irCall(symbols.getObjectTypeInfo.owner).apply {
putValueArgument(0, dispatchReceiver)
})
})
}
// Insert proper unboxing (unreachable code):
+irCoerce(throwExpr, symbols.getTypeConversion(throwExpr.type, type))
}
optimize && possibleCallees.size == 1 -> { // Monomorphic callsite.
irBlock(expression) {
val parameters = expression.getArgumentsWithSymbols().mapIndexed { index, arg ->
irSplitCoercion(arg.second, "arg$index", arg.first.owner.type)
}
+irDevirtualizedCall(expression, type, possibleCallees[0], parameters)
}
}
else -> irBlock(expression) {
val arguments = expression.getArgumentsWithSymbols().mapIndexed { index, arg ->
irSplitCoercion(arg.second, "arg$index", arg.first.owner.type)
}
val typeInfo = irTemporary(irCall(symbols.getObjectTypeInfo).apply {
putValueArgument(0, arguments[0].getFullValue(this@irBlock))
})
val branches = mutableListOf<IrBranchImpl>()
possibleCallees.mapIndexedTo(branches) { index, devirtualizedCallee ->
val actualReceiverType = devirtualizedCallee.receiverType as DataFlowIR.Type.Declared
val expectedTypeInfo = IrClassReferenceImpl(
startOffset, endOffset,
symbols.nativePtrType,
actualReceiverType.irClass!!.symbol,
actualReceiverType.irClass.defaultType
)
val condition =
if (optimize && index == possibleCallees.size - 1)
irTrue() // Don't check last type in optimize mode.
else
irCall(nativePtrEqualityOperatorSymbol).apply {
putValueArgument(0, irGet(typeInfo))
putValueArgument(1, expectedTypeInfo)
}
IrBranchImpl(
startOffset = startOffset,
endOffset = endOffset,
condition = condition,
result = irDevirtualizedCall(expression, type, devirtualizedCallee, arguments)
)
}
if (!optimize) { // Add else branch throwing exception for debug purposes.
branches.add(IrBranchImpl(
startOffset = startOffset,
endOffset = endOffset,
condition = irTrue(),
result = irCall(symbols.throwInvalidReceiverTypeException).apply {
putValueArgument(0,
irCall(symbols.kClassImplConstructor,
listOf(dispatchReceiver.type)
).apply {
putValueArgument(0, irGet(typeInfo))
}
)
})
)
}
+IrWhenImpl(
startOffset = startOffset,
endOffset = endOffset,
type = type,
origin = expression.origin,
branches = branches
)
}
}
}
}
})
}
private fun removeRedundantCoercions(irModule: IrModuleFragment, context: Context) {
class PossiblyFoldedExpression(val expression: IrExpression, val folded: Boolean) {
fun getFullExpression(coercion: IrCall, cast: IrTypeOperatorCall?): IrExpression {
if (folded) return expression
assert (coercion.dispatchReceiver == null && coercion.extensionReceiver == null) {
"Expected either <box> or <unbox> function without any receivers"
}
val castedExpression =
if (cast == null)
expression
else with (cast) {
IrTypeOperatorCallImpl(startOffset, endOffset, type, operator,
typeOperand, expression)
}
with (coercion) {
return IrCallImpl(startOffset, endOffset, type, symbol, typeArgumentsCount, origin).apply {
putValueArgument(0, castedExpression)
}
}
}
}
// Possible values of a returnable block.
val returnableBlockValues = mutableMapOf<IrReturnableBlock, MutableList<IrExpression>>()
irModule.acceptChildrenVoid(object: IrElementVisitorVoid {
override fun visitElement(element: IrElement) {
element.acceptChildrenVoid(this)
}
override fun visitContainerExpression(expression: IrContainerExpression) {
if (expression is IrReturnableBlock)
returnableBlockValues[expression] = mutableListOf()
super.visitContainerExpression(expression)
}
override fun visitReturn(expression: IrReturn) {
val returnableBlock = expression.returnTargetSymbol.owner as? IrReturnableBlock
if (returnableBlock != null)
returnableBlockValues[returnableBlock]!!.add(expression.value)
super.visitReturn(expression)
}
})
irModule.transformChildrenVoid(object: IrElementTransformerVoid() {
fun IrFunction.getCoercedClass(): IrClass {
if (name.asString().endsWith("-box>"))
return valueParameters[0].type.classifierOrFail.owner as IrClass
if (name.asString().endsWith("-unbox>"))
return returnType.classifierOrFail.owner as IrClass
error("Unexpected coercion: ${this.dump()}")
}
fun fold(expression: IrExpression, coercion: IrCall, cast: IrTypeOperatorCall?,
transformRecursively: Boolean): PossiblyFoldedExpression {
val transformer = this
fun IrExpression.transformIfAsked() =
if (transformRecursively) this.transform(transformer, data = null) else this
fun IrElement.transformIfAsked() =
if (transformRecursively) this.transform(transformer, data = null) else this
val coercionDeclaringClass = coercion.symbol.owner.getCoercedClass()
if (expression.isBoxOrUnboxCall()) {
expression as IrCall
val result =
if (coercionDeclaringClass == expression.symbol.owner.getCoercedClass())
expression.getArguments().single().second
else expression
return PossiblyFoldedExpression(result.transformIfAsked(), result != expression)
}
return when (expression) {
is IrReturnableBlock -> {
val foldedReturnableBlockValues = returnableBlockValues[expression]!!.associate {
it to fold(it, coercion, cast, false)
}
val someoneFolded = foldedReturnableBlockValues.any { it.value.folded }
val transformedReturnableBlock =
if (!someoneFolded)
expression
else {
val oldSymbol = expression.symbol
val newSymbol = IrReturnableBlockSymbolImpl(expression.descriptor)
val transformedReturnableBlock = with(expression) {
IrReturnableBlockImpl(
startOffset = startOffset,
endOffset = endOffset,
type = coercion.type,
symbol = newSymbol,
origin = origin,
statements = statements,
inlineFunctionSymbol = inlineFunctionSymbol)
}
transformedReturnableBlock.transformChildrenVoid(object: IrElementTransformerVoid() {
override fun visitExpression(expression: IrExpression): IrExpression {
foldedReturnableBlockValues[expression]?.let {
return it.getFullExpression(coercion, cast)
}
return super.visitExpression(expression)
}
override fun visitReturn(expression: IrReturn): IrExpression {
expression.transformChildrenVoid(this)
return if (expression.returnTargetSymbol != oldSymbol)
expression
else with(expression) {
IrReturnImpl(
startOffset = startOffset,
endOffset = endOffset,
type = context.irBuiltIns.nothingType,
returnTargetSymbol = newSymbol,
value = value)
}
}
})
transformedReturnableBlock
}
if (transformRecursively)
transformedReturnableBlock.transformChildrenVoid(this)
PossiblyFoldedExpression(transformedReturnableBlock, someoneFolded)
}
is IrBlock -> {
val statements = expression.statements
if (statements.isEmpty())
PossiblyFoldedExpression(expression, false)
else {
val lastStatement = statements.last() as IrExpression
val foldedLastStatement = fold(lastStatement, coercion, cast, transformRecursively)
statements.transform {
if (it == lastStatement)
foldedLastStatement.expression
else
it.transformIfAsked()
}
val transformedBlock =
if (!foldedLastStatement.folded)
expression
else with(expression) {
IrBlockImpl(
startOffset = startOffset,
endOffset = endOffset,
type = coercion.type,
origin = origin,
statements = statements)
}
PossiblyFoldedExpression(transformedBlock, foldedLastStatement.folded)
}
}
is IrWhen -> {
val foldedBranches = expression.branches.map { fold(it.result, coercion, cast, transformRecursively) }
val someoneFolded = foldedBranches.any { it.folded }
val transformedWhen = with(expression) {
IrWhenImpl(startOffset, endOffset, if (someoneFolded) coercion.type else type, origin,
branches.asSequence().withIndex().map { (index, branch) ->
IrBranchImpl(
startOffset = branch.startOffset,
endOffset = branch.endOffset,
condition = branch.condition.transformIfAsked(),
result = if (someoneFolded)
foldedBranches[index].getFullExpression(coercion, cast)
else foldedBranches[index].expression)
}.toList())
}
return PossiblyFoldedExpression(transformedWhen, someoneFolded)
}
is IrTypeOperatorCall ->
if (expression.operator != IrTypeOperator.CAST
&& expression.operator != IrTypeOperator.IMPLICIT_CAST
&& expression.operator != IrTypeOperator.SAFE_CAST)
PossiblyFoldedExpression(expression.transformIfAsked(), false)
else {
if (expression.typeOperand.getInlinedClassNative() != coercionDeclaringClass)
PossiblyFoldedExpression(expression.transformIfAsked(), false)
else {
val foldedArgument = fold(expression.argument, coercion, expression, transformRecursively)
if (foldedArgument.folded)
foldedArgument
else
PossiblyFoldedExpression(expression.apply { argument = foldedArgument.expression }, false)
}
}
else -> PossiblyFoldedExpression(expression.transformIfAsked(), false)
}
}
override fun visitCall(expression: IrCall): IrExpression {
if (!expression.isBoxOrUnboxCall())
return super.visitCall(expression)
val argument = expression.getArguments().single().second
val foldedArgument = fold(
expression = argument,
coercion = expression,
cast = null,
transformRecursively = true)
return foldedArgument.getFullExpression(expression, null)
}
})
}
}
| apache-2.0 | f2bead1da7ae2415b501875a7a29eccc | 50.565708 | 135 | 0.509155 | 5.900736 | false | false | false | false |
loloof64/chess-pgn-experiment | src/main/kotlin/com/loloof64/chess_pgn_experiment/PromotionDialog.kt | 1 | 2274 | package com.loloof64.chess_pgn_experiment
import com.loloof64.chess_core.pieces.*
import javafx.beans.property.ObjectProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.scene.control.ButtonType
import javafx.scene.control.Dialog
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.util.Callback
import tornadofx.*
class PromotionDialog(whiteTurn: Boolean) : Dialog<PromotablePiece>() {
companion object {
private val picturesSize = 75.0
private val wantedSize = 60.0
private val picturesScales = wantedSize / picturesSize
}
private val promotablePieces = mapOf(
Queen(whiteTurn) to if (whiteTurn) "chess_ql.png" else "chess_qd.png",
Rook(whiteTurn) to if (whiteTurn) "chess_rl.png" else "chess_rd.png",
Bishop(whiteTurn) to if (whiteTurn) "chess_bl.png" else "chess_bd.png",
Knight(whiteTurn) to if (whiteTurn) "chess_nl.png" else "chess_nd.png"
)
private val selectedPieceProperty: ObjectProperty<PromotablePiece> = SimpleObjectProperty(promotablePieces.keys.first())
val selectedPiece: PromotablePiece get() = selectedPieceProperty.value
init {
title = "Choosing the promotion piece"
headerText = "Choose your promotion piece"
graphic = ImageView(if (whiteTurn) "chess_pl.png" else "chess_pd.png")
dialogPane.buttonTypes.add(ButtonType.OK)
dialogPane.content = vbox {
hbox {
promotablePieces.forEach { piece, image ->
button {
graphic = imageview(image, lazyload = false).scaled()
setOnAction { selectedPieceProperty.value = piece }
}
}
}
hbox {
label("Selected piece")
imageview(promotablePieces[selectedPiece], lazyload = false) {
imageProperty().bind(objectBinding(selectedPieceProperty) { Image(promotablePieces[value]) })
scaled()
}
}
}
resultConverter = Callback { selectedPiece }
}
fun ImageView.scaled() = apply {
scaleX = picturesScales
scaleY = picturesScales
}
} | mit | ba060e69e4bad2e5e7ed19e8824a6487 | 36.295082 | 124 | 0.631486 | 4.331429 | false | false | false | false |
KyuBlade/kotlin-discord-bot | src/main/kotlin/com/omega/discord/bot/listener/MessageListener.kt | 1 | 1183 | package com.omega.discord.bot.listener
import com.omega.discord.bot.command.CommandHandler
import com.omega.discord.bot.property.GuildProperty
import com.omega.discord.bot.property.GuildPropertyManager
import sx.blah.discord.api.events.EventSubscriber
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent
class MessageListener {
@EventSubscriber
fun onMessage(event: MessageReceivedEvent) {
val message = event.message
val messageContent = message.content
val guild = event.guild
val prefix = if (guild != null)
GuildPropertyManager.get(event.guild, GuildProperty.COMMAND_PREFIX)?.value as String
else
"!"
if (messageContent.startsWith(prefix)) {
var indexEndOfCommandName: Int = messageContent.indexOfFirst { it == ' ' }
if (indexEndOfCommandName == -1) {
indexEndOfCommandName = messageContent.length
}
val commandName: String? = messageContent.substring(1, indexEndOfCommandName)
if (commandName != null)
CommandHandler.handle(commandName, message)
}
}
} | gpl-3.0 | b54db1d21c1d3e4fad9053d0bc8b0864 | 31 | 96 | 0.678783 | 4.770161 | false | false | false | false |
MimiReader/mimi-reader | chanlib/src/main/java/com/mimireader/chanlib/models/ErrorChanThread.kt | 1 | 654 | package com.mimireader.chanlib.models
import java.io.PrintWriter
import java.io.StringWriter
class ErrorChanThread(chanThread: ChanThread, val error: Throwable) : ChanThread() {
init {
boardName = chanThread.boardName
threadId = chanThread.threadId
posts.addAll(chanThread.posts)
}
override fun toString(): String {
val sw = StringWriter()
val pw = PrintWriter(sw)
error.printStackTrace(pw)
val trace: String = sw.toString()
return "ErrorChanThread{board='$boardName',\ntitle='$boardTitle',\nthread id='$threadId',\npost count='${posts.size}',\nexception=${trace}}"
}
} | apache-2.0 | 25d97560a1b6fe41daf1f7b8384942dd | 28.772727 | 148 | 0.671254 | 4.219355 | false | false | false | false |
material-components/material-components-android-motion-codelab | app/src/main/java/com/materialstudies/reply/ui/email/EmailAttachmentGridAdapter.kt | 1 | 2038 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.reply.ui.email
import androidx.recyclerview.widget.GridLayoutManager
import com.materialstudies.reply.R
import com.materialstudies.reply.ui.common.EmailAttachmentAdapter
import kotlin.random.Random
class EmailAttachmentGridAdapter(
private val spans: Int
) : EmailAttachmentAdapter() {
/**
* A [GridLayoutManager.SpanSizeLookup] which randomly assigns a span count to each item
* in this adapter.
*/
val variableSpanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
private var indexSpanCounts: List<Int> = emptyList()
override fun getSpanSize(position: Int): Int {
return indexSpanCounts[position]
}
private fun generateSpanCountForItems(count: Int): List<Int> {
val list = mutableListOf<Int>()
var rowSpansOccupied = 0
repeat(count) {
val size = Random.nextInt(1, spans + 1 - rowSpansOccupied)
rowSpansOccupied += size
if (rowSpansOccupied >= 3) rowSpansOccupied = 0
list.add(size)
}
return list
}
override fun invalidateSpanIndexCache() {
super.invalidateSpanIndexCache()
indexSpanCounts = generateSpanCountForItems(itemCount)
}
}
override fun getLayoutIdForPosition(position: Int): Int =
R.layout.email_attachment_grid_item_layout
} | apache-2.0 | 1ecb4915bde4215cc13aee05a1291de1 | 31.887097 | 92 | 0.678116 | 4.739535 | false | false | false | false |
RocketChat/Rocket.Chat.Android.Lily | app/src/main/java/chat/rocket/android/directory/ui/DirectorySortingBottomSheetFragment.kt | 2 | 4769 | package chat.rocket.android.directory.ui
import DrawableHelper
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.FragmentManager
import chat.rocket.android.R
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.android.synthetic.main.bottom_sheet_fragment_directory_sorting.*
fun showDirectorySortingBottomSheetFragment(
isSortByChannels: Boolean,
isSearchForGlobalUsers: Boolean,
supportFragmentManager: FragmentManager
) = DirectorySortingBottomSheetFragment().apply {
arguments = Bundle(2).apply {
putBoolean(BUNDLE_IS_SORT_BY_CHANNELS, isSortByChannels)
putBoolean(BUNDLE_IS_SEARCH_FOR_GLOBAL_USERS, isSearchForGlobalUsers)
}
}.show(supportFragmentManager, TAG)
internal const val TAG = "DirectorySortingBottomSheetFragment"
private const val BUNDLE_IS_SORT_BY_CHANNELS = "is_sort_by_channels"
private const val BUNDLE_IS_SEARCH_FOR_GLOBAL_USERS = "is_search_for_global_users"
class DirectorySortingBottomSheetFragment : BottomSheetDialogFragment() {
private var isSortByChannels = true
private var isSearchForGlobalUsers = false
private val hashtagDrawable by lazy {
DrawableHelper.getDrawableFromId(R.drawable.ic_hashtag_16dp, requireContext())
}
private val userDrawable by lazy {
DrawableHelper.getDrawableFromId(R.drawable.ic_user_16dp, requireContext())
}
private val checkDrawable by lazy {
DrawableHelper.getDrawableFromId(R.drawable.ic_check, requireContext())
}
private val directoryFragment by lazy {
activity?.supportFragmentManager?.findFragmentByTag(TAG_DIRECTORY_FRAGMENT) as DirectoryFragment
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.run {
isSortByChannels = getBoolean(BUNDLE_IS_SORT_BY_CHANNELS)
isSearchForGlobalUsers = getBoolean(BUNDLE_IS_SEARCH_FOR_GLOBAL_USERS)
}
?: requireNotNull(arguments) { "no arguments supplied when the bottom sheet fragment was instantiated" }
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? =
inflater.inflate(R.layout.bottom_sheet_fragment_directory_sorting, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupView()
setupListeners()
}
private fun setupView() {
if (isSortByChannels) {
checkSelection(text_channels, hashtagDrawable)
} else {
checkSelection(text_users, userDrawable)
}
switch_global_users.isChecked = isSearchForGlobalUsers
}
private fun setupListeners() {
dialog.setOnShowListener { dialog ->
val bottomSheet = (dialog as BottomSheetDialog).findViewById<View>(
com.google.android.material.R.id.design_bottom_sheet
)
bottomSheet?.let {
BottomSheetBehavior.from(bottomSheet).peekHeight = bottomSheet.height
}
}
text_channels.setOnClickListener {
checkSelection(text_channels, hashtagDrawable)
uncheckSelection(text_users, userDrawable)
isSortByChannels = true
directoryFragment.updateSorting(isSortByChannels, isSearchForGlobalUsers)
}
text_users.setOnClickListener {
checkSelection(text_users, userDrawable)
uncheckSelection(text_channels, hashtagDrawable)
isSortByChannels = false
directoryFragment.updateSorting(isSortByChannels, isSearchForGlobalUsers)
}
switch_global_users.setOnCheckedChangeListener { _, isChecked ->
isSearchForGlobalUsers = isChecked
directoryFragment.updateSorting(isSortByChannels, isSearchForGlobalUsers)
}
}
private fun checkSelection(textView: TextView, startDrawable: Drawable) {
context?.let {
DrawableHelper.compoundStartAndEndDrawable(
textView,
startDrawable,
checkDrawable
)
}
}
private fun uncheckSelection(textView: TextView, startDrawable: Drawable) {
context?.let {
DrawableHelper.compoundStartDrawable(
textView,
startDrawable
)
}
}
} | mit | 80bc2b8022d31707ad39647b003c4092 | 35.976744 | 116 | 0.698679 | 5.089648 | false | false | false | false |
calebprior/Android-Boilerplate | app/src/main/kotlin/com/calebprior/boilerplate/di/Injector.kt | 1 | 1393 | package com.calebprior.boilerplate.di
import android.content.Context
import com.calebprior.boilerplate.di.components.ApplicationComponent
import com.calebprior.boilerplate.di.components.DaggerApplicationComponent
import com.calebprior.boilerplate.di.components.GenericApplicationComponent
import com.calebprior.boilerplate.di.modules.ApplicationModule
import com.calebprior.boilerplate.di.modules.PresenterModule
import com.nobleworks_software.injection.GenericComponent
import com.nobleworks_software.injection.android.kotlin.Injector
class Injector : Injector {
var appComponent: GenericComponent<ApplicationComponent>? = null
fun getAppComponent(context: Context): GenericComponent<ApplicationComponent> {
if (appComponent == null) {
val application = context.applicationContext
appComponent = GenericApplicationComponent(DaggerApplicationComponent.builder()
.applicationModule(ApplicationModule(application))
.presenterModule(PresenterModule(context))
.build())
}
return appComponent !!
}
override fun <T> inject(context: Context, target: T) {
var component: GenericComponent<*>? = null
if (component == null) {
component = getAppComponent(context)
}
component.getInjector(target)?.injectMembers(target)
}
} | mit | c500ebed0e2a40bb10798ebfdca172e6 | 34.74359 | 91 | 0.730797 | 5.378378 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/org/mariotaku/ktextension/LocaleExtension.kt | 1 | 2324 | package org.mariotaku.ktextension
import android.os.Build
import java.util.*
/**
* Created by mariotaku on 16/8/15.
*/
/**
* Modified from:
* https://github.com/apache/cordova-plugin-globalization/blob/master/src/android/Globalization.java
* Returns a well-formed ITEF BCP 47 language tag representing this locale string
* identifier for the client's current locale
* @return String: The BCP 47 language tag for the current locale
*/
val Locale.bcp47Tag: String
get() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return toLanguageTag()
}
// we will use a dash as per BCP 47
val SEP = '-'
var language = language
var country = country
var variant = variant
// special case for Norwegian Nynorsk since "NY" cannot be a variant as per BCP 47
// this goes before the string matching since "NY" wont pass the variant checks
if (language == "no" && country == "NO" && variant == "NY") {
language = "nn"
country = "NO"
variant = ""
}
if (language.isEmpty() || !language.matches("\\p{Alpha}{2,8}".toRegex())) {
language = "und" // Follow the Locale#toLanguageTag() implementation
// which says to return "und" for Undetermined
} else if (language == "iw") {
language = "he" // correct deprecated "Hebrew"
} else if (language == "in") {
language = "id" // correct deprecated "Indonesian"
} else if (language == "ji") {
language = "yi" // correct deprecated "Yiddish"
}
// ensure valid country code, if not well formed, it's omitted
if (!country.matches("\\p{Alpha}{2}|\\p{Digit}{3}".toRegex())) {
country = ""
}
// variant subtags that begin with a letter must be at least 5 characters long
if (!variant.matches("\\p{Alnum}{5,8}|\\p{Digit}\\p{Alnum}{3}".toRegex())) {
variant = ""
}
val bcp47Tag = StringBuilder(language)
if (!country.isEmpty()) {
bcp47Tag.append(SEP).append(country)
}
if (!variant.isEmpty()) {
bcp47Tag.append(SEP).append(variant)
}
return bcp47Tag.toString()
} | gpl-3.0 | 8ec5bbad1cdbe12320486190c5b1550f | 32.695652 | 100 | 0.570998 | 4.034722 | false | false | false | false |
android/graphics-samples | PdfRendererBasic/Application/src/main/java/com/example/android/pdfrendererbasic/PdfRendererBasicFragment.kt | 1 | 2152 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.pdfrendererbasic
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
/**
* This fragment has a big [ImageView] that shows PDF pages, and 2 [Button]s to move between pages.
*/
class PdfRendererBasicFragment : Fragment(R.layout.pdf_renderer_basic_fragment) {
private val viewModel: PdfRendererBasicViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// View references.
val image: ImageView = view.findViewById(R.id.image)
val buttonPrevious: Button = view.findViewById(R.id.previous)
val buttonNext: Button = view.findViewById(R.id.next)
// Bind data.
viewModel.pageInfo.observe(viewLifecycleOwner) { (index, count) ->
activity?.title = getString(R.string.app_name_with_index, index + 1, count)
}
viewModel.pageBitmap.observe(viewLifecycleOwner, Observer { image.setImageBitmap(it) })
viewModel.previousEnabled.observe(viewLifecycleOwner, Observer {
buttonPrevious.isEnabled = it
})
viewModel.nextEnabled.observe(viewLifecycleOwner, Observer {
buttonNext.isEnabled = it
})
// Bind events.
buttonPrevious.setOnClickListener { viewModel.showPrevious() }
buttonNext.setOnClickListener { viewModel.showNext() }
}
}
| apache-2.0 | e13c85c99c99040795bf165aaf5fc510 | 36.754386 | 99 | 0.717937 | 4.400818 | false | false | false | false |
AndroidX/androidx | compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/SnapshotState.kt | 3 | 10066 | /*
* 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.
*/
@file:JvmName("SnapshotStateKt")
@file:JvmMultifileClass
package androidx.compose.runtime
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.runtime.snapshots.SnapshotMutableState
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.compose.runtime.snapshots.StateObject
import androidx.compose.runtime.snapshots.StateRecord
import androidx.compose.runtime.snapshots.overwritable
import androidx.compose.runtime.snapshots.readable
import androidx.compose.runtime.snapshots.withCurrent
// Explicit imports for jvm annotations needed in common source sets.
import kotlin.jvm.JvmName
import kotlin.jvm.JvmMultifileClass
import kotlin.reflect.KProperty
/**
* Return a new [MutableState] initialized with the passed in [value]
*
* The MutableState class is a single value holder whose reads and writes are observed by
* Compose. Additionally, writes to it are transacted as part of the [Snapshot] system.
*
* @param value the initial value for the [MutableState]
* @param policy a policy to controls how changes are handled in mutable snapshots.
*
* @sample androidx.compose.runtime.samples.SimpleStateSample
* @sample androidx.compose.runtime.samples.DestructuredStateSample
* @sample androidx.compose.runtime.samples.observeUserSample
* @sample androidx.compose.runtime.samples.stateSample
*
* @see State
* @see MutableState
* @see SnapshotMutationPolicy
*/
fun <T> mutableStateOf(
value: T,
policy: SnapshotMutationPolicy<T> = structuralEqualityPolicy()
): MutableState<T> = createSnapshotMutableState(value, policy)
/**
* A value holder where reads to the [value] property during the execution of a [Composable]
* function, the current [RecomposeScope] will be subscribed to changes of that value.
*
* @see [MutableState]
* @see [mutableStateOf]
*/
@Stable
interface State<out T> {
val value: T
}
/**
* Permits property delegation of `val`s using `by` for [State].
*
* @sample androidx.compose.runtime.samples.DelegatedReadOnlyStateSample
*/
@Suppress("NOTHING_TO_INLINE")
inline operator fun <T> State<T>.getValue(thisObj: Any?, property: KProperty<*>): T = value
/**
* A mutable value holder where reads to the [value] property during the execution of a [Composable]
* function, the current [RecomposeScope] will be subscribed to changes of that value. When the
* [value] property is written to and changed, a recomposition of any subscribed [RecomposeScope]s
* will be scheduled. If [value] is written to with the same value, no recompositions will be
* scheduled.
*
* @see [State]
* @see [mutableStateOf]
*/
@Stable
interface MutableState<T> : State<T> {
override var value: T
operator fun component1(): T
operator fun component2(): (T) -> Unit
}
/**
* Permits property delegation of `var`s using `by` for [MutableState].
*
* @sample androidx.compose.runtime.samples.DelegatedStateSample
*/
@Suppress("NOTHING_TO_INLINE")
inline operator fun <T> MutableState<T>.setValue(thisObj: Any?, property: KProperty<*>, value: T) {
this.value = value
}
/**
* Returns platform specific implementation based on [SnapshotMutableStateImpl].
*/
internal expect fun <T> createSnapshotMutableState(
value: T,
policy: SnapshotMutationPolicy<T>
): SnapshotMutableState<T>
/**
* A single value holder whose reads and writes are observed by Compose.
*
* Additionally, writes to it are transacted as part of the [Snapshot] system.
*
* @param value the wrapped value
* @param policy a policy to control how changes are handled in a mutable snapshot.
*
* @see mutableStateOf
* @see SnapshotMutationPolicy
*/
internal open class SnapshotMutableStateImpl<T>(
value: T,
override val policy: SnapshotMutationPolicy<T>
) : StateObject, SnapshotMutableState<T> {
@Suppress("UNCHECKED_CAST")
override var value: T
get() = next.readable(this).value
set(value) = next.withCurrent {
if (!policy.equivalent(it.value, value)) {
next.overwritable(this, it) { this.value = value }
}
}
private var next: StateStateRecord<T> = StateStateRecord(value)
override val firstStateRecord: StateRecord
get() = next
override fun prependStateRecord(value: StateRecord) {
@Suppress("UNCHECKED_CAST")
next = value as StateStateRecord<T>
}
@Suppress("UNCHECKED_CAST")
override fun mergeRecords(
previous: StateRecord,
current: StateRecord,
applied: StateRecord
): StateRecord? {
val previousRecord = previous as StateStateRecord<T>
val currentRecord = current as StateStateRecord<T>
val appliedRecord = applied as StateStateRecord<T>
return if (policy.equivalent(currentRecord.value, appliedRecord.value))
current
else {
val merged = policy.merge(
previousRecord.value,
currentRecord.value,
appliedRecord.value
)
if (merged != null) {
appliedRecord.create().also {
(it as StateStateRecord<T>).value = merged
}
} else {
null
}
}
}
override fun toString(): String = next.withCurrent {
"MutableState(value=${it.value})@${hashCode()}"
}
private class StateStateRecord<T>(myValue: T) : StateRecord() {
override fun assign(value: StateRecord) {
@Suppress("UNCHECKED_CAST")
this.value = (value as StateStateRecord<T>).value
}
override fun create(): StateRecord = StateStateRecord(value)
var value: T = myValue
}
/**
* The componentN() operators allow state objects to be used with the property destructuring
* syntax
*
* ```
* var (foo, setFoo) = remember { mutableStateOf(0) }
* setFoo(123) // set
* foo == 123 // get
* ```
*/
override operator fun component1(): T = value
override operator fun component2(): (T) -> Unit = { value = it }
/**
* A function used by the debugger to display the value of the current value of the mutable
* state object without triggering read observers.
*/
@Suppress("unused")
val debuggerDisplayValue: T
@JvmName("getDebuggerDisplayValue")
get() = next.withCurrent { it }.value
}
/**
* Create a instance of [MutableList]<T> that is observable and can be snapshot.
*
* @sample androidx.compose.runtime.samples.stateListSample
*
* @see mutableStateOf
* @see mutableListOf
* @see MutableList
* @see Snapshot.takeSnapshot
*/
fun <T> mutableStateListOf() = SnapshotStateList<T>()
/**
* Create an instance of [MutableList]<T> that is observable and can be snapshot.
*
* @see mutableStateOf
* @see mutableListOf
* @see MutableList
* @see Snapshot.takeSnapshot
*/
fun <T> mutableStateListOf(vararg elements: T) =
SnapshotStateList<T>().also { it.addAll(elements.toList()) }
/**
* Create an instance of [MutableList]<T> from a collection that is observable and can be
* snapshot.
*/
fun <T> Collection<T>.toMutableStateList() = SnapshotStateList<T>().also { it.addAll(this) }
/**
* Create a instance of [MutableMap]<K, V> that is observable and can be snapshot.
*
* @sample androidx.compose.runtime.samples.stateMapSample
*
* @see mutableStateOf
* @see mutableMapOf
* @see MutableMap
* @see Snapshot.takeSnapshot
*/
fun <K, V> mutableStateMapOf() = SnapshotStateMap<K, V>()
/**
* Create a instance of [MutableMap]<K, V> that is observable and can be snapshot.
*
* @see mutableStateOf
* @see mutableMapOf
* @see MutableMap
* @see Snapshot.takeSnapshot
*/
fun <K, V> mutableStateMapOf(vararg pairs: Pair<K, V>) =
SnapshotStateMap<K, V>().apply { putAll(pairs.toMap()) }
/**
* Create an instance of [MutableMap]<K, V> from a collection of pairs that is observable and can be
* snapshot.
*/
@Suppress("unused")
fun <K, V> Iterable<Pair<K, V>>.toMutableStateMap() =
SnapshotStateMap<K, V>().also { it.putAll(this.toMap()) }
/**
* [remember] a [mutableStateOf] [newValue] and update its value to [newValue] on each
* recomposition of the [rememberUpdatedState] call.
*
* [rememberUpdatedState] should be used when parameters or values computed during composition
* are referenced by a long-lived lambda or object expression. Recomposition will update the
* resulting [State] without recreating the long-lived lambda or object, allowing that object to
* persist without cancelling and resubscribing, or relaunching a long-lived operation that may
* be expensive or prohibitive to recreate and restart.
* This may be common when working with [DisposableEffect] or [LaunchedEffect], for example:
*
* @sample androidx.compose.runtime.samples.rememberUpdatedStateSampleWithDisposableEffect
*
* [LaunchedEffect]s often describe state machines that should not be reset and restarted if a
* parameter or event callback changes, but they should have the current value available when
* needed. For example:
*
* @sample androidx.compose.runtime.samples.rememberUpdatedStateSampleWithLaunchedEffect
*
* By using [rememberUpdatedState] a composable function can update these operations in progress.
*/
@Composable
fun <T> rememberUpdatedState(newValue: T): State<T> = remember {
mutableStateOf(newValue)
}.apply { value = newValue }
| apache-2.0 | 5eee7bc32a065620156b38676765cdfa | 32.892256 | 100 | 0.705444 | 4.194167 | false | false | false | false |
afollestad/photo-affix | engine/src/main/java/com/afollestad/photoaffix/engine/bitmaps/BitmapManipulator.kt | 1 | 2699 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.afollestad.photoaffix.engine.bitmaps
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat
import android.graphics.Bitmap.Config.ARGB_8888
import android.graphics.BitmapFactory.Options
import android.graphics.BitmapFactory.decodeStream
import android.net.Uri
import com.afollestad.photoaffix.engine.photos.Photo
import com.afollestad.photoaffix.utilities.IoManager
import com.afollestad.photoaffix.utilities.ext.closeQuietely
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import javax.inject.Inject
/** @author Aidan Follestad (afollestad) */
interface BitmapManipulator {
fun decodePhoto(
photo: Photo,
options: Options
): Bitmap?
fun decodeUri(
uri: Uri,
options: Options
): Bitmap?
fun createOptions(onlyGetBounds: Boolean = true): Options
fun createEmptyBitmap(
width: Int,
height: Int
): Bitmap
fun encodeBitmap(
bitmap: Bitmap,
format: CompressFormat,
quality: Int,
file: File
)
}
class RealBitmapManipulator @Inject constructor(
private val ioManager: IoManager
) : BitmapManipulator {
override fun decodePhoto(
photo: Photo,
options: Options
) = decodeUri(photo.uri, options)
override fun decodeUri(
uri: Uri,
options: Options
): Bitmap? {
var inputStream: InputStream? = null
try {
inputStream = ioManager.openStream(uri)
return decodeStream(inputStream, null, options)
} finally {
inputStream.closeQuietely()
}
}
override fun createOptions(onlyGetBounds: Boolean) = Options()
.apply {
inJustDecodeBounds = onlyGetBounds
}
override fun createEmptyBitmap(
width: Int,
height: Int
): Bitmap = Bitmap.createBitmap(width, height, ARGB_8888)
override fun encodeBitmap(
bitmap: Bitmap,
format: CompressFormat,
quality: Int,
file: File
) {
var os: FileOutputStream? = null
try {
os = FileOutputStream(file)
bitmap.compress(format, quality, os)
} finally {
os.closeQuietely()
}
}
}
| apache-2.0 | ec9e5c09a032fefe48f5d8119baea17c | 24.462264 | 75 | 0.718414 | 4.217188 | false | false | false | false |
mvarnagiris/expensius | app-core/src/test/kotlin/com/mvcoding/expensius/RxSchedulersTestExtensions.kt | 1 | 862 | /*
* Copyright (C) 2016 Mantas Varnagiris.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.mvcoding.expensius
import rx.Scheduler
import rx.schedulers.Schedulers.immediate
fun rxSchedulers() = RxSchedulers(immediate(), immediate(), immediate())
fun RxSchedulers.withIo(scheduler: Scheduler) = copy(io = scheduler)
fun RxSchedulers.withMain(scheduler: Scheduler) = copy(main = scheduler) | gpl-3.0 | 61f328881d512d2d4c20416dffbd8f8c | 38.227273 | 72 | 0.765661 | 4.353535 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/resolve2/DetachedDefMap.kt | 2 | 3906 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve2
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import org.rust.lang.core.crate.Crate
import org.rust.lang.core.crate.impl.CargoBasedCrate
import org.rust.lang.core.crate.impl.DoctestCrate
import org.rust.lang.core.crate.impl.FakeDetachedCrate
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.RsModItem
import org.rust.lang.core.psi.ext.RsItemsOwner
import org.rust.lang.core.psi.ext.RsMod
import org.rust.lang.core.psi.ext.getChildModule
import org.rust.openapiext.getCachedOrCompute
import java.lang.ref.SoftReference
fun Project.getDetachedModInfo(scope: RsMod, crate: FakeDetachedCrate): RsModInfo? =
getModInfoInDetachedCrate(scope, crate)
fun Project.getDoctestModInfo(scope: RsMod, crate: DoctestCrate): RsModInfo? =
getModInfoInDetachedCrate(scope, crate)
private fun Project.getModInfoInDetachedCrate(scope: RsMod, crate: Crate): RsModInfo? {
val defMap = defMapService.cachedGetDefMapForNonCargoCrate(crate) ?: return null
val dataPsiHelper = DetachedFileDataPsiHelper(crate.rootMod ?: return null, defMap)
val modData = dataPsiHelper.psiToData(scope) ?: return null
return RsModInfo(this, defMap, modData, crate, dataPsiHelper)
}
private class DetachedFileDataPsiHelper(
private val root: RsFile,
private val defMap: CrateDefMap
) : DataPsiHelper {
override fun psiToData(scope: RsItemsOwner): ModData? {
return when {
scope.containingFile != root -> null
scope == root -> defMap.root
scope is RsModItem -> {
val superMod = scope.`super` ?: return null
val superModData = psiToData(superMod) ?: return null
superModData.childModules[scope.modName]
}
else -> null
}
}
override fun dataToPsi(data: ModData): RsMod? {
return when {
data.crate != defMap.crate -> null
data == defMap.root -> root
else -> {
val superModData = data.parent ?: return null
val superMod = dataToPsi(superModData) ?: return null
superMod.getChildModule(data.name)
}
}
}
}
private fun DefMapService.cachedGetDefMapForNonCargoCrate(crate: Crate): CrateDefMap? {
check(crate.id != null)
check(crate !is CargoBasedCrate)
val crateRoot = crate.rootMod ?: return null
val allDependenciesDefMaps = crate.getAllDependenciesDefMaps()
val dependenciesStamps = allDependenciesDefMaps.map {
val holder = getDefMapHolder(it.value.crate)
holder.modificationCount
}
val dependencies = dependenciesStamps + crateRoot.modificationStamp
return getCachedOrCompute(crateRoot, DEF_MAP_KEY, dependencies) {
val indicator = ProgressManager.getGlobalProgressIndicator() ?: EmptyProgressIndicator()
buildDefMap(crate, allDependenciesDefMaps, pool = null, indicator, isNormalCrate = false)
?: error("null detached DefMap")
}
}
private val DEF_MAP_KEY: Key<SoftReference<Pair<CrateDefMap, List<Long>>>> = Key.create("DEF_MAP_KEY")
private fun Crate.getAllDependenciesDefMaps(): Map<Crate, CrateDefMap> {
val allDependencies = flatDependencies
val ids = allDependencies.mapNotNull { it.id }
val crateById = allDependencies.associateBy { it.id }
val defMapById = project.defMapService.getOrUpdateIfNeeded(ids)
return defMapById.mapNotNull { (crateId, defMap) ->
val crate = crateById[crateId]
if (crate != null && defMap != null) {
crate to defMap
} else {
null
}
}.toMap(hashMapOf())
}
| mit | 6ffc05add74d3d00499717be1b47de36 | 37.294118 | 102 | 0.700717 | 4.222703 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/types/ty/TyAnon.kt | 2 | 1303 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.ty
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.RsTraitType
import org.rust.lang.core.psi.ext.getFlattenHierarchy
import org.rust.lang.core.psi.ext.isImpl
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.HAS_TY_OPAQUE_MASK
import org.rust.lang.core.types.infer.TypeFolder
import org.rust.lang.core.types.infer.TypeVisitor
import org.rust.lang.core.types.mergeElementFlags
/**
* Represents "impl Trait".
*/
data class TyAnon(
val definition: RsTraitType?,
val traits: List<BoundElement<RsTraitItem>>
) : Ty(mergeElementFlags(traits) or HAS_TY_OPAQUE_MASK) {
init {
require(definition == null || definition.isImpl) {
"Can't construct TyAnon from non `impl Trait` definition $definition"
}
}
override fun superFoldWith(folder: TypeFolder): Ty =
TyAnon(definition, traits.map { it.foldWith(folder) })
override fun superVisitWith(visitor: TypeVisitor): Boolean =
traits.any { it.visitWith(visitor) }
fun getTraitBoundsTransitively(): Collection<BoundElement<RsTraitItem>> =
traits.flatMap { it.getFlattenHierarchy(this) }
}
| mit | cd5362ef53bd54dcdc1a8fdfb8237156 | 31.575 | 81 | 0.728319 | 3.639665 | false | false | false | false |
Dr-Horv/Advent-of-Code-2017 | src/main/kotlin/solutions/day07/Day7.kt | 1 | 3964 | package solutions.day07
import solutions.Solver
import utils.splitAtWhitespace
import java.util.*
data class Program(val name: String, val weight: Int, var parent: Program?, var children: List<Program>, var totalWeight: Int, var level: Int)
data class Tuple(val program: Program, val diff: Int)
class LevelComparator : Comparator<Program> {
override fun compare(p0: Program?, p1: Program?): Int {
return p1!!.level - p0!!.level
}
}
class Day7 : Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val map: Map<String, Program> = constructTree(input)
val root = findRoot(map.values.first())
if (!partTwo) {
return root.name
}
correctLevels(root)
correctTotalWeights(map)
val (p, diff) = findCulprit(root)
return (p.weight + diff).toString()
}
private fun correctTotalWeights(map: Map<String, Program>) {
val queue: Queue<Program> = PriorityQueue(LevelComparator())
queue.addAll(map.values)
while (queue.isNotEmpty()) {
val next = queue.poll()
if (next.parent != null) {
val parent = next.parent!!
parent.totalWeight += next.totalWeight
if (!queue.contains(parent)) {
queue.add(parent)
}
}
}
}
private fun constructTree(input: List<String>): Map<String, Program> {
val map: MutableMap<String, Program> = mutableMapOf()
val programsWithChildren: MutableMap<Program, List<String>> = mutableMapOf()
input
.map { it.split("->").map(String::trim) }
.forEach {
createProgramNode(it, map, programsWithChildren)
}
programsWithChildren.forEach { (p, cs) ->
val children = cs.map { map.getValue(it) }.toList()
p.children = children
children.forEach { it.parent = p }
}
return map
}
private fun createProgramNode(parts: List<String>, map: MutableMap<String, Program>, programsWithChildren: MutableMap<Program, List<String>>) {
val firstParts = parts[0].splitAtWhitespace()
val name = firstParts[0]
val weightStr = firstParts[1]
val weight = weightStr.substring(1, weightStr.lastIndex).toInt()
val p = Program(name, weight, null, mutableListOf(), weight, -1)
map.put(name, p)
if (parts.size > 1) {
val children = parts[1].split(",").map(String::trim)
programsWithChildren.put(p, children)
}
}
private fun correctLevels(root: Program, level: Int = 0) {
root.level = level
root.children.forEach { correctLevels(it, level + 1) }
}
private fun findCulprit(root: Program): Tuple {
val weightSorted = root.children.sortedBy { it.totalWeight }
if (weightSorted.size < 3) {
throw RuntimeException("Cannot determine too heavy or too light")
}
val first = weightSorted.first()
val last = weightSorted.last()
val middle = weightSorted[weightSorted.size / 2]
return if (first.totalWeight != middle.totalWeight) {
find(first, first.totalWeight - middle.totalWeight, { it.totalWeight })
} else {
find(last, middle.totalWeight - last.totalWeight, { -it.totalWeight })
}
}
private fun find(p: Program, diff: Int, sortedBy: (Program) -> Int ): Tuple {
val sorted = p.children.sortedBy(sortedBy)
return if (sorted.first().totalWeight == sorted.last().totalWeight) {
Tuple(p, diff)
} else {
find(sorted.first(), diff, sortedBy)
}
}
private fun findRoot(program: Program): Program {
return if (program.parent != null) {
findRoot(program.parent!!)
} else {
program
}
}
}
| mit | 6368cd03a599c1fd202773d99b071fee | 30.967742 | 147 | 0.585772 | 4.181435 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/TutorialView.kt | 1 | 3092 | package com.habitrpg.android.habitica.ui
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.habitrpg.android.habitica.databinding.OverlayTutorialBinding
import com.habitrpg.android.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.models.TutorialStep
class TutorialView(context: Context, var step: TutorialStep, var onReaction: OnTutorialReaction?) : FrameLayout(context) {
private val binding = OverlayTutorialBinding.inflate(context.layoutInflater, this, true)
private var tutorialTexts: List<String> = emptyList()
private var currentTextIndex: Int = 0
private val isDisplayingLastStep: Boolean
get() = currentTextIndex == tutorialTexts.size - 1
init {
binding.speechBubbleView.setConfirmationButtonVisibility(View.GONE)
binding.speechBubbleView.setShowNextListener(object : SpeechBubbleView.ShowNextListener {
override fun showNextStep() {
displayNextTutorialText()
}
})
binding.speechBubbleView.binding.completeButton.setOnClickListener { completeButtonClicked() }
binding.speechBubbleView.binding.dismissButton.setOnClickListener { dismissButtonClicked() }
binding.background.setOnClickListener { backgroundClicked() }
}
fun setTutorialText(text: String) {
binding.speechBubbleView.animateText(text)
binding.speechBubbleView.setConfirmationButtonVisibility(View.VISIBLE)
}
fun setTutorialTexts(texts: List<String>) {
tutorialTexts = texts
currentTextIndex = -1
displayNextTutorialText()
}
fun setCanBeDeferred(canBeDeferred: Boolean) {
binding.speechBubbleView.binding.dismissButton.visibility = if (canBeDeferred) View.VISIBLE else View.GONE
}
private fun displayNextTutorialText() {
currentTextIndex++
if (currentTextIndex < tutorialTexts.size) {
binding.speechBubbleView.animateText(tutorialTexts[currentTextIndex])
if (isDisplayingLastStep) {
binding.speechBubbleView.setConfirmationButtonVisibility(View.VISIBLE)
binding.speechBubbleView.setHasMoreContent(false)
} else {
binding.speechBubbleView.setHasMoreContent(true)
}
} else {
this.onReaction?.onTutorialCompleted(this.step)
}
}
private fun completeButtonClicked() {
this.onReaction?.onTutorialCompleted(this.step)
(parent as? ViewGroup)?.removeView(this)
}
private fun dismissButtonClicked() {
this.onReaction?.onTutorialDeferred(this.step)
(parent as? ViewGroup)?.removeView(this)
}
private fun backgroundClicked() {
binding.speechBubbleView.onClick(binding.speechBubbleView)
}
interface OnTutorialReaction {
fun onTutorialCompleted(step: TutorialStep)
fun onTutorialDeferred(step: TutorialStep)
}
}
| gpl-3.0 | 4b4f48fabced50a2dba46e49d867cd64 | 36.17284 | 122 | 0.695019 | 5.019481 | false | false | false | false |
ryan652/EasyCrypt | appKotlin/src/main/java/com/pvryan/easycryptsample/settings/SettingsActivity.kt | 1 | 3447 | /*
* Copyright 2018 Priyank Vasa
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pvryan.easycryptsample.settings
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.Preference
import android.preference.PreferenceFragment
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import com.pvryan.easycryptsample.Constants
import com.pvryan.easycryptsample.R
import kotlinx.android.synthetic.main.activity_settings.*
import org.jetbrains.anko.defaultSharedPreferences
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = intent.extras[Constants.TITLE] as String
fragmentManager.beginTransaction().replace(R.id.container, SettingsFragment()).commit()
}
class SettingsFragment : PreferenceFragment(),
SharedPreferences.OnSharedPreferenceChangeListener {
private lateinit var preference: Preference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.preferences)
val prefApiKey = getString(R.string.pref_api_key)
preference = findPreference(prefApiKey)
if (!defaultSharedPreferences.getString(prefApiKey, "").isBlank()) {
preference.summary = getString(R.string.summary_set)
}
}
override fun onPause() {
super.onPause()
preferenceScreen.sharedPreferences
.unregisterOnSharedPreferenceChangeListener(this@SettingsFragment)
}
override fun onResume() {
super.onResume()
preferenceScreen.sharedPreferences
.registerOnSharedPreferenceChangeListener(this@SettingsFragment)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?,
key: String?) {
when (key) {
getString(R.string.pref_api_key) -> {
val apiKey = defaultSharedPreferences.getString(key, "")
if (apiKey.isBlank()) {
preference.summary = getString(R.string.summary_not_set)
} else {
preference.summary = getString(R.string.summary_set)
}
}
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
super.onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
| apache-2.0 | 20765aa9a67d300900ddc3302c8107ea | 35.284211 | 95 | 0.654772 | 5.50639 | false | false | false | false |
androidx/androidx | compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/focus/CaptureFocusDemo.kt | 3 | 3181 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.demos.focus
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color.Companion.Red
import androidx.compose.ui.graphics.Color.Companion.Transparent
import androidx.compose.ui.unit.dp
@Composable
fun CaptureFocusDemo() {
Column {
Text(
"This demo demonstrates how a component can capture focus when it is in an " +
"invalidated state."
)
Spacer(Modifier.height(30.dp))
Text("Enter a word that is 5 characters or shorter")
val shortWord = remember { FocusRequester() }
var shortString by remember { mutableStateOf("apple") }
var shortStringBorder by remember { mutableStateOf(Transparent) }
TextField(
value = shortString,
onValueChange = {
shortString = it
if (shortString.length > 5) shortWord.captureFocus() else shortWord.freeFocus()
},
modifier = Modifier
.border(2.dp, shortStringBorder)
.focusRequester(shortWord)
.onFocusChanged { shortStringBorder = if (it.isCaptured) Red else Transparent }
)
Spacer(Modifier.height(30.dp))
Text("Enter a word that is longer than 5 characters")
val longWord = remember { FocusRequester() }
var longString by remember { mutableStateOf("pineapple") }
var longStringBorder by remember { mutableStateOf(Transparent) }
TextField(
value = longString,
onValueChange = {
longString = it
if (longString.length < 5) longWord.captureFocus() else longWord.freeFocus()
},
modifier = Modifier
.border(2.dp, longStringBorder)
.focusRequester(longWord)
.onFocusChanged { longStringBorder = if (it.isCaptured) Red else Transparent }
)
}
} | apache-2.0 | 1110c8e3a333d5c111bd8fe7daee5071 | 37.337349 | 95 | 0.688463 | 4.698671 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/service/TimelineDownloaderOther.kt | 1 | 7331 | /*
* Copyright (C) 2013 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.service
import io.vavr.control.Try
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.data.DataUpdater
import org.andstatus.app.net.http.ConnectionException
import org.andstatus.app.net.http.StatusCode
import org.andstatus.app.net.social.Actor
import org.andstatus.app.net.social.InputTimelinePage
import org.andstatus.app.net.social.TimelinePosition
import org.andstatus.app.timeline.meta.TimelineType
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.RelativeTime
import org.andstatus.app.util.TriState
import org.andstatus.app.util.TryUtils
import java.util.*
import java.util.concurrent.TimeUnit
internal class TimelineDownloaderOther(execContext: CommandExecutionContext) : TimelineDownloader(execContext) {
override suspend fun download(): Try<Boolean> {
if (!getTimeline().isSyncable()) {
return Try.failure(IllegalArgumentException("Timeline cannot be synced: ${getTimeline()}"))
}
val syncTracker = TimelineSyncTracker(getTimeline(), isSyncYounger())
val hours = MyPreferences.getDontSynchronizeOldNotes()
var downloadingLatest = false
if (hours > 0 && RelativeTime.moreSecondsAgoThan(syncTracker.getPreviousSyncedDate(),
TimeUnit.HOURS.toSeconds(hours))) {
downloadingLatest = true
syncTracker.clearPosition()
} else if (syncTracker.getPreviousPosition().isEmpty) {
downloadingLatest = true
}
val tryActor = getActorWithOid()
val toDownload = if (downloadingLatest) LATEST_NOTES_TO_DOWNLOAD_MAX else
if (isSyncYounger()) YOUNGER_NOTES_TO_DOWNLOAD_MAX else OLDER_NOTES_TO_DOWNLOAD_MAX
var positionToRequest = syncTracker.getPreviousPosition()
if (MyLog.isDebugEnabled()) {
var strLog = ("Loading "
+ (if (downloadingLatest) "latest " else "")
+ execContext.commandData.toCommandSummary(execContext.myContext))
if (syncTracker.getPreviousItemDate() > 0) {
strLog += ("; last Timeline item at=" + Date(syncTracker.getPreviousItemDate()).toString()
+ "; last time downloaded at=" + Date(syncTracker.getPreviousSyncedDate()).toString())
}
strLog += "; Position to request: " + positionToRequest.getPosition()
MyLog.d(TAG, strLog)
}
syncTracker.onTimelineDownloaded()
val dataUpdater = DataUpdater(execContext)
for (loopCounter in 0..99) {
val limit = getConnection().fixedDownloadLimit(
toDownload, getTimeline().timelineType.connectionApiRoutine)
syncTracker.onPositionRequested(positionToRequest)
var tryPage: Try<InputTimelinePage>
tryPage = when (getTimeline().timelineType) {
TimelineType.SEARCH -> getConnection().searchNotes(isSyncYounger(),
if (isSyncYounger()) positionToRequest else TimelinePosition.EMPTY,
if (isSyncYounger()) TimelinePosition.EMPTY else positionToRequest,
limit, getTimeline().getSearchQuery())
else -> {
val positionToRequest2 = positionToRequest
tryActor.flatMap { actor: Actor ->
getConnection().getTimeline(isSyncYounger(),
getTimeline().timelineType.connectionApiRoutine,
if (isSyncYounger()) positionToRequest2 else TimelinePosition.EMPTY,
if (isSyncYounger()) TimelinePosition.EMPTY else positionToRequest2,
limit, actor)
}
}
}
if (tryPage.isSuccess()) {
val page = tryPage.get()
syncTracker.onNewPage(page)
for (activity in page.items) {
syncTracker.onNewActivity(activity.getUpdatedDate(), activity.getPrevTimelinePosition(),
activity.getNextTimelinePosition())
if (activity.isSubscribedByMe() != TriState.FALSE
&& activity.getUpdatedDate() > 0 && execContext.getTimeline().timelineType.isSubscribedByMe()
&& execContext.myContext.users.isMe(execContext.getTimeline().actor)) {
activity.setSubscribedByMe(TriState.TRUE)
}
dataUpdater.onActivity(activity, false)
}
val optPositionToRequest = syncTracker.getNextPositionToRequest()
if (toDownload - syncTracker.getDownloadedCounter() <= 0 || !optPositionToRequest.isPresent) {
break
}
positionToRequest = optPositionToRequest.get()
}
if (tryPage.isFailure()) {
if (ConnectionException.of(tryPage.getCause()).statusCode != StatusCode.NOT_FOUND) {
return Try.failure(tryPage.getCause())
}
val optPositionToRequest = syncTracker.onNotFound()
if (!optPositionToRequest.isPresent) {
return Try.failure(ConnectionException.fromStatusCode(StatusCode.NOT_FOUND,
"Timeline was not found at " + syncTracker.requestedPositions))
}
MyLog.d(TAG, "Trying default timeline position")
positionToRequest = optPositionToRequest.get()
}
}
dataUpdater.saveLum()
return TryUtils.TRUE
}
private fun getActorWithOid(): Try<Actor> {
if (getActor().actorId == 0L) {
if (getTimeline().myAccountToSync.isValid) {
return Try.success(getTimeline().myAccountToSync.actor)
}
} else {
val actor: Actor = Actor.load(execContext.myContext, getActor().actorId)
return if (actor.oid.isEmpty()) {
Try.failure(ConnectionException("No ActorOid for $actor, timeline:${getTimeline()}"))
} else Try.success(actor)
}
return if (getTimeline().timelineType.isForUser()) {
Try.failure(ConnectionException("No actor for the timeline:${getTimeline()}"))
} else Try.success(Actor.EMPTY)
}
companion object {
private val TAG: String = TimelineDownloaderOther::class.simpleName!!
private const val YOUNGER_NOTES_TO_DOWNLOAD_MAX = 200
private const val OLDER_NOTES_TO_DOWNLOAD_MAX = 40
private const val LATEST_NOTES_TO_DOWNLOAD_MAX = 20
}
}
| apache-2.0 | 3fb481a0ed1d8c58b04d2ce05e32efb5 | 49.558621 | 121 | 0.62188 | 4.930061 | false | true | false | false |
czyzby/ktx | math/src/main/kotlin/ktx/math/matrix4.kt | 2 | 7509 | package ktx.math
import com.badlogic.gdx.math.Matrix4
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.math.Vector3
/**
* A utility factory function that allows to create [Matrix4] instances with named parameters.
* @param m00 first row, first column.
* @param m01 first row, second column.
* @param m02 first row, third column.
* @param m03 first row, forth column.
* @param m10 second row, first column.
* @param m11 second row, second column.
* @param m12 second row, third column.
* @param m13 second row, forth column.
* @param m20 third row, first column.
* @param m21 third row, second column.
* @param m22 third row, third column.
* @param m23 third row, forth column.
* @param m30 forth row, first column.
* @param m31 forth row, second column.
* @param m32 forth row, third column.
* @param m33 forth row, forth column.
* @return a new instance of [Matrix4].
*/
fun mat4(
m00: Float = 0f,
m01: Float = 0f,
m02: Float = 0f,
m03: Float = 0f,
m10: Float = 0f,
m11: Float = 0f,
m12: Float = 0f,
m13: Float = 0f,
m20: Float = 0f,
m21: Float = 0f,
m22: Float = 0f,
m23: Float = 0f,
m30: Float = 0f,
m31: Float = 0f,
m32: Float = 0f,
m33: Float = 0f
): Matrix4 {
val matrix = Matrix4()
val values = matrix.`val`
values[Matrix4.M00] = m00
values[Matrix4.M01] = m01
values[Matrix4.M02] = m02
values[Matrix4.M03] = m03
values[Matrix4.M10] = m10
values[Matrix4.M11] = m11
values[Matrix4.M12] = m12
values[Matrix4.M13] = m13
values[Matrix4.M20] = m20
values[Matrix4.M21] = m21
values[Matrix4.M22] = m22
values[Matrix4.M23] = m23
values[Matrix4.M30] = m30
values[Matrix4.M31] = m31
values[Matrix4.M32] = m32
values[Matrix4.M33] = m33
return matrix
}
/**
* Inverts currently stored values.
* @return a new [Matrix4] with the operation result.
*/
operator fun Matrix4.unaryMinus(): Matrix4 {
val matrix = Matrix4()
for (index in 0..15) {
matrix.`val`[index] = -this.`val`[index]
}
return matrix
}
/**
* Inverts the current matrix.
* @return a new [Matrix4] with the operation result.
* @see Matrix4.inv
*/
operator fun Matrix4.not(): Matrix4 = Matrix4(this).inv()
/**
* @param matrix4 values from this matrix will be added to this matrix.
*/
operator fun Matrix4.plusAssign(matrix4: Matrix4) {
for (index in 0..15) {
this.`val`[index] += matrix4.`val`[index]
}
}
/**
* @param matrix4 values from this matrix will be subtracted from this matrix.
*/
operator fun Matrix4.minusAssign(matrix4: Matrix4) {
for (index in 0..15) {
this.`val`[index] -= matrix4.`val`[index]
}
}
/**
* @param matrix4 values from this matrix will right-multiply this matrix. A*B results in AB.
* @see Matrix4.mulLeft
*/
operator fun Matrix4.timesAssign(matrix4: Matrix4) {
this.mul(matrix4)
}
/**
* @param scalar scales the matrix in the x, y and z components.
*/
operator fun Matrix4.timesAssign(scalar: Float) {
this.scl(scalar)
}
/**
* @param scale scales the matrix in the both the x and y components.
*/
operator fun Matrix4.timesAssign(scale: Vector2) {
this.scl(vec3(scale, 1f))
}
/**
* @param scale scales the matrix in the x, y and z components.
*/
operator fun Matrix4.timesAssign(scale: Vector3) {
this.scl(scale)
}
/**
* @param matrix4 this vector will be left-multiplied by this matrix, assuming the forth component is 1f.
*/
operator fun Vector3.timesAssign(matrix4: Matrix4) {
this.mul(matrix4)
}
/**
* @param matrix4 values from this matrix will be added to this matrix.
* @return this matrix for chaining.
*/
operator fun Matrix4.plus(matrix4: Matrix4): Matrix4 {
val result = Matrix4(this)
for (index in 0..15) {
result.`val`[index] += matrix4.`val`[index]
}
return result
}
/**
* @param matrix4 values from this matrix will be subtracted from this matrix.
* @return this matrix for chaining.
*/
operator fun Matrix4.minus(matrix4: Matrix4): Matrix4 {
val result = Matrix4(this)
for (index in 0..15) {
result.`val`[index] -= matrix4.`val`[index]
}
return result
}
/**
* @param matrix4 values from this matrix will right-multiply this matrix. A*B results in AB.
* @return this matrix for chaining.
* @see Matrix4.mulLeft
*/
operator fun Matrix4.times(matrix4: Matrix4): Matrix4 = Matrix4(this).mul(matrix4)
/**
* @param scalar scales the matrix in the x, y and z components.
* @return this matrix for chaining.
*/
operator fun Matrix4.times(scalar: Float): Matrix4 = Matrix4(this).scl(scalar)
/**
* @param vector3 this vector will be left-multiplied by this matrix, assuming the forth component is 1f.
* @return this matrix for chaining.
*/
operator fun Matrix4.times(vector3: Vector3): Vector3 = Vector3(vector3).mul(this)
/**
* Operator function that allows to deconstruct this matrix.
* @return first row, first column.
*/
operator fun Matrix4.component1(): Float = this.`val`[Matrix4.M00]
/**
* Operator function that allows to deconstruct this matrix.
* @return first row, second column.
*/
operator fun Matrix4.component2(): Float = this.`val`[Matrix4.M01]
/**
* Operator function that allows to deconstruct this matrix.
* @return first row, third column.
*/
operator fun Matrix4.component3(): Float = this.`val`[Matrix4.M02]
/**
* Operator function that allows to deconstruct this matrix.
* @return first row, forth column.
*/
operator fun Matrix4.component4(): Float = this.`val`[Matrix4.M03]
/**
* Operator function that allows to deconstruct this matrix.
* @return second row, first column.
*/
operator fun Matrix4.component5(): Float = this.`val`[Matrix4.M10]
/**
* Operator function that allows to deconstruct this matrix.
* @return second row, second column.
*/
operator fun Matrix4.component6(): Float = this.`val`[Matrix4.M11]
/**
* Operator function that allows to deconstruct this matrix.
* @return second row, third column.
*/
operator fun Matrix4.component7(): Float = this.`val`[Matrix4.M12]
/**
* Operator function that allows to deconstruct this matrix.
* @return second row, forth column.
*/
operator fun Matrix4.component8(): Float = this.`val`[Matrix4.M13]
/**
* Operator function that allows to deconstruct this matrix.
* @return third row, first column.
*/
operator fun Matrix4.component9(): Float = this.`val`[Matrix4.M20]
/**
* Operator function that allows to deconstruct this matrix.
* @return third row, second column.
*/
operator fun Matrix4.component10(): Float = this.`val`[Matrix4.M21]
/**
* Operator function that allows to deconstruct this matrix.
* @return third row, third column.
*/
operator fun Matrix4.component11(): Float = this.`val`[Matrix4.M22]
/**
* Operator function that allows to deconstruct this matrix.
* @return third row, forth column.
*/
operator fun Matrix4.component12(): Float = this.`val`[Matrix4.M23]
/**
* Operator function that allows to deconstruct this matrix.
* @return forth row, first column.
*/
operator fun Matrix4.component13(): Float = this.`val`[Matrix4.M30]
/**
* Operator function that allows to deconstruct this matrix.
* @return forth row, second column.
*/
operator fun Matrix4.component14(): Float = this.`val`[Matrix4.M31]
/**
* Operator function that allows to deconstruct this matrix.
* @return forth row, third column.
*/
operator fun Matrix4.component15(): Float = this.`val`[Matrix4.M32]
/**
* Operator function that allows to deconstruct this matrix.
* @return forth row, forth column.
*/
operator fun Matrix4.component16(): Float = this.`val`[Matrix4.M33]
| cc0-1.0 | 5c489132af749165c9a7ed5d0b6eb181 | 26.206522 | 105 | 0.69703 | 3.225515 | false | false | false | false |
PropaFramework/Propa | src/main/kotlin/io/propa/framework/dom/PropaDomElement.kt | 1 | 2837 | package io.propa.framework.dom
import com.github.snabbdom.*
import io.propa.framework.common.PropaConstant
import io.propa.framework.common.PropaDelegateProperty
import io.propa.framework.common.assertSafeCast
/**
* Created by gbaldeck on 6/5/2017.
*/
open class PropaDomElement(){
open lateinit var selector: String
open lateinit var vnode: VNode
open var vnodeData: VNodeData = assertSafeCast(Any())
open val children: Array<dynamic /* VNode | String */> = arrayOf()
constructor(selector: String): this() {
this.selector = selector
}
init {
vnodeData.hero = assertSafeCast(Any())
vnodeData.attachData = assertSafeCast(Any())
vnodeData.hook = assertSafeCast(Any())
vnodeData.ns = undefined
vnodeData.fn = undefined
vnodeData.args = arrayOf()
vnodeData.props = assertSafeCast(Any())
vnodeData.attrs = assertSafeCast(Any())
vnodeData.`class` = assertSafeCast(Any())
vnodeData.style = assertSafeCast(Any())
vnodeData.dataset = assertSafeCast(Any())
vnodeData.on = assertSafeCast(Any())
vnodeData.key = undefined
}
private val _getVnodeData = { vnodeData }
val hero: Hero by PropaDelegateProperty(_getVnodeData)
val attachData: AttachData by PropaDelegateProperty(_getVnodeData)
val hook: Hooks by PropaDelegateProperty(_getVnodeData)
var ns: String? by PropaDelegateProperty(_getVnodeData)
var fn: (() -> VNode)? by PropaDelegateProperty(_getVnodeData)
val args: Array<dynamic> by PropaDelegateProperty(_getVnodeData)
val props: Props by PropaDelegateProperty(_getVnodeData)
val attrs: Attrs by PropaDelegateProperty(_getVnodeData)
val classes: Classes by PropaDelegateProperty(_getVnodeData, "class")
val styles: VNodeStyle by PropaDelegateProperty(_getVnodeData, "style")
val dataset: Dataset by PropaDelegateProperty(_getVnodeData)
val on: On by PropaDelegateProperty(_getVnodeData)
var key: dynamic by PropaDelegateProperty(_getVnodeData)
fun applyAttributes(vararg attrs: Pair<String, String>){
_applyAttrs(attrs)
}
fun applyAttributes(vararg attrs: Pair<String, Number>){
_applyAttrs(attrs)
}
fun applyAttributes(vararg attrs: Pair<String, Boolean>){
_applyAttrs(attrs)
}
private fun _applyAttrs(pairs: Array<out Pair<String, dynamic>>){
val _attrs: dynamic = attrs
pairs.forEach {
(key, value) ->
_attrs[key] = value
}
}
fun deleteAttributes(vararg keys: String){
val _attrs: dynamic = attrs
keys.forEach {
key ->
_attrs[key] = PropaConstant.DELETE
}
val newAttrs: dynamic = Any()
val attrKeys = _attrs.keys() as Array<String>
attrKeys.forEach {
key ->
if(_attrs[key] !== PropaConstant.DELETE)
newAttrs[key] = _attrs[key]
}
val _vnodeData: dynamic = vnodeData
_vnodeData.attrs = newAttrs
}
} | mit | c135eb285582e693af8be97d9dc101ae | 30.186813 | 73 | 0.710962 | 3.67487 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/achievement/ui/view/VectorRatingBar.kt | 2 | 4398 | package org.stepik.android.view.achievement.ui.view
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.View
import androidx.annotation.DrawableRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.graphics.drawable.toBitmap
import org.stepic.droid.R
import kotlin.math.max
import kotlin.math.min
import kotlin.properties.Delegates
class VectorRatingBar
@JvmOverloads
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {
private lateinit var progressBitmap: Bitmap
private lateinit var secondaryProgressBitmap: Bitmap
private lateinit var backgroundBitmap: Bitmap
@DrawableRes var progressRes: Int
@DrawableRes var secondaryProgressRes: Int
@DrawableRes var backgroundRes: Int
var progress: Int by Delegates.observable(0) { _, _, _ -> requestLayout() }
var total: Int by Delegates.observable(0) { _, _, _ -> requestLayout() }
var gap: Float by Delegates.observable(0f) { _, _, _ -> requestLayout() }
init {
val attributes = context.obtainStyledAttributes(attrs, R.styleable.VectorRatingBar)
try {
backgroundRes = attributes.getResourceId(R.styleable.VectorRatingBar_backgroundIcon, android.R.drawable.star_off)
secondaryProgressRes = attributes.getResourceId(R.styleable.VectorRatingBar_secondaryIcon, android.R.drawable.star_on)
progressRes = attributes.getResourceId(R.styleable.VectorRatingBar_progressIcon, android.R.drawable.star_off)
progress = attributes.getInteger(R.styleable.VectorRatingBar_currentProgress, 0)
total = attributes.getInteger(R.styleable.VectorRatingBar_totalProgress, 0)
gap = attributes.getDimension(R.styleable.VectorRatingBar_itemsGap, 0f)
} finally {
attributes.recycle()
}
}
override fun onDraw(canvas: Canvas) {
var offset = 0f
for (i in 0 until min(progress, total)) {
canvas.drawBitmap(progressBitmap, offset, 0f, null)
offset += progressBitmap.width + gap
}
if (progress < total) {
canvas.drawBitmap(secondaryProgressBitmap, offset, 0f, null)
offset += secondaryProgressBitmap.width + gap
}
for (i in progress + 1 until total) {
canvas.drawBitmap(backgroundBitmap, offset, 0f, null)
offset += backgroundBitmap.width + gap
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
val heightSize = MeasureSpec.getSize(heightMeasureSpec)
progressBitmap = getBitmap(progressRes, heightMode, heightSize)
secondaryProgressBitmap = getBitmap(secondaryProgressRes, heightMode, heightSize)
backgroundBitmap = getBitmap(backgroundRes, heightMode, heightSize)
val height = maxOf(progressBitmap.height, secondaryProgressBitmap.height, backgroundBitmap.height)
val totalWidth = progressBitmap.width * min(total, progress) +
secondaryProgressBitmap.width * min(1, max(0, total - progress)) +
backgroundBitmap.width * max(0, total - progress - 1) +
(gap * (total - 1)).toInt()
@SuppressLint("SwitchIntDef")
val width = when (widthMode) {
MeasureSpec.EXACTLY -> widthSize
MeasureSpec.AT_MOST -> min(widthSize, totalWidth)
else -> totalWidth
}
setMeasuredDimension(width, height)
}
private fun getBitmap(@DrawableRes resId: Int, heightMode: Int, heightSize: Int): Bitmap {
val drawable = AppCompatResources.getDrawable(context, resId)!!
val targetHeight = when (heightMode) {
MeasureSpec.EXACTLY -> heightSize
MeasureSpec.AT_MOST -> min(drawable.intrinsicHeight, heightSize)
else -> drawable.intrinsicHeight
}
val targetWidth = (drawable.intrinsicWidth * (targetHeight.toFloat() / drawable.intrinsicHeight)).toInt()
return drawable.toBitmap(targetWidth, targetHeight)
}
} | apache-2.0 | c8a7d30262fcd008db4d6a16ceffb68f | 40.11215 | 130 | 0.693952 | 4.875831 | false | false | false | false |
hotmobmobile/hotmob-android-sdk | AndroidStudio/HotmobSDKShowcase/app/src/main/java/com/hotmob/sdk/hotmobsdkshowcase/interstitial/InterstitialShowcaseFragment.kt | 1 | 3582 | package com.hotmob.sdk.hotmobsdkshowcase.interstitial
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import com.hotmob.sdk.ad.HotmobAdDeepLinkListener
import com.hotmob.sdk.ad.HotmobAdEvent
import com.hotmob.sdk.ad.HotmobAdListener
import com.hotmob.sdk.ad.HotmobInterstitial
import com.hotmob.sdk.hotmobsdkshowcase.MainActivity
import com.hotmob.sdk.hotmobsdkshowcase.R
import com.hotmob.sdk.hotmobsdkshowcase.databinding.FragmentInterstitialitemListBinding
/**
* A fragment representing a list of Items.
*/
class InterstitialShowcaseFragment : androidx.fragment.app.Fragment(),
InterstitialItemAdapter.ItemClickListener,
HotmobAdListener,
HotmobAdDeepLinkListener {
private val interstitial = HotmobInterstitial("ShowcaseInterstitial", "")
private var _binding: FragmentInterstitialitemListBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentInterstitialitemListBinding.inflate(inflater, container, false)
interstitial.listener = this
interstitial.deepLinkListener = this
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Set the adapter
with(binding.list) {
layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
val interstitialArray = mutableListOf<InterstitialItem>()
val clickActionList = resources.getStringArray(R.array.click_actions)
val clickActionAdCodeList = resources.getStringArray(R.array.interstitial_click_action_adcodes)
for (i in clickActionList.indices) {
interstitialArray.add(
InterstitialItem(
name = clickActionList[i],
adCode = clickActionAdCodeList[i]
))
}
adapter = InterstitialItemAdapter(
interstitialArray,
this@InterstitialShowcaseFragment
)
}
binding.customAdCode.setOnEditorActionListener { _, actionId, _ ->
val result = actionId and EditorInfo.IME_MASK_ACTION
if (result == EditorInfo.IME_ACTION_DONE) {
val customCode = binding.customAdCode.text.toString()
// 1. hide the Banner
onItemClick(InterstitialItem("Custom", customCode))
}
false
}
}
override fun onDestroy() {
super.onDestroy()
interstitial.listener = null
interstitial.deepLinkListener = null
}
override fun onItemClick(interstitialItem: InterstitialItem) {
Log.d("InterstitialShowcase", "${interstitialItem.name} clicked.")
val c = context
if (c != null) {
interstitial.adCode = interstitialItem.adCode
interstitial.loadAd(c)
}
}
override fun onAdEvent(adEvent: HotmobAdEvent) {
if (adEvent == HotmobAdEvent.NO_AD) {
Toast.makeText(context, "No ad returned", Toast.LENGTH_SHORT).show()
}
}
override fun onDeepLink(deepLink: String) {
if (context is MainActivity) {
(context as MainActivity).goToDeepPage(deepLink)
}
}
}
| mit | 43b98ccef63a0378604561c676906c96 | 33.776699 | 107 | 0.666387 | 4.795181 | false | false | false | false |
jayrave/moshi-pristine-models | src/test/kotlin/com/jayrave/moshi/pristineModels/FieldMappingImplTest.kt | 1 | 9754 | package com.jayrave.moshi.pristineModels
import com.jayrave.moshi.pristineModels.testLib.StringSink
import com.jayrave.moshi.pristineModels.testLib.jsonReaderFrom
import com.jayrave.moshi.pristineModels.testLib.jsonString
import com.jayrave.moshi.pristineModels.testLib.jsonWriterTo
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.lang.reflect.Type
import java.util.concurrent.CountDownLatch
import kotlin.reflect.KProperty1
import kotlin.reflect.jvm.javaType
class FieldMappingImplTest {
@Test
fun existingJsonAdapterOrAcquireFromReturnsExistingAdapter() {
class ExampleModel(@Suppress("unused") val boolean: Boolean)
val fieldMapping = buildFieldMapping("boolean_field", ExampleModel::boolean)
// Make the mapping acquire json adapter
fieldMapping.acquireJsonAdapterIfRequired(Moshi.Builder().add({ type, _, _ -> when (type) {
Boolean::class.javaPrimitiveType -> BooleanAsIntJsonAdapter()
else -> null
} }).build())
val actualAdapter = fieldMapping.existingJsonAdapterOrAcquireFrom(Moshi.Builder().build())
assertThat(actualAdapter).isInstanceOf(BooleanAsIntJsonAdapter::class.java)
}
@Test
fun existingJsonAdapterOrAcquireFromAcquiresInCaseAdapterDoesNotExistAlready() {
class ExampleModel(@Suppress("unused") val boolean: Boolean)
val fieldMapping = buildFieldMapping("boolean_field", ExampleModel::boolean)
val moshi = Moshi.Builder().add({ type, _, _ -> when (type) {
Boolean::class.javaPrimitiveType -> BooleanAsIntJsonAdapter()
else -> null
} }).build()
val actualAdapter = fieldMapping.existingJsonAdapterOrAcquireFrom(moshi)
assertThat(actualAdapter).isInstanceOf(BooleanAsIntJsonAdapter::class.java)
}
@Test
fun valueIsRead() {
class ExampleModel(val int: Int)
val fieldName = "int_field"
val fieldValue = 5
val fieldMapping = buildFieldMapping(fieldName, ExampleModel::int)
fieldMapping.acquireJsonAdapterIfRequired(Moshi.Builder().build())
fieldMapping.read(jsonReaderFrom(jsonString(fieldValue)))
assertThat(fieldMapping.lastReadValueInCurrentThread()).isEqualTo(fieldValue)
}
@Test
fun valueIsWritten() {
class ExampleModel(val int: Int)
val fieldName = "int_field"
val model = ExampleModel(5)
val fieldMapping = buildFieldMapping(fieldName, ExampleModel::int)
val stringSink = StringSink.create()
fieldMapping.acquireJsonAdapterIfRequired(Moshi.Builder().build())
fieldMapping.write(jsonWriterTo(stringSink), model)
assertThat(stringSink.toString()).isEqualTo(jsonString(model.int))
}
@Test(expected = IllegalStateException::class)
fun readWithoutAcquiringAdapterThrowsWhenNotUsingExplicitJsonAdapter() {
class ExampleModel(val int: Int)
buildFieldMapping("int_field", ExampleModel::int).read(jsonReaderFrom(jsonString(5)))
}
@Test(expected = IllegalStateException::class)
fun writeWithoutAcquiringAdapterThrowsWhenNotUsingExplicitJsonAdapter() {
class ExampleModel(val int: Int)
buildFieldMapping("int_field", ExampleModel::int).write(
jsonWriterTo(StringSink.create()), ExampleModel(5)
)
}
@Test
fun explicitlyPassedInJsonAdapterIsUsed() {
val trueInt = BooleanAsIntJsonAdapter.TRUE_INT
val falseInt = BooleanAsIntJsonAdapter.FALSE_INT
class ExampleModel(val boolean: Boolean)
val fieldMapping = buildFieldMapping("b", ExampleModel::boolean, BooleanAsIntJsonAdapter())
fieldMapping.read(jsonReaderFrom(jsonString(trueInt)))
assertThat(fieldMapping.lastReadValueInCurrentThread()).isTrue()
fieldMapping.read(jsonReaderFrom(jsonString(falseInt)))
assertThat(fieldMapping.lastReadValueInCurrentThread()).isFalse()
val stringSink1 = StringSink.create()
fieldMapping.write(jsonWriterTo(stringSink1), ExampleModel(true))
assertThat(stringSink1.toString()).isEqualTo(jsonString(trueInt))
val stringSink2 = StringSink.create()
fieldMapping.write(jsonWriterTo(stringSink2), ExampleModel(false))
assertThat(stringSink2.toString()).isEqualTo(jsonString(falseInt))
}
@Test
fun explicitlyPassedInJsonAdapterIsNotOverwrittenEvenIfAcquiredAdapterIsCalled() {
val trueInt = BooleanAsIntJsonAdapter.TRUE_INT
class ExampleModel(val boolean: Boolean)
// Build binding with custom adapter & ask to acquire json adapter
val fieldMapping = buildFieldMapping("b", ExampleModel::boolean, BooleanAsIntJsonAdapter())
fieldMapping.acquireJsonAdapterIfRequired(Moshi.Builder().build())
fieldMapping.read(jsonReaderFrom(jsonString(trueInt)))
assertThat(fieldMapping.lastReadValueInCurrentThread()).isTrue()
val stringSink = StringSink.create()
fieldMapping.write(jsonWriterTo(stringSink), ExampleModel(true))
assertThat(stringSink.toString()).isEqualTo(jsonString(trueInt))
}
@Test
fun readWorksInMultiThreadedScenarios() {
class ExampleModel(val int: Int)
val fieldName = "int_field"
val fieldMapping = buildFieldMapping(fieldName, ExampleModel::int)
fieldMapping.acquireJsonAdapterIfRequired(Moshi.Builder().build())
fun runThread(
threadSpecificFieldValue: Int, latch1: CountDownLatch,
latch2: CountDownLatch, awaitOnLatch: CountDownLatch) {
Thread {
// Read & assert value
fieldMapping.read(jsonReaderFrom(jsonString(threadSpecificFieldValue)))
assertThat(fieldMapping.lastReadValueInCurrentThread()).isEqualTo(
threadSpecificFieldValue
)
// Count down & await on the other latch
latch1.countDown()
awaitOnLatch.await()
// Assert again
assertThat(fieldMapping.lastReadValueInCurrentThread()).isEqualTo(
threadSpecificFieldValue
)
// Count down the second latch
latch2.countDown()
}.start()
}
val thread1Latch1 = CountDownLatch(1)
val thread1Latch2 = CountDownLatch(1)
val thread2Latch1 = CountDownLatch(1)
val thread2Latch2 = CountDownLatch(1)
runThread(5, thread1Latch1, thread1Latch2, thread2Latch1)
runThread(12, thread2Latch1, thread2Latch2, thread1Latch1)
thread1Latch2.await()
thread2Latch2.await()
}
@Test
fun valueCanNotBeNullExceptionNotThrownForNullableType() {
class ExampleModelWithNullableType(val int: Int?)
val mapping = buildFieldMapping("nullable_int_field", ExampleModelWithNullableType::int)
mapping.acquireJsonAdapterIfRequired(Moshi.Builder().build())
// Assert exception is not thrown when value is null
assertThat(mapping.lastReadValueInCurrentThread()).isNull()
// Assert exception is not thrown when value is non-null
mapping.read(jsonReaderFrom(jsonString(5)))
assertThat(mapping.lastReadValueInCurrentThread()).isEqualTo(5)
}
@Test(expected = FieldMappingImpl.ValueCanNotBeNullException::class)
fun valueCanNotBeNullExceptionIsThrownForNonNullTypeIfValueIsNull() {
class ExampleModel(val int: Int)
val mapping = buildFieldMapping("int_field", ExampleModel::int)
mapping.acquireJsonAdapterIfRequired(Moshi.Builder().build())
mapping.lastReadValueInCurrentThread()
}
@Test
fun clearLastReadValueInCurrentThreadWorks() {
class ExampleModelWithNullableType(val int: Int?)
val mapping = buildFieldMapping("nullable_int_field", ExampleModelWithNullableType::int)
mapping.acquireJsonAdapterIfRequired(Moshi.Builder().build())
// Read & assert value was read
mapping.read(jsonReaderFrom(jsonString(5)))
assertThat(mapping.lastReadValueInCurrentThread()).isNotNull()
// Clear & assert value was cleared
mapping.clearLastReadValueInCurrentThread()
assertThat(mapping.lastReadValueInCurrentThread()).isNull()
}
private class BooleanAsIntJsonAdapter : JsonAdapter<Boolean>() {
override fun fromJson(reader: JsonReader): Boolean {
return when (reader.nextInt()) {
TRUE_INT -> true
FALSE_INT -> false
else -> throw IllegalArgumentException()
}
}
override fun toJson(writer: JsonWriter, value: Boolean) {
when (value) {
true -> writer.value(TRUE_INT)
else -> writer.value(FALSE_INT)
}
}
companion object {
const val TRUE_INT = 1
const val FALSE_INT = 0
}
}
companion object {
private fun <T : Any, F> buildFieldMapping(
name: String, property: KProperty1<T, F>, jsonAdapter: JsonAdapter<F>? = null):
FieldMappingImpl<T, F> {
val propertyExtractor = object : PropertyExtractor<T, F> {
override val type: Type = property.returnType.javaType
override fun extractFrom(t: T): F = property.get(t)
}
return FieldMappingImpl(
name, property.returnType.isMarkedNullable, propertyExtractor, jsonAdapter
)
}
}
} | apache-2.0 | 363033317991f0a8aa2c9fdfae2ecf46 | 35.811321 | 99 | 0.678081 | 4.85999 | false | true | false | false |
apollostack/apollo-android | composite/samples/multiplatform/kmp-android-app/src/main/java/com/apollographql/apollo3/kmpsample/repositories/MainActivity.kt | 1 | 2482 | package com.apollographql.apollo3.kmpsample.repositories
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.apollographql.apollo3.kmpsample.data.ApolloCoroutinesRepository
import com.apollographql.apollo3.kmpsample.databinding.ActivityMainBinding
import com.apollographql.apollo3.kmpsample.repositoryDetail.RepositoryDetailActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MainActivity : AppCompatActivity() {
private val dataSource by lazy { ApolloCoroutinesRepository() }
private lateinit var binding: ActivityMainBinding
private lateinit var repositoriesAdapter: RepositoriesAdapter
private lateinit var job: Job
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
binding.tvError.visibility = View.GONE
binding.rvRepositories.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
binding.rvRepositories.addItemDecoration(DividerItemDecoration(this, LinearLayout.VERTICAL))
repositoriesAdapter = RepositoriesAdapter { repositoryFragment ->
RepositoryDetailActivity.start(this@MainActivity, repositoryFragment.name)
}
binding.rvRepositories.adapter = repositoriesAdapter
setContentView(binding.root)
fetchRepositories()
}
private fun fetchRepositories() {
job = CoroutineScope(Dispatchers.IO).launch {
try {
val repos = dataSource.fetchRepositories()
withContext(Dispatchers.Main) {
binding.progressBar.visibility = View.GONE
binding.rvRepositories.visibility = View.VISIBLE
repositoriesAdapter.setItems(repos)
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
handleError(e)
}
}
}
}
private fun handleError(error: Throwable?) {
binding.tvError.text = error?.localizedMessage
binding.tvError.visibility = View.VISIBLE
binding.progressBar.visibility = View.GONE
error?.printStackTrace()
}
override fun onDestroy() {
job.cancel()
super.onDestroy()
}
}
| mit | 9a19cfcd318877d4d1081cbda1716d13 | 33 | 98 | 0.77639 | 5.05499 | false | false | false | false |
sn3d/nomic | nomic-core/src/main/kotlin/nomic/core/Bundle.kt | 1 | 8462 | /*
* Copyright 2017 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nomic.core
import nomic.core.exception.BundleDoesNotExistException
import nomic.core.exception.WtfException
import nomic.core.script.BundleScript
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.file.*
import java.util.zip.ZipInputStream
/**
* It's kind of package. It's bundled [Script] with all content the box
* need as archive or directory. Every bundle must have 'nomic.box' [Script]
* on root.
*
* @author [email protected]
*/
interface Bundle {
/**
* find and return entry on given path. Each path must start with root '/'. */
fun entry(path: String): Entry?
/** return collection of all entries in bundle, folders are excluded.*/
fun entries(filter: (Entry) -> Boolean = { true }): List<Entry>
companion object {
fun create(path: String): Bundle =
create(FileSystems.getDefault().getPath(path))
fun create(path: Path): Bundle {
if (Files.isDirectory(path)) {
return FileSystemBundle(path)
} else if (Files.isRegularFile(path)) {
return ArchiveBundle(path)
} else {
throw BundleDoesNotExistException(path)
}
}
}
}
//-------------------------------------------------------------------------------------------------
// extensions
//-------------------------------------------------------------------------------------------------
val Bundle.script: Script
get() = BundleScript(this)
fun String.asBundle(): Bundle =
Bundle.create(this)
fun String.asBundleFrom(fs: FileSystem): Bundle =
Bundle.create(fs.getPath(this))
//-------------------------------------------------------------------------------------------------
// implementations
//-------------------------------------------------------------------------------------------------
/**
* This implementation operates with bundle as directory on
* FileSystem where bundle's [Entry]-ies are all files inside root
* directory.
*/
internal class FileSystemBundle(val root: Path) : Bundle {
constructor(root: String, fs: FileSystem = FileSystems.getDefault()) : this(fs.getPath(root))
override fun entry(path: String): Entry? {
val entryPath =
when {
path.startsWith("/") -> root.resolve(path.removePrefix("/"))
else -> root.resolve(path)
}
if (Files.exists(entryPath) && Files.isRegularFile(entryPath)) {
return FileSystemEntry(entryPath)
} else {
return null;
}
}
override fun entries(filter: (Entry) -> Boolean): List<Entry> =
listDirectory(root)
.map { file -> FileSystemEntry(file) }
.filter { entry -> filter(entry) }
.toList()
private fun listDirectory(path: Path) : Sequence<Path> =
Files.newDirectoryStream(path).asSequence()
.flatMap { p ->
when {
Files.isDirectory(p) -> listDirectory(p)
Files.isRegularFile(p) -> sequenceOf(p)
else -> throw WtfException()
}
}
private inner class FileSystemEntry(private val path: Path) : Entry {
override val name: String by lazy {
"/" + root.relativize(path).normalize().toString()
}
override fun openInputStream(): InputStream =
Files.newInputStream(root.resolve(name.removePrefix("/")))
override fun toString(): String {
return "FileSystemEntry($name)"
}
}
}
/**
* This implementation operates with bundle inside another bundle (nested bundle). This is used
* mainly in big bundles they're grouping multiple smaller bundles via 'module'.
*
* @author [email protected]
*/
class NestedBundle : Bundle {
private val parent: Bundle
private val root: String
constructor(parent: Bundle, root: String) {
this.parent = parent;
this.root = root;
}
override fun entry(path: String): Entry? = when {
path.startsWith("/") -> parent.entry("${root}${path}")?.let { this.NestedEntry(it) }
else -> parent.entry("${root}/${path}")?.let { this.NestedEntry(it) }
}
override fun entries(filter: (Entry) -> Boolean): List<Entry> =
parent.entries(this::isNestedEntry).map(this::toNestedEntry)
private fun isNestedEntry(parentEntry: Entry): Boolean =
parentEntry.name.startsWith(root);
private fun toNestedEntry(parentEntry: Entry): Entry =
this.NestedEntry(parentEntry)
private inner class NestedEntry(private val parentEntry: Entry) : Entry {
override val name: String
get() = parentEntry.name.removePrefix(root)
override fun openInputStream(): InputStream = parentEntry.openInputStream()
override fun toString(): String {
return "NestedEntry($name)"
}
}
}
/**
* This implementation holds all entries in-memory. It's useful for unit testing purpose because
* it can be easily created.
*
* ```
* val bundle = InMemoryBundle(
* "/nomic.box" to ByteBuffer.wrap("script".toByteArray()),
* "/file.txt" to ByteBuffer.wrap("Hello World".toByteArray()),
* )
* ```
*/
open class InMemoryBundle private constructor(private val entries: List<InMemoryEntry>) : Bundle {
constructor(vararg entries: Pair<String, ByteBuffer>): this(entries.toMap())
constructor(entries: Map<String, ByteBuffer>) : this( entries.map { e -> InMemoryEntry(e.key, e.value) } )
override fun entry(path: String): Entry? =
entries.asSequence()
.find { e -> e.name == path }
override fun entries(filter: (Entry) -> Boolean): List<Entry> =
entries.asSequence()
.filter(filter)
.toList()
class InMemoryEntry(override val name: String, private val data: ByteBuffer) : Entry {
override fun openInputStream(): InputStream = ByteArrayInputStream(data.array())
}
}
/**
* This implementation load bundle as ZIP archive and access to entries inside ZIP folder. This implementation
* is used when you're trying open file instead of directory.
*
* @author [email protected]
*/
class ArchiveBundle : Bundle {
// hold the unzipped entries in memory
private val entries: List<ArchiveEntry>;
/**
* unzip the file on [path] and hold the unzipped
* bundle in memory
*/
constructor(path: Path) : this(Files.newInputStream(path))
/**
* read/unzip the input stream content and load it
* into memory as [ArchiveEntry]
*/
constructor(input: InputStream) {
entries = unzipArchive(input)
}
override fun entry(path: String): Entry? =
entries.asSequence()
.find { e -> e.name == normalized(path) }
override fun entries(filter: (Entry) -> Boolean): List<Entry> =
entries.asSequence()
.filter(filter)
.toList()
/**
* main unzipping function. It's only for internal usage
*/
private fun unzipArchive(input:InputStream): List<ArchiveEntry> {
val out = mutableListOf<ArchiveEntry>()
ZipInputStream(input).use { zipStream ->
var zipEntry = zipStream.nextEntry
while(zipEntry != null) {
// read data of entry
if (!zipEntry.isDirectory) {
val archiveEntry = ArchiveEntry(
name = zipEntry.name,
data = zipStream.readData()
)
out.add(archiveEntry)
}
zipEntry = zipStream.nextEntry
}
}
return out;
}
private fun ZipInputStream.readData():ByteBuffer {
ByteArrayOutputStream().use { outStream ->
val buffer = ByteArray(2048)
// loop for reading data
var len = [email protected](buffer)
while(len > 0) {
outStream.write(buffer, 0, len)
len = [email protected](buffer)
}
return ByteBuffer.wrap(outStream.toByteArray())
}
}
/**
* this method is normalizing paths (e.g. if start with '/' character, the character is removed)
*/
private fun normalized(path: String): String =
when {
path.startsWith("/") -> path.substring(1, path.length)
else -> path
}
/**
* internal [Entry] implementation for [ArchiveBundle]
*/
private class ArchiveEntry(override val name: String, private val data: ByteBuffer) : Entry {
override fun openInputStream(): InputStream = ByteArrayInputStream(data.array())
override fun toString(): String {
return "ArchiveEntry(name='$name')"
}
}
}
| apache-2.0 | beade0232718027e781813c2c07d7d54 | 26.653595 | 110 | 0.6658 | 3.863927 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/workflow/PrepareTreatmentsDataWorker.kt | 1 | 7403 | package info.nightscout.androidaps.workflow
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.GlucoseUnit
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.overview.OverviewData
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.*
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress
import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.Translator
import javax.inject.Inject
class PrepareTreatmentsDataWorker(
context: Context,
params: WorkerParameters
) : Worker(context, params) {
@Inject lateinit var dataWorker: DataWorker
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var rh: ResourceHelper
@Inject lateinit var rxBus: RxBus
@Inject lateinit var translator: Translator
@Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var repository: AppRepository
@Inject lateinit var defaultValueHelper: DefaultValueHelper
init {
(context.applicationContext as HasAndroidInjector).androidInjector().inject(this)
}
class PrepareTreatmentsData(
val overviewData: OverviewData
)
override fun doWork(): Result {
val data = dataWorker.pickupObject(inputData.getLong(DataWorker.STORE_KEY, -1)) as PrepareTreatmentsData?
?: return Result.failure(workDataOf("Error" to "missing input data"))
rxBus.send(EventIobCalculationProgress(CalculationWorkflow.ProgressData.PREPARE_TREATMENTS_DATA, 0, null))
data.overviewData.maxTreatmentsValue = 0.0
data.overviewData.maxEpsValue = 0.0
val filteredTreatments: MutableList<DataPointWithLabelInterface> = ArrayList()
val filteredTherapyEvents: MutableList<DataPointWithLabelInterface> = ArrayList()
val filteredEps: MutableList<DataPointWithLabelInterface> = ArrayList()
repository.getBolusesDataFromTimeToTime(data.overviewData.fromTime, data.overviewData.endTime, true).blockingGet()
.map { BolusDataPoint(it, rh, activePlugin, defaultValueHelper) }
.filter { it.data.type == Bolus.Type.NORMAL || it.data.type == Bolus.Type.SMB }
.forEach {
it.y = getNearestBg(data.overviewData, it.x.toLong())
filteredTreatments.add(it)
}
repository.getCarbsDataFromTimeToTimeExpanded(data.overviewData.fromTime, data.overviewData.endTime, true).blockingGet()
.map { CarbsDataPoint(it, rh) }
.forEach {
it.y = getNearestBg(data.overviewData, it.x.toLong())
filteredTreatments.add(it)
}
// ProfileSwitch
repository.getEffectiveProfileSwitchDataFromTimeToTime(data.overviewData.fromTime, data.overviewData.endTime, true).blockingGet()
.map { EffectiveProfileSwitchDataPoint(it, rh, data.overviewData.epsScale) }
.forEach {
data.overviewData.maxEpsValue = maxOf(data.overviewData.maxEpsValue, it.data.originalPercentage.toDouble())
filteredEps.add(it)
}
// OfflineEvent
repository.getOfflineEventDataFromTimeToTime(data.overviewData.fromTime, data.overviewData.endTime, true).blockingGet()
.map {
TherapyEventDataPoint(
TherapyEvent(timestamp = it.timestamp, duration = it.duration, type = TherapyEvent.Type.APS_OFFLINE, glucoseUnit = TherapyEvent.GlucoseUnit.MMOL),
rh,
profileFunction,
translator
)
}
.forEach(filteredTreatments::add)
// Extended bolus
if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) {
repository.getExtendedBolusDataFromTimeToTime(data.overviewData.fromTime, data.overviewData.endTime, true).blockingGet()
.map { ExtendedBolusDataPoint(it, rh) }
.filter { it.duration != 0L }
.forEach {
it.y = getNearestBg(data.overviewData, it.x.toLong())
filteredTreatments.add(it)
}
}
// Careportal
repository.compatGetTherapyEventDataFromToTime(data.overviewData.fromTime - T.hours(6).msecs(), data.overviewData.endTime).blockingGet()
.map { TherapyEventDataPoint(it, rh, profileFunction, translator) }
.filterTimeframe(data.overviewData.fromTime, data.overviewData.endTime)
.forEach {
if (it.y == 0.0) it.y = getNearestBg(data.overviewData, it.x.toLong())
filteredTherapyEvents.add(it)
}
// increase maxY if a treatment forces it's own height that's higher than a BG value
filteredTreatments.map { it.y }
.maxOrNull()
?.let(::addUpperChartMargin)
?.let { data.overviewData.maxTreatmentsValue = maxOf(data.overviewData.maxTreatmentsValue, it) }
filteredTherapyEvents.map { it.y }
.maxOrNull()
?.let(::addUpperChartMargin)
?.let { data.overviewData.maxTherapyEventValue = maxOf(data.overviewData.maxTherapyEventValue, it) }
data.overviewData.treatmentsSeries = PointsWithLabelGraphSeries(filteredTreatments.toTypedArray())
data.overviewData.therapyEventSeries = PointsWithLabelGraphSeries(filteredTherapyEvents.toTypedArray())
data.overviewData.epsSeries = PointsWithLabelGraphSeries(filteredEps.toTypedArray())
rxBus.send(EventIobCalculationProgress(CalculationWorkflow.ProgressData.PREPARE_TREATMENTS_DATA, 100, null))
return Result.success()
}
private fun addUpperChartMargin(maxBgValue: Double) =
if (profileFunction.getUnits() == GlucoseUnit.MGDL) Round.roundTo(maxBgValue, 40.0) + 80 else Round.roundTo(maxBgValue, 2.0) + 4
private fun getNearestBg(overviewData: OverviewData, date: Long): Double {
overviewData.bgReadingsArray.let { bgReadingsArray ->
for (reading in bgReadingsArray) {
if (reading.timestamp > date) continue
return Profile.fromMgdlToUnits(reading.value, profileFunction.getUnits())
}
return if (bgReadingsArray.isNotEmpty()) Profile.fromMgdlToUnits(bgReadingsArray[0].value, profileFunction.getUnits())
else Profile.fromMgdlToUnits(100.0, profileFunction.getUnits())
}
}
private fun <E : DataPointWithLabelInterface> List<E>.filterTimeframe(fromTime: Long, endTime: Long): List<E> =
filter { it.x + it.duration >= fromTime && it.x <= endTime }
} | agpl-3.0 | 9d84944ff238f11d0ff22d5f43884227 | 48.691275 | 166 | 0.704444 | 4.785391 | false | false | false | false |
Heiner1/AndroidAPS | omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt | 1 | 2888 | package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition
import java.util.*
class BasalProgram(
segments: List<Segment>
) {
val segments: MutableList<Segment> = segments.toMutableList()
get() = Collections.unmodifiableList(field)
fun addSegment(segment: Segment) {
segments.add(segment)
}
fun hasZeroUnitSegments() = segments.any { it.basalRateInHundredthUnitsPerHour == 0 }
fun rateAt(date: Long): Double {
val instance = Calendar.getInstance()
instance.timeInMillis = date
val hourOfDay = instance[Calendar.HOUR_OF_DAY]
val minuteOfHour = instance[Calendar.MINUTE]
val slotIndex = hourOfDay * 2 + minuteOfHour.div(30)
val slot = segments.find { it.startSlotIndex <= slotIndex && slotIndex < it.endSlotIndex }
return (slot?.basalRateInHundredthUnitsPerHour ?: 0).toDouble() / 100
}
class Segment(
val startSlotIndex: Short,
val endSlotIndex: Short,
val basalRateInHundredthUnitsPerHour: Int
) {
fun getPulsesPerHour(): Short {
return (basalRateInHundredthUnitsPerHour * PULSES_PER_UNIT / 100).toShort()
}
fun getNumberOfSlots(): Short {
return (endSlotIndex - startSlotIndex).toShort()
}
override fun toString(): String {
return "Segment{" +
"startSlotIndex=" + startSlotIndex +
", endSlotIndex=" + endSlotIndex +
", basalRateInHundredthUnitsPerHour=" + basalRateInHundredthUnitsPerHour +
'}'
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Segment
if (startSlotIndex != other.startSlotIndex) return false
if (endSlotIndex != other.endSlotIndex) return false
if (basalRateInHundredthUnitsPerHour != other.basalRateInHundredthUnitsPerHour) return false
return true
}
override fun hashCode(): Int {
var result: Int = startSlotIndex.toInt()
result = 31 * result + endSlotIndex
result = 31 * result + basalRateInHundredthUnitsPerHour
return result
}
companion object {
private const val PULSES_PER_UNIT: Byte = 20
}
}
override fun toString(): String {
return "BasalProgram{" +
"segments=" + segments +
'}'
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BasalProgram
if (segments != other.segments) return false
return true
}
override fun hashCode(): Int {
return segments.hashCode()
}
}
| agpl-3.0 | e21eb9e5929472456b11cc001b1b6d9d | 29.083333 | 104 | 0.605609 | 4.6208 | false | false | false | false |
square/wire | wire-library/wire-compiler/src/test/java/com/squareup/wire/schema/OptionsLinkingTest.kt | 1 | 6783 | /*
* Copyright (C) 2019 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.
*/
@file:Suppress("UsePropertyAccessSyntax")
package com.squareup.wire.schema
import com.squareup.wire.testing.add
import okio.Path
import okio.Path.Companion.toPath
import okio.fakefilesystem.FakeFileSystem
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class OptionsLinkingTest {
private val fs = FakeFileSystem().apply {
if (Path.DIRECTORY_SEPARATOR == "\\") emulateWindows() else emulateUnix()
}
@Test
fun extensionOnTheSourcePathIsApplied() {
fs.add(
"source-path/a.proto",
"""
|import "formatting_options.proto";
|message A {
| optional string s = 1 [(formatting_options).language = "English"];
|}
""".trimMargin()
)
fs.add(
"source-path/formatting_options.proto",
"""
|import "google/protobuf/descriptor.proto";
|
|message FormattingOptions {
| optional string language = 1;
|}
|
|extend google.protobuf.FieldOptions {
| optional FormattingOptions formatting_options = 22001;
|}
""".trimMargin()
)
val schema = loadAndLinkSchema()
val typeA = schema.getType("A") as MessageType
assertThat(typeA.field("s")!!.options.map).isEqualTo(
mapOf(
formattingOptionsField to mapOf(
languageField to "English"
)
)
)
}
@Test
fun extensionOnTheProtoPathIsApplied() {
fs.add(
"source-path/a.proto",
"""
|import "formatting_options.proto";
|message A {
| optional string s = 1 [(formatting_options).language = "English"];
|}
""".trimMargin()
)
fs.add(
"proto-path/formatting_options.proto",
"""
|import "google/protobuf/descriptor.proto";
|
|message FormattingOptions {
| optional string language = 1;
|}
|
|extend google.protobuf.FieldOptions {
| optional FormattingOptions formatting_options = 22001;
|}
""".trimMargin()
)
val schema = loadAndLinkSchema()
val typeA = schema.getType("A") as MessageType
assertThat(typeA.field("s")!!.options.map).isEqualTo(
mapOf(
formattingOptionsField to mapOf(
languageField to "English"
)
)
)
}
@Test
fun fieldsOfExtensions() {
fs.add(
"source-path/a.proto",
"""
|import "formatting_options.proto";
|message A {
| optional string s = 1 [(formatting_options).language.name = "English"];
| optional string t = 2 [(length).max = 80];
|}
""".trimMargin()
)
fs.add(
"proto-path/formatting_options.proto",
"""
|import "google/protobuf/descriptor.proto";
|
|message FormattingOptions {
| optional Language language = 1;
| optional StringCasing string_casing = 2;
|}
|
|extend google.protobuf.FieldOptions {
| optional FormattingOptions formatting_options = 22001;
| optional Range length = 22002;
|}
|
|message Language {
| optional string name = 1;
| optional string locale = 2;
|}
|
|enum StringCasing {
| LOWER_CASE = 1;
| TITLE_CASE = 2;
| SENTENCE_CASE = 3;
|}
|
|message Range {
| optional double min = 1;
| optional double max = 2;
|}
""".trimMargin()
)
val schema = loadAndLinkSchema()
val typeA = schema.getType("A") as MessageType
assertThat(typeA.field("s")!!.options.map).isEqualTo(
mapOf(
formattingOptionsField to mapOf(
languageField to mapOf(
nameField to "English"
)
)
)
)
val typeLanguage = schema.getType("Language") as MessageType
assertThat(typeLanguage.field("name")).isNotNull()
val typeRange = schema.getType("Range") as MessageType
assertThat(typeRange.field("max")).isNotNull()
}
@Test
fun extensionTypesInExternalFile() {
fs.add(
"source-path/a.proto",
"""
|import "extensions.proto";
|
|message A {
| optional string s = 2 [(length).max = 80];
|}
""".trimMargin()
)
fs.add(
"proto-path/extensions.proto",
"""
|import "google/protobuf/descriptor.proto";
|import "range.proto";
|
|extend google.protobuf.FieldOptions {
| optional Range length = 22002;
|}
""".trimMargin()
)
fs.add(
"proto-path/range.proto",
"""
|
|message Range {
| optional double min = 1;
| optional double max = 2;
|}
""".trimMargin()
)
val schema = loadAndLinkSchema()
val typeRange = schema.getType("Range") as MessageType
assertThat(typeRange.field("max")).isNotNull()
}
private fun loadAndLinkSchema(): Schema {
val loader = SchemaLoader(fs)
val protoPath = when {
fs.exists("proto-path".toPath()) -> listOf(Location.get("proto-path"))
else -> listOf()
}
loader.initRoots(
sourcePath = listOf(Location.get("source-path")),
protoPath = protoPath
)
return loader.loadSchema()
}
companion object {
private val fieldOptions = ProtoType.get("google.protobuf.FieldOptions")
private val formattingOptionsField = ProtoMember.get(fieldOptions, "formatting_options")
private val formattingOptionsType = ProtoType.get("FormattingOptions")
private val languageField = ProtoMember.get(formattingOptionsType, "language")
private val languageType = ProtoType.get("Language")
private val nameField = ProtoMember.get(languageType, "name")
}
}
| apache-2.0 | ca10303e44d039c0c109332ffbc716e3 | 28.111588 | 92 | 0.559487 | 4.528037 | false | false | false | false |
dempe/pinterest-java | src/main/java/com/chrisdempewolf/pinterest/methods/board/BoardEndPointURIBuilder.kt | 1 | 1967 | package com.chrisdempewolf.pinterest.methods.board
import org.apache.http.client.utils.URIBuilder
import java.net.URI
import java.net.URISyntaxException
import java.util.regex.Pattern
import org.apache.commons.lang3.StringUtils.isNotBlank
object BoardEndPointURIBuilder {
private const val BASE_URL = "https://api.pinterest.com"
private const val BASE_BOARD_PATH = "/v1/boards/"
private const val BOARD_PATH = "$BASE_BOARD_PATH{BOARD_NAME}/"
private const val MY_BOARD_PATH = "/v1/me/boards/"
private val BOARD_NAME_PATTERN = Pattern.compile("\\{BOARD_NAME\\}")
@JvmStatic
@Throws(URISyntaxException::class)
fun buildBaseBoardURI(accessToken: String, fields: String?): URI {
val uriBuilder = URIBuilder(BASE_URL)
.setPath(BASE_BOARD_PATH)
.setParameter("access_token", accessToken)
if (isNotBlank(fields)) {
uriBuilder.setParameter("fields", fields)
}
return uriBuilder.build()
}
@JvmStatic
@Throws(URISyntaxException::class)
fun buildBoardURI(accessToken: String, boardName: String, fields: String?): URI {
val uriBuilder = URIBuilder(BASE_URL)
.setPath(BOARD_NAME_PATTERN.matcher(BOARD_PATH).replaceFirst(boardName))
.setParameter("access_token", accessToken)
if (isNotBlank(fields)) {
uriBuilder.setParameter("fields", fields)
}
return uriBuilder.build()
}
@JvmStatic
@Throws(URISyntaxException::class)
fun buildMyBoardURI(accessToken: String, fields: String?): URI {
val uriBuilder = URIBuilder(BASE_URL)
.setPath(MY_BOARD_PATH)
.setParameter("access_token", accessToken)
if (isNotBlank(fields)) {
uriBuilder.setParameter("fields", fields)
}
return uriBuilder.build()
}
}
| mit | 5e142ab56a2cf944d88afd3c566fadff | 31.245902 | 100 | 0.626335 | 4.532258 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/leftright/MotionLeftWrapAction.kt | 1 | 2007 | /*
* 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.action.motion.leftright
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.MotionType
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.Motion
import com.maddyhome.idea.vim.handler.MotionActionHandler
import com.maddyhome.idea.vim.handler.toMotionOrError
import kotlin.math.max
import kotlin.math.min
class MotionLeftWrapAction : MotionActionHandler.ForEachCaret() {
override fun getOffset(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments,
): Motion {
val moveCaretHorizontalWrap = moveCaretHorizontalWrap(editor, caret, -operatorArguments.count1)
return if (moveCaretHorizontalWrap < 0) Motion.Error else Motion.AbsoluteOffset(moveCaretHorizontalWrap)
}
override val motionType: MotionType = MotionType.EXCLUSIVE
}
class MotionRightWrapAction : MotionActionHandler.ForEachCaret() {
override fun getOffset(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments,
): Motion {
return moveCaretHorizontalWrap(editor, caret, operatorArguments.count1).toMotionOrError()
}
override val motionType: MotionType = MotionType.EXCLUSIVE
}
fun moveCaretHorizontalWrap(editor: VimEditor, caret: VimCaret, count: Int): Int {
// FIX - allows cursor over newlines
val oldOffset = caret.offset.point
val offset = min(max(0, caret.offset.point + count), editor.fileSize().toInt())
return if (offset == oldOffset) {
-1
} else {
offset
}
}
| mit | ba176da8cfecf9f0fc8bbd51e92a94a1 | 32.45 | 108 | 0.769806 | 4.198745 | false | false | false | false |
dbrant/apps-android-commons | app/src/main/java/fr/free/nrw/commons/Media.kt | 1 | 3330 | package fr.free.nrw.commons
import android.os.Parcelable
import fr.free.nrw.commons.location.LatLng
import kotlinx.android.parcel.Parcelize
import org.wikipedia.page.PageTitle
import java.util.*
@Parcelize
class Media constructor(
/**
* @return pageId for the current media object
* Wikibase Identifier associated with media files
*/
val pageId: String = UUID.randomUUID().toString(),
val thumbUrl: String? = null,
/**
* Gets image URL
* @return Image URL
*/
val imageUrl: String? = null,
/**
* Gets the name of the file.
* @return file name as a string
*/
val filename: String? = null,
/**
* Gets the file description.
* @return file description as a string
*/
// monolingual description on input...
/**
* Sets the file description.
* @param fallbackDescription the new description of the file
*/
var fallbackDescription: String? = null,
/**
* Gets the upload date of the file.
* Can be null.
* @return upload date as a Date
*/
val dateUploaded: Date? = null,
/**
* Gets the license name of the file.
* @return license as a String
*/
/**
* Sets the license name of the file.
*
* @param license license name as a String
*/
var license: String? = null,
val licenseUrl: String? = null,
/**
* Gets the name of the creator of the file.
* @return creator name as a String
*/
/**
* Sets the creator name of the file.
* @param creator creator name as a string
*/
var creator: String? = null,
/**
* Gets the categories the file falls under.
* @return file categories as an ArrayList of Strings
*/
val categories: List<String>? = null,
/**
* Gets the coordinates of where the file was created.
* @return file coordinates as a LatLng
*/
val coordinates: LatLng? = null,
val captions: Map<String, String> = emptyMap(),
val descriptions: Map<String, String> = emptyMap(),
val depictionIds: List<String> = emptyList()
) : Parcelable {
constructor(
captions: Map<String, String>,
categories: List<String>?,
filename: String?,
fallbackDescription: String?,
creator: String?
) : this(
filename = filename,
fallbackDescription = fallbackDescription,
dateUploaded = Date(),
creator = creator,
categories = categories,
captions = captions
)
/**
* Gets media display title
* @return Media title
*/
val displayTitle: String
get() =
if (filename != null)
pageTitle.displayTextWithoutNamespace.replaceFirst("[.][^.]+$".toRegex(), "")
else
""
/**
* Gets file page title
* @return New media page title
*/
val pageTitle: PageTitle get() = Utils.getPageTitle(filename!!)
/**
* Returns wikicode to use the media file on a MediaWiki site
* @return
*/
val wikiCode: String
get() = String.format("[[%s|thumb|%s]]", filename, mostRelevantCaption)
val mostRelevantCaption: String
get() = captions[Locale.getDefault().language]
?: captions.values.firstOrNull()
?: displayTitle
}
| apache-2.0 | e95c9d5f0dfed13218bddefb411afe2b | 25.854839 | 93 | 0.595495 | 4.518318 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/deeplearning/attention/han/HANEncodersPool.kt | 1 | 2129 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.deeplearning.attention.han
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import com.kotlinnlp.utils.ItemsPool
/**
* A pool of [HANEncoder]s which allows to allocate and release one when needed, without creating a new one.
* It is useful to optimize the creation of new structures every time a new encoder is created.
*
* @property model the HAN model of the [HANEncoder]s of the pool
* @param biRNNDropout the probability of dropout for the BiRNNs (default 0.0)
* @param attentionDropout the probability of attention dropout (default 0.0)
* @param outputDropout the probability of output dropout (default 0.0)
* @param propagateToInput whether to propagate the errors to the input during the backward
* @param mePropK the k factor of the 'meProp' algorithm to propagate from the k (in percentage) output nodes with
* the top errors of the transform layers (ignored if null, the default)
*/
class HANEncodersPool<InputNDArrayType : NDArray<InputNDArrayType>>(
val model: HAN,
private val biRNNDropout: Double = 0.0,
private val attentionDropout: Double = 0.0,
private val outputDropout: Double = 0.0,
private val propagateToInput: Boolean,
private val mePropK: Double? = null
) : ItemsPool<HANEncoder<InputNDArrayType>>() {
/**
* The factory of a new [HANEncoder].
*
* @param id the unique id of the item to create
*
* @return a new [HANEncoder] with the given [id]
*/
override fun itemFactory(id: Int) = HANEncoder<InputNDArrayType>(
model = this.model,
biRNNDropout = this.biRNNDropout,
attentionDropout = this.attentionDropout,
outputDropout = this.outputDropout,
propagateToInput = this.propagateToInput,
mePropK = this.mePropK,
id = id
)
}
| mpl-2.0 | fe70decd424e6976cc1bce82396df198 | 41.58 | 114 | 0.711602 | 3.964618 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/ui/fragments/other/ForumRulesFragment.kt | 1 | 7253 | package forpdateam.ru.forpda.ui.fragments.other
import android.app.SearchManager
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatImageButton
import androidx.appcompat.widget.SearchView
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.widget.ImageView
import android.widget.LinearLayout
import moxy.presenter.InjectPresenter
import moxy.presenter.ProvidePresenter
import java.util.ArrayList
import forpdateam.ru.forpda.App
import forpdateam.ru.forpda.R
import forpdateam.ru.forpda.common.Utils
import forpdateam.ru.forpda.common.webview.CustomWebChromeClient
import forpdateam.ru.forpda.common.webview.CustomWebViewClient
import forpdateam.ru.forpda.common.webview.DialogsHelper
import forpdateam.ru.forpda.entity.remote.forum.ForumRules
import forpdateam.ru.forpda.presentation.forumrules.ForumRulesPresenter
import forpdateam.ru.forpda.presentation.forumrules.ForumRulesView
import forpdateam.ru.forpda.ui.fragments.TabFragment
import forpdateam.ru.forpda.ui.fragments.TabTopScroller
import forpdateam.ru.forpda.ui.fragments.WebViewTopScroller
import forpdateam.ru.forpda.ui.views.ExtendedWebView
/**
* Created by radiationx on 16.10.17.
*/
class ForumRulesFragment : TabFragment(), ForumRulesView, TabTopScroller {
private var searchViewTag = 0
private lateinit var webView: ExtendedWebView
private lateinit var topScroller: WebViewTopScroller
@InjectPresenter
lateinit var presenter: ForumRulesPresenter
@ProvidePresenter
internal fun providePresenter(): ForumRulesPresenter = ForumRulesPresenter(
App.get().Di().forumRepository,
App.get().Di().mainPreferencesHolder,
App.get().Di().forumRulesTemplate,
App.get().Di().templateManager,
App.get().Di().errorHandler
)
init {
configuration.defaultTitle = "Правила форума"
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
webView = ExtendedWebView(context)
webView.setDialogsHelper(DialogsHelper(
webView.context,
App.get().Di().linkHandler,
App.get().Di().systemLinkHandler,
App.get().Di().router
))
attachWebView(webView)
fragmentContent.addView(webView)
return viewFragment
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
webView.addJavascriptInterface(this, JS_INTERFACE)
webView.webViewClient = CustomWebViewClient()
webView.webChromeClient = CustomWebChromeClient()
webView.setJsLifeCycleListener(object : ExtendedWebView.JsLifeCycleListener {
override fun onDomContentComplete(actions: ArrayList<String>) {
setRefreshing(false)
}
override fun onPageComplete(actions: ArrayList<String>) {
}
})
topScroller = WebViewTopScroller(webView, appBarLayout)
}
override fun toggleScrollTop() {
topScroller.toggleScrollTop()
}
override fun addBaseToolbarMenu(menu: Menu) {
super.addBaseToolbarMenu(menu)
addSearchOnPageItem(menu)
}
override fun showData(data: ForumRules) {
webView.loadDataWithBaseURL("https://4pda.to/forum/", data.html, "text/html", "utf-8", null)
}
override fun setStyleType(type: String) {
webView.evalJs("changeStyleType(\"$type\")")
}
override fun setFontSize(size: Int) {
webView.setRelativeFontSize(size)
}
@JavascriptInterface
fun copyRule(text: String) {
if (context == null)
return
runInUiThread(Runnable {
if (context == null)
return@Runnable
AlertDialog.Builder(context!!)
.setMessage("Скопировать правило в буфер обмена?")
.setPositiveButton(R.string.ok) { _, _ ->
Utils.copyToClipBoard(text)
}
.setNegativeButton(R.string.cancel, null)
.show()
})
}
private fun addSearchOnPageItem(menu: Menu) {
toolbar.inflateMenu(R.menu.theme_search_menu)
val searchOnPageMenuItem = menu.findItem(R.id.action_search)
searchOnPageMenuItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS)
val searchView = searchOnPageMenuItem.actionView as SearchView
searchView.tag = searchViewTag
searchView.setOnSearchClickListener { _ ->
if (searchView.tag == searchViewTag) {
val searchClose = searchView.findViewById<View>(androidx.appcompat.R.id.search_close_btn) as ImageView?
if (searchClose != null)
(searchClose.parent as ViewGroup).removeView(searchClose)
val navButtonsParams = ViewGroup.LayoutParams(App.px48, App.px48)
val outValue = TypedValue()
context?.theme?.resolveAttribute(android.R.attr.actionBarItemBackground, outValue, true)
val btnNext = AppCompatImageButton(searchView.context)
btnNext.setImageDrawable(App.getVecDrawable(context, R.drawable.ic_toolbar_search_next))
btnNext.setBackgroundResource(outValue.resourceId)
val btnPrev = AppCompatImageButton(searchView.context)
btnPrev.setImageDrawable(App.getVecDrawable(context, R.drawable.ic_toolbar_search_prev))
btnPrev.setBackgroundResource(outValue.resourceId)
(searchView.getChildAt(0) as LinearLayout).addView(btnPrev, navButtonsParams)
(searchView.getChildAt(0) as LinearLayout).addView(btnNext, navButtonsParams)
btnNext.setOnClickListener { findNext(true) }
btnPrev.setOnClickListener { findNext(false) }
searchViewTag++
}
}
val searchManager = activity?.getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchView.setSearchableInfo(searchManager.getSearchableInfo(activity?.componentName))
searchView.setIconifiedByDefault(true)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(newText: String): Boolean {
findText(newText)
return false
}
})
}
private fun findNext(next: Boolean) {
webView.findNext(next)
}
private fun findText(text: String) {
webView.findAllAsync(text)
}
override fun onDestroy() {
super.onDestroy()
webView.endWork()
}
companion object {
const val JS_INTERFACE = "IRules"
}
}
| gpl-3.0 | bce152d7d5db048c7ac2295527ed0cc8 | 35.231156 | 119 | 0.678225 | 4.851952 | false | false | false | false |
NCBSinfo/NCBSinfo | app/src/main/java/com/rohitsuratekar/NCBSinfo/fragments/HomeFragment.kt | 1 | 4913 | package com.rohitsuratekar.NCBSinfo.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.rohitsuratekar.NCBSinfo.R
import com.rohitsuratekar.NCBSinfo.common.Constants
import com.rohitsuratekar.NCBSinfo.common.hideMe
import com.rohitsuratekar.NCBSinfo.common.showMe
import com.rohitsuratekar.NCBSinfo.common.toast
import com.rohitsuratekar.NCBSinfo.database.RouteData
import com.rohitsuratekar.NCBSinfo.models.MyFragment
import com.rohitsuratekar.NCBSinfo.models.NextTrip
import com.rohitsuratekar.NCBSinfo.models.Route
import com.rohitsuratekar.NCBSinfo.viewmodels.HomeViewModel
import kotlinx.android.synthetic.main.fragment_home.*
import java.util.*
class HomeFragment : MyFragment() {
private lateinit var viewModel: HomeViewModel
private val routeList = mutableListOf<RouteData>()
private var currentRoute: Route? = null
private val currentCalendar = Calendar.getInstance()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
subscribe()
viewModel.getRouteList(repository)
viewModel.getFavorite(repository)
hm_fav.setOnClickListener {
currentRoute?.routeData?.let { r ->
callback?.showProgress()
context?.toast("Favorite Route Changed!")
if (currentRoute?.routeData?.favorite == "yes") {
viewModel.changeFavorite(r, false, repository)
} else {
viewModel.changeFavorite(r, true, repository)
}
}
}
hm_change_route.setOnClickListener {
currentRoute?.routeData?.routeID?.let { routeID ->
callback?.showRouteList(routeID)
}
}
hm_see_all.setOnClickListener {
callback?.navigate(Constants.NAVIGATE_TIMETABLE)
}
}
private fun subscribe() {
viewModel.routeList.observe(viewLifecycleOwner, Observer {
routeList.clear()
routeList.addAll(it)
})
viewModel.returnedRoute.observe(viewLifecycleOwner, Observer {
if (sharedModel.currentRoute.value == null) {
sharedModel.changeCurrentRoute(it)
} else {
currentRoute = it
updateUI()
}
})
sharedModel.currentRoute.observe(viewLifecycleOwner, Observer {
changeRoute(it.routeData)
})
}
private fun updateUI() {
callback?.hideProgress()
currentRoute?.let {
hm_origin.text = it.routeData.origin?.toUpperCase(Locale.getDefault())
hm_destination.text = it.routeData.destination?.toUpperCase(Locale.getDefault())
hm_type.text = getString(R.string.hm_next, it.routeData.type)
if (it.routeData.type == "other") {
hm_type.text = getString(R.string.hm_next, "transport")
}
hm_time.text = NextTrip(it.tripData).calculate(currentCalendar).displayTime()
if (it.routeData.favorite == "yes") {
hm_fav.setImageResource(R.drawable.icon_fav)
hm_fav.setColorFilter(ContextCompat.getColor(requireContext(), R.color.colorAccent))
} else {
hm_fav.setImageResource(R.drawable.icon_fav_empty)
hm_fav.setColorFilter(ContextCompat.getColor(requireContext(), R.color.colorPrimary))
}
val day = NextTrip(it.tripData).calculate(currentCalendar)
if (day.tripHighlightDay() == currentCalendar.get(Calendar.DAY_OF_WEEK)
) {
hm_next_day.hideMe()
} else {
hm_next_day.showMe()
hm_next_day.text = getString(
R.string.hm_next_day, day.tripCalender()
.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault())
)
}
}
}
private fun changeRoute(routeData: RouteData) {
callback?.showProgress()
viewModel.changeCurrentRoute(routeData, repository)
}
}
| mit | c609310c8b99f41c6bb169bb92b81bf0 | 34.125 | 101 | 0.62243 | 4.927783 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/project-wizard/maven/src/org/jetbrains/kotlin/tools/projectWizard/maven/MavenKotlinNewProjectWizard.kt | 2 | 3757 | // 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.maven
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logAddSampleCodeChanged
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logSdkFinished
import com.intellij.ide.projectWizard.NewProjectWizardConstants.BuildSystem.MAVEN
import com.intellij.ide.projectWizard.generators.AssetsNewProjectWizardStep
import com.intellij.ide.starters.local.StandardAssetsProvider
import com.intellij.ide.wizard.GitNewProjectWizardData.Companion.gitData
import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.name
import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.path
import com.intellij.ide.wizard.NewProjectWizardStep
import com.intellij.ide.wizard.chain
import com.intellij.openapi.observable.util.bindBooleanStorage
import com.intellij.openapi.project.Project
import com.intellij.ui.UIBundle
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.builder.TopGap
import com.intellij.ui.dsl.builder.bindSelected
import com.intellij.ui.dsl.builder.whenStateChangedFromUi
import org.jetbrains.idea.maven.wizards.MavenNewProjectWizardStep
import org.jetbrains.kotlin.tools.projectWizard.BuildSystemKotlinNewProjectWizard
import org.jetbrains.kotlin.tools.projectWizard.BuildSystemKotlinNewProjectWizardData
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizard
import org.jetbrains.kotlin.tools.projectWizard.kmpWizardLink
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType
internal class MavenKotlinNewProjectWizard : BuildSystemKotlinNewProjectWizard {
override val name = MAVEN
override val ordinal = 100
override fun createStep(parent: KotlinNewProjectWizard.Step): NewProjectWizardStep {
return Step(parent).chain(::AssetsStep)
}
class Step(parent: KotlinNewProjectWizard.Step) :
MavenNewProjectWizardStep<KotlinNewProjectWizard.Step>(parent),
BuildSystemKotlinNewProjectWizardData by parent {
private val addSampleCodeProperty = propertyGraph.property(true)
.bindBooleanStorage("NewProjectWizard.addSampleCodeState")
private val addSampleCode by addSampleCodeProperty
override fun setupSettingsUI(builder: Panel) {
super.setupSettingsUI(builder)
with(builder) {
row {
checkBox(UIBundle.message("label.project.wizard.new.project.add.sample.code"))
.bindSelected(addSampleCodeProperty)
.whenStateChangedFromUi { logAddSampleCodeChanged(it) }
}.topGap(TopGap.SMALL)
kmpWizardLink(context)
}
}
override fun setupProject(project: Project) {
logSdkFinished(sdk)
KotlinNewProjectWizard.generateProject(
project = project,
projectPath = "$path/$name",
projectName = name,
sdk = sdk,
buildSystemType = BuildSystemType.Maven,
projectGroupId = groupId,
artifactId = artifactId,
version = version,
addSampleCode = addSampleCode
)
}
}
private class AssetsStep(parent: NewProjectWizardStep) : AssetsNewProjectWizardStep(parent) {
override fun setupAssets(project: Project) {
outputDirectory = "$path/$name"
if (gitData?.git == true) {
addAssets(StandardAssetsProvider().getMavenIgnoreAssets())
}
}
}
}
| apache-2.0 | 25182c740d04d9203e6371d176ad4fd9 | 43.2 | 158 | 0.730104 | 5.203601 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/TreeEntityImpl.kt | 1 | 11670 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class TreeEntityImpl: TreeEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeEntity::class.java, TreeEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeEntity::class.java, TreeEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
PARENTENTITY_CONNECTION_ID,
)
}
@JvmField var _data: String? = null
override val data: String
get() = _data!!
override val children: List<TreeEntity>
get() = snapshot.extractOneToManyChildren<TreeEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override val parentEntity: TreeEntity
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: TreeEntityData?): ModifiableWorkspaceEntityBase<TreeEntity>(), TreeEntity.Builder {
constructor(): this(TreeEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity TreeEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isDataInitialized()) {
error("Field TreeEntity#data should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field TreeEntity#entitySource should be initialized")
}
// Check initialization for collection with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field TreeEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field TreeEntity#children should be initialized")
}
}
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field TreeEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field TreeEntity#parentEntity should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
// List of non-abstract referenced types
var _children: List<TreeEntity>? = emptyList()
override var children: List<TreeEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<TreeEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<TreeEntity> ?: emptyList())
} else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<TreeEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override var parentEntity: TreeEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as TreeEntity
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as TreeEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): TreeEntityData = result ?: super.getEntityData() as TreeEntityData
override fun getEntityClass(): Class<TreeEntity> = TreeEntity::class.java
}
}
class TreeEntityData : WorkspaceEntityData<TreeEntity>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<TreeEntity> {
val modifiable = TreeEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): TreeEntity {
val entity = TreeEntityImpl()
entity._data = data
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return TreeEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as TreeEntityData
if (this.data != other.data) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as TreeEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
} | apache-2.0 | 1db9dc0063725f3c463f8357dc3baecd | 42.066421 | 202 | 0.597087 | 5.86727 | false | false | false | false |
elpassion/cloud-timer-android | app/src/main/java/pl/elpassion/cloudtimer/login/authtoken/AuthTokenSharedPreferences.kt | 1 | 1043 | package pl.elpassion.cloudtimer.login.authtoken
import android.content.Context.MODE_PRIVATE
import pl.elpassion.cloudtimer.base.CloudTimerApp.Companion.applicationContext
object AuthTokenSharedPreferences {
private val sharedPreferencesKey = "pl.elpassion.cloud-timer"
private val authTokenKey = "authToken"
private val emailKey = "emailKey"
val sharedPreferences = applicationContext.getSharedPreferences(sharedPreferencesKey, MODE_PRIVATE)
fun isLoggedIn(): Boolean = sharedPreferences.contains(authTokenKey)
fun saveAuthToken(authToken: String) = sharedPreferences.edit().putString(authTokenKey, authToken).commit()
fun readAuthToken(): String? {
if (isLoggedIn())
return sharedPreferences.getString(authTokenKey, "")
return null
}
fun readEmail(): String? {
if (isLoggedIn())
return sharedPreferences.getString(emailKey, "")
return null
}
fun saveEmail(email: String) = sharedPreferences.edit().putString(emailKey, email).commit()
} | apache-2.0 | a41d02a7e115ed1aa296aa9c7e640036 | 35 | 111 | 0.733461 | 4.943128 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/clipper/ClipperTransitData.kt | 1 | 7134 | /*
* ClipperTransitData.kt
*
* Copyright 2011 "an anonymous contributor"
* Copyright 2011-2014 Eric Butler <[email protected]>
* Copyright 2018 Michael Farrell <[email protected]>
* Copyright 2018 Google
*
* Thanks to:
* An anonymous contributor for reverse engineering Clipper data and providing
* most of the code here.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.clipper
import au.id.micolous.metrodroid.time.Epoch
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.transit.*
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.desfire.DesfireCard
import au.id.micolous.metrodroid.card.desfire.DesfireCardTransitFactory
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.util.StationTableReader
import au.id.micolous.metrodroid.util.ImmutableByteArray
@Parcelize
class ClipperTransitData (private val mSerialNumber: Long?,
private val mBalance: Int?,
private val mExpiry: Int,
private val mTrips: List<ClipperTrip>,
private val mRefills: List<ClipperRefill>): TransitData() {
override val cardName: String
get() = "Clipper"
public override val balance: TransitBalance?
get() = if (mBalance != null)
TransitBalanceStored(TransitCurrency.USD(mBalance), null, clipperTimestampToCalendar(mExpiry * 86400L))
else
null
override val serialNumber: String?
get() = mSerialNumber?.toString()
// This is done in a roundabout way, as the base type used is the first parameter. Adding it
// to an empty Trip[] first, coerces types correctly from the start.
override val trips get(): List<Trip> = mTrips + mRefills
companion object {
private fun parseTrips(card: DesfireCard): List<ClipperTrip> {
val file = card.getApplication(APP_ID)?.getFile(0x0e)
/*
* This file reads very much like a record file but it professes to
* be only a regular file. As such, we'll need to extract the records
* manually.
*/
val data = file?.data ?: return emptyList()
val result = mutableListOf<ClipperTrip>()
var pos = data.size - RECORD_LENGTH
while (pos >= 0) {
if (data.byteArrayToInt(pos + 0x2, 2) == 0) {
pos -= RECORD_LENGTH
continue
}
val trip = ClipperTrip(data.sliceOffLen(pos, RECORD_LENGTH))
// Some transaction types are temporary -- remove previous trip with the same timestamp.
val existingTrip = result.find { otherTrip -> trip.startTimestamp == otherTrip.startTimestamp }
if (existingTrip != null) {
if (existingTrip.endTimestamp != null) {
// Old trip has exit timestamp, and is therefore better.
pos -= RECORD_LENGTH
continue
} else {
result.remove(existingTrip)
}
}
result.add(trip)
pos -= RECORD_LENGTH
}
return result
}
private fun parseRefills(card: DesfireCard): List<ClipperRefill> {
/*
* This file reads very much like a record file but it professes to
* be only a regular file. As such, we'll need to extract the records
* manually.
*/
val data = card.getApplication(APP_ID)?.getFile(0x04)?.data ?: return emptyList()
return (0 until data.size step RECORD_LENGTH).reversed().
map { pos -> data.sliceOffLen(pos, RECORD_LENGTH) }.
mapNotNull { slice -> createRefill(slice) }
}
private fun createRefill(useData: ImmutableByteArray): ClipperRefill? {
val agency: Int = useData.byteArrayToInt(0x2, 2)
val timestamp: Long = useData.byteArrayToLong(0x4, 4)
val machineid: String = useData.getHexString(0x8, 4)
val amount: Int = useData.byteArrayToInt(0xe, 2)
if (timestamp == 0L) return null
return ClipperRefill(clipperTimestampToCalendar(timestamp), amount, agency, machineid)
}
private fun parse(desfireCard: DesfireCard) =
ClipperTransitData(
mExpiry = desfireCard.getApplication(APP_ID)?.getFile(0x01)?.data?.byteArrayToInt(8, 2) ?: 0,
mSerialNumber = desfireCard.getApplication(APP_ID)?.getFile(0x08)?.data?.byteArrayToLong(1, 4),
mRefills = parseRefills(desfireCard),
mBalance = desfireCard.getApplication(APP_ID)?.getFile(0x02)?.data?.byteArrayToInt(18, 2)?.toShort()?.toInt(),
mTrips = parseTrips(desfireCard))
private const val RECORD_LENGTH = 32
private val CLIPPER_EPOCH = Epoch.utc(1900, MetroTimeZone.LOS_ANGELES)
private val CARD_INFO = CardInfo(
imageId = R.drawable.clipper_card,
name = "Clipper",
locationId = R.string.location_san_francisco,
cardType = CardType.MifareDesfire,
region = TransitRegion.USA,
resourceExtraNote = R.string.card_note_clipper)
const val APP_ID = 0x9011f2
val FACTORY: DesfireCardTransitFactory = object : DesfireCardTransitFactory {
override val allCards: List<CardInfo>
get() = listOf(CARD_INFO)
override fun earlyCheck(appIds: IntArray) = APP_ID in appIds
override fun parseTransitData(card: DesfireCard) = parse(card)
override fun parseTransitIdentity(card: DesfireCard) =
TransitIdentity("Clipper",
card.getApplication(APP_ID)?.getFile(0x08)?.data?.byteArrayToLong(1, 4)?.toString())
override val notice: String?
get() = StationTableReader.getNotice(ClipperData.CLIPPER_STR)
}
internal fun clipperTimestampToCalendar(timestamp: Long): TimestampFull? {
return if (timestamp == 0L) null else CLIPPER_EPOCH.seconds(timestamp)
}
}
}
| gpl-3.0 | d49c4fa72b6eecd09eeb2cc2d2d1cd66 | 41.718563 | 134 | 0.619708 | 4.546845 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/warsaw/WarsawTransitData.kt | 1 | 7637 | /*
* WarsawTransitData.java
*
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.warsaw
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.classic.ClassicCard
import au.id.micolous.metrodroid.card.classic.ClassicCardTransitFactory
import au.id.micolous.metrodroid.card.classic.ClassicSector
import au.id.micolous.metrodroid.multi.*
import au.id.micolous.metrodroid.time.Daystamp
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.transit.*
import au.id.micolous.metrodroid.ui.HeaderListItem
import au.id.micolous.metrodroid.ui.ListItem
import au.id.micolous.metrodroid.util.ImmutableByteArray
import au.id.micolous.metrodroid.util.NumberUtils
import au.id.micolous.metrodroid.util.hexString
/**
* Warsaw cards.
*/
private fun parseDateTime(raw: ImmutableByteArray, off: Int) = if (raw.getBitsFromBuffer(off, 26) == 0) null else TimestampFull(
MetroTimeZone.WARSAW,
raw.getBitsFromBuffer(off, 6) + 2000,
raw.getBitsFromBuffer(off+6, 4) - 1,
raw.getBitsFromBuffer(off+10, 5),
raw.getBitsFromBuffer(off+15, 5),
raw.getBitsFromBuffer(off+20, 6)
)
private fun parseDate(raw: ImmutableByteArray, off: Int) = if (raw.getBitsFromBuffer(off, 16) == 0) null else Daystamp(
raw.getBitsFromBuffer(off, 7) + 2000,
raw.getBitsFromBuffer(off+7, 4) - 1,
raw.getBitsFromBuffer(off+11, 5)
)
@Parcelize
data class WarsawTrip(
override val startTimestamp: TimestampFull,
private val mTripType: Int //educated guess
): Trip() {
override val fare: TransitCurrency?
get() = null
override val mode: Mode
get() = Mode.OTHER
}
@Parcelize
data class WarsawSubscription(
override val validTo: Daystamp,
private val mTicketType: Int // educated guess
): Subscription() {
override val subscriptionName: String?
get() = when (mTicketType) {
0xbf6 -> Localizer.localizeString(R.string.warsaw_90_days)
else -> Localizer.localizeString(R.string.unknown_format, mTicketType.hexString)
}
}
@Parcelize
data class WarsawSector(
private val mTripTimestamp: TimestampFull?,
private val mExpiryTimestamp: Daystamp?,
private val mTicketType: Int, // educated guess
private val mTripType: Int, //educated guess
private val mCounter: Int
): Parcelable, Comparable<WarsawSector> {
fun getRawFields(level: TransitData.RawLevel): List<ListItem>? =
if (level == TransitData.RawLevel.ALL)
listOf(
ListItem(FormattedString("Trip timestamp"), mTripTimestamp?.format()),
ListItem(FormattedString("Expiry timestamp"), mExpiryTimestamp?.format()),
ListItem("Trip type", mTripType.hexString),
ListItem("Ticket type", mTicketType.hexString),
ListItem("Counter", mCounter.hexString)
)
else
null
override operator fun compareTo(other: WarsawSector): Int = when {
mTripTimestamp == null && other.mTripTimestamp == null -> 0
mTripTimestamp == null -> -1
other.mTripTimestamp == null -> + 1
mTripTimestamp.timeInMillis.compareTo(other = other.mTripTimestamp.timeInMillis) != 0 ->
mTripTimestamp.timeInMillis.compareTo(other = other.mTripTimestamp.timeInMillis)
else -> -((mCounter - other.mCounter) and 0xff).compareTo(0x80)
}
val trip get() = if (mTripTimestamp == null) null else WarsawTrip(mTripTimestamp, mTripType)
val subscription get() = if (mExpiryTimestamp == null) null else WarsawSubscription(mExpiryTimestamp, mTicketType)
companion object {
fun parse(sec: ClassicSector) = WarsawSector(
mCounter = sec[0].data.byteArrayToInt(1, 1),
mExpiryTimestamp = parseDate(sec[0].data, 16),
mTicketType = sec[0].data.getBitsFromBuffer(32, 12),
mTripType = sec[0].data.byteArrayToInt(9, 3),
mTripTimestamp = parseDateTime(sec[0].data, 44)
)
}
}
@Parcelize
data class WarsawTransitData (private val mSerial: Pair<Int, Int>,
private val sectorA: WarsawSector,
private val sectorB: WarsawSector): TransitData() {
override val serialNumber get() = formatSerial(mSerial)
override val cardName get() = NAME
override val trips: List<Trip>?
get() = listOfNotNull(sectorA.trip, sectorB.trip)
override val subscriptions: List<Subscription>?
get() = listOfNotNull(maxOf(sectorA, sectorB).subscription)
override fun getRawFields(level: RawLevel): List<ListItem>? = listOf(
HeaderListItem("Sector 2")) + sectorA.getRawFields(level).orEmpty() +
listOf(HeaderListItem("Sector 3")) + sectorB.getRawFields(level).orEmpty()
companion object {
private const val NAME = "Warszawska Karta Miejska"
private val CARD_INFO = CardInfo(
name = NAME,
locationId = R.string.location_warsaw,
cardType = CardType.MifareClassic,
resourceExtraNote = R.string.card_note_card_number_only,
keysRequired = true, keyBundle = "warsaw",
imageId = R.drawable.warsaw_card,
imageAlphaId = R.drawable.iso7810_id1_alpha,
region = TransitRegion.POLAND,
preview = true)
private fun formatSerial(serial: Pair<Int, Int>) =
NumberUtils.zeroPad(serial.first, 3) + " " +
NumberUtils.zeroPad(serial.second, 8)
private fun getSerial(card: ClassicCard) = Pair(
card[0, 0].data[3].toInt() and 0xff,
card[0, 0].data.byteArrayToIntReversed(0, 3))
fun parse(card: ClassicCard): WarsawTransitData {
return WarsawTransitData(mSerial = getSerial(card),
sectorA = WarsawSector.parse(card[2]),
sectorB = WarsawSector.parse(card[3]))
}
val FACTORY: ClassicCardTransitFactory = object : ClassicCardTransitFactory {
override fun parseTransitIdentity(card: ClassicCard) =
TransitIdentity(NAME,
formatSerial(getSerial(card)))
override fun parseTransitData(card: ClassicCard) =
parse(card)
override fun earlyCheck(sectors: List<ClassicSector>): Boolean {
val toc = sectors[0][1].data
// Check toc entries for sectors 1, 2 and 3
return (toc.byteArrayToInt(2, 2) == 0x1320
&& toc.byteArrayToInt(4, 2) == 0x1320
&& toc.byteArrayToInt(6, 2) == 0x1320)
}
override val earlySectors get() = 1
override val allCards get() = listOf(CARD_INFO)
}
}
}
| gpl-3.0 | 83e4509ebea13adfdf1300c5cba82cac | 40.281081 | 128 | 0.648553 | 4.245136 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/avatar/Avatars.kt | 1 | 5802 | package org.thoughtcrime.securesms.avatar
import android.content.Context
import android.graphics.Paint
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.annotation.Px
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.conversation.colors.AvatarColor
import kotlin.math.abs
import kotlin.math.min
object Avatars {
/**
* Enum class mirroring AvatarColors codes but utilizing foreground colors for text or icon tinting.
*/
enum class ForegroundColor(private val code: String, @ColorInt val colorInt: Int) {
A100("A100", 0xFF3838F5.toInt()),
A110("A110", 0xFF1251D3.toInt()),
A120("A120", 0xFF086DA0.toInt()),
A130("A130", 0xFF067906.toInt()),
A140("A140", 0xFF661AFF.toInt()),
A150("A150", 0xFF9F00F0.toInt()),
A160("A160", 0xFFB8057C.toInt()),
A170("A170", 0xFFBE0404.toInt()),
A180("A180", 0xFF836B01.toInt()),
A190("A190", 0xFF7D6F40.toInt()),
A200("A200", 0xFF4F4F6D.toInt()),
A210("A210", 0xFF5C5C5C.toInt());
fun deserialize(code: String): ForegroundColor {
return values().find { it.code == code } ?: throw IllegalArgumentException()
}
fun serialize(): String = code
}
/**
* Mapping which associates color codes to ColorPair objects containing background and foreground colors.
*/
val colorMap: Map<String, ColorPair> = ForegroundColor.values().map {
ColorPair(AvatarColor.deserialize(it.serialize()), it)
}.associateBy {
it.code
}
val colors: List<ColorPair> = colorMap.values.toList()
val defaultAvatarsForSelf = linkedMapOf(
"avatar_abstract_01" to DefaultAvatar(R.drawable.ic_avatar_abstract_01, "A130"),
"avatar_abstract_02" to DefaultAvatar(R.drawable.ic_avatar_abstract_02, "A120"),
"avatar_abstract_03" to DefaultAvatar(R.drawable.ic_avatar_abstract_03, "A170"),
"avatar_cat" to DefaultAvatar(R.drawable.ic_avatar_cat, "A190"),
"avatar_dog" to DefaultAvatar(R.drawable.ic_avatar_dog, "A140"),
"avatar_fox" to DefaultAvatar(R.drawable.ic_avatar_fox, "A190"),
"avatar_tucan" to DefaultAvatar(R.drawable.ic_avatar_tucan, "A120"),
"avatar_sloth" to DefaultAvatar(R.drawable.ic_avatar_sloth, "A160"),
"avatar_dinosaur" to DefaultAvatar(R.drawable.ic_avatar_dinosour, "A130"),
"avatar_pig" to DefaultAvatar(R.drawable.ic_avatar_pig, "A180"),
"avatar_incognito" to DefaultAvatar(R.drawable.ic_avatar_incognito, "A220"),
"avatar_ghost" to DefaultAvatar(R.drawable.ic_avatar_ghost, "A100")
)
val defaultAvatarsForGroup = linkedMapOf(
"avatar_heart" to DefaultAvatar(R.drawable.ic_avatar_heart, "A180"),
"avatar_house" to DefaultAvatar(R.drawable.ic_avatar_house, "A120"),
"avatar_melon" to DefaultAvatar(R.drawable.ic_avatar_melon, "A110"),
"avatar_drink" to DefaultAvatar(R.drawable.ic_avatar_drink, "A170"),
"avatar_celebration" to DefaultAvatar(R.drawable.ic_avatar_celebration, "A100"),
"avatar_balloon" to DefaultAvatar(R.drawable.ic_avatar_balloon, "A220"),
"avatar_book" to DefaultAvatar(R.drawable.ic_avatar_book, "A100"),
"avatar_briefcase" to DefaultAvatar(R.drawable.ic_avatar_briefcase, "A180"),
"avatar_sunset" to DefaultAvatar(R.drawable.ic_avatar_sunset, "A120"),
"avatar_surfboard" to DefaultAvatar(R.drawable.ic_avatar_surfboard, "A110"),
"avatar_soccerball" to DefaultAvatar(R.drawable.ic_avatar_soccerball, "A130"),
"avatar_football" to DefaultAvatar(R.drawable.ic_avatar_football, "A220"),
)
@DrawableRes
fun getDrawableResource(key: String): Int? {
val defaultAvatar = defaultAvatarsForSelf.getOrDefault(key, defaultAvatarsForGroup[key])
return defaultAvatar?.vectorDrawableId
}
private fun textPaint(context: Context) = Paint().apply {
isAntiAlias = true
typeface = AvatarRenderer.getTypeface(context)
textSize = 1f
}
/**
* Calculate the text size for a give string using a maximum desired width and a maximum desired font size.
*/
@JvmStatic
fun getTextSizeForLength(context: Context, text: String, @Px maxWidth: Float, @Px maxSize: Float): Float {
val paint = textPaint(context)
return branchSizes(0f, maxWidth / 2, maxWidth, maxSize, paint, text)
}
/**
* Uses binary search to determine optimal font size to within 1% given the input parameters.
*/
private fun branchSizes(@Px lastFontSize: Float, @Px fontSize: Float, @Px target: Float, @Px maxFontSize: Float, paint: Paint, text: String): Float {
paint.textSize = fontSize
val textWidth = paint.measureText(text)
val delta = abs(lastFontSize - fontSize) / 2f
val isWithinThreshold = abs(1f - (textWidth / target)) <= 0.01f
if (textWidth == 0f) {
return maxFontSize
}
if (delta == 0f) {
return min(maxFontSize, fontSize)
}
return when {
fontSize >= maxFontSize -> {
maxFontSize
}
isWithinThreshold -> {
fontSize
}
textWidth > target -> {
branchSizes(fontSize, fontSize - delta, target, maxFontSize, paint, text)
}
else -> {
branchSizes(fontSize, fontSize + delta, target, maxFontSize, paint, text)
}
}
}
@JvmStatic
fun getForegroundColor(avatarColor: AvatarColor): ForegroundColor {
return ForegroundColor.values().firstOrNull { it.serialize() == avatarColor.serialize() } ?: ForegroundColor.A210
}
data class DefaultAvatar(
@DrawableRes val vectorDrawableId: Int,
val colorCode: String
)
data class ColorPair(
val backgroundAvatarColor: AvatarColor,
val foregroundAvatarColor: ForegroundColor
) {
@ColorInt val backgroundColor: Int = backgroundAvatarColor.colorInt()
@ColorInt val foregroundColor: Int = foregroundAvatarColor.colorInt
val code: String = backgroundAvatarColor.serialize()
}
}
| gpl-3.0 | e1c76da5b2584c54c6b57aa2ba4f163f | 36.921569 | 151 | 0.70355 | 3.603727 | false | false | false | false |
hzsweers/CatchUp | app/src/main/kotlin/io/sweers/catchup/ui/activity/OrderServicesActivity2.kt | 1 | 12711 | /*
* Copyright (C) 2020. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sweers.catchup.ui.activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.expandIn
import androidx.compose.animation.shrinkOut
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstrainedLayoutReference
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.chibatching.kotpref.bulk
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.components.FragmentComponent
import dagger.multibindings.Multibinds
import dev.zacsweers.catchup.appconfig.AppConfig
import dev.zacsweers.catchup.compose.CatchUpTheme
import io.sweers.catchup.CatchUpPreferences
import io.sweers.catchup.R
import io.sweers.catchup.base.ui.InjectableBaseFragment
import io.sweers.catchup.databinding.FragmentOrderServicesBinding
import io.sweers.catchup.edu.Syllabus
import io.sweers.catchup.flowFor
import io.sweers.catchup.injection.DaggerMap
import io.sweers.catchup.service.api.ServiceMeta
import io.sweers.catchup.ui.FontHelper
import io.sweers.catchup.util.setLightStatusBar
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
/*
* This is a WIP implementation of OrderServices view with Compose.
*
* TODO:
* * Syllabus handling - requires integrating tap target on the location
* * Drag-and-drop - compose doesn't support this out of the box.
* * An intermediate solution might be to add up/down arrows
*/
private class OrderServicesViewModel(
serviceMetasMap: DaggerMap<String, ServiceMeta>,
private val catchUpPreferences: CatchUpPreferences
) : ViewModel() {
private val storedOrder: StateFlow<List<String>>
private val _serviceMetas: MutableStateFlow<List<ServiceMeta>>
val serviceMetas: StateFlow<List<ServiceMeta>> get() = _serviceMetas
val canSave: StateFlow<Boolean>
init {
val initialOrder = catchUpPreferences.servicesOrder?.split(",") ?: emptyList()
val initialOrderedServices = serviceMetasMap.values.sortedBy { initialOrder.indexOf(it.id) }
storedOrder = catchUpPreferences.flowFor { ::servicesOrder }
.drop(1) // Ignore the initial value we read synchronously
.map { it?.split(",") ?: emptyList() }
.stateIn(viewModelScope, SharingStarted.Lazily, initialOrder)
_serviceMetas = MutableStateFlow(initialOrderedServices)
viewModelScope.launch {
storedOrder
.map { newOrder ->
serviceMetasMap.values.sortedBy { newOrder.indexOf(it.id) }
}
.collect {
_serviceMetas.value = it
}
}
canSave = serviceMetas
.map { it != initialOrderedServices }
.stateIn(viewModelScope, SharingStarted.Lazily, false)
}
fun shuffle() {
val items = serviceMetas.value.toMutableList()
items.shuffle()
_serviceMetas.value = items
}
fun save() {
catchUpPreferences.bulk {
servicesOrder = serviceMetas.value.joinToString(",", transform = ServiceMeta::id)
}
}
fun shouldShowSyllabus(): Boolean {
// TODO implement this
return false
}
}
@AndroidEntryPoint
class OrderServicesFragment2 : InjectableBaseFragment<FragmentOrderServicesBinding>() {
@Inject
lateinit var serviceMetas: DaggerMap<String, ServiceMeta>
@Inject
lateinit var catchUpPreferences: CatchUpPreferences
@Inject
internal lateinit var syllabus: Syllabus
@Inject
internal lateinit var fontHelper: FontHelper
@Inject
internal lateinit var appConfig: AppConfig
// Have to do this here because we can't set a factory separately
@Suppress("UNCHECKED_CAST")
private val viewModel by viewModels<OrderServicesViewModel> {
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return OrderServicesViewModel(serviceMetas, catchUpPreferences) as T
}
}
}
// TODO remove with viewbinding API change
override val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> FragmentOrderServicesBinding =
FragmentOrderServicesBinding::inflate
override fun initView(inflater: LayoutInflater, container: ViewGroup?): View {
return ComposeView(inflater.context).apply {
setLightStatusBar(appConfig)
setContent {
CatchUpTheme {
// Have to pass the viewmodel here rather than use compose' viewModel() because otherwise it
// will try the reflective instantiation since the factory isn't initialized because lol
ScaffoldContent(viewModel)
}
}
}
}
@OptIn(ExperimentalAnimationApi::class)
@Composable
private fun ScaffoldContent(viewModel: OrderServicesViewModel) {
val canSave: Boolean by viewModel.canSave.collectAsState()
Scaffold(
topBar = {
TopAppBar(
title = {
Text(stringResource(id = R.string.pref_reorder_services))
},
navigationIcon = {
IconButton(
onClick = ::onBackPressed,
content = {
Image(
painterResource(id = R.drawable.ic_arrow_back_black_24dp),
stringResource(id = R.string.back)
)
}
)
},
actions = {
IconButton(
onClick = viewModel::shuffle,
content = {
Image(
painterResource(R.drawable.ic_shuffle_black_24dp),
stringResource(R.string.shuffle)
)
}
)
}
)
},
content = { ListContent(viewModel) },
floatingActionButton = {
AnimatedVisibility(
visible = canSave,
enter = expandIn(expandFrom = Alignment.Center),
exit = shrinkOut(shrinkTowards = Alignment.Center)
) {
// TODO ripple color?
FloatingActionButton(
modifier = Modifier
.indication(
MutableInteractionSource(),
indication = rememberRipple(
color = Color.White
)
)
.onGloballyPositioned { coordinates ->
val (x, y) = coordinates.positionInRoot()
// TODO show syllabus on fab
},
backgroundColor = colorResource(R.color.colorAccent),
onClick = {
viewModel.save()
activity?.finish()
},
content = {
Image(
painterResource(R.drawable.ic_save_black_24dp),
stringResource(R.string.save),
colorFilter = ColorFilter.tint(Color.White)
)
}
)
}
}
)
}
@Composable
private fun ListContent(viewModel: OrderServicesViewModel) {
val currentItemsSorted by viewModel.serviceMetas.collectAsState()
Surface(Modifier.fillMaxSize()) {
LazyColumn {
items(currentItemsSorted.size) { index ->
val item = currentItemsSorted[index]
Box(
Modifier
.background(colorResource(id = item.themeColor))
.padding(16.dp)
) {
ConstraintLayout(
modifier = Modifier
.fillMaxWidth() // TODO remove this...?
.wrapContentHeight()
.wrapContentWidth(Alignment.Start)
) {
val (icon, spacer, text) = createRefs()
Image(
painterResource(id = item.icon),
stringResource(R.string.service_icon),
modifier = Modifier
.width(40.dp)
.height(40.dp)
.constrainAs(icon) {
bottom.linkTo(parent.bottom)
end.linkTo(spacer.start)
start.linkTo(parent.start)
top.linkTo(parent.top)
}
)
Spacer(
modifier = Modifier
.width(8.dp)
.height(40.dp)
.constrainAs(spacer) {
bottom.linkTo(parent.bottom)
end.linkTo(text.start)
start.linkTo(icon.end)
top.linkTo(parent.top)
}
)
val startRef: ConstrainedLayoutReference = spacer
Text(
text = stringResource(id = item.name),
modifier = Modifier.constrainAs(text) {
bottom.linkTo(parent.bottom)
end.linkTo(parent.end)
start.linkTo(startRef.end)
top.linkTo(parent.top)
},
fontStyle = FontStyle.Normal,
// TODO what about Subhead?
style = MaterialTheme.typography.subtitle1,
color = Color.White
)
}
}
}
}
}
}
override fun onBackPressed(): Boolean {
if (viewModel.canSave.value) {
AlertDialog.Builder(requireContext())
.setTitle(R.string.pending_changes_title)
.setMessage(R.string.pending_changes_message)
.setNeutralButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() }
.setPositiveButton(R.string.dontsave) { dialog, _ ->
dialog.dismiss()
activity?.finish()
}
.setNegativeButton(R.string.save) { dialog, _ ->
dialog.dismiss()
viewModel.save()
activity?.finish()
}
.show()
return true
}
activity?.finish()
return false
}
}
@InstallIn(FragmentComponent::class)
@Module
abstract class OrderServicesModule2 {
@Multibinds
abstract fun serviceMetas(): Map<String, ServiceMeta>
}
| apache-2.0 | 0fe9cadba477947b5e9977d2926e7775 | 33.540761 | 103 | 0.667296 | 4.831243 | false | false | false | false |
square/picasso | picasso/src/main/java/com/squareup/picasso3/ResourceDrawableRequestHandler.kt | 1 | 1769 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso3
import android.content.Context
import androidx.core.content.ContextCompat
import com.squareup.picasso3.BitmapUtils.isXmlResource
import com.squareup.picasso3.Picasso.LoadedFrom.DISK
internal class ResourceDrawableRequestHandler private constructor(
private val context: Context,
private val loader: DrawableLoader
) : RequestHandler() {
override fun canHandleRequest(data: Request): Boolean {
return data.resourceId != 0 && isXmlResource(context.resources, data.resourceId)
}
override fun load(
picasso: Picasso,
request: Request,
callback: Callback
) {
val drawable = loader.load(request.resourceId)
if (drawable == null) {
callback.onError(
IllegalArgumentException("invalid resId: ${Integer.toHexString(request.resourceId)}")
)
} else {
callback.onSuccess(Result.Drawable(drawable, DISK))
}
}
internal companion object {
@JvmName("-create")
internal fun create(
context: Context,
loader: DrawableLoader = DrawableLoader { resId -> ContextCompat.getDrawable(context, resId) }
) = ResourceDrawableRequestHandler(context, loader)
}
}
| apache-2.0 | 9b09fd6cdab3891c2e5b29adb7f49312 | 32.377358 | 100 | 0.730356 | 4.378713 | false | false | false | false |
thaapasa/jalkametri-android | app/src/test/java/fi/tuska/jalkametri/util/TimeUtilTest.kt | 1 | 4102 | package fi.tuska.jalkametri.util
import junit.framework.Assert.assertEquals
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertTrue
import org.joda.time.DateTime
import org.joda.time.DateTimeConstants
import org.joda.time.LocalDateTime
import org.junit.Before
import org.junit.Test
import java.util.Locale
class TimeUtilTest {
private val FI = Locale("fi", "FI")
private val EN = Locale.ENGLISH
private val timeUtilEN = TimeUtil(MockResources.en(), EN)
private val timeUtilFI = TimeUtil(MockResources.fi(), FI)
private val timeUtil = timeUtilEN
fun getTime(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): DateTime
= LocalDateTime(year, month, day, hour, minute, second).toDateTime(timeUtil.timeZone)
@Before
fun before() {
LogUtil.logger = NoopLogger
}
@Test
fun testGetTime() {
val time = getTime(2011, 5, 16, 10, 35, 47).toDateTime()
assertEquals(2011, time.year)
assertEquals(DateTimeConstants.MAY, time.monthOfYear)
assertEquals(5, time.monthOfYear)
assertEquals(16, time.dayOfMonth)
assertEquals(10, time.hourOfDay)
assertEquals(35, time.minuteOfHour)
assertEquals(47, time.secondOfMinute)
}
@Test
fun testDateFormatFull() {
val date = getTime(2011, 5, 16, 10, 0, 0)
timeUtil.dateFormatFull.let { formatter ->
assertEquals("Mon 5/16/2011 10:00", formatter.print(date))
}
timeUtilFI.dateFormatFull.let { formatter ->
assertEquals("ma 16.5.2011 10:00", formatter.print(date))
}
}
@Test
fun testTimeFormat() {
val date = getTime(2011, 5, 16, 10, 0, 0)
timeUtil.timeFormat.let { formatter ->
assertEquals("10:00", formatter.print(date))
}
timeUtilFI.timeFormat.let { formatter ->
assertEquals("10:00", formatter.print(date))
}
}
@Test
fun testDateFormatWDay() {
val date = getTime(2011, 5, 16, 10, 0, 0)
assertEquals("Mon 5/16", timeUtilEN.dateFormatWDay.print(date))
assertEquals("ma 16.5.", timeUtilFI.dateFormatWDay.print(date))
}
@Test
fun testIsLeapYear() {
timeUtil.apply {
assertTrue(isLeapYear(1996))
assertTrue(isLeapYear(1992))
assertTrue(isLeapYear(2012))
assertTrue(isLeapYear(2000))
assertTrue(isLeapYear(2400))
assertFalse(isLeapYear(1998))
assertFalse(isLeapYear(2001))
assertFalse(isLeapYear(1997))
assertFalse(isLeapYear(1900))
assertFalse(isLeapYear(1800))
}
}
@Test
fun testGetDaysInMonth() {
timeUtil.apply {
assertEquals(31, getDaysInMonth(1, 2001))
assertEquals(31, getDaysInMonth(12, 2001))
assertEquals(31, getDaysInMonth(1, 2000))
assertEquals(30, getDaysInMonth(6, 2001))
assertEquals(31, getDaysInMonth(7, 1999))
assertEquals(31, getDaysInMonth(8, 1999))
assertEquals(28, getDaysInMonth(2, 1999))
assertEquals(29, getDaysInMonth(2, 1996))
assertEquals(29, getDaysInMonth(2, 2000))
assertEquals(28, getDaysInMonth(2, 2100))
assertEquals(31, getDaysInMonth(1, 1993))
assertEquals(28, getDaysInMonth(2, 1993))
assertEquals(31, getDaysInMonth(3, 1993))
assertEquals(30, getDaysInMonth(4, 1993))
assertEquals(31, getDaysInMonth(5, 1993))
assertEquals(30, getDaysInMonth(6, 1993))
assertEquals(31, getDaysInMonth(7, 1993))
assertEquals(31, getDaysInMonth(8, 1993))
assertEquals(30, getDaysInMonth(9, 1993))
assertEquals(31, getDaysInMonth(10, 1993))
assertEquals(30, getDaysInMonth(11, 1993))
assertEquals(31, getDaysInMonth(12, 1993))
assertEquals(0, getDaysInMonth(0, 1993))
assertEquals(0, getDaysInMonth(13, 1993))
}
}
}
| mit | 87e2f65165de18e81bc66398c6927297 | 31.816 | 97 | 0.622623 | 4.073486 | false | true | false | false |
GunoH/intellij-community | platform/webSymbols/src/com/intellij/webSymbols/framework/impl/WebSymbolsFrameworkExtensionPoint.kt | 2 | 1200 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.webSymbols.framework.impl
import com.intellij.openapi.extensions.DefaultPluginDescriptor
import com.intellij.openapi.extensions.RequiredElement
import com.intellij.serviceContainer.BaseKeyedLazyInstance
import com.intellij.util.KeyedLazyInstance
import com.intellij.util.xmlb.annotations.Attribute
import org.jetbrains.annotations.TestOnly
open class WebSymbolsFrameworkExtensionPoint<T : Any> : BaseKeyedLazyInstance<T>, KeyedLazyInstance<T> {
// these must be public for scrambling compatibility
@Attribute("framework")
@RequiredElement
var framework: String? = null
@Attribute("implementation")
@RequiredElement
var implementation: String? = null
constructor() : super()
@TestOnly
constructor(framework: String, instance: T) : super(instance) {
this.framework = framework
implementation = instance::class.java.name
pluginDescriptor = DefaultPluginDescriptor("test")
}
override fun getImplementationClassName(): String? {
return implementation
}
override fun getKey(): String? {
return framework
}
} | apache-2.0 | 7e302fb3988e922e3a061d8120765e28 | 31.459459 | 120 | 0.78 | 4.761905 | false | true | false | false |
jk1/intellij-community | python/src/com/jetbrains/python/inspections/PyTypeHintsInspection.kt | 3 | 31339 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.inspections
import com.intellij.codeInsight.controlflow.ControlFlowUtil
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache
import com.jetbrains.python.codeInsight.controlflow.ReadWriteInstruction
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.codeInsight.functionTypeComments.PyFunctionTypeAnnotationDialect
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.documentation.PythonDocumentationProvider
import com.jetbrains.python.documentation.doctest.PyDocstringFile
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.impl.PyPsiUtils
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.resolve.PyResolveUtil
import com.jetbrains.python.psi.types.PyGenericType
import com.jetbrains.python.psi.types.PyInstantiableType
import com.jetbrains.python.psi.types.PyTypeChecker
class PyTypeHintsInspection : PyInspection() {
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, session)
private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) {
private val genericQName = QualifiedName.fromDottedString(PyTypingTypeProvider.GENERIC)
override fun visitPyCallExpression(node: PyCallExpression?) {
super.visitPyCallExpression(node)
if (node != null) {
val callee = node.callee as? PyReferenceExpression
val calleeQName = callee?.let { PyResolveUtil.resolveImportedElementQNameLocally(it) } ?: emptyList()
if (QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_VAR) in calleeQName) {
val target = (node.parent as? PyAssignmentStatement)?.targetsToValuesMapping?.firstOrNull { it.second == node }?.first
checkTypeVarPlacement(node, target)
checkTypeVarArguments(node, target)
checkTypeVarRedefinition(target)
}
checkInstanceAndClassChecks(node)
checkParenthesesOnGenerics(node)
}
}
override fun visitPyClass(node: PyClass?) {
super.visitPyClass(node)
if (node != null) {
val superClassExpressions = node.superClassExpressions.toList()
checkPlainGenericInheritance(superClassExpressions)
checkGenericDuplication(superClassExpressions)
checkGenericCompleteness(node)
}
}
override fun visitPySubscriptionExpression(node: PySubscriptionExpression) {
super.visitPySubscriptionExpression(node)
checkParameters(node)
}
override fun visitPyReferenceExpression(node: PyReferenceExpression) {
super.visitPyReferenceExpression(node)
if (node.referencedName == PyNames.CANONICAL_SELF && PyTypingTypeProvider.isInAnnotationOrTypeComment(node)) {
val typeName = myTypeEvalContext.getType(node)?.name
if (typeName != null && typeName != PyNames.CANONICAL_SELF) {
registerProblem(node, "Invalid type 'self'", ProblemHighlightType.GENERIC_ERROR, null, ReplaceWithTypeNameQuickFix(typeName))
}
}
}
override fun visitPyFile(node: PyFile?) {
super.visitPyFile(node)
if (node is PyDocstringFile && PyTypingTypeProvider.isInAnnotationOrTypeComment(node)) {
node.children.singleOrNull().also { if (it is PyExpressionStatement) checkTupleMatching(it.expression) }
}
}
override fun visitPyElement(node: PyElement?) {
super.visitPyElement(node)
if (node is PyTypeCommentOwner && node is PyAnnotationOwner && node.typeCommentAnnotation != null) {
val message = "Type(s) specified both in type comment and annotation"
if (node is PyFunction) {
if (node.annotationValue != null || node.parameterList.parameters.any { it is PyNamedParameter && it.annotationValue != null }) {
registerProblem(node.typeComment, message, RemoveElementQuickFix("Remove type comment"))
registerProblem(node.nameIdentifier, message, RemoveFunctionAnnotations())
}
}
else if (node.annotationValue != null) {
registerProblem(node.typeComment, message, RemoveElementQuickFix("Remove type comment"))
registerProblem(node.annotation, message, RemoveElementQuickFix("Remove annotation"))
}
}
}
override fun visitPyFunction(node: PyFunction) {
super.visitPyFunction(node)
checkTypeCommentAndParameters(node)
}
private fun checkTypeVarPlacement(call: PyCallExpression, target: PyExpression?) {
if (target == null) {
registerProblem(call, "A 'TypeVar()' expression must always directly be assigned to a variable")
}
}
private fun checkTypeVarRedefinition(target: PyExpression?) {
val scopeOwner = ScopeUtil.getScopeOwner(target) ?: return
val name = target?.name ?: return
val instructions = ControlFlowCache.getControlFlow(scopeOwner).instructions
val startInstruction = ControlFlowUtil.findInstructionNumberByElement(instructions, target)
ControlFlowUtil.iteratePrev(
startInstruction,
instructions,
{ instruction ->
if (instruction is ReadWriteInstruction &&
instruction.num() != startInstruction &&
name == instruction.name &&
instruction.access.isWriteAccess) {
registerProblem(target, "Type variables must not be redefined")
ControlFlowUtil.Operation.BREAK
}
else {
ControlFlowUtil.Operation.NEXT
}
}
)
}
private fun checkTypeVarArguments(call: PyCallExpression, target: PyExpression?) {
val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext)
var covariant = false
var contravariant = false
var bound: PyExpression? = null
val constraints = mutableListOf<PyExpression?>()
call.multiMapArguments(resolveContext).firstOrNull { it.unmappedArguments.isEmpty() && it.unmappedParameters.isEmpty() }?.let {
it.mappedParameters.entries.forEach {
val name = it.value.name
val argument = PyUtil.peelArgument(it.key)
when (name) {
"name" ->
if (argument !is PyStringLiteralExpression) {
registerProblem(argument, "'TypeVar()' expects a string literal as first argument")
}
else {
val targetName = target?.name
if (targetName != null && targetName != argument.stringValue) {
registerProblem(argument,
"The argument to 'TypeVar()' must be a string equal to the variable name to which it is assigned",
ReplaceWithTargetNameQuickFix(targetName))
}
}
"covariant" -> covariant = PyEvaluator.evaluateAsBoolean(argument, false)
"contravariant" -> contravariant = PyEvaluator.evaluateAsBoolean(argument, false)
"bound" -> bound = argument
"constraints" -> constraints.add(argument)
}
}
}
if (covariant && contravariant) {
registerProblem(call, "Bivariant type variables are not supported", ProblemHighlightType.GENERIC_ERROR)
}
if (constraints.isNotEmpty() && bound != null) {
registerProblem(call, "Constraints cannot be combined with bound=...", ProblemHighlightType.GENERIC_ERROR)
}
if (constraints.size == 1) {
registerProblem(call, "A single constraint is not allowed", ProblemHighlightType.GENERIC_ERROR)
}
constraints.asSequence().plus(bound).forEach {
if (it != null) {
val type = PyTypingTypeProvider.getType(it, myTypeEvalContext)?.get()
if (PyTypeChecker.hasGenerics(type, myTypeEvalContext)) {
registerProblem(it, "Constraints cannot be parametrized by type variables")
}
}
}
}
private fun checkInstanceAndClassChecks(call: PyCallExpression) {
if (call.isCalleeText(PyNames.ISINSTANCE, PyNames.ISSUBCLASS)) {
val base = call.arguments.getOrNull(1) ?: return
checkInstanceAndClassChecksOnTypeVar(base)
checkInstanceAndClassChecksOnReference(base)
checkInstanceAndClassChecksOnSubscription(base)
}
}
private fun checkInstanceAndClassChecksOnTypeVar(base: PyExpression) {
if (myTypeEvalContext.getType(base) is PyGenericType) {
registerProblem(base,
"Type variables cannot be used with instance and class checks",
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun checkInstanceAndClassChecksOnReference(base: PyExpression) {
if (base is PyReferenceExpression) {
val resolvedBase = multiFollowAssignmentsChain(base)
resolvedBase
.asSequence()
.filterIsInstance<PyQualifiedNameOwner>()
.mapNotNull { it.qualifiedName }
.forEach {
when (it) {
PyTypingTypeProvider.ANY,
PyTypingTypeProvider.UNION,
PyTypingTypeProvider.GENERIC,
PyTypingTypeProvider.OPTIONAL,
PyTypingTypeProvider.CLASS_VAR,
PyTypingTypeProvider.NO_RETURN ->
registerProblem(base,
"'${it.substringAfterLast('.')}' cannot be used with instance and class checks",
ProblemHighlightType.GENERIC_ERROR)
}
}
resolvedBase
.asSequence()
.filterIsInstance<PySubscriptionExpression>()
.filter { myTypeEvalContext.maySwitchToAST(it) }
.forEach { checkInstanceAndClassChecksOnSubscriptionOperand(base, it.operand) }
}
}
private fun checkInstanceAndClassChecksOnSubscription(base: PyExpression) {
if (base is PySubscriptionExpression) {
checkInstanceAndClassChecksOnSubscriptionOperand(base, base.operand)
}
}
private fun checkInstanceAndClassChecksOnSubscriptionOperand(base: PyExpression, operand: PyExpression) {
if (operand is PyReferenceExpression) {
multiFollowAssignmentsChain(operand)
.forEach {
if (it is PyQualifiedNameOwner) {
val qName = it.qualifiedName
when (qName) {
PyTypingTypeProvider.GENERIC -> {
registerProblem(base, "'Generic' cannot be used with instance and class checks", ProblemHighlightType.GENERIC_ERROR)
return@forEach
}
PyTypingTypeProvider.UNION,
PyTypingTypeProvider.OPTIONAL,
PyTypingTypeProvider.CLASS_VAR -> {
registerProblem(base,
"'${qName.substringAfterLast('.')}' cannot be used with instance and class checks",
ProblemHighlightType.GENERIC_ERROR)
return@forEach
}
PyTypingTypeProvider.CALLABLE,
PyTypingTypeProvider.TYPE,
PyTypingTypeProvider.PROTOCOL,
PyTypingTypeProvider.PROTOCOL_EXT -> {
registerProblem(base,
"Parameterized generics cannot be used with instance and class checks",
ProblemHighlightType.GENERIC_ERROR,
null,
if (base is PySubscriptionExpression) RemoveGenericParametersQuickFix() else null)
return@forEach
}
}
}
if (it is PyTypedElement) {
val type = myTypeEvalContext.getType(it)
if (type is PyWithAncestors && PyTypingTypeProvider.isGeneric(type, myTypeEvalContext)) {
registerProblem(base,
"Parameterized generics cannot be used with instance and class checks",
ProblemHighlightType.GENERIC_ERROR,
null,
if (base is PySubscriptionExpression) RemoveGenericParametersQuickFix() else null)
}
}
}
}
}
private fun checkParenthesesOnGenerics(call: PyCallExpression) {
val callee = call.callee
if (callee is PyReferenceExpression) {
if (PyResolveUtil.resolveImportedElementQNameLocally(callee).any { PyTypingTypeProvider.GENERIC_CLASSES.contains(it.toString()) }) {
registerProblem(call,
"Generics should be specified through square brackets",
ProblemHighlightType.GENERIC_ERROR,
null,
ReplaceWithSubscriptionQuickFix())
}
else if (PyTypingTypeProvider.isInAnnotationOrTypeComment(call)) {
multiFollowAssignmentsChain(callee)
.asSequence()
.map { if (it is PyFunction) it.containingClass else it }
.any { it is PyWithAncestors && PyTypingTypeProvider.isGeneric(it, myTypeEvalContext) }
.also {
if (it) registerProblem(call, "Generics should be specified through square brackets", ReplaceWithSubscriptionQuickFix())
}
}
}
}
private fun checkPlainGenericInheritance(superClassExpressions: List<PyExpression>) {
superClassExpressions
.asSequence()
.filterIsInstance<PyReferenceExpression>()
.filter { genericQName in PyResolveUtil.resolveImportedElementQNameLocally(it) }
.forEach { registerProblem(it, "Cannot inherit from plain 'Generic'", ProblemHighlightType.GENERIC_ERROR) }
}
private fun checkGenericDuplication(superClassExpressions: List<PyExpression>) {
superClassExpressions
.asSequence()
.filter {
val resolved = if (it is PyReferenceExpression) multiFollowAssignmentsChain(it) else listOf(it)
resolved
.asSequence()
.filterIsInstance<PySubscriptionExpression>()
.filter { myTypeEvalContext.maySwitchToAST(it) }
.mapNotNull { it.operand as? PyReferenceExpression }
.any { genericQName in PyResolveUtil.resolveImportedElementQNameLocally(it) }
}
.drop(1)
.forEach { registerProblem(it, "Cannot inherit from 'Generic[...]' multiple times", ProblemHighlightType.GENERIC_ERROR) }
}
private fun checkGenericCompleteness(cls: PyClass) {
var seenGeneric = false
val genericTypeVars = linkedSetOf<PsiElement>()
val nonGenericTypeVars = linkedSetOf<PsiElement>()
cls.superClassExpressions.forEach {
val generics = collectGenerics(it)
generics.first?.let {
genericTypeVars.addAll(it)
seenGeneric = true
}
nonGenericTypeVars.addAll(generics.second)
}
if (seenGeneric && (nonGenericTypeVars - genericTypeVars).isNotEmpty()) {
val nonGenericTypeVarsNames = nonGenericTypeVars
.asSequence()
.filterIsInstance<PyTargetExpression>()
.mapNotNull { it.name }
.joinToString(", ")
val genericTypeVarsNames = genericTypeVars
.asSequence()
.filterIsInstance<PyTargetExpression>()
.mapNotNull { it.name }
.joinToString(", ")
registerProblem(cls.superClassExpressionList,
"Some type variables ($nonGenericTypeVarsNames) are not listed in 'Generic[$genericTypeVarsNames]'",
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun collectGenerics(superClassExpression: PyExpression): Pair<Set<PsiElement>?, Set<PsiElement>> {
val resolvedSuperClass =
if (superClassExpression is PyReferenceExpression) multiFollowAssignmentsChain(superClassExpression)
else listOf(superClassExpression)
var seenGeneric = false
val genericTypeVars = linkedSetOf<PsiElement>()
val nonGenericTypeVars = linkedSetOf<PsiElement>()
resolvedSuperClass
.asSequence()
.filterIsInstance<PySubscriptionExpression>()
.filter { myTypeEvalContext.maySwitchToAST(it) }
.forEach {
val operand = it.operand
val generic =
operand is PyReferenceExpression &&
genericQName in PyResolveUtil.resolveImportedElementQNameLocally(operand)
val index = it.indexExpression
val parameters = (index as? PyTupleExpression)?.elements ?: arrayOf(index)
val superClassTypeVars = parameters
.asSequence()
.filterIsInstance<PyReferenceExpression>()
.map { multiFollowAssignmentsChain(it, this::followNotTypeVar).toSet() }
.fold(emptySet<PsiElement>(), { acc, typeVars -> acc.union(typeVars) })
if (generic) genericTypeVars.addAll(superClassTypeVars) else nonGenericTypeVars.addAll(superClassTypeVars)
seenGeneric = seenGeneric || generic
}
return Pair(if (seenGeneric) genericTypeVars else null, nonGenericTypeVars)
}
private fun checkParameters(node: PySubscriptionExpression) {
val operand = node.operand as? PyReferenceExpression ?: return
val index = node.indexExpression ?: return
val callableQName = QualifiedName.fromDottedString(PyTypingTypeProvider.CALLABLE)
val qNames = PyResolveUtil.resolveImportedElementQNameLocally(operand)
var typingOnly = true
var callableExists = false
qNames.forEach {
when (it) {
genericQName -> checkGenericParameters(index)
callableQName -> {
callableExists = true
checkCallableParameters(index)
}
}
typingOnly = typingOnly && it.firstComponent == PyTypingTypeProvider.TYPING
}
if (qNames.isNotEmpty() && typingOnly) {
checkTypingMemberParameters(index, callableExists)
}
}
private fun checkGenericParameters(index: PyExpression) {
val parameters = (index as? PyTupleExpression)?.elements ?: arrayOf(index)
val typeVars = mutableSetOf<PsiElement>()
parameters.forEach {
if (it !is PyReferenceExpression) {
registerProblem(it, "Parameters to 'Generic[...]' must all be type variables", ProblemHighlightType.GENERIC_ERROR)
}
else {
val type = myTypeEvalContext.getType(it)
if (type != null) {
if (type is PyGenericType) {
if (!typeVars.addAll(multiFollowAssignmentsChain(it))) {
registerProblem(it, "Parameters to 'Generic[...]' must all be unique", ProblemHighlightType.GENERIC_ERROR)
}
}
else {
registerProblem(it, "Parameters to 'Generic[...]' must all be type variables", ProblemHighlightType.GENERIC_ERROR)
}
}
}
}
}
private fun checkCallableParameters(index: PyExpression) {
val message = "'Callable' must be used as 'Callable[[arg, ...], result]'"
if (index !is PyTupleExpression) {
registerProblem(index, message, ProblemHighlightType.GENERIC_ERROR)
return
}
val parameters = index.elements
if (parameters.size > 2) {
val possiblyLastParameter = parameters[parameters.size - 2]
registerProblem(index,
message,
ProblemHighlightType.GENERIC_ERROR,
null,
TextRange.create(0, possiblyLastParameter.startOffsetInParent + possiblyLastParameter.textLength),
SurroundElementsWithSquareBracketsQuickFix())
}
else if (parameters.size < 2) {
registerProblem(index, message, ProblemHighlightType.GENERIC_ERROR)
}
else {
val first = parameters.first()
if (first !is PyListLiteralExpression && !(first is PyNoneLiteralExpression && first.isEllipsis)) {
registerProblem(first,
message,
ProblemHighlightType.GENERIC_ERROR,
null,
if (first is PyParenthesizedExpression) ReplaceWithListQuickFix() else SurroundElementWithSquareBracketsQuickFix())
}
}
}
private fun checkTypingMemberParameters(index: PyExpression, isCallable: Boolean) {
val parameters = if (index is PyTupleExpression) index.elements else arrayOf(index)
parameters
.asSequence()
.drop(if (isCallable) 1 else 0)
.forEach {
if (it is PyListLiteralExpression) {
registerProblem(it,
"Parameters to generic types must be types",
ProblemHighlightType.GENERIC_ERROR,
null,
RemoveSquareBracketsQuickFix())
}
else if (it is PyReferenceExpression && multiFollowAssignmentsChain(it).any { it is PyListLiteralExpression }) {
registerProblem(it, "Parameters to generic types must be types", ProblemHighlightType.GENERIC_ERROR)
}
}
}
private fun checkTupleMatching(expression: PyExpression) {
if (expression !is PyTupleExpression) return
val assignment = PyPsiUtils.getRealContext(expression).parent as? PyAssignmentStatement ?: return
val lhs = assignment.leftHandSideExpression ?: return
if (PyTypingTypeProvider.mapTargetsToAnnotations(lhs, expression).isEmpty() &&
(expression.elements.isNotEmpty() || assignment.rawTargets.isNotEmpty())) {
registerProblem(expression, "Type comment cannot be matched with unpacked variables")
}
}
private fun checkTypeCommentAndParameters(node: PyFunction) {
val functionTypeAnnotation = PyTypingTypeProvider.getFunctionTypeAnnotation(node) ?: return
val parameterTypes = functionTypeAnnotation.parameterTypeList.parameterTypes
if (parameterTypes.singleOrNull().let { it is PyNoneLiteralExpression && it.isEllipsis }) return
val actualParametersSize = node.parameterList.parameters.size
val commentParametersSize = parameterTypes.size
val cls = node.containingClass
val modifier = node.modifier
val hasSelf = cls != null && modifier != PyFunction.Modifier.STATICMETHOD
if (commentParametersSize < actualParametersSize - if (hasSelf) 1 else 0) {
registerProblem(node.typeComment, "Type signature has too few arguments")
}
else if (commentParametersSize > actualParametersSize) {
registerProblem(node.typeComment, "Type signature has too many arguments")
}
else if (hasSelf && actualParametersSize == commentParametersSize) {
val actualSelfType =
(myTypeEvalContext.getType(cls!!) as? PyInstantiableType<*>)
?.let { if (modifier == PyFunction.Modifier.CLASSMETHOD) it.toClass() else it.toInstance() }
?: return
val commentSelfType =
parameterTypes.firstOrNull()
?.let { PyTypingTypeProvider.getType(it, myTypeEvalContext) }
?.get()
?: return
if (!PyTypeChecker.match(commentSelfType, actualSelfType, myTypeEvalContext)) {
val actualSelfTypeDescription = PythonDocumentationProvider.getTypeDescription(actualSelfType, myTypeEvalContext)
val commentSelfTypeDescription = PythonDocumentationProvider.getTypeDescription(commentSelfType, myTypeEvalContext)
registerProblem(node.typeComment,
"The type of self '$commentSelfTypeDescription' is not a supertype of its class '$actualSelfTypeDescription'")
}
}
}
private fun followNotTypingOpaque(target: PyTargetExpression): Boolean {
return !PyTypingTypeProvider.OPAQUE_NAMES.contains(target.qualifiedName)
}
private fun followNotTypeVar(target: PyTargetExpression): Boolean {
return !myTypeEvalContext.maySwitchToAST(target) || target.findAssignedValue() !is PyCallExpression
}
private fun multiFollowAssignmentsChain(referenceExpression: PyReferenceExpression,
follow: (PyTargetExpression) -> Boolean = this::followNotTypingOpaque): List<PsiElement> {
val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext)
return referenceExpression.multiFollowAssignmentsChain(resolveContext, follow).mapNotNull { it.element }
}
}
companion object {
private class ReplaceWithTypeNameQuickFix(private val typeName: String) : LocalQuickFix {
override fun getFamilyName() = "Replace with type name"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? PyReferenceExpression ?: return
element.reference.handleElementRename(typeName)
}
}
private class RemoveElementQuickFix(private val description: String) : LocalQuickFix {
override fun getFamilyName() = description
override fun applyFix(project: Project, descriptor: ProblemDescriptor) = descriptor.psiElement.delete()
}
private class RemoveFunctionAnnotations : LocalQuickFix {
override fun getFamilyName() = "Remove function annotations"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val function = (descriptor.psiElement.parent as? PyFunction) ?: return
function.annotation?.delete()
function.parameterList.parameters
.asSequence()
.filterIsInstance<PyNamedParameter>()
.mapNotNull { it.annotation }
.forEach { it.delete() }
}
}
private class ReplaceWithTargetNameQuickFix(private val targetName: String) : LocalQuickFix {
override fun getFamilyName() = "Replace with target name"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val old = descriptor.psiElement as? PyStringLiteralExpression ?: return
val new = PyElementGenerator.getInstance(project).createStringLiteral(old, targetName) ?: return
old.replace(new)
}
}
private class RemoveGenericParametersQuickFix : LocalQuickFix {
override fun getFamilyName() = "Remove generic parameter(s)"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val old = descriptor.psiElement as? PySubscriptionExpression ?: return
old.replace(old.operand)
}
}
private class ReplaceWithSubscriptionQuickFix : LocalQuickFix {
override fun getFamilyName() = "Replace with square brackets"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? PyCallExpression ?: return
val callee = element.callee?.text ?: return
val argumentList = element.argumentList ?: return
val index = argumentList.text.let { it.substring(1, it.length - 1) }
val language = element.containingFile.language
val text = if (language == PyFunctionTypeAnnotationDialect.INSTANCE) "() -> $callee[$index]" else "$callee[$index]"
PsiFileFactory
.getInstance(project)
// it's important to create file with same language as element's file to have correct behaviour in injections
.createFileFromText(language, text)
?.let { it.firstChild.lastChild as? PySubscriptionExpression }
?.let { element.replace(it) }
}
}
private class SurroundElementsWithSquareBracketsQuickFix : LocalQuickFix {
override fun getFamilyName() = "Surround with square brackets"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? PyTupleExpression ?: return
val list = PyElementGenerator.getInstance(project).createListLiteral()
val originalElements = element.elements
originalElements.dropLast(1).forEach { list.add(it) }
originalElements.dropLast(2).forEach { it.delete() }
element.elements.first().replace(list)
}
}
private class SurroundElementWithSquareBracketsQuickFix : LocalQuickFix {
override fun getFamilyName() = "Surround with square brackets"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
val list = PyElementGenerator.getInstance(project).createListLiteral()
list.add(element)
element.replace(list)
}
}
private class ReplaceWithListQuickFix : LocalQuickFix {
override fun getFamilyName() = "Replace with square brackets"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
val expression = (element as? PyParenthesizedExpression)?.containedExpression ?: return
val elements = expression.let { if (it is PyTupleExpression) it.elements else arrayOf(it) }
val list = PyElementGenerator.getInstance(project).createListLiteral()
elements.forEach { list.add(it) }
element.replace(list)
}
}
private class RemoveSquareBracketsQuickFix : LocalQuickFix {
override fun getFamilyName() = "Remove square brackets"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? PyListLiteralExpression ?: return
val subscription = PsiTreeUtil.getParentOfType(element, PySubscriptionExpression::class.java, true, ScopeOwner::class.java)
val index = subscription?.indexExpression ?: return
val newIndexElements = if (index is PyTupleExpression) {
index.elements.flatMap { if (it == element) element.elements.asList() else listOf(it) }
}
else {
element.elements.asList()
}
if (newIndexElements.size == 1) {
index.replace(newIndexElements.first())
}
else {
val newIndexText = newIndexElements.joinToString(prefix = "(", postfix = ")") { it.text }
val expression = PyElementGenerator.getInstance(project).createExpressionFromText(LanguageLevel.forElement(element), newIndexText)
val newIndex = (expression as? PyParenthesizedExpression)?.containedExpression as? PyTupleExpression ?: return
index.replace(newIndex)
}
}
}
}
} | apache-2.0 | 1471e655e103e8ece501c09e5454abf7 | 39.913838 | 141 | 0.662944 | 5.440799 | false | false | false | false |
marcbaldwin/RxAdapter | rxadapter/src/main/kotlin/xyz/marcb/rxadapter/OptionalItem.kt | 1 | 831 | package xyz.marcb.rxadapter
import androidx.recyclerview.widget.RecyclerView
import io.reactivex.Observable
import xyz.marcb.rxadapter.internal.EmptySnapshot
import xyz.marcb.rxadapter.internal.Snapshot
class OptionalItem<O, I, VH>(
private val vhClass: Class<VH>,
private val item: Observable<O>,
private val unwrap: (O) -> I?,
private val id: Long = RecyclerView.NO_ID
) : AdapterPart where VH : RecyclerView.ViewHolder {
var binder: (VH.(I) -> Unit)? = null
var onClick: (VH.(I) -> Unit)? = null
override var visible: Observable<Boolean>? = null
override val snapshots: Observable<AdapterPartSnapshot>
get() = item.map { item ->
unwrap(item)
?.let { Snapshot(vhClass, listOf(it), listOf(id), binder, onClick) }
?: EmptySnapshot
}
}
| mit | 40cf51752f5a89cf0b7f2d8e17f68e47 | 32.24 | 84 | 0.663057 | 3.883178 | false | false | false | false |
linheimx/ZimuDog | app/src/main/java/com/linheimx/zimudog/vp/browzimu/SdCardFragment.kt | 1 | 12041 | package com.linheimx.zimudog.vp.browzimu
import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.afollestad.materialdialogs.folderselector.FolderChooserDialog
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.github.rubensousa.bottomsheetbuilder.BottomSheetBuilder
import com.hu.p7zip.ZipUtils
import com.linheimx.zimudog.App
import com.linheimx.zimudog.R
import com.linheimx.zimudog.m.bean.DirChange
import com.linheimx.zimudog.m.bean.Ok
import com.linheimx.zimudog.utils.Utils
import java.io.File
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Arrays
import java.util.Date
import es.dmoral.toasty.Toasty
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import com.linheimx.zimudog.utils.Utils.convertFileSize
import com.linheimx.zimudog.utils.bindView
import com.linheimx.zimudog.utils.rxbus.RxBus_Behavior
import org.jetbrains.anko.support.v4.toast
/**
* Created by LJIAN on 2017/5/9.
*/
class SdCardFragment : TitleFragment() {
val _rv: RecyclerView by bindView(R.id.rv)
val _tv_nav: TextView by bindView(R.id.tv_nav)
val _srl: SwipeRefreshLayout by bindView(R.id.srl)
val _menu: View by bindView(R.id.tv_setting)
lateinit var _QuickAdapter: QuickAdapter
override val title: String
get() = "已下载"
val progressDialog: ProgressDialog by lazy { ProgressDialog(activity) }
override fun _ProvideLayout(): Int = R.layout.fragment_sdcard
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_tv_nav.setOnClickListener { onNav() }
_rv!!.setHasFixedSize(true)
_rv!!.layoutManager = LinearLayoutManager(activity)
_QuickAdapter = QuickAdapter()
_QuickAdapter.bindToRecyclerView(_rv)
_QuickAdapter.openLoadAnimation()
_QuickAdapter.setEmptyView(R.layout.rv_empty_view_sdcard)
RxBus_Behavior.toFlowable(Ok::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
_rv.postDelayed({ _QuickAdapter.filesChanged() }, 200)
})
RxBus_Behavior.toFlowable(DirChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
_rv.postDelayed({ _QuickAdapter.rest2ZimuDog() }, 200)
})
_srl!!.setOnRefreshListener {
_rv!!.postDelayed({
_QuickAdapter.rest2ZimuDog()
Toasty.info(App.get()!!, "定位到了默认目录", Toast.LENGTH_LONG).show()
_srl!!.isRefreshing = false
}, 200)
}
_menu.setOnClickListener {
FolderChooserDialog.Builder(activity!!)
.chooseButton(R.string.choose) // changes label of the choose button
.initialPath("/sdcard/") // changes initial path, defaults to external storage directory
.goUpLabel("上一级") // custom go up label, default label is "..."
.show(activity)
}
}
override fun onResume() {
super.onResume()
if (view == null) {
return
}
view!!.isFocusableInTouchMode = true
view!!.requestFocus()
view!!.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
if (event.action == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
// handle back button's click listener
onNav()
return@OnKeyListener true
}
false
})
_QuickAdapter.filesChanged()
}
fun onNav() {
val currentDir = _QuickAdapter.currentDir
val parent = currentDir.parentFile
if (parent != null) {
// 安全检查
if (parent.listFiles() == null) {
return
}
_QuickAdapter.currentDir = parent
_QuickAdapter.filesChanged()
}
}
inner class QuickAdapter : BaseQuickAdapter<File, BaseViewHolder>(R.layout.rv_item_sdcard) {
lateinit var currentDir: File
init {
rest2ZimuDog()
}
fun rest2ZimuDog() {
val dir_zimu = File(Utils.rootDirPath)
currentDir = dir_zimu
Log.e("===>",currentDir.toString())
filesChanged()
}
fun filesChanged() {
_tv_nav!!.text = currentDir.path
val files = currentDir.listFiles()
if (files != null && files.size > 0) { // check
Arrays.sort(files) { o1, o2 ->
val ret = o1.lastModified() - o2.lastModified()
if (ret > 0) {
-1
} else if (ret == 0L) {
0
} else {
1
}
}
val fileList = Arrays.asList(*files)
if (mData != null) {
mData.clear()
}
// make sure length > 0
try {
for (file in fileList) {
if (file.length() > 0) {
mData.add(file)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
} else {
mData = ArrayList()
}
notifyDataSetChanged()
}
override fun convert(helper: BaseViewHolder, file: File) {
// type
val tv = helper.getView<TextView>(R.id.tv_type)
if (file.isFile) {
tv.setBackgroundColor(ContextCompat.getColor(activity!!.applicationContext, R.color.tv_file))
val name = file.name
try {
val types = name.split("\\.".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
if (types != null && types.size > 0) {
helper.setText(R.id.tv_type, types[types.size - 1])
}
} catch (e: Exception) {
}
} else {
tv.setBackgroundColor(ContextCompat.getColor(activity!!.applicationContext, R.color.tv_dir))
tv.text = ""
}
// title
helper.setText(R.id.tv_name, file.name)
// size
var size = ""
try {
if (file.isFile) {
size = convertFileSize(file.length())
} else {
size = file.listFiles().size.toString() + "项"
}
} catch (e: Exception) {
}
helper.setText(R.id.tv_size, size)
// time
val currentTime = Date(file.lastModified())
val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val dateString = formatter.format(currentTime)
helper.setText(R.id.tv_time, dateString + "")
helper.itemView.setOnClickListener {
if (file.isFile) {
showMenu(file)
} else {
currentDir = file
filesChanged()
}
}
helper.itemView.setOnLongClickListener {
if (!file.isFile) {
showMenu(file)
}
true
}
}
}
private fun showMenu(file: File) {
val dialog = BottomSheetBuilder(activity)
.setMode(BottomSheetBuilder.MODE_LIST)
.addTitleItem("选择操作")
.addItem(0, "删除", R.drawable.op_delete)
.addItem(1, "解压", R.drawable.op_open)
.setItemClickListener { item ->
if (item.title == "删除") {
op_delete(file)
} else if (item.title == "解压") {
// check
if (file.name.endsWith("zip") || file.name.endsWith("rar")) {
op_unZipRar(file)
} else {
Toasty.info(App.get()!!, "不支持的解压格式", Toast.LENGTH_SHORT).show()
}
}
}.createDialog()
dialog.show()
}
private fun op_delete(file: File) {
deleFileRe(file)
_QuickAdapter.filesChanged()
}
/**
* 递归删除文件
*
* @param file
*/
private fun deleFileRe(file: File) {
if (file.isFile) {
file.delete()
} else {
for (f in file.listFiles()) {
deleFileRe(f)
}
if (file.listFiles().size == 0) {
file.delete()
}
}
}
private fun op_unZipRar(file: File) {
progressDialog.setTitle("解压中...")
progressDialog.show()
Flowable
.fromCallable {
var ret = -1
try {
Thread.sleep(1000)//延时一下
val parentPath = file.parent
// 考虑到文件名字的原因,重命名!
val originFileName = file.name
val newFileName = parentPath + "/" + System.currentTimeMillis()
val tmpFile = File(newFileName)
file.renameTo(tmpFile)
// out dir
val tmpDir = File(file.parent + "/d" + System.currentTimeMillis())
if (!tmpDir.exists()) {
tmpDir.mkdir()
} else {
deleFileRe(tmpDir)
tmpDir.mkdir()
}
// cmd
val cmd = StringBuilder("7z x")
cmd.append(" " + tmpFile.path) //7z x 'aaa/bbb.zip'
cmd.append(" -o" + tmpDir.path + "") //7z x 'a.zip' '-o/out/'
ret = ZipUtils.executeCommand(cmd.toString())
// 恢复名称
val finalFile = File(parentPath + "/" + originFileName)
finalFile.createNewFile()
tmpFile.renameTo(finalFile)
val dirName = originFileName.split("\\.".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[0]
val finalDir = File(parentPath + "/" + dirName)
if (finalDir.exists()) {
deleFileRe(finalDir)
}
finalDir.mkdir()
tmpDir.renameTo(finalDir)
} catch (e: InterruptedException) {
Log.e("===>", e.message)
e.printStackTrace()
}
ret != -1
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
_QuickAdapter.filesChanged()
progressDialog!!.dismiss()
if (!it) {
Toasty.error(App.get()!!, "解压失败", Toast.LENGTH_LONG).show()
}
})
}
}
| apache-2.0 | ded1856a2b634bfe776aa846ba140134 | 31.853591 | 125 | 0.498276 | 4.759104 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/fields/implWsDataClassFiledCode.kt | 2 | 2394 | package com.intellij.workspaceModel.codegen.fields
import com.intellij.workspaceModel.codegen.*
import com.intellij.workspaceModel.codegen.fields.javaType
import com.intellij.workspaceModel.codegen.isRefType
import com.intellij.workspaceModel.codegen.deft.*
import com.intellij.workspaceModel.codegen.deft.Field
val Field<*, *>.implWsDataFieldCode: String
get() = buildString {
if (hasSetter) {
if (isOverride && name !in listOf("name", "entitySource")) append(implWsBlockingCodeOverride)
else append(implWsDataBlockingCode)
}
else {
if (defaultValue!!.startsWith("=")) {
append("var $javaName: ${type.javaType} ${defaultValue}")
} else {
append("var $javaName: ${type.javaType} = ${defaultValue}")
}
}
}
private val Field<*, *>.implWsDataBlockingCode: String
get() = implWsDataBlockCode(type, name)
private fun Field<*, *>.implWsDataBlockCode(fieldType: ValueType<*>, name: String, isOptional: Boolean = false): String {
return when (fieldType) {
TInt -> "var $javaName: ${fieldType.javaType} = 0"
TBoolean -> "var $javaName: ${fieldType.javaType} = false"
TString -> "lateinit var $javaName: String"
is TRef -> error("Reference type at EntityData not supported")
is TList<*>, is TMap<*, *> -> {
if (fieldType.isRefType()) error("Reference type at EntityData not supported")
if (!isOptional) {
"lateinit var $javaName: ${fieldType.javaType}"
}
else {
"var $javaName: ${fieldType.javaType}? = null"
}
}
is TOptional<*> -> when (fieldType.type) {
TInt, TBoolean, TString -> "var $javaName: ${fieldType.javaType} = null"
else -> implWsDataBlockCode(fieldType.type, name, true)
}
is TBlob<*> -> {
if (!isOptional) {
"lateinit var $javaName: ${fieldType.javaType}"
}
else {
"var $javaName: ${fieldType.javaType}? = null"
}
}
else -> error("Unsupported field type: $this")
}
}
val Field<*, *>.implWsDataFieldInitializedCode: String
get() = when (type) {
is TInt, is TBoolean -> ""
is TString, is TBlob<*>, is TList<*>, is TMap<*, *> -> {
val capitalizedFieldName = javaName.replaceFirstChar { it.titlecaseChar() }
"fun is${capitalizedFieldName}Initialized(): Boolean = ::${javaName}.isInitialized"
}
else -> error("Unsupported field type: $this")
}
| apache-2.0 | 4a205ff896203f04efa284abd548cb2a | 35.830769 | 121 | 0.646617 | 4.030303 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/longest_subsequence/LongestSubsequence0.kt | 1 | 2049 | package katas.kotlin.longest_subsequence
import nonstdlib.printed
import datsok.shouldEqual
import org.junit.Test
import kotlin.random.Random
class LongestSubsequence0 {
@Test fun `longest subsequence of two strings`() {
longestSubsequence("", "") shouldEqual ""
longestSubsequence("a", "") shouldEqual ""
longestSubsequence("", "a") shouldEqual ""
longestSubsequence("a", "a") shouldEqual "a"
longestSubsequence("abc", "abc") shouldEqual "abc"
longestSubsequence("abc", "_abc") shouldEqual "abc"
longestSubsequence("abc", "__abc") shouldEqual "abc"
longestSubsequence("abc", "abc_") shouldEqual "abc"
longestSubsequence("abc", "abc__") shouldEqual "abc"
longestSubsequence("abc", "_abc_") shouldEqual "abc"
longestSubsequence("abc", "a_bc") shouldEqual "abc"
longestSubsequence("abc", "ab_c") shouldEqual "abc"
longestSubsequence("abc", "a_b_c") shouldEqual "abc"
longestSubsequence("abc", "_a_b_c") shouldEqual "abc"
longestSubsequence("abc", "_a_b_c_") shouldEqual "abc"
longestSubsequence("_a_b_c_", "abc") shouldEqual "abc"
longestSubsequence("_a_b_c_", "-a-b-c-") shouldEqual "abc"
longestSubsequence("_a_a_a_", "-a-a-a-") shouldEqual "aaa"
longestSubsequence("abcde", "ab__cd__cde") shouldEqual "abcde"
val s1 = Random.nextInt().toString().padStart(20, '_').printed()
val s2 = Random.nextInt().toString().padStart(20, '_').printed()
val mixed = s1.zip(s2).joinToString("") { it.first.toString() + it.second}.printed()
longestSubsequence(s1, mixed) shouldEqual s1
longestSubsequence(s2, mixed) shouldEqual s2
}
private fun longestSubsequence(s1: String, s2: String): String {
if (s1.isEmpty() || s2.isEmpty()) return ""
val c = s1.first()
val i = s2.indexOf(c)
return if (i == -1) longestSubsequence(s1.drop(1), s2)
else c.toString() + longestSubsequence(s1.drop(1), s2.drop(i + 1))
}
} | unlicense | 3274725ae6eb08e4f58440fc3c313672 | 40.836735 | 92 | 0.627623 | 3.910305 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/eclipse/src/org/jetbrains/idea/eclipse/codeStyleMapping/util/SettingMapping.kt | 6 | 6436 | // 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.idea.eclipse.codeStyleMapping.util
import java.lang.IllegalArgumentException
import kotlin.reflect.KMutableProperty0
interface SettingMapping<External> {
/**
* @throws IllegalStateException if [isExportAllowed] == false
*/
fun export(): External
/**
* @throws IllegalStateException if [isImportAllowed] == false
* @throws UnexpectedIncomingValue if [value] could not be converted anywhere in the chain
*/
fun import(value: External)
val isExportAllowed
get() = true
val isImportAllowed
get() = true
}
fun <E> SettingMapping<E>.importIfAllowed(value: E) {
if (isImportAllowed) import(value)
}
abstract class WrappingSettingMapping<Outer, Inner>(val wrappee: SettingMapping<Inner>) : SettingMapping<Outer> {
override val isExportAllowed by wrappee::isExportAllowed
override val isImportAllowed by wrappee::isImportAllowed
}
class ConvertingSettingMapping<External, Internal>(
wrappee: SettingMapping<Internal>,
val convertor: Convertor<External, Internal>
) : WrappingSettingMapping<External, Internal>(wrappee) {
override fun export(): External = convertor.convertOutgoing(wrappee.export())
override fun import(value: External) = wrappee.import(convertor.convertIncoming(value))
}
class ConstSettingMapping<E>(val value: E) : SettingMapping<E> {
override fun export(): E = value
override fun import(value: E) { throw IllegalStateException("const setting mapping cannot import anything") }
override val isImportAllowed = false
}
interface Convertor<E, I> {
fun convertIncoming(value: E): I
fun convertOutgoing(value: I): E
}
/**
* Signalizes that a value could not be parsed correctly on import.
*/
class UnexpectedIncomingValue(val value: Any) : IllegalArgumentException(value.toString())
object IntConvertor : Convertor<String, Int> {
override fun convertOutgoing(value: Int): String = value.toString()
override fun convertIncoming(value: String): Int = try {
value.toInt()
}
catch (e: NumberFormatException) {
throw UnexpectedIncomingValue(value)
}
}
object BooleanConvertor : Convertor<String, Boolean> {
override fun convertOutgoing(value: Boolean): String = value.toString()
override fun convertIncoming(value: String): Boolean = when (value.lowercase()) {
"true" -> true
"false" -> false
else -> throw UnexpectedIncomingValue(value)
}
}
class FieldSettingMapping<I>(
val field: KMutableProperty0<I>,
) : SettingMapping<I> {
override fun export(): I = field.getter.call()
override fun import(value: I) = field.setter.call(value)
}
class AlsoImportFieldsSettingMapping<I>(
wrappee: SettingMapping<I>,
val fields: Array<out KMutableProperty0<I>>
) : WrappingSettingMapping<I, I>(wrappee) {
override fun export(): I = wrappee.export()
override fun import(value: I) {
fields.forEach { it.setter.call(value) }
wrappee.import(value)
}
}
class ComputableSettingMapping<I>(
val _import: (I) -> Unit,
val _export: () -> I
) : SettingMapping<I> {
override fun export() = _export()
override fun import(value: I) = _import(value)
}
class ConditionalImportSettingMapping<External>(
wrappee: SettingMapping<External>,
override val isImportAllowed: Boolean
) : WrappingSettingMapping<External, External>(wrappee) {
override fun export(): External = wrappee.export()
override fun import(value: External) {
if (isImportAllowed) {
wrappee.import(value)
}
else {
throw IllegalStateException()
}
}
}
object SettingsMappingHelpers {
/**
* Create export only mapping.
*
* Meant for cases when there is no corresponding IDEA settings field (the behavior is *constant*).
* I.e. for Eclipse options, that do not have a counterpart in IDEA,
* but the default behaviour in IDEA corresponds to one of the possible values for this Eclipse option.
*/
fun <I> const(value: I) = ConstSettingMapping(value)
/**
* Create mapping to a **bound** property.
*
* Note that the property has to be public, so that the mapping object can call its getter/setter
*/
fun <T> field(field: KMutableProperty0<T>) = FieldSettingMapping(field)
fun <I> compute(import: (I) -> Unit, export: () -> I) = ComputableSettingMapping(import, export)
/**
* Does not export nor import any setting.
*
* It is used to explicitly declare that an Eclipse option is not mapped to anything.
*/
fun ignored() = IgnoredSettingMapping
}
fun <External, Internal> SettingMapping<Internal>.convert(convertor: Convertor<External, Internal>) =
ConvertingSettingMapping(this, convertor)
fun SettingMapping<Boolean>.convertBoolean() = convert(BooleanConvertor)
fun SettingMapping<Int>.convertInt() = convert(IntConvertor)
/**
* Specifies that a [FieldSettingMapping] should only be used for export.
*
* Useful for N to 1 (external to internal) mappings.
* I.e. when multiple options in Eclipse correspond to a single IDEA setting (field).
* This function allows us to control which one of the Eclipse options will be used to set the IDEA setting,
* otherwise, the result depends on the order, in which settings are imported.
*/
fun <External> SettingMapping<External>.doNotImport() =
ConditionalImportSettingMapping(this, false)
/**
* Specify fields whose values should be set alongside a [FieldSettingMapping] on import.
*
* Useful 1 to N (external to internal) mappings.
* I.e. when setting one option in Eclipse corresponds to setting multiple settings in IDEA.
* Only the original ([FieldSettingMapping]) will be used for export.
*/
fun <Internal> FieldSettingMapping<Internal>.alsoSet(vararg fields: KMutableProperty0<Internal>) =
AlsoImportFieldsSettingMapping(this, fields)
class InvertingBooleanSettingMapping(wrappee: SettingMapping<Boolean>)
: WrappingSettingMapping<Boolean, Boolean>(wrappee) {
override fun export(): Boolean = !wrappee.export()
override fun import(value: Boolean) = wrappee.import(!value)
}
fun SettingMapping<Boolean>.invert() = InvertingBooleanSettingMapping(this)
object IgnoredSettingMapping : SettingMapping<String> {
override fun export(): String {
throw IllegalStateException()
}
override fun import(value: String) {
throw IllegalStateException()
}
override val isExportAllowed = false
override val isImportAllowed = false
} | apache-2.0 | c82e9a1d62fcec1594bb52fa4101323e | 31.185 | 120 | 0.737415 | 4.045255 | false | false | false | false |
mikepenz/FastAdapter | app/src/main/java/com/mikepenz/fastadapter/app/ExpandableMultiselectDeleteSampleActivity.kt | 1 | 10750 | package com.mikepenz.fastadapter.app
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.ActionMode
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.michaelflisar.dragselectrecyclerview.DragSelectTouchListener
import com.mikepenz.fastadapter.*
import com.mikepenz.fastadapter.adapters.FastItemAdapter
import com.mikepenz.fastadapter.adapters.GenericFastItemAdapter
import com.mikepenz.fastadapter.app.databinding.ActivitySampleBinding
import com.mikepenz.fastadapter.app.items.HeaderSelectionItem
import com.mikepenz.fastadapter.app.items.expandable.SimpleSubItem
import com.mikepenz.fastadapter.app.utils.getThemeColor
import com.mikepenz.fastadapter.expandable.ExpandableExtension
import com.mikepenz.fastadapter.expandable.getExpandableExtension
import com.mikepenz.fastadapter.helpers.ActionModeHelper
import com.mikepenz.fastadapter.helpers.RangeSelectorHelper
import com.mikepenz.fastadapter.select.SelectExtension
import com.mikepenz.fastadapter.select.getSelectExtension
import com.mikepenz.fastadapter.utils.SubItemUtil
import com.mikepenz.itemanimators.SlideDownAlphaAnimator
import java.util.*
class ExpandableMultiselectDeleteSampleActivity : AppCompatActivity() {
private lateinit var binding: ActivitySampleBinding
//save our FastAdapter
private lateinit var fastItemAdapter: GenericFastItemAdapter
private lateinit var mExpandableExtension: ExpandableExtension<IItem<*>>
private lateinit var mSelectExtension: SelectExtension<IItem<*>>
private lateinit var mRangeSelectorHelper: RangeSelectorHelper<*>
private lateinit var mDragSelectTouchListener: DragSelectTouchListener
private var mActionModeHelper: ActionModeHelper<GenericItem>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySampleBinding.inflate(layoutInflater).also {
setContentView(it.root)
}
setSupportActionBar(binding.toolbar)
supportActionBar?.setTitle(R.string.sample_collapsible)
//create our FastAdapter
fastItemAdapter = FastItemAdapter()
mExpandableExtension = fastItemAdapter.getExpandableExtension()
mSelectExtension = fastItemAdapter.getSelectExtension()
mSelectExtension.isSelectable = true
mSelectExtension.multiSelect = true
mSelectExtension.selectOnLongClick = true
fastItemAdapter.onPreClickListener = { _: View?, _: IAdapter<GenericItem>, item: GenericItem, _: Int ->
//we handle the default onClick behavior for the actionMode. This will return null if it didn't do anything and you can handle a normal onClick
val res = mActionModeHelper?.onClick(this@ExpandableMultiselectDeleteSampleActivity, item)
// in this example, we want to consume a click, if the ActionModeHelper will remove the ActionMode
// so that the click listener is not fired
if (res != null && !res) true else res ?: false
}
fastItemAdapter.onClickListener = { _: View?, _: IAdapter<GenericItem>, item: GenericItem, _: Int ->
// check if the actionMode consumes the click. This returns true, if it does, false if not
if (mActionModeHelper?.isActive == false) {
Toast.makeText(this@ExpandableMultiselectDeleteSampleActivity, (item as SimpleSubItem).name.toString() + " clicked!", Toast.LENGTH_SHORT).show()
mRangeSelectorHelper.onClick()
}
false
}
fastItemAdapter.onPreLongClickListener = { _: View, _: IAdapter<GenericItem>, _: GenericItem, position: Int ->
val actionModeWasActive = mActionModeHelper?.isActive ?: false
val actionMode = mActionModeHelper?.onLongClick(this@ExpandableMultiselectDeleteSampleActivity, position)
mRangeSelectorHelper.onLongClick(position)
if (actionMode != null) {
//we want color our CAB
[email protected]<View>(R.id.action_mode_bar).setBackgroundColor(
[email protected](
R.attr.colorPrimary,
ContextCompat.getColor(this, R.color.colorPrimary)
)
)
// start the drag selection
mDragSelectTouchListener.startDragSelection(position)
}
//if we have no actionMode we do not consume the event
actionMode != null && !actionModeWasActive
}
// provide a custom title provider that even shows the count of sub items
mActionModeHelper = ActionModeHelper(fastItemAdapter, R.menu.cab, ActionBarCallBack())
.withTitleProvider(object : ActionModeHelper.ActionModeTitleProvider {
override fun getTitle(selected: Int): String {
return selected.toString() + "/" + SubItemUtil.countItems(fastItemAdapter.itemAdapter, false)
}
})
// this will take care of selecting range of items via long press on the first and afterwards on the last item
mRangeSelectorHelper = RangeSelectorHelper(fastItemAdapter)
.withSavedInstanceState(savedInstanceState)
.withActionModeHelper(mActionModeHelper)
// setup the drag select listener and add it to the RecyclerView
mDragSelectTouchListener = DragSelectTouchListener()
.withSelectListener { start, end, isSelected ->
mRangeSelectorHelper.selectRange(start, end, isSelected, true)
// we handled the long press, so we reset the range selector
mRangeSelectorHelper.reset()
}
binding.rv.addOnItemTouchListener(mDragSelectTouchListener)
// do basic RecyclerView setup
binding.rv.layoutManager = LinearLayoutManager(this)
binding.rv.itemAnimator = SlideDownAlphaAnimator()
binding.rv.adapter = fastItemAdapter
//fill with some sample data
val items = ArrayList<GenericItem>()
for (i in 0..19) {
if (i % 2 == 0) {
val expandableItem = HeaderSelectionItem()
expandableItem.withSubSelectionProvider { SubItemUtil.countSelectedSubItems(fastItemAdapter, expandableItem) }
expandableItem
.withName("Test " + (i + 1))
.withDescription("ID: " + (i + 1))
.identifier = (i + 1).toLong()
//.withIsExpanded(true) don't use this in such a setup, use adapter.expand() to expand all items instead
//add subItems so we can showcase the collapsible functionality
val subItems = LinkedList<ISubItem<*>>()
for (ii in 1..5) {
val sampleItem = SimpleSubItem()
sampleItem
.withName("-- Test " + (i + 1) + "." + ii)
.withDescription("ID: " + ((i + 1) * 100 + ii))
.identifier = ((i + 1) * 100 + ii).toLong()
subItems.add(sampleItem)
}
expandableItem.subItems = subItems
items.add(expandableItem)
} else {
val sampleItem = SimpleSubItem()
sampleItem
.withName("Test " + (i + 1))
.withDescription("ID: " + (i + 1))
.identifier = (i + 1).toLong()
items.add(sampleItem)
}
}
fastItemAdapter.add(items)
mExpandableExtension.expand()
mSelectExtension.selectionListener = object : ISelectionListener<IItem<*>> {
override fun onSelectionChanged(item: IItem<*>, selected: Boolean) {
if (item is SimpleSubItem) {
val headerItem = item.parent
if (headerItem != null) {
val pos = fastItemAdapter.getAdapterPosition(headerItem)
// Important: notify the header directly, not via the notifyAdapterItemChanged!
// we just want to update the view and we are sure, nothing else has to be done
fastItemAdapter.notifyItemChanged(pos)
}
}
}
}
//restore selections (this has to be done after the items were added
fastItemAdapter.withSavedInstanceState(savedInstanceState)
//set the back arrow in the toolbar
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(false)
// restore action mode
if (savedInstanceState != null)
mActionModeHelper?.checkActionMode(this)
}
override fun onSaveInstanceState(_outState: Bundle) {
var outState = _outState
//add the values which need to be saved from the adapter to the bundle
outState = fastItemAdapter.saveInstanceState(outState)
outState = mRangeSelectorHelper.saveInstanceState(outState)
super.onSaveInstanceState(outState)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
//handle the click on the back arrow click
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
internal inner class ActionBarCallBack : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
return true
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
// delete the selected items with the SubItemUtil to correctly handle sub items
// this will even delete empty headers if you want to
SubItemUtil.deleteSelected(fastItemAdapter, mSelectExtension, mExpandableExtension, notifyParent = true, deleteEmptyHeaders = true)
//as we no longer have a selection so the actionMode can be finished
mode.finish()
//we consume the event
return true
}
override fun onDestroyActionMode(mode: ActionMode) {
// reset the range selector
mRangeSelectorHelper.reset()
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
}
}
| apache-2.0 | 85e05ce48a7a0f07a1332305861f7e39 | 45.336207 | 160 | 0.653209 | 5.316518 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/textract/src/main/kotlin/com/kotlin/textract/DetectDocumentText.kt | 1 | 2343 | // snippet-sourcedescription:[DetectDocumentText.kt demonstrates how to detect text in the input document.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Textract]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.textract
// snippet-start:[textract.kotlin._detect_doc_text.import]
import aws.sdk.kotlin.services.textract.TextractClient
import aws.sdk.kotlin.services.textract.model.DetectDocumentTextRequest
import aws.sdk.kotlin.services.textract.model.Document
import java.io.File
import java.io.FileInputStream
import kotlin.system.exitProcess
// snippet-end:[textract.kotlin._detect_doc_text.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<sourceDoc>
Where:
sourceDoc - The path where the document is located (must be an image, for example, C:/AWS/book.png).
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val sourceDoc = args[0]
detectDocText(sourceDoc)
}
// snippet-start:[textract.kotlin._detect_doc_text.main]
suspend fun detectDocText(sourceDoc: String) {
val sourceStream = FileInputStream(File(sourceDoc))
val sourceBytes = sourceStream.readBytes()
// Get the input Document object as bytes.
val myDoc = Document {
bytes = sourceBytes
}
val detectDocumentTextRequest = DetectDocumentTextRequest {
document = myDoc
}
TextractClient { region = "us-east-1" }.use { textractClient ->
val response = textractClient.detectDocumentText(detectDocumentTextRequest)
response.blocks?.forEach { block ->
println("The block type is ${block.blockType}")
}
val documentMetadata = response.documentMetadata
if (documentMetadata != null) {
println("The number of pages in the document is ${documentMetadata.pages}")
}
}
}
// snippet-end:[textract.kotlin._detect_doc_text.main]
| apache-2.0 | a71013b98018eddd6c10c6e276e0d64f | 29.662162 | 109 | 0.685019 | 3.971186 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/usecases/creating_workflows_stepfunctions/src/main/kotlin/example2/HandlerTicket.kt | 1 | 1375 | /*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package example2
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.RequestHandler
import com.google.gson.GsonBuilder
import kotlinx.coroutines.runBlocking
class HandlerTicket: RequestHandler<String, String> {
override fun handleRequest(event: String, context: Context): String = runBlocking {
var phoneNum = "<Enter Mobile number>"
var phoneNum2 = "<Enter Mobile number>"
val logger = context.logger
val gson = GsonBuilder().create()
val value: String = event
logger.log("CASE is about to be assigned $value")
// Create very simple logic to assign case to an employee
val tmp = if (Math.random() <= 0.5) 1 else 2
val perCase = PersistCase()
logger.log("TMP IS $tmp")
var phone = ""
if (tmp == 1) {
// assign to tblue
phone = phoneNum
perCase.putItemInTable(value, "Tom Blue", phone)
} else {
// assign to swhite
phone = phoneNum2
perCase.putItemInTable(value, "Sarah White", phone)
}
logger.log("Phone num IS $phone")
return@runBlocking phone
}
}
| apache-2.0 | afefbef12e06c53438527be4c63e0d5a | 27.891304 | 87 | 0.607273 | 4.323899 | false | false | false | false |
zanata/zanata-platform | server/services/src/main/java/org/zanata/security/ExternalSAMLConfigurationProvider.kt | 1 | 4191 | /*
* Copyright 2017, Red Hat, Inc. and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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 this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.zanata.security
import org.picketlink.common.ErrorCodes
import org.picketlink.common.exceptions.ConfigurationException
import org.picketlink.common.exceptions.ProcessingException
import org.picketlink.config.federation.IDPType
import org.picketlink.config.federation.PicketLinkType
import org.picketlink.config.federation.SPType
import org.picketlink.identity.federation.web.config.AbstractSAMLConfigurationProvider
import org.picketlink.identity.federation.web.util.ConfigurationUtil
import org.slf4j.LoggerFactory
import java.io.File
import java.io.InputStream
import java.net.URL
import java.nio.file.Paths
/**
* This file is responsible to load the picketlink configuration file (path
* given by system property).
*
* @author Patrick Huang
* [[email protected]](mailto:[email protected])
*/
class ExternalSAMLConfigurationProvider : AbstractSAMLConfigurationProvider() {
@Throws(ProcessingException::class)
override fun getIDPConfiguration(): IDPType {
throw RuntimeException(ErrorCodes.ILLEGAL_METHOD_CALLED)
}
@Throws(ProcessingException::class)
override fun getSPConfiguration(): SPType? {
try {
val inputStream: InputStream? = readConfigurationFile()
return inputStream?.use {
ConfigurationUtil.getSPConfiguration(it)
}
} catch (e: Exception) {
throw RuntimeException("Could not load SP configuration: $configurationFilePath", e)
}
}
@Throws(ProcessingException::class)
override fun getPicketLinkConfiguration(): PicketLinkType? {
try {
val inputStream: InputStream? = readConfigurationFile()
return inputStream?.use {
ConfigurationUtil.getConfiguration(it)
}
} catch (e: Exception) {
throw RuntimeException(
"Could not load PicketLink configuration: $configurationFilePath", e)
}
}
companion object {
private val log = LoggerFactory.getLogger(ExternalSAMLConfigurationProvider::class.java)
private val configFile: String? = System.getProperty("picketlink.file")
// Returns the picketlink configuration file path including protocol.
private val configurationFilePath: URL by lazy { Paths.get(configFile).toUri().toURL() }
private fun isFileExists(filePath: String): Boolean {
val file = File(filePath)
return file.exists() && file.canRead()
}
@Throws(ConfigurationException::class)
private fun readConfigurationFile(): InputStream? {
if (configFile == null || !isFileExists(configFile)) {
log.info("picketlink.xml can not be found: {}", configFile)
return null
}
return try {
val configurationFileURL: URL = Thread.currentThread()
.contextClassLoader.getResource(configFile) ?: configurationFilePath
configurationFileURL.openStream()
} catch (e: Exception) {
throw RuntimeException(
"The file could not be loaded: $configFile", e)
}
}
}
}
| lgpl-2.1 | 4f388fb56ead095cd421ce1499542931 | 37.449541 | 96 | 0.687664 | 4.630939 | false | true | false | false |
paplorinc/intellij-community | plugins/settings-repository/src/git/JGitCredentialsProvider.kt | 3 | 5426 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.settingsRepository.git
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.intellij.credentialStore.Credentials
import com.intellij.credentialStore.isFulfilled
import com.intellij.credentialStore.isMacOsCredentialStoreSupported
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.util.text.nullize
import com.intellij.util.ui.UIUtil
import kotlinx.coroutines.runBlocking
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.transport.CredentialItem
import org.eclipse.jgit.transport.CredentialsProvider
import org.eclipse.jgit.transport.URIish
import org.jetbrains.settingsRepository.IcsCredentialsStore
import org.jetbrains.settingsRepository.catchAndLog
import org.jetbrains.settingsRepository.showAuthenticationForm
import java.util.concurrent.TimeUnit
class JGitCredentialsProvider(private val credentialsStore: Lazy<IcsCredentialsStore>, private val repository: Repository) : CredentialsProvider() {
private val credentialsFromGit = CacheBuilder.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES)
.build(object : CacheLoader<URIish, Credentials>() {
override fun load(it: URIish) = getCredentialsUsingGit(it, repository) ?: Credentials(null)
})
override fun isInteractive(): Boolean = true
override fun supports(vararg items: CredentialItem): Boolean {
for (item in items) {
if (item is CredentialItem.Password || item is CredentialItem.Username || item is CredentialItem.StringType || item is CredentialItem.YesNoType) {
continue
}
return false
}
return true
}
override fun get(uri: URIish, vararg items: CredentialItem): Boolean {
var userNameItem: CredentialItem.Username? = null
var passwordItem: CredentialItem? = null
var sshKeyFile: String? = null
for (item in items) {
if (item is CredentialItem.Username) {
userNameItem = item
}
else if (item is CredentialItem.Password) {
passwordItem = item
}
else if (item is CredentialItem.StringType) {
val promptText = item.promptText
if (promptText != null) {
val marker = "Passphrase for "
if (promptText.startsWith(marker) /* JSch prompt */) {
sshKeyFile = promptText.substring(marker.length)
passwordItem = item
continue
}
}
}
else if (item is CredentialItem.YesNoType) {
UIUtil.invokeAndWaitIfNeeded(Runnable {
item.value = MessageDialogBuilder.yesNo("", item.promptText!!).show() == Messages.YES
})
return true
}
}
if (userNameItem == null && passwordItem == null) {
return false
}
return runBlocking { doGet(uri, userNameItem, passwordItem, sshKeyFile) }
}
private suspend fun doGet(uri: URIish, userNameItem: CredentialItem.Username?, passwordItem: CredentialItem?, sshKeyFile: String?): Boolean {
var credentials: Credentials? = null
// SSH URL [email protected]:develar/_idea_settings.git, so, username will be "git", we ignore it because in case of SSH credentials account name equals to key filename, but not to username
val userFromUri: String? = if (sshKeyFile == null) uri.user.nullize() else null
val passwordFromUri: String? = uri.pass.nullize()
if (userFromUri != null && passwordFromUri != null) {
credentials = Credentials(userFromUri, passwordFromUri)
}
else {
catchAndLog {
credentials = credentialsStore.value.get(uri.host, sshKeyFile, userFromUri)
// we open password protected SSH key file using OS X keychain - "git credentials" is pointless in this case
if (!credentials.isFulfilled() && (sshKeyFile == null || !isMacOsCredentialStoreSupported)) {
credentials = credentialsFromGit.get(uri)
}
}
}
if (!credentials.isFulfilled()) {
credentials = showAuthenticationForm(credentials, uri.toStringWithoutCredentials(), uri.host, uri.path, sshKeyFile)
if (credentials.isFulfilled()) {
credentialsStore.value.set(uri.host, sshKeyFile, credentials)
}
}
userNameItem?.value = credentials?.userName
if (passwordItem != null) {
if (passwordItem is CredentialItem.Password) {
passwordItem.value = credentials?.password?.toCharArray()
}
else {
(passwordItem as CredentialItem.StringType).value = credentials?.password?.toString()
}
}
return credentials.isFulfilled()
}
override fun reset(uri: URIish) {
credentialsFromGit.invalidate(uri)
credentialsFromGit.cleanUp()
credentialsStore.value.set(uri.host!!, null, null)
}
}
private fun URIish.toStringWithoutCredentials(): String {
val r = StringBuilder()
if (scheme != null) {
r.append(scheme)
r.append("://")
}
if (host != null) {
r.append(host)
if (scheme != null && port > 0) {
r.append(':')
r.append(port)
}
}
if (path != null) {
if (scheme != null) {
if (!path!!.startsWith("/")) {
r.append('/')
}
}
else if (host != null) {
r.append(':')
}
r.append(if (scheme != null) rawPath else path)
}
return r.toString()
}
| apache-2.0 | 4bc9636b7ae6f568ca826be7096dc7ee | 34.697368 | 190 | 0.688537 | 4.559664 | false | false | false | false |
algra/pact-jvm | pact-jvm-matchers/src/main/kotlin/au/com/dius/pact/matchers/MultipartMessageBodyMatcher.kt | 1 | 3112 | package au.com.dius.pact.matchers
import au.com.dius.pact.model.HttpPart
import au.com.dius.pact.model.isEmpty
import au.com.dius.pact.model.isMissing
import au.com.dius.pact.model.isNotPresent
import au.com.dius.pact.model.isPresent
import au.com.dius.pact.model.orElse
import java.util.Enumeration
import javax.mail.BodyPart
import javax.mail.Header
import javax.mail.internet.MimeMultipart
import javax.mail.util.ByteArrayDataSource
class MultipartMessageBodyMatcher : BodyMatcher {
override fun matchBody(expected: HttpPart, actual: HttpPart, allowUnexpectedKeys: Boolean): List<BodyMismatch> {
val expectedBody = expected.body
val actualBody = actual.body
return when {
expectedBody.isMissing() -> emptyList()
expectedBody.isPresent() && actualBody.isNotPresent() -> listOf(BodyMismatch(expectedBody.orElse(""),
null, "Expected a multipart body but was missing"))
expectedBody.isEmpty() && actualBody.isEmpty() -> emptyList()
else -> {
val expectedMultipart = parseMultipart(expectedBody.orElse(""), expected.contentTypeHeader().orEmpty())
val actualMultipart = parseMultipart(actualBody.orElse(""), actual.contentTypeHeader().orEmpty())
compareHeaders(expectedMultipart, actualMultipart) + compareContents(expectedMultipart, actualMultipart)
}
}
}
private fun compareContents(expectedMultipart: BodyPart, actualMultipart: BodyPart): List<BodyMismatch> {
val expectedContents = expectedMultipart.content.toString().trim()
val actualContents = actualMultipart.content.toString().trim()
return when {
expectedContents.isEmpty() && actualContents.isEmpty() -> emptyList()
expectedContents.isNotEmpty() && actualContents.isNotEmpty() -> emptyList()
expectedContents.isEmpty() && actualContents.isNotEmpty() -> listOf(BodyMismatch(expectedContents,
actualContents, "Expected no contents, but received ${actualContents.toByteArray().size} bytes of content"))
else -> listOf(BodyMismatch(expectedContents,
actualContents, "Expected content with the multipart, but received no bytes of content"))
}
}
private fun compareHeaders(expectedMultipart: BodyPart, actualMultipart: BodyPart): List<BodyMismatch> {
val mismatches = mutableListOf<BodyMismatch>()
(expectedMultipart.allHeaders as Enumeration<Header>).asSequence().forEach {
val header = actualMultipart.getHeader(it.name)
if (header != null) {
val actualValue = header.joinToString(separator = ", ")
if (actualValue != it.value) {
mismatches.add(BodyMismatch(it.toString(), null,
"Expected a multipart header '${it.name}' with value '${it.value}', but was '$actualValue'"))
}
} else {
mismatches.add(BodyMismatch(it.toString(), null, "Expected a multipart header '${it.name}', but was missing"))
}
}
return mismatches
}
private fun parseMultipart(body: String, contentType: String): BodyPart {
val multipart = MimeMultipart(ByteArrayDataSource(body, contentType))
return multipart.getBodyPart(0)
}
}
| apache-2.0 | f49eda01b67ead761c64769e8c0fc883 | 44.764706 | 118 | 0.725257 | 4.510145 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Coord.kt | 1 | 2777 | package org.runestar.client.updater.mapper.std.classes
import org.objectweb.asm.Opcodes.GETFIELD
import org.objectweb.asm.Opcodes.IOR
import org.objectweb.asm.Type.BOOLEAN_TYPE
import org.objectweb.asm.Type.INT_TYPE
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.mark
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
class Coord : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == Any::class.type }
.and { it.instanceFields.size == 3 }
.and { it.instanceFields.all { it.type == INT_TYPE } }
.and { it.instanceMethods.any { it.mark == Any::hashCode.mark } }
// class set : IdentityMapper.InstanceMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
// .and { it.arguments.startsWith(INT_TYPE, INT_TYPE, INT_TYPE) }
// .and { it.arguments.size in 3..4 }
// }
@DependsOn(toString0::class)
class y : OrderMapper.InMethod.Field(toString0::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == INT_TYPE }
}
@DependsOn(toString0::class)
class x : OrderMapper.InMethod.Field(toString0::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == INT_TYPE }
}
@DependsOn(toString0::class)
class z : OrderMapper.InMethod.Field(toString0::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == INT_TYPE }
}
@MethodParameters("separator")
class toString0 : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == String::class.type }
.and { it.arguments == listOf(String::class.type) }
}
@MethodParameters("other")
class equals0 : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
.and { it.arguments == listOf(type<Coord>()) }
}
@MethodParameters()
class packed : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE }
.and { it.instructions.any { it.opcode == IOR } }
}
} | mit | f63186f2260f84c938df35c4a247b7be | 43.095238 | 112 | 0.692834 | 3.989943 | false | false | false | false |
apollographql/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/IncomingOptions.kt | 1 | 2488 | package com.apollographql.apollo3.compiler
import com.apollographql.apollo3.annotations.ApolloExperimental
import com.apollographql.apollo3.ast.GQLDocument
import com.apollographql.apollo3.ast.GQLSchemaDefinition
import com.apollographql.apollo3.ast.GQLTypeDefinition
import com.apollographql.apollo3.ast.Schema
import com.apollographql.apollo3.ast.apolloDefinitions
import com.apollographql.apollo3.ast.validateAsSchema
import com.apollographql.apollo3.compiler.introspection.toGQLDocument
import com.apollographql.apollo3.compiler.introspection.toSchema
import com.apollographql.apollo3.compiler.introspection.toSchemaGQLDocument
import java.io.File
/**
* These are the options that should be the same in all modules.
*/
class IncomingOptions(
val schema: Schema,
val codegenModels: String,
val schemaPackageName: String,
) {
companion object {
fun fromMetadata(commonMetadata: CommonMetadata, packageNameGenerator: PackageNameGenerator): IncomingOptions {
return IncomingOptions(
schema = commonMetadata.schema,
codegenModels = commonMetadata.codegenModels,
schemaPackageName = packageNameGenerator.packageName(commonMetadata.schemaPath)
)
}
@OptIn(ApolloExperimental::class)
fun resolveSchema(schemaFiles: Collection<File>, rootFolders: List<String>): Pair<Schema, String> {
check(schemaFiles.isNotEmpty()) {
"No schema file found in:\n${rootFolders.joinToString("\n")}"
}
val schemaDocuments = schemaFiles.map {
it.toSchemaGQLDocument()
}
// Locate the mainSchemaDocument. It's the one that contains the operation roots
val mainSchemaDocuments = schemaDocuments.filter {
it.definitions.filterIsInstance<GQLSchemaDefinition>().isNotEmpty()
|| it.definitions.filterIsInstance<GQLTypeDefinition>().any { it.name == "Query" }
}
check(mainSchemaDocuments.size == 1) {
"Multiple schemas found:\n${mainSchemaDocuments.map { it.filePath }.joinToString("\n")}\n" +
"Use different services for different schemas"
}
val mainSchemaDocument = mainSchemaDocuments.single()
val schemaDefinitions = schemaDocuments.flatMap { it.definitions }
val schemaDocument = GQLDocument(
definitions = schemaDefinitions + apolloDefinitions(),
filePath = null
)
return schemaDocument.validateAsSchema().valueAssertNoErrors() to mainSchemaDocument.filePath!!
}
}
} | mit | 9179785db4f2e9869410a41f32975f69 | 37.890625 | 115 | 0.740756 | 4.633147 | false | false | false | false |
JetBrains/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/CreateMemberAction.kt | 1 | 3339 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.java.actions
import com.intellij.codeInsight.intention.FileModifier
import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.actions.ActionRequest
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.createSmartPointer
import com.intellij.util.ReflectionUtil
internal abstract class CreateTargetAction<T : PsiElement>(
target: T,
@SafeFieldForPreview protected open val request: ActionRequest
) : IntentionAction, Cloneable {
@SafeFieldForPreview
private val myTargetPointer = target.createSmartPointer()
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
return myTargetPointer.element != null && request.isValid
}
protected val target: T
get() = requireNotNull(myTargetPointer.element) {
"Don't access this property if isAvailable() returned false"
}
override fun getElementToMakeWritable(currentFile: PsiFile): PsiElement? = target
/**
* This implementation clones current intention replacing [myTargetPointer]
* field value with the pointer to the corresponding element
* in the target file. It returns null if subclass has potentially unsafe fields not
* marked with [@SafeFieldForPreview][SafeFieldForPreview].
*/
override fun getFileModifierForPreview(target: PsiFile): FileModifier? {
// Check field safety in subclass
if (super.getFileModifierForPreview(target) !== this) return null
val oldElement: PsiElement = this.target
if (target.originalFile != oldElement.containingFile) {
throw IllegalStateException("Intention action ${this::class} ($familyName) refers to the element from another source file. " +
"It's likely that it's going to modify a file not opened in the editor, " +
"so default preview strategy won't work. Also, if another file is modified, " +
"getElementToMakeWritable() must be properly implemented to denote the actual file " +
"to be modified.")
}
val newElement = PsiTreeUtil.findSameElementInCopy(oldElement, target)
val clone = try {
super.clone() as CreateTargetAction<*>
} catch (e: CloneNotSupportedException) {
throw InternalError(e) // should not happen as we implement Cloneable
}
if (!ReflectionUtil.setField(
CreateTargetAction::class.java, clone, SmartPsiElementPointer::class.java, "myTargetPointer",
newElement.createSmartPointer()
)) {
return null
}
return clone
}
override fun startInWriteAction(): Boolean = true
}
internal abstract class CreateMemberAction(target: PsiClass, request: ActionRequest
) : CreateTargetAction<PsiClass>(target, request) {
open fun getTarget(): JvmClass = target
}
| apache-2.0 | 650f01d2d303c2cb86617329387d89ea | 41.807692 | 140 | 0.734052 | 4.860262 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/domain/course_search/model/CourseSearchResult.kt | 1 | 656 | package org.stepik.android.domain.course_search.model
import org.stepik.android.model.Lesson
import org.stepik.android.model.Progress
import org.stepik.android.model.SearchResult
import org.stepik.android.model.Section
import org.stepik.android.model.user.User
import org.stepik.android.model.Unit
import ru.nobird.app.core.model.Identifiable
data class CourseSearchResult(
val searchResult: SearchResult,
val lesson: Lesson? = null,
val progress: Progress? = null,
val unit: Unit? = null,
val section: Section? = null,
val commentOwner: User? = null
) : Identifiable<Long> {
override val id: Long =
searchResult.id
}
| apache-2.0 | 9e8ab6d67bffabe2a99e011e16d96ccf | 30.238095 | 53 | 0.751524 | 3.727273 | false | false | false | false |
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/service/AuroraDeploymentSpecConfigFieldValidator.kt | 1 | 3332 | package no.skatteetaten.aurora.boober.service
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import mu.KotlinLogging
import no.skatteetaten.aurora.boober.model.AuroraConfigField
import no.skatteetaten.aurora.boober.model.AuroraConfigFieldHandler
import no.skatteetaten.aurora.boober.model.AuroraConfigFile
import no.skatteetaten.aurora.boober.model.ConfigFieldErrorDetail
import no.skatteetaten.aurora.boober.utils.findAllPointers
private val logger = KotlinLogging.logger {}
class AuroraDeploymentSpecConfigFieldValidator(
val applicationFiles: List<AuroraConfigFile>,
val fieldHandlers: Set<AuroraConfigFieldHandler>,
val fields: Map<String, AuroraConfigField>
) {
fun validate(fullValidation: Boolean = true): List<ConfigFieldErrorDetail> {
val errors: List<ConfigFieldErrorDetail> = fieldHandlers.mapNotNull { e ->
val rawField = fields[e.name]
if (rawField == null) {
e.validator(null)?.let {
ConfigFieldErrorDetail.missing(it.localizedMessage, e.name)
}
} else {
val fieldDeclaredInAllowedFile: Boolean = rawField.run { isDefault || e.isAllowedFileType(fileType) }
logger.trace("Validating field=${e.name}")
val auroraConfigField: JsonNode = rawField.value
logger.trace("value is=${jacksonObjectMapper().writeValueAsString(auroraConfigField)}")
val result = e.validator(auroraConfigField)
logger.trace("validator result is=$result")
val err = when {
!fieldDeclaredInAllowedFile ->
ConfigFieldErrorDetail.forSeverity(
"Invalid Source field=${e.name}. Actual source=${rawField.name} (File type: ${rawField.fileType}). Must be placed within files of type: ${e.allowedFilesTypes}",
e.name,
rawField,
e.validationSeverity
)
result == null -> null
auroraConfigField != null -> ConfigFieldErrorDetail.illegal(
result.localizedMessage,
e.name,
rawField
)
else -> ConfigFieldErrorDetail.missing(result.localizedMessage, e.name)
}
if (err != null) {
logger.trace("Error=$err message=${err.message}")
}
err
}
}
// TODO test unmapped
val unmappedErrors = if (fullValidation) {
getUnmappedPointers().flatMap { pointerError ->
pointerError.value.map { ConfigFieldErrorDetail.invalid(pointerError.key, it) }
}
} else {
emptyList()
}
return errors + unmappedErrors
}
private fun getUnmappedPointers(): Map<String, List<String>> {
val allPaths = fieldHandlers.map { "/${it.name}" }
val filePointers = applicationFiles.associateBy({ it.configName }, { it.asJsonNode.findAllPointers(3) })
return filePointers.mapValues { it.value - allPaths }.filterValues { it.isNotEmpty() }
}
}
| apache-2.0 | 0c1aeba05405bd0c06bd678f6c1001c1 | 40.135802 | 188 | 0.602341 | 5.18196 | false | true | false | false |
ahjsrhj/ShareToQRCode | app/src/main/java/cn/imrhj/sharetoqrcode/util/ExtensionUtils.kt | 1 | 483 | package cn.imrhj.sharetoqrcode.util
import java.io.BufferedReader
val BufferedReader.lines: Iterator<String>
get() = object : Iterator<String> {
var line = [email protected]()
override fun next(): String {
if (line == null) {
throw NoSuchElementException()
}
val result = line
line = [email protected]()
return result
}
override fun hasNext() = line != null
} | apache-2.0 | ff7b2b4697752ce2c1a540bbd4954506 | 24.473684 | 46 | 0.559006 | 4.644231 | false | false | false | false |
ids1024/whitakers-words-android | src/main/java/com/ids1024/whitakerswords/parse_words.kt | 1 | 2927 | package com.ids1024.whitakerswords
import android.graphics.Color
import android.graphics.Typeface
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
/**
* Parses plain text from `words` to add basic formatting (such as italics).
*/
fun parse_words(input: String): ArrayList<SpannableStringBuilder> {
val results = ArrayList<SpannableStringBuilder>()
var processed_result = SpannableStringBuilder()
for (line in input.split("\n".toRegex())) {
val words = line.split(" +".toRegex())
var handled_line = TextUtils.join(" ", words)
var pearse_code = 0
if (words.isNotEmpty() && words[0].length == 2) {
try {
pearse_code = Integer.parseInt(words[0])
handled_line = handled_line.substring(3)
} catch (e: NumberFormatException) {
}
}
// Indent meanings
if (pearse_code == 3) {
handled_line = " $handled_line"
}
if (line.isEmpty() || line == "*") {
if (line == "*") {
processed_result.append("*")
}
val finalresult = processed_result.toString().trim()
if (finalresult.isNotEmpty()) {
results.add(processed_result)
}
processed_result = SpannableStringBuilder()
continue
}
val startindex = processed_result.length
processed_result.append(handled_line + "\n")
var span: Any? = null
var endindex = processed_result.length
when (pearse_code) {
// Forms
1 -> {
span = StyleSpan(Typeface.BOLD)
endindex = startindex + words[1].length
}
// Dictionary forms
2 -> {
// A HACK(?) for parsing output of searches like
// "quod", which show shorter output for dictionary forms
if (!words[1].startsWith("[")) {
var index = 1
endindex = startindex
do {
endindex += words[index].length + 1
index += 1
} while (words[index - 1].endsWith(","))
span = StyleSpan(Typeface.BOLD)
}
}
// Meaning
3 -> span = StyleSpan(Typeface.ITALIC)
// Not found
4 -> span = ForegroundColorSpan(Color.RED)
// Addons
5 -> {
}
// Tricks/syncope/addons?
6 -> {
}
}
processed_result.setSpan(span, startindex, endindex, 0)
}
val finalresult = processed_result.toString().trim()
if (finalresult.isNotEmpty()) {
results.add(processed_result)
}
return results
}
| mit | 87050bdd850fde6fa9c4f96e3f161144 | 31.522222 | 75 | 0.519986 | 4.736246 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.