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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kohesive/kovert | vertx/src/main/kotlin/uy/kohesive/kovert/vertx/internal/ControllerDispatch.kt | 1 | 12178 | package uy.kohesive.kovert.vertx.internal
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.type.TypeFactory
import io.netty.handler.codec.http.HttpHeaderNames
import io.vertx.core.json.Json
import io.vertx.core.logging.Logger
import io.vertx.ext.web.Route
import nl.komponents.kovenant.Promise
import nl.komponents.kovenant.task
import uy.klutter.conversion.TypeConversionConfig
import uy.klutter.core.common.mustNotStartWith
import uy.klutter.reflect.isAssignableFrom
import uy.klutter.reflect.unwrapInvokeException
import uy.kohesive.kovert.core.*
import uy.kohesive.kovert.vertx.ContextFactory
import uy.kohesive.kovert.vertx.InterceptDispatch
import kotlin.reflect.KCallable
import kotlin.reflect.KParameter
import kotlin.reflect.jvm.jvmErasure
@Suppress("UNCHECKED_CAST")
internal fun setHandlerDispatchWithDataBinding(
route: Route, logger: Logger,
controller: Any, member: Any, dispatchInstance: Any,
dispatchFunction: KCallable<*>,
contextFactory: ContextFactory<*>,
disallowVoid: Boolean, defaultSuccessStatus: Int,
rendererInfo: RendererInfo
) {
val JSON: ObjectMapper = Json.mapper
route.handler { routeContext ->
val requestContext = contextFactory.createContext(routeContext)
val request = routeContext.request()
val useValuesInOrder = mutableListOf<Any?>()
val useValuesByName = hashMapOf<KParameter, Any?>()
var usedBodyJsonAlready = false
fun useValueForParm(param: KParameter, value: Any?) {
useValuesInOrder.add(value)
useValuesByName.put(param, value)
}
try {
for (param in dispatchFunction.parameters) {
if (param.kind == KParameter.Kind.INSTANCE) {
useValueForParm(param, dispatchInstance)
} else if (param.kind == KParameter.Kind.EXTENSION_RECEIVER) {
useValueForParm(param, requestContext)
} else if (isSimpleDataType(param.type) || isEnum(param.type)) {
val missing = request.params().contains(param.name).not()
if (missing && param.isOptional) {
// this is ok, optional parameter not resolved will have default value
} else {
val parmVal = request.getParam(param.name)
if ((missing || parmVal == null) && !param.isOptional && !param.type.isMarkedNullable) {
throw HttpErrorCode(
"Expected parameter ${param.name} for non optional and non nullable parameter, but parameter is missing for [$dispatchFunction]",
400
)
}
if (parmVal != null) {
try {
val temp: Any = TypeConversionConfig.defaultConverter.convertValue<Any, Any>(
parmVal.javaClass,
param.type.jvmErasure.java,
parmVal
)
//val temp: Any = JSON.convertValue<Any>(parmVal, TypeFactory.defaultInstance().constructType(param.type.javaType))
useValueForParm(param, temp)
} catch (ex: Exception) {
throw RuntimeException("Data binding failed due to: ${ex.message} for [$dispatchFunction]")
}
} else {
useValueForParm(param, null)
}
}
} else {
// see if parameter has prefixed values in the input parameters that match
val parmPrefix = param.name + "."
val tempMap = request.params().entries().filter { it.key.startsWith(parmPrefix) }
.map { it.key.mustNotStartWith(parmPrefix) to it.value }.toMap()
val bodyJson = routeContext.getBodyAsString()
val hasBodyJson = bodyJson.isNullOrBlank().not()
val hasPrefixParams = tempMap.isNotEmpty()
val hasMultiPartForm = request.isExpectMultipart()
if (!hasPrefixParams && (!hasBodyJson || usedBodyJsonAlready) && param.isOptional) {
// this is ok, optional parameter not resolved will have default value
} else if (hasPrefixParams) {
// TODO: later but for each property: val temp: Any = TypeConversionConfig.defaultConverter.convertValue<Any, Any>(parmVal.javaClass, param.type.jvmErasure.java, parmVal)
val temp: Any = JSON.convertValue<Any>(
tempMap,
TypeFactory.defaultInstance().constructType(param.type.jvmErasure.java)
)
useValueForParm(param, temp)
} else if (usedBodyJsonAlready) {
throw HttpErrorCode("Already consumed JSON Body, and cannot bind parameter ${param.name} from incoming path, query or multipart form parameters for [$dispatchFunction]")
} else if (routeContext.request().getHeader(HttpHeaderNames.CONTENT_TYPE) != "application/json" &&
!routeContext.request().getHeader(HttpHeaderNames.CONTENT_TYPE).startsWith("application/json;")
) {
throw HttpErrorCode("No JSON Body obviously present (Content-Type header application/json missing), cannot bind parameter ${param.name} from incoming path, query or multipart form parameters for [$dispatchFunction]")
} else {
try {
usedBodyJsonAlready = true
val temp: Any = JSON.readValue(
routeContext.getBodyAsString(),
TypeFactory.defaultInstance().constructType(param.type.jvmErasure.java)
)
useValueForParm(param, temp)
} catch (ex: Throwable) {
throw HttpErrorCode(
"cannot bind parameter ${param.name} from incoming data, expected valid JSON. Failed due to ${ex.message} for [$dispatchFunction]",
causedBy = ex
)
}
}
}
}
} catch (rawEx: Throwable) {
val ex = unwrapInvokeException(rawEx)
routeContext.fail(ex)
return@handler
}
fun sendStringResponse(result: String, contentType: String) {
if (routeContext.response().getStatusCode() == 200) {
routeContext.response().setStatusCode(defaultSuccessStatus)
}
routeContext.response().putHeader(HttpHeaderNames.CONTENT_TYPE, contentType).end(result)
}
fun sendResponse(result: Any?) {
if (disallowVoid
&& (dispatchFunction.returnType.jvmErasure.simpleName == "void"
|| dispatchFunction.returnType.jvmErasure.simpleName == "Unit")
) {
routeContext.fail(RuntimeException("Failure after invocation of route function: A route without a return type must redirect. for [$dispatchFunction]"))
return
} else if (dispatchFunction.returnType.jvmErasure.isAssignableFrom(String::class) || result is String) {
val contentType = routeContext.response().headers().get(HttpHeaderNames.CONTENT_TYPE)
?: routeContext.getAcceptableContentType()
// ?: producesContentType.nullIfBlank()
?: "text/html"
if (result == null) {
routeContext.fail(RuntimeException("Handler did not return any content, only a null which for HTML doesn't really make sense. for [$dispatchFunction]"))
return
}
sendStringResponse(result as String, contentType)
} else {
// at this point we really just need to make a JSON object because we have data not text
// TODO: should we check if getAcceptableContentType() conflicts with application/json
// TODO: should we check if the produces content type conflicts with application/json
// TODO: we now return what they want as content type, but we are really creating JSON
if (routeContext.response().getStatusCode() == 200) {
routeContext.response().setStatusCode(defaultSuccessStatus)
}
val contentType = routeContext.getAcceptableContentType()
?: /* producesContentType.nullIfBlank() ?: */ "application/json"
if (result is Void || result is Unit || result is Nothing) {
routeContext.response().putHeader(HttpHeaderNames.CONTENT_TYPE, contentType).end()
} else {
routeContext.response().putHeader(HttpHeaderNames.CONTENT_TYPE, contentType)
.end(JSON.writeValueAsString(result))
}
}
}
fun prepareResponse(result: Any?) {
if (rendererInfo.enabled) {
val (engine, template, model) = if (rendererInfo.dynamic) {
if (result is ModelAndTemplateRendering<*>) {
Triple(KovertConfig.engineForTemplate(result.template), result.template, result.model)
} else {
throw Exception("The method with dynamic rendering did not return a ModelAndRenderTemplate for [$dispatchFunction]")
}
} else {
// TODO: maybe a better exception here if one of these !! assertions could really fail, think only result!! could fail
Triple(rendererInfo.engine!!, rendererInfo.template!!, result!!)
}
task { engine.templateEngine.render(template, model) }.success { output ->
sendStringResponse(output, rendererInfo.overrideContentType ?: engine.contentType)
}.fail { rawEx ->
val ex = unwrapInvokeException(rawEx)
routeContext.fail(ex)
}
} else {
sendResponse(result)
}
}
fun invokeDispatchFunction(): Any? {
return if (useValuesInOrder.size == dispatchFunction.parameters.size) {
dispatchFunction.call(*useValuesInOrder.toTypedArray())
} else {
dispatchFunction.callBy(useValuesByName)
}
}
try {
// dispatch via intercept, or directly depending on the controller
val result: Any? = if (controller is InterceptDispatch<*>) {
(controller as InterceptDispatch<Any>)._internal(requestContext, member, {
invokeDispatchFunction()
})
} else {
invokeDispatchFunction()
}
// if a promise, need to wait for it to succeed or fail
if (result != null && result is Promise<*, *>) {
(result as Promise<Any, Throwable>).success { promisedResult ->
prepareResponse(promisedResult)
}.fail { rawEx ->
val ex = unwrapInvokeException(rawEx)
routeContext.fail(ex)
}
return@handler
} else {
prepareResponse(result)
return@handler
}
} catch (rawEx: Throwable) {
val ex = unwrapInvokeException(rawEx)
routeContext.fail(ex)
return@handler
}
}
}
| mit | 057779b1f855ca545024a823c1fb0f38 | 47.907631 | 240 | 0.555674 | 5.483116 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/export/ExportDialogsFactory.kt | 2 | 1886 | /*
Copyright (c) 2021 Tarek Mohamed Abdalla <[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.export
import androidx.fragment.app.Fragment
import com.ichi2.anki.dialogs.ExportCompleteDialog
import com.ichi2.anki.dialogs.ExportCompleteDialog.ExportCompleteDialogListener
import com.ichi2.anki.dialogs.ExportDialog
import com.ichi2.anki.dialogs.ExportDialog.ExportDialogListener
import com.ichi2.utils.ExtendedFragmentFactory
internal class ExportDialogsFactory(
private val exportCompleteDialogListener: ExportCompleteDialogListener,
private val exportDialogListener: ExportDialogListener
) : ExtendedFragmentFactory() {
override fun instantiate(classLoader: ClassLoader, className: String): Fragment {
val cls = loadFragmentClass(classLoader, className)
if (cls == ExportDialog::class.java) {
return newExportDialog()
}
return if (cls == ExportCompleteDialog::class.java) {
newExportCompleteDialog()
} else super.instantiate(classLoader, className)
}
fun newExportDialog(): ExportDialog {
return ExportDialog(exportDialogListener)
}
fun newExportCompleteDialog(): ExportCompleteDialog {
return ExportCompleteDialog(exportCompleteDialogListener)
}
}
| gpl-3.0 | 3ceff2ccc017de43313773177f71826f | 39.12766 | 85 | 0.767232 | 4.622549 | false | false | false | false |
yichen0831/RobotM | core/src/game/robotm/gamesys/ObjBuilder.kt | 1 | 25298 | package game.robotm.gamesys
import com.badlogic.ashley.core.Engine
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.graphics.g2d.Animation
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.*
import com.badlogic.gdx.utils.Array
import game.robotm.ecs.components.*
import java.util.*
object ObjBuilder {
/* Render Order
* Floor: 2 (first / bottom)
* Player: 3
* Spike, Spring, Item: 4
* Wall: 5
* Ceiling & Ring-saw: 6 (last / top)
* Player explosion pieces: 7, 8, 9
*/
var assetManager: AssetManager? = null
var world: World? = null
var engine: Engine? = null
val tmpVec1 = Vector2()
val tmpVec2 = Vector2()
fun createPlayer(x: Float, y: Float) {
val scale = GM.PLAYER_SCALE
val bodyDef = BodyDef()
bodyDef.type = BodyDef.BodyType.DynamicBody
bodyDef.position.set(x, y)
bodyDef.fixedRotation = true
val body = world!!.createBody(bodyDef)
val boxShape = PolygonShape()
boxShape.setAsBox(0.3f * scale, 0.3f * scale)
val fixtureDef = FixtureDef()
fixtureDef.shape = boxShape
fixtureDef.density = 0.5f
fixtureDef.filter.categoryBits = GM.CATEGORY_BITS_PLAYER.toShort()
fixtureDef.filter.maskBits = GM.MASK_BITS_PLAYER.toShort()
fixtureDef.friction = 0f
body.createFixture(fixtureDef)
boxShape.dispose()
val edgeShape = EdgeShape()
// sides
edgeShape.set(tmpVec1.set(-0.45f, 0.3f).scl(scale), tmpVec2.set(-0.45f, -0.36f).scl(scale))
fixtureDef.shape = edgeShape
fixtureDef.friction = 0f
fixtureDef.filter.categoryBits = GM.CATEGORY_BITS_PLAYER.toShort()
fixtureDef.filter.maskBits = GM.MASK_BITS_PLAYER.toShort()
body.createFixture(fixtureDef)
edgeShape.set(tmpVec1.set(0.45f, 0.3f).scl(scale), tmpVec2.set(0.45f, -0.36f).scl(scale))
fixtureDef.shape = edgeShape
body.createFixture(fixtureDef)
// feet
edgeShape.set(tmpVec1.set(-0.45f, -0.375f).scl(scale), tmpVec2.set(0.45f, -0.375f).scl(scale))
fixtureDef.shape = edgeShape
fixtureDef.friction = 0.8f
body.createFixture(fixtureDef)
edgeShape.dispose()
val textureRegion = assetManager!!.get("img/actors.atlas", TextureAtlas::class.java).findRegion("RobotM")
val animations = HashMap<String, Animation>()
var anim: Animation
var keyFrames = Array<TextureRegion>()
// idle animation
keyFrames.add(TextureRegion(textureRegion, 64 * 3, 0, 64, 48))
anim = Animation(0.1f, keyFrames, Animation.PlayMode.LOOP)
animations.put("idle", anim)
keyFrames.clear()
// move animation
for (i in 0..1) {
keyFrames.add(TextureRegion(textureRegion, 64 * (3 + i), 0, 64, 48))
}
anim = Animation(0.1f, keyFrames, Animation.PlayMode.LOOP)
animations.put("move", anim)
keyFrames.clear()
// fall animation
keyFrames.add(TextureRegion(textureRegion, 64 * 6, 0, 64, 48))
anim = Animation(0.1f, keyFrames, Animation.PlayMode.LOOP)
animations.put("fall", anim)
keyFrames.clear()
// idle animation (damaged)
keyFrames.add(TextureRegion(textureRegion, 64 * 3, 0, 64, 48))
keyFrames.add(TextureRegion(textureRegion, 64 * 11, 0, 64, 48))
anim = Animation(0.05f, keyFrames, Animation.PlayMode.LOOP)
animations.put("idle_damaged", anim)
// move animation (damaged)
keyFrames.add(TextureRegion(textureRegion, 64 * 3, 0, 64, 48))
keyFrames.add(TextureRegion(textureRegion, 64 * 11, 0, 64, 48))
keyFrames.add(TextureRegion(textureRegion, 64 * 4, 0, 64, 48))
keyFrames.add(TextureRegion(textureRegion, 64 * 12, 0, 64, 48))
anim = Animation(0.05f, keyFrames, Animation.PlayMode.LOOP)
animations.put("move_damaged", anim)
keyFrames.clear()
// fall animation (damaged)
keyFrames.add(TextureRegion(textureRegion, 64 * 6, 0, 64, 48))
keyFrames.add(TextureRegion(textureRegion, 64 * 13, 0, 64, 48))
anim = Animation(0.05f, keyFrames, Animation.PlayMode.LOOP)
animations.put("fall_damaged", anim)
val entity = Entity()
entity.add(PlayerComponent())
entity.add(PhysicsComponent(body))
entity.add(RendererComponent(TextureRegion(textureRegion, 64 * 3, 0, 64, 48), 64 / GM.PPM * scale, 48 / GM.PPM * scale, renderOrder = 3))
entity.add(AnimationComponent(animations, "idle"))
entity.add(TransformComponent(x, y))
engine!!.addEntity(entity)
body.userData = entity
}
fun createPlayerExplosionEffect(x: Float, y: Float) {
val scale = GM.PLAYER_SCALE
// main body
val bodyDef = BodyDef()
bodyDef.type = BodyDef.BodyType.DynamicBody
bodyDef.position.set(x, y)
val mainBody = world!!.createBody(bodyDef)
val polygonShape = PolygonShape()
polygonShape.setAsBox(0.45f * scale, 0.375f * scale)
val fixtureDef = FixtureDef()
fixtureDef.shape = polygonShape
fixtureDef.density = 0.5f
fixtureDef.filter.categoryBits = GM.CATEGORY_BITS_NOTHING.toShort()
fixtureDef.filter.maskBits = GM.MASK_BITS_NOTHING.toShort()
mainBody.createFixture(fixtureDef)
// left wheels
bodyDef.position.set(x + 0.15f * scale, y - 0.2f * scale)
val leftWheelsBody = world!!.createBody(bodyDef)
polygonShape.setAsBox(0.3f * scale, 0.2f * scale)
fixtureDef.shape = polygonShape
leftWheelsBody.createFixture(fixtureDef)
// right wheels
bodyDef.position.set(x - 0.15f * scale, y - 0.2f * scale)
val rightWheelsBody = world!!.createBody(bodyDef)
rightWheelsBody.createFixture(fixtureDef)
polygonShape.dispose()
mainBody.applyLinearImpulse(tmpVec1.set(MathUtils.random(-2f, 2f), MathUtils.random(2f, 6f)).scl(mainBody.mass), mainBody.worldCenter, true)
mainBody.applyAngularImpulse(MathUtils.random(-MathUtils.PI / 10f, MathUtils.PI / 10f), true)
leftWheelsBody.applyLinearImpulse(tmpVec1.set(MathUtils.random(-4f, 4f), MathUtils.random(2f, 6f)).scl(leftWheelsBody.mass), leftWheelsBody.worldCenter, true)
leftWheelsBody.applyAngularImpulse(MathUtils.random(-MathUtils.PI / 10f, MathUtils.PI / 10f), true)
rightWheelsBody.applyLinearImpulse(tmpVec1.set(MathUtils.random(-4f, 4f), MathUtils.random(2f, 6f)).scl(rightWheelsBody.mass), rightWheelsBody.worldCenter, true)
rightWheelsBody.applyAngularImpulse(MathUtils.random(-MathUtils.PI / 10f, MathUtils.PI / 10f), true)
val textureRegion = assetManager!!.get("img/actors.atlas", TextureAtlas::class.java).findRegion("RobotM")
val mainBodyEntity = Entity()
mainBodyEntity.add(TransformComponent(mainBody.position.x, mainBody.position.y))
mainBodyEntity.add(PhysicsComponent(mainBody))
mainBodyEntity.add(RendererComponent(TextureRegion(textureRegion, 64 * 2, 0, 64, 48), 1f * scale, 0.75f * scale, renderOrder = 8))
val leftWheelsEntity = Entity()
leftWheelsEntity.add(TransformComponent(leftWheelsBody.position.x, leftWheelsBody.position.y))
leftWheelsEntity.add(PhysicsComponent(leftWheelsBody))
leftWheelsEntity.add(RendererComponent(TextureRegion(textureRegion, 64 * 7, 0, 64, 48), 1f * scale, 0.75f * scale, renderOrder = 7))
val rightWheelsEntity = Entity()
rightWheelsEntity.add(TransformComponent(rightWheelsBody.position.x, rightWheelsBody.position.y))
rightWheelsEntity.add(PhysicsComponent(rightWheelsBody))
rightWheelsEntity.add(RendererComponent(TextureRegion(textureRegion, 64 * 9, 0, 64, 48), 1f * scale, 0.75f * scale, renderOrder = 9))
engine!!.addEntity(mainBodyEntity)
engine!!.addEntity(leftWheelsEntity)
engine!!.addEntity(rightWheelsEntity)
}
private fun createWallBody(x: Float, y: Float): Body {
val bodyDef = BodyDef()
bodyDef.position.set(x, y)
bodyDef.type = BodyDef.BodyType.StaticBody
val body = world!!.createBody(bodyDef)
val shape = PolygonShape()
shape.setAsBox(0.5f, 0.5f)
val fixtureDef = FixtureDef()
fixtureDef.shape = shape
fixtureDef.filter.categoryBits = GM.CATEGORY_BITS_WALL.toShort()
fixtureDef.filter.maskBits = GM.MASK_BITS_WALL.toShort()
fixtureDef.friction = 0f
body.createFixture(fixtureDef)
shape.dispose()
return body
}
fun createWall(left: Float, right: Float, top: Float, height: Int, type: String = "Grass") {
val textureAtlas = assetManager!!.get("img/actors.atlas", TextureAtlas::class.java)
val textureRegion = TextureRegion(textureAtlas.findRegion(type), 64 * 5, 0, 64, 64)
var body: Body
var entity: Entity
for (i in 0..height - 1) {
body = createWallBody(left, top - i)
entity = Entity()
entity.add(TransformComponent(left, top - i))
entity.add(PhysicsComponent(body))
entity.add(RendererComponent(textureRegion, 1f, 1f))
body.userData = entity
engine!!.addEntity(entity)
body = createWallBody(right, top - i)
entity = Entity()
entity.add(TransformComponent(right, top - i))
entity.add(PhysicsComponent(body))
entity.add(RendererComponent(textureRegion, 1f, 1f, renderOrder = 5))
body.userData = entity
engine!!.addEntity(entity)
}
}
fun createFloor(x: Float, y: Float, width: Int, type: String = "Grass") {
val textureAtlas = assetManager!!.get("img/actors.atlas", TextureAtlas::class.java)
for (i in 0..width - 1) {
val bodyDef = BodyDef()
bodyDef.type = BodyDef.BodyType.StaticBody
bodyDef.position.set(x + i, y)
val body = world!!.createBody(bodyDef)
val shape = PolygonShape()
shape.setAsBox(0.5f, 0.5f)
val fixtureDef = FixtureDef()
fixtureDef.shape = shape
when (type) {
"Purple" -> {
fixtureDef.filter.categoryBits = GM.CATEGORY_BITS_FLOOR_UNJUMPABLE.toShort()
fixtureDef.filter.maskBits = GM.MAST_BITS_FLOOR_UNJUMPABLE.toShort()
}
else -> {
fixtureDef.filter.categoryBits = GM.CATEGORY_BITS_FLOOR.toShort()
fixtureDef.filter.maskBits = GM.MASK_BITS_FLOOR.toShort()
}
}
when (type) {
"Grass" -> fixtureDef.friction = 0.8f
"Sand" -> fixtureDef.friction = 1f
"Choco" -> fixtureDef.friction = 0.01f
"Purple" -> fixtureDef.friction = 0.5f
else -> fixtureDef.friction = 0.8f
}
body.createFixture(fixtureDef)
shape.dispose()
val textureRegion: TextureRegion
if (width == 1) {
textureRegion = TextureRegion(textureAtlas.findRegion(type), 0, 0, 64, 64)
} else {
when (i) {
0 -> textureRegion = TextureRegion(textureAtlas.findRegion(type), 64 * 1, 0, 64, 64)
width - 1 -> textureRegion = TextureRegion(textureAtlas.findRegion(type), 64 * 3, 0, 64, 64)
else -> textureRegion = TextureRegion(textureAtlas.findRegion(type), 64 * 2, 0, 64, 64)
}
}
val entity = Entity()
entity.add(TransformComponent(x + i, y))
entity.add(PhysicsComponent(body))
entity.add(RendererComponent(textureRegion, 1f, 1f, renderOrder = 2))
engine!!.addEntity(entity)
body.userData = entity
}
}
private fun shouldMakeSpike(y: Float): Boolean {
if (y > -150f) {
return MathUtils.randomBoolean(0.15f)
}
if (y > -300) {
return MathUtils.randomBoolean(0.15f)
}
if (y > -450) {
return MathUtils.randomBoolean(0.20f)
}
if (y > -600) {
return MathUtils.randomBoolean(0.20f)
}
if (y > -750) {
return MathUtils.randomBoolean(0.25f)
}
if (y > -900) {
return MathUtils.randomBoolean(0.3f)
}
if (y > -1000) {
return MathUtils.randomBoolean(0.4f)
}
if (y > -1200) {
return MathUtils.randomBoolean(0.5f)
}
return MathUtils.randomBoolean(0.6f)
}
private fun shouldMakeSpring(y: Float): Boolean {
if (y > -150f) {
return MathUtils.randomBoolean(0.1f)
}
if (y > -300) {
return MathUtils.randomBoolean(0.15f)
}
if (y > -450) {
return MathUtils.randomBoolean(0.15f)
}
if (y > -600) {
return MathUtils.randomBoolean(0.20f)
}
if (y > -750) {
return MathUtils.randomBoolean(0.25f)
}
if (y > -900) {
return MathUtils.randomBoolean(0.25f)
}
if (y > -1000) {
return MathUtils.randomBoolean(0.3f)
}
if (y > -1200) {
return MathUtils.randomBoolean(0.35f)
}
return MathUtils.randomBoolean(0.4f)
}
fun generateFloors(start: Float, height: Int, leftBound: Float, rightBound: Float, type: String = "Grass") {
var gap: Int = MathUtils.random(4, 6)
var length: Int = MathUtils.random(4, 6)
var x: Float = MathUtils.random(leftBound.toInt() + 1, rightBound.toInt() - length - 2) + 0.5f
var y: Float = MathUtils.floor(start) - gap + 0.5f
while (y >= start - height) {
if (gap <= 5 || MathUtils.random() > 0.05f) {
if (length >= 6 && MathUtils.randomBoolean(0.6f)) {
length = MathUtils.random(2, 3)
x = MathUtils.random(-GM.SCREEN_WIDTH.toInt() / 2 + 1, -length - 2) + 0.5f
createFloor(x, y, length, type)
if (shouldMakeSpike(y)) {
generateSpikes(x, y + 1, length)
}
else if (shouldMakeSpring(y)) {
generateSprings(x, y + 1, length)
} else if (MathUtils.randomBoolean(0.1f)) {
generateRandomPowerUpItem(x + MathUtils.random(length - 1), y + 1.5f)
}
length = MathUtils.random(2, 3)
x = MathUtils.random(0, GM.SCREEN_WIDTH.toInt() / 2 - length - 2) + 0.5f
createFloor(x, y, length, type)
if (shouldMakeSpike(y)) {
generateSpikes(x, y + 1, length)
} else if (shouldMakeSpring(y)) {
generateSprings(x, y + 1, length)
} else if (MathUtils.randomBoolean(0.1f)) {
generateRandomPowerUpItem(x + MathUtils.random(length - 1), y + 1.5f)
}
} else {
createFloor(x, y, length, type)
if (shouldMakeSpike(y)) {
generateSpikes(x, y + 1, length)
} else if (shouldMakeSpring(y)) {
generateSprings(x, y + 1, length)
} else if (MathUtils.randomBoolean(0.1f)) {
generateRandomPowerUpItem(x + MathUtils.random(length - 1), y + 1.5f)
}
}
}
x = MathUtils.random(-GM.SCREEN_WIDTH.toInt() / 2 + 1, GM.SCREEN_WIDTH.toInt() / 2 - length - 2) + 0.5f
y -= gap
gap = MathUtils.random(4, 6)
length = MathUtils.random(4, 6)
}
}
fun generateFloorsAndWalls(start: Float, height: Int, left: Float = -GM.SCREEN_WIDTH / 2f + 0.5f, right: Float = GM.SCREEN_WIDTH / 2f - 0.5f) {
val types = arrayOf("Grass", "Sand", "Choco", "Purple")
var floorType: String
var wallType: String
if (start > -150f) {
floorType = types[0]
wallType = types[0]
} else if (start > -300f) {
floorType = types[1]
wallType = types[1]
} else if (start > -450f) {
floorType = types[2]
wallType = types[2]
} else if (start > -600f) {
floorType = types[3]
wallType = types[3]
} else {
// random floor type
floorType = types[MathUtils.random(0, types.size - 1)]
wallType = "Purple"
}
generateFloors(start, height, left, right, floorType)
createWall(left, right, start, height, wallType)
}
fun createRingSaw(x: Float, y: Float) {
val bodyDef = BodyDef()
bodyDef.type = BodyDef.BodyType.KinematicBody
bodyDef.position.set(x, y)
val body = world!!.createBody(bodyDef)
val polygonShape = PolygonShape()
polygonShape.setAsBox(0.5f, 0.25f, tmpVec1.set(0f, 0.25f), 0f)
val fixtureDef = FixtureDef()
fixtureDef.shape = polygonShape
fixtureDef.isSensor = true
fixtureDef.filter.categoryBits = GM.CATEGORY_BITS_LETHAL.toShort()
fixtureDef.filter.maskBits = GM.MASK_BITS_LETHAL.toShort()
body.createFixture(fixtureDef)
polygonShape.dispose()
val textureRegion = assetManager!!.get("img/actors.atlas", TextureAtlas::class.java).findRegion("Spin")
val keyFrames = Array<TextureRegion>()
keyFrames.add(TextureRegion(textureRegion, 0, 0, 64, 64))
keyFrames.add(TextureRegion(textureRegion, 64, 0, 64, 64))
val animation = Animation(0.1f, keyFrames, Animation.PlayMode.LOOP)
val anims = HashMap<String, Animation>()
anims.put("sawing", animation)
val entity = Entity()
entity.add(TransformComponent(x, y))
entity.add(PhysicsComponent(body))
entity.add(RendererComponent(TextureRegion(textureRegion, 0, 0, 64, 64), 1f, 1f, originX = 0.5f, originY = 0.5f, renderOrder = 6))
entity.add(AnimationComponent(anims, "sawing"))
entity.add(FollowCameraComponent(x, y))
body.userData = entity
engine!!.addEntity(entity)
}
fun generateRingSaws(x: Float, y: Float, length: Int) {
for (i in 0..length - 1) {
createRingSaw(x + i, y)
}
}
fun createCeiling(x: Float, y: Float) {
val bodyDef = BodyDef()
bodyDef.position.set(x, y)
bodyDef.type = BodyDef.BodyType.KinematicBody
val body = world!!.createBody(bodyDef)
val polygonShape = PolygonShape()
polygonShape.setAsBox(0.5f, 0.5f)
val fixtureDef = FixtureDef()
fixtureDef.shape = polygonShape
fixtureDef.filter.categoryBits = GM.CATEGORY_BITS_CEILING.toShort()
fixtureDef.filter.maskBits = GM.MASK_BITS_CEILING.toShort()
body.createFixture(fixtureDef)
polygonShape.dispose()
val textureRegion = assetManager!!.get("img/actors.atlas", TextureAtlas::class.java).findRegion("Purple")
val entity = Entity()
entity.add(TransformComponent(x, y))
entity.add(PhysicsComponent(body))
entity.add(FollowCameraComponent(x, y))
entity.add(RendererComponent(TextureRegion(textureRegion, 64 * 5, 0, 64, 64), 1f, 1f, renderOrder = 6))
engine!!.addEntity(entity)
body.userData = entity
}
fun generateCeilings(x: Float, y: Float, length: Int) {
for (i in 0..length - 1) {
createCeiling(x + i, y)
}
}
fun createSpike(x: Float, y: Float) {
val bodyDef = BodyDef()
bodyDef.type = BodyDef.BodyType.StaticBody
bodyDef.position.set(x, y)
val body = world!!.createBody(bodyDef)
val polygonShape = PolygonShape()
polygonShape.setAsBox(0.5f, 0.25f, tmpVec1.set(0f, -0.25f), 0f)
val fixtureDef = FixtureDef()
fixtureDef.shape = polygonShape
fixtureDef.isSensor = true
fixtureDef.filter.categoryBits = GM.CATEGORY_BITS_LETHAL.toShort()
fixtureDef.filter.maskBits = GM.MASK_BITS_LETHAL.toShort()
body.createFixture(fixtureDef)
polygonShape.dispose()
val textureRegion = assetManager!!.get("img/actors.atlas", TextureAtlas::class.java).findRegion("Spikes")
val entity = Entity()
entity.add(TransformComponent(x, y))
entity.add(PhysicsComponent(body))
entity.add(RendererComponent(textureRegion, 1.0f, 1.0f, renderOrder = 4))
engine!!.addEntity(entity)
body.userData = entity
}
fun generateSpikes(x: Float, y: Float, length: Int) {
for (i in 0..length - 1) {
createSpike(x + i, y)
}
}
fun createSpring(x: Float, y: Float) {
val bodyDef = BodyDef()
bodyDef.type = BodyDef.BodyType.KinematicBody
bodyDef.position.set(x, y)
val body = world!!.createBody(bodyDef)
val polygonShape = PolygonShape()
polygonShape.setAsBox(0.5f, 0.25f, tmpVec1.set(0f, -0.25f), 0f)
val fixtureDef = FixtureDef()
fixtureDef.shape = polygonShape
fixtureDef.isSensor = true
fixtureDef.filter.categoryBits = GM.CATEGORY_BITS_SPRING.toShort()
fixtureDef.filter.maskBits = GM.MASK_BITS_SPRING.toShort()
body.createFixture(fixtureDef)
polygonShape.dispose()
val textureRegion = assetManager!!.get("img/actors.atlas", TextureAtlas::class.java).findRegion("Spring")
var animation: Animation
val anims = HashMap<String, Animation>()
val keyFrames = Array<TextureRegion>()
keyFrames.add(TextureRegion(textureRegion, 0, 0, 64, 64))
animation = Animation(0.1f, keyFrames, Animation.PlayMode.NORMAL)
anims.put("normal", animation)
keyFrames.clear()
keyFrames.add(TextureRegion(textureRegion, 64, 0, 64, 64))
animation = Animation(0.1f, keyFrames, Animation.PlayMode.NORMAL)
anims.put("hit", animation)
val entity = Entity()
entity.add(TransformComponent(x, y))
entity.add(InteractionComponent(InteractionType.SPRING))
entity.add(PhysicsComponent(body))
entity.add(AnimationComponent(anims, "normal"))
entity.add(RendererComponent(TextureRegion(textureRegion, 0, 0, 64, 64), 1f, 1f, renderOrder = 4))
engine!!.addEntity(entity)
body.userData = entity
}
fun generateSprings(x: Float, y: Float, length: Int) {
for (i in 0..length - 1) {
createSpring(x + i, y)
}
}
fun createPowerUpItem(x: Float, y: Float, type: ItemType) {
val bodyDef = BodyDef()
bodyDef.type = BodyDef.BodyType.KinematicBody
bodyDef.position.set(x, y)
val body = world!!.createBody(bodyDef)
val circleShape = CircleShape()
circleShape.radius = 0.4f
val fixtureDef = FixtureDef()
fixtureDef.shape = circleShape
fixtureDef.isSensor = true
fixtureDef.filter.categoryBits = GM.CATEGORY_BITS_ITEM.toShort()
fixtureDef.filter.maskBits = GM.MASK_BITS_ITEM.toShort()
body.createFixture(fixtureDef)
circleShape.dispose()
val textureRegion = assetManager!!.get("img/actors.atlas", TextureAtlas::class.java).findRegion("Items")
val itemTextureRegion: TextureRegion
when (type) {
ItemType.FastFeet -> itemTextureRegion = TextureRegion(textureRegion, 0, 0, 64, 64)
ItemType.HardSkin -> itemTextureRegion = TextureRegion(textureRegion, 64, 0, 64, 64)
ItemType.QuickHealing -> itemTextureRegion = TextureRegion(textureRegion, 128, 0, 64, 64)
ItemType.LowGravity -> itemTextureRegion = TextureRegion(textureRegion, 192, 0, 64, 64)
else -> itemTextureRegion = TextureRegion(textureRegion, 0, 0, 64, 64)
}
val anims = HashMap<String, Animation>()
var animation: Animation
val keyFrames = Array<TextureRegion>()
keyFrames.add(itemTextureRegion)
animation = Animation(0.1f, keyFrames, Animation.PlayMode.LOOP)
anims.put("normal", animation)
val entity = Entity()
entity.add(TransformComponent(x, y))
entity.add(InteractionComponent(InteractionType.ITEM, type.name))
entity.add(PhysicsComponent(body))
entity.add(RendererComponent(itemTextureRegion, 1f, 1f, renderOrder = 4))
entity.add(AnimationComponent(anims, "normal"))
engine!!.addEntity(entity)
body.userData = entity
}
fun generateRandomPowerUpItem(x: Float, y: Float) {
createPowerUpItem(x, y, ItemType.randomType())
}
} | apache-2.0 | 3ad20f203fb99e6c3dd9909fd63c7169 | 34.383217 | 169 | 0.600759 | 3.8998 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/src/commonMain/kotlin/nl/adaptivity/process/engine/processModel/XmlProcessNodeInstance.kt | 1 | 3559 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.06 at 08:14:28 PM BST
//
package nl.adaptivity.process.engine.processModel
import net.devrieze.util.Handle
import nl.adaptivity.process.ProcessConsts.Engine
import nl.adaptivity.process.engine.ProcessData
import nl.adaptivity.xmlutil.QName
import nl.adaptivity.xmlutil.XmlReader
import nl.adaptivity.xmlutil.serialization.XML
import nl.adaptivity.xmlutil.util.ICompactFragment
class XmlProcessNodeInstance {
constructor()
constructor(
nodeId: String,
predecessors: Iterable<Handle<XmlProcessNodeInstance>>,
processInstance: Long,
handle: Handle<XmlProcessNodeInstance>,
state: NodeInstanceState,
results: Iterable<ProcessData>,
body: ICompactFragment?
) {
this.nodeId = nodeId
this._predecessors.addAll(predecessors)
this.processInstance = processInstance
this.handle = handle.handleValue
this.state = state
this.results.addAll(results)
this.body = body
}
private val _predecessors = mutableListOf<Handle<XmlProcessNodeInstance>>()
/**
* Gets the value of the predecessor property.
*/
val predecessors: List<Handle<XmlProcessNodeInstance>>
get() = _predecessors
var body: ICompactFragment? = null
var handle = -1L
var entryNo = 0
var state: NodeInstanceState? = null
var stateXml: String?
get() = state?.name
set(value) {
state = value?.let { NodeInstanceState.valueOf(it) }
}
var processInstance: Long = -1
var nodeId: String? = null
var results: MutableList<ProcessData> = mutableListOf()
var xmlProcessinstance: Long?
get() = if (processInstance == -1L) null else processInstance
set(value) {
this.processInstance = value ?: -1L
}
companion object {
const val ELEMENTLOCALNAME = "nodeInstance"
val ELEMENTNAME = QName(Engine.NAMESPACE, ELEMENTLOCALNAME, Engine.NSPREFIX)
const val PREDECESSOR_LOCALNAME = "predecessor"
val PREDECESSOR_ELEMENTNAME = QName(Engine.NAMESPACE, PREDECESSOR_LOCALNAME, Engine.NSPREFIX)
const val RESULT_LOCALNAME = "result"
val RESULT_ELEMENTNAME = QName(Engine.NAMESPACE, RESULT_LOCALNAME, Engine.NSPREFIX)
const private val BODY_LOCALNAME = "body"
internal val BODY_ELEMENTNAME = QName(Engine.NAMESPACE, BODY_LOCALNAME, Engine.NSPREFIX)
fun deserialize(reader: XmlReader): XmlProcessNodeInstance {
return XML.decodeFromReader(reader)
}
}
}
| lgpl-3.0 | 3321e815174615959eec7d015519593e | 31.953704 | 112 | 0.69542 | 4.437656 | false | false | false | false |
openMF/self-service-app | app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingsAccountApplicationPayload.kt | 1 | 442 | package org.mifos.mobile.models.accounts.savings
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
/*
* Created by saksham on 01/July/2018
*/
@Parcelize
data class SavingsAccountApplicationPayload(
var submittedOnDate: String? = null,
var clientId: Int? = null,
var productId: Int? = null,
var locale: String = "en",
var dateFormat: String = "dd MMMM yyyy"
) : Parcelable
| mpl-2.0 | 6e3d18a9b1704ad423c2288fa1b5102d | 18.217391 | 48 | 0.680995 | 3.911504 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/filterer/CollectionNameFilter.kt | 1 | 1178 | package com.boardgamegeek.filterer
import android.content.Context
import com.boardgamegeek.R
import com.boardgamegeek.entities.CollectionItemEntity
class CollectionNameFilter(context: Context) : CollectionFilterer(context) {
var filterText = ""
var startsWith = false
override val typeResourceId = R.string.collection_filter_type_collection_name
override fun inflate(data: String) {
filterText = data.substringBeforeLast(DELIMITER)
startsWith = data.substringAfterLast(DELIMITER) == "1"
}
override fun deflate() = "$filterText$DELIMITER${if (startsWith) "1" else "0"}"
override val iconResourceId: Int
get() = R.drawable.ic_baseline_format_quote_24
override fun chipText() = if (startsWith) "$filterText*" else "*$filterText*"
override fun description() = context.getString(if (startsWith) R.string.starts_with_prefix else R.string.named_prefix, filterText)
override fun filter(item: CollectionItemEntity): Boolean {
return if (startsWith) {
item.collectionName.startsWith(filterText, true)
} else {
item.collectionName.contains(filterText, true)
}
}
}
| gpl-3.0 | 614449d02bf36aa1c53211dffc5a0cd1 | 33.647059 | 134 | 0.70798 | 4.428571 | false | false | false | false |
ekager/focus-android | app/src/main/java/org/mozilla/focus/shortcut/IconGenerator.kt | 1 | 6341 | /* 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 org.mozilla.focus.shortcut
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.net.Uri
import android.os.Build
import android.support.graphics.drawable.VectorDrawableCompat
import android.support.v4.content.ContextCompat
import android.util.TypedValue
import org.mozilla.focus.R
import org.mozilla.focus.utils.UrlUtils
class IconGenerator {
companion object {
private val TEXT_SIZE_DP = 36f
private val DEFAULT_ICON_CHAR = '?'
private const val SEARCH_ICON_FRAME = 0.15
/**
* See [generateAdaptiveLauncherIcon] for more details.
*/
@JvmStatic
fun generateLauncherIcon(context: Context, url: String?): Bitmap {
val startingChar = getRepresentativeCharacter(url)
return generateCharacterIcon(context, startingChar)
}
/**
* Generate an icon with the given character. The icon will be drawn
* on top of a generic launcher icon shape that we provide.
*/
private fun generateCharacterIcon(context: Context, character: Char) =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
generateAdaptiveLauncherIcon(context, character)
else
generateLauncherIconPreOreo(context, character)
/*
* This method needs to be separate from generateAdaptiveLauncherIcon so that we can generate
* the pre-Oreo icon to display in the Add To Home screen Dialog
*/
@JvmStatic
fun generateLauncherIconPreOreo(context: Context, character: Char): Bitmap {
val options = BitmapFactory.Options()
options.inMutable = true
val shape = BitmapFactory.decodeResource(context.resources, R.drawable.ic_homescreen_shape, options)
return drawCharacterOnBitmap(context, character, shape)
}
@JvmStatic
fun generateSearchEngineIcon(context: Context): Bitmap {
val options = BitmapFactory.Options()
options.inMutable = true
val shape = BitmapFactory.decodeResource(context.resources, R.drawable.ic_search_engine_shape, options)
return drawVectorOnBitmap(context, R.drawable.ic_search, shape, SEARCH_ICON_FRAME)
}
private fun drawVectorOnBitmap(context: Context, vectorId: Int, bitmap: Bitmap, frame: Double): Bitmap {
val canvas = Canvas(bitmap)
// Select the area to draw with a frame
val rect = Rect((frame * canvas.width).toInt(),
(frame * canvas.height).toInt(),
((1 - frame) * canvas.width).toInt(),
((1 - frame) * canvas.height).toInt())
val icon = VectorDrawableCompat.create(context.resources, vectorId, null)
icon!!.bounds = rect
icon.draw(canvas)
return bitmap
}
/**
* Generates a launcher icon for versions of Android that support Adaptive Icons (Oreo+):
* https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive.html
*/
private fun generateAdaptiveLauncherIcon(context: Context, character: Char): Bitmap {
val res = context.resources
val adaptiveIconDimen = res.getDimensionPixelSize(R.dimen.adaptive_icon_drawable_dimen)
val bitmap = Bitmap.createBitmap(adaptiveIconDimen, adaptiveIconDimen, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
// Adaptive Icons have two layers: a background that fills the canvas and
// a foreground that's centered. First, we draw the background...
canvas.drawColor(ContextCompat.getColor(context, R.color.add_to_homescreen_icon_background))
// Then draw the foreground
return drawCharacterOnBitmap(context, character, bitmap)
}
private fun drawCharacterOnBitmap(context: Context, character: Char, bitmap: Bitmap): Bitmap {
val canvas = Canvas(bitmap)
val paint = Paint()
val textSize = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DP, context.resources.displayMetrics)
paint.color = Color.WHITE
paint.textAlign = Paint.Align.CENTER
paint.textSize = textSize
paint.isAntiAlias = true
canvas.drawText(character.toString(),
canvas.width / 2.0f,
canvas.height / 2.0f - (paint.descent() + paint.ascent()) / 2.0f,
paint)
return bitmap
}
/**
* Get a representative character for the given URL.
*
* For example this method will return "f" for "http://m.facebook.com/foobar".
*/
@JvmStatic
fun getRepresentativeCharacter(url: String?): Char {
val firstChar = getRepresentativeSnippet(url)?.find { it.isLetterOrDigit() }?.toUpperCase()
return (firstChar ?: DEFAULT_ICON_CHAR)
}
/**
* Get the representative part of the URL. Usually this is the host (without common prefixes).
*
* @return the representative snippet or null if one could not be found.
*/
private fun getRepresentativeSnippet(url: String?): String? {
if (url == null || url.isEmpty()) return null
val uri = Uri.parse(url)
val snippet = if (!uri.host.isNullOrEmpty()) {
uri.host // cached by Uri class.
} else if (!uri.path.isNullOrEmpty()) { // The uri may not have a host for e.g. file:// uri
uri.path // cached by Uri class.
} else {
return null
}
// Strip common prefixes that we do not want to use to determine the representative characters
return UrlUtils.stripCommonSubdomains(snippet)
}
}
}
| mpl-2.0 | 0d1d4d0183d3a044c243382c6b1a4091 | 40.175325 | 115 | 0.625611 | 4.782051 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/json/commonMain/src/kotlinx/serialization/json/internal/JsonPath.kt | 1 | 5106 | package kotlinx.serialization.json.internal
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.internal.*
/**
* Internal representation of the current JSON path.
* It is stored as the array of serial descriptors (for regular classes)
* and `Any?` in case of Map keys.
*
* Example of the state when decoding the list
* ```
* class Foo(val a: Int, val l: List<String>)
*
* // {"l": ["a", "b", "c"] }
*
* Current path when decoding array elements:
* Foo.descriptor, List(String).descriptor
* 1 (index of the 'l'), 2 (index of currently being decoded "c")
* ```
*/
internal class JsonPath {
// Tombstone indicates that we are within a map, but the map key is currently being decoded.
// It is also used to overwrite a previous map key to avoid memory leaks and misattribution.
private object Tombstone
/*
* Serial descriptor, map key or the tombstone for map key
*/
private var currentObjectPath = arrayOfNulls<Any?>(8)
/*
* Index is a small state-machine used to determine the state of the path:
* >=0 -> index of the element being decoded with the outer class currentObjectPath[currentDepth]
* -1 -> nested elements are not yet decoded
* -2 -> the map is being decoded and both its descriptor AND the last key were added to the path.
*
* -2 is effectively required to specify that two slots has been claimed and both should be
* cleaned up when the decoding is done.
* The cleanup is essential in order to avoid memory leaks for huge strings and structured keys.
*/
private var indicies = IntArray(8) { -1 }
private var currentDepth = -1
// Invoked when class is started being decoded
fun pushDescriptor(sd: SerialDescriptor) {
val depth = ++currentDepth
if (depth == currentObjectPath.size) {
resize()
}
currentObjectPath[depth] = sd
}
// Invoked when index-th element of the current descriptor is being decoded
fun updateDescriptorIndex(index: Int) {
indicies[currentDepth] = index
}
/*
* For maps we cannot use indicies and should use the key as an element of the path instead.
* The key can be even an object (e.g. in a case of 'allowStructuredMapKeys') where
* 'toString' is way too heavy or have side-effects.
* For that we are storing the key instead.
*/
fun updateCurrentMapKey(key: Any?) {
// idx != -2 -> this is the very first key being added
if (indicies[currentDepth] != -2 && ++currentDepth == currentObjectPath.size) {
resize()
}
currentObjectPath[currentDepth] = key
indicies[currentDepth] = -2
}
/** Used to indicate that we are in the process of decoding the key itself and can't specify it in path */
fun resetCurrentMapKey() {
if (indicies[currentDepth] == -2) {
currentObjectPath[currentDepth] = Tombstone
}
}
fun popDescriptor() {
// When we are ending map, we pop the last key and the outer field as well
val depth = currentDepth
if (indicies[depth] == -2) {
indicies[depth] = -1
currentDepth--
}
// Guard against top-level maps
if (currentDepth != -1) {
// No need to clean idx up as it was already cleaned by updateDescriptorIndex(DECODE_DONE)
currentDepth--
}
}
@OptIn(ExperimentalSerializationApi::class)
fun getPath(): String {
return buildString {
append("$")
repeat(currentDepth + 1) {
val element = currentObjectPath[it]
if (element is SerialDescriptor) {
if (element.kind == StructureKind.LIST) {
if (indicies[it] != -1) {
append("[")
append(indicies[it])
append("]")
}
} else {
val idx = indicies[it]
// If an actual element is being decoded
if (idx >= 0) {
append(".")
append(element.getElementName(idx))
}
}
} else if (element !== Tombstone) {
append("[")
// All non-indicies should be properly quoted by JsonPath convention
append("'")
// Else -- map key
append(element)
append("'")
append("]")
}
}
}
}
@OptIn(ExperimentalSerializationApi::class)
private fun prettyString(it: Any?) = (it as? SerialDescriptor)?.serialName ?: it.toString()
private fun resize() {
val newSize = currentDepth * 2
currentObjectPath = currentObjectPath.copyOf(newSize)
indicies = indicies.copyOf(newSize)
}
override fun toString(): String = getPath()
}
| apache-2.0 | 9c79bd75b033c180a5ab9953371e7443 | 35.212766 | 110 | 0.574814 | 4.736549 | false | false | false | false |
if710/if710.github.io | 2019-09-18/Services/app/src/main/java/br/ufpe/cin/android/services/MusicPlayerNoBindingService.kt | 1 | 1338 | package br.ufpe.cin.android.services
import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.IBinder
class MusicPlayerNoBindingService : Service() {
private val TAG = "MusicPlayerNoBindingService"
private var mPlayer: MediaPlayer? = null
private var mStartID: Int = 0
override fun onCreate() {
super.onCreate()
// configurar media player
mPlayer = MediaPlayer.create(this, R.raw.moonlightsonata)
//nao deixa entrar em loop
mPlayer?.isLooping = false
// encerrar o service quando terminar a musica
mPlayer?.setOnCompletionListener {
// encerra se foi iniciado com o mesmo ID
stopSelf(mStartID)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (mPlayer != null) {
mStartID = startId
if (mPlayer!!.isPlaying()) {
mPlayer?.seekTo(0)
}
else {
mPlayer?.start()
}
}
return Service.START_NOT_STICKY
}
override fun onDestroy() {
mPlayer?.release()
super.onDestroy()
}
override fun onBind(intent: Intent): IBinder {
TODO("Return the communication channel to the service.")
}
}
| mit | b72ff7091578425fd5c9415eb32ffe3c | 24.730769 | 81 | 0.604634 | 4.505051 | false | false | false | false |
FHannes/intellij-community | platform/platform-api/src/com/intellij/openapi/project/ProjectUtil.kt | 1 | 7830 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("ProjectUtil")
package com.intellij.openapi.project
import com.intellij.ide.DataManager
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.appSystemDir
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.fileEditor.UniqueVFilePathBuilder
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.ModifiableModuleModel
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFilePathWrapper
import com.intellij.util.PathUtilRt
import com.intellij.util.io.exists
import com.intellij.util.text.trimMiddle
import java.nio.file.InvalidPathException
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.function.Consumer
import javax.swing.JComponent
val Module.rootManager: ModuleRootManager
get() = ModuleRootManager.getInstance(this)
@JvmOverloads
fun calcRelativeToProjectPath(file: VirtualFile, project: Project?, includeFilePath: Boolean = true, includeUniqueFilePath: Boolean = false, keepModuleAlwaysOnTheLeft: Boolean = false): String {
if (file is VirtualFilePathWrapper && file.enforcePresentableName()) {
return if (includeFilePath) file.presentablePath else file.name
}
val url = if (includeFilePath) {
file.presentableUrl
}
else if (includeUniqueFilePath) {
UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(project, file)
}
else {
file.name
}
if (project == null) {
return url
}
return displayUrlRelativeToProject(file, url, project, includeFilePath, keepModuleAlwaysOnTheLeft)
}
fun guessProjectForFile(file: VirtualFile?): Project? = ProjectLocator.getInstance().guessProjectForFile(file)
/***
* guessProjectForFile works incorrectly - even if file is config (idea config file) first opened project will be returned
*/
@JvmOverloads
fun guessProjectForContentFile(file: VirtualFile, fileType: FileType = file.fileType): Project? {
if (ProjectCoreUtil.isProjectOrWorkspaceFile(file, fileType)) {
return null
}
return ProjectManager.getInstance().openProjects.firstOrNull { !it.isDefault && it.isInitialized && !it.isDisposed && ProjectRootManager.getInstance(it).fileIndex.isInContent(file) }
}
fun isProjectOrWorkspaceFile(file: VirtualFile): Boolean {
// do not use file.getFileType() to avoid autodetection by content loading for arbitrary files
return ProjectCoreUtil.isProjectOrWorkspaceFile(file, FileTypeManager.getInstance().getFileTypeByFileName(file.name))
}
fun guessCurrentProject(component: JComponent?): Project {
var project: Project? = null
if (component != null) {
project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(component))
}
@Suppress("DEPRECATION")
return project
?: ProjectManager.getInstance().openProjects.firstOrNull()
?: CommonDataKeys.PROJECT.getData(DataManager.getInstance().dataContext)
?: ProjectManager.getInstance().defaultProject
}
inline fun <T> Project.modifyModules(crossinline task: ModifiableModuleModel.() -> T): T {
val model = ModuleManager.getInstance(this).modifiableModel
val result = model.task()
runWriteAction {
model.commit()
}
return result
}
fun isProjectDirectoryExistsUsingIo(parent: VirtualFile): Boolean {
try {
return Paths.get(FileUtil.toSystemDependentName(parent.path), Project.DIRECTORY_STORE_FOLDER).exists()
}
catch (e: InvalidPathException) {
return false
}
}
/**
* Tries to guess the "main project directory" of the project.
*
* There is no strict definition of what is a project directory, since a project can contain multiple modules located in different places,
* and the `.idea` directory can be located elsewhere (making the popular [Project.getBaseDir] method not applicable to get the "project
* directory"). This method should be preferred, although it can't provide perfect accuracy either.
*
* @throws IllegalStateException if called on the default project, since there is no sense in "project dir" in that case.
*/
fun Project.guessProjectDir() : VirtualFile {
if (isDefault) {
throw IllegalStateException("Not applicable for default project")
}
val modules = ModuleManager.getInstance(this).modules
val module = if (modules.size == 1) modules.first() else modules.find { it.name == this.name }
module?.rootManager?.contentRoots?.firstOrNull()?.let {
return it
}
return this.baseDir!!
}
private fun Project.getProjectCacheFileName(forceNameUse: Boolean, hashSeparator: String): String {
val presentableUrl = presentableUrl
var name = if (forceNameUse || presentableUrl == null) {
name
}
else {
// lower case here is used for cosmetic reasons (develar - discussed with jeka - leave it as it was, user projects will not have long names as in our tests)
FileUtil.sanitizeFileName(PathUtilRt.getFileName(presentableUrl).toLowerCase(Locale.US).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION), false)
}
// do not use project.locationHash to avoid prefix for IPR projects (not required in our case because name in any case is prepended).
val locationHash = Integer.toHexString((presentableUrl ?: name).hashCode())
// trim to avoid "File name too long"
name = name.trimMiddle(Math.min(name.length, 255 - hashSeparator.length - locationHash.length), useEllipsisSymbol = false)
return "$name$hashSeparator${locationHash}"
}
@JvmOverloads
fun Project.getProjectCachePath(cacheName: String, forceNameUse: Boolean = false): Path {
return getProjectCachePath(appSystemDir.resolve(cacheName), forceNameUse)
}
/**
* Use parameters only for migration purposes, once all usages will be migrated, parameters will be removed
*/
@JvmOverloads
fun Project.getProjectCachePath(baseDir: Path, forceNameUse: Boolean = false, hashSeparator: String = "."): Path {
return baseDir.resolve(getProjectCacheFileName(forceNameUse, hashSeparator))
}
/**
* Add one-time projectOpened listener.
*/
fun Project.runWhenProjectOpened(handler: Runnable) = runWhenProjectOpened(this) { handler.run() }
/**
* Add one-time first projectOpened listener.
*/
@JvmOverloads
fun runWhenProjectOpened(project: Project? = null, handler: Consumer<Project>) = runWhenProjectOpened(project) { handler.accept(it) }
/**
* Add one-time projectOpened listener.
*/
inline fun runWhenProjectOpened(project: Project? = null, crossinline handler: (project: Project) -> Unit) {
val connection = (project ?: ApplicationManager.getApplication()).messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectOpened(eventProject: Project) {
if (project == null || project === eventProject) {
connection.disconnect()
handler(eventProject)
}
}
})
} | apache-2.0 | 35876dd25c9cb0add2ebddaecb0659e8 | 38.550505 | 194 | 0.769604 | 4.469178 | false | false | false | false |
myTargetSDK/mytarget-android | myTargetDemo/app/src/main/java/com/my/targetDemoApp/helpers/BannerHelper.kt | 1 | 1744 | package com.my.targetDemoApp.helpers
import android.view.View
import android.view.ViewGroup
import com.google.android.material.snackbar.Snackbar
import com.my.target.ads.MyTargetView
import com.my.targetDemoApp.R
import com.my.targetDemoApp.addParsedString
import com.my.targetDemoApp.showLoading
class BannerHelper : MyTargetView.MyTargetViewListener {
var bannerView: MyTargetView? = null
private var bar: Snackbar? = null
private var afterLoad: (() -> Unit)? = null
private var parent: View? = null
override fun onLoad(p0: MyTargetView) {
bar?.dismiss()
afterLoad?.invoke()
}
override fun onClick(p0: MyTargetView) {
}
override fun onShow(p0: MyTargetView) {
}
override fun onNoAd(p0: String, p1: MyTargetView) {
parent?.let {
Snackbar.make(it, String.format(p1.context.getString(R.string.error_msg), p0),
Snackbar.LENGTH_SHORT)
.show()
}
}
fun load(defaultSlot: Int, adSize: MyTargetView.AdSize, params: String?, parent: ViewGroup,
function: (() -> Unit)? = null) {
afterLoad = function
bannerView = MyTargetView(parent.context).also { myTargetView ->
myTargetView.setSlotId(defaultSlot)
myTargetView.setAdSize(adSize)
myTargetView.listener = this
myTargetView.customParams.addParsedString(params)
myTargetView.load()
}
this.parent = parent
showLoading(parent)
}
private fun showLoading(parent: View) {
bar = Snackbar.make(parent, "Loading", Snackbar.LENGTH_INDEFINITE)
.showLoading()
}
fun destroy() {
bannerView?.destroy()
}
} | lgpl-3.0 | 1c3ff8089c53587b8375331a0dc4d247 | 28.083333 | 95 | 0.639335 | 4.192308 | false | false | false | false |
henrikfroehling/timekeeper | domain/src/main/kotlin/de/froehling/henrik/timekeeper/domain/usecases/tags/GetTagsUseCase.kt | 1 | 2028 | package de.froehling.henrik.timekeeper.domain.usecases.tags
import android.support.annotation.IntDef
import kotlin.annotation.AnnotationRetention
import kotlin.annotation.Retention
import de.froehling.henrik.timekeeper.domain.executor.IPostThreadExecutor
import de.froehling.henrik.timekeeper.domain.executor.IThreadExecutor
import de.froehling.henrik.timekeeper.domain.repository.ITagsRepository
import de.froehling.henrik.timekeeper.domain.usecases.UseCase
import rx.Observable
sealed class GetTagsUseCase(private val mTagsRepository: ITagsRepository,
threadExecutor: IThreadExecutor,
postThreadExecutor: IPostThreadExecutor) : UseCase(threadExecutor, postThreadExecutor) {
@IntDef(FILTER_REQUEST_NAME_ASCENDING.toLong(), FILTER_REQUEST_NAME_DESCENDING.toLong(),
FILTER_REQUEST_CREATED_ASCENDING.toLong(), FILTER_REQUEST_CREATED_DESCENDING.toLong())
@Retention(AnnotationRetention.SOURCE)
annotation class FilterRequest
@FilterRequest
private var mFilterRequest = FILTER_REQUEST_NAME_ASCENDING
fun setFilterRequest(@FilterRequest filterRequest: Int) {
mFilterRequest = filterRequest
}
override fun buildUseCaseObservable(): Observable<out Any> {
when (mFilterRequest) {
FILTER_REQUEST_NAME_ASCENDING -> return mTagsRepository.getTagsFilteredByName(true)
FILTER_REQUEST_NAME_DESCENDING -> return mTagsRepository.getTagsFilteredByName(false)
FILTER_REQUEST_CREATED_ASCENDING -> return mTagsRepository.getTagsFilteredByCreated(true)
FILTER_REQUEST_CREATED_DESCENDING -> return mTagsRepository.getTagsFilteredByCreated(false)
}
return mTagsRepository.getTagsFilteredByName(true)
}
companion object {
const val FILTER_REQUEST_NAME_ASCENDING = 100
const val FILTER_REQUEST_NAME_DESCENDING = 200
const val FILTER_REQUEST_CREATED_ASCENDING = 300
const val FILTER_REQUEST_CREATED_DESCENDING = 400
}
}
| gpl-3.0 | 6afbc9b585238cf1fe3187c95a7049ab | 42.148936 | 116 | 0.751479 | 4.662069 | false | false | false | false |
meteochu/DecisionKitchen | Android/app/src/main/java/com/decisionkitchen/decisionkitchen/MainActivity.kt | 1 | 12006 | package com.decisionkitchen.decisionkitchen
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.constraint.ConstraintLayout
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import com.facebook.*
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.*
import com.google.firebase.database.*
import org.json.JSONObject
import java.util.Arrays
class MainActivity : AppCompatActivity() {
private val mAuth: FirebaseAuth = FirebaseAuth.getInstance()
internal var callbackManager: CallbackManager = CallbackManager.Factory.create()
private var user:FirebaseUser? = null
private var mRecyclerView:RecyclerView? = null
private var mAdapter:RecyclerView.Adapter<GroupAdapter.ViewHolder>? = null
private var mLayoutManager:RecyclerView.LayoutManager? = null
private fun getActivity(): Activity {
return this
}
private fun getContext(): Context {
return this
}
public fun getUser(): FirebaseUser? {
return user;
}
private fun getMainActivity(): MainActivity {
return this;
}
private fun loadData(user: FirebaseUser?) {
if (user == null) return
Log.e("test", "test")
val uid:String = user.uid
val ref:DatabaseReference = FirebaseDatabase.getInstance().getReference("groups")
ref.addValueEventListener( object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
var groups:List<Group> = ArrayList<Group>()
if (!snapshot.hasChildren())
return
val data = snapshot.children
for (point in data) {
val group = point.getValue(Group::class.java)
if (group != null && group.members!!.contains(user.uid)) {
groups += group
}
}
mAdapter = GroupAdapter(groups, mRecyclerView, getMainActivity())
mRecyclerView!!.adapter = mAdapter;
// var scrollView:ScrollView = getActivity().findViewById(R.id.groups) as ScrollView
//
// if (!snapshot.hasChildren()) {
// val noChats: TextView = TextView(getActivity())
// noChats.setText(R.string.no_groups_text)
// noChats.setPadding(0, 20, 0, 0)
// noChats.gravity = Gravity.CENTER
// noChats.textSize = 20f
//
// scrollView.removeAllViews()
// scrollView.addView(noChats)
//
// } else {
// val groups = snapshot.children
// val layout = LinearLayout(getContext())
// val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
// layout.layoutParams = layoutParams
// for (data in groups) {
// val groupLayout = LinearLayout(layout.context)
// groupLayout.orientation = LinearLayout.VERTICAL
// val groupLayoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
// groupLayout.layoutParams = groupLayoutParams
// val title = TextView(layout.context)
//
// val group = data.getValue(Group::class.java)
// title.text = group!!.name
// title.textSize = 20f
// title.width
// title.setTextColor(Color.BLACK)
// title.setPadding(0, 5, 0, 15)
// groupLayout.addView(title)
//
// val password = TextView(layout.context)
// password.text = group.password
// password.textSize = 13f
// password.setPadding(0, 5, 0, 15)
// password.setTextColor(Color.GRAY)
// groupLayout.addView(password)
//
// val divider = LinearLayout(layout.context)
// val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 2)
// divider.setBackgroundColor(Color.BLACK)
// divider.layoutParams = params
// groupLayout.addView(divider)
//
// layout.addView(groupLayout)
// groupLayout.setOnClickListener(object : View.OnClickListener {
// override fun onClick(v: View?) {
// goTest(data.key)
// }
// })
// }
// scrollView.removeAllViews()
// scrollView.addView(layout)
// }
//
// var linearLayout:LinearLayout = LinearLayout(getContext())
}
override fun onCancelled(error: DatabaseError) {
Log.e("error loading: ", error.toString())
}
})
}
private fun handleFacebookAccessToken(token: AccessToken) {
val credential:AuthCredential = FacebookAuthProvider.getCredential(token.token);
mAuth.signInWithCredential(credential).addOnCompleteListener(this, object : OnCompleteListener<AuthResult> {
override fun onComplete(task: Task<AuthResult>) {
if (task.isSuccessful) {
Toast.makeText(applicationContext, "Facebook Authentication succeeded.",
Toast.LENGTH_SHORT).show()
user = mAuth.currentUser
loadData(user)
val ref = FirebaseDatabase.getInstance().getReference("users")
ref.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
Log.e("error", p0.toString())
}
override fun onDataChange(snapshot: DataSnapshot) {
val u = user!!
if (snapshot.hasChild(u.uid))
return
val request : GraphRequest = GraphRequest.newMeRequest(token, GraphRequest.GraphJSONObjectCallback { json, response -> run {
ref.child(u.uid).child("img").setValue(json.getJSONObject("picture").getJSONObject("data").get("url"))
ref.child(u.uid).child("id").setValue(u.uid)
ref.child(u.uid).child("email").setValue(u.email)
ref.child(u.uid).child("name").setValue(json.get("name"))
ref.child(u.uid).child("first_name").setValue(json.get("first_name"))
ref.child(u.uid).child("last_name").setValue(json.get("last_name"))
}});
val parameters : Bundle = Bundle();
parameters.putString("fields", "name, picture, first_name, last_name");
request.parameters = parameters;
request.executeAsync();
}
})
} else {
// If sign in fails, display a message to the user.
Toast.makeText(applicationContext, "Google Authentication failed.",
Toast.LENGTH_SHORT).show()
}
}
});
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
user = mAuth.currentUser
if (user == null) {
LoginManager.getInstance().registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
handleFacebookAccessToken(loginResult.accessToken)
}
override fun onCancel() {
applicationContext.startActivity(Intent(applicationContext, LoginActivity::class.java))
}
override fun onError(error: FacebookException) {
Toast.makeText(applicationContext, "FB Authentication failed.",
Toast.LENGTH_SHORT).show();
/* throw error */
}
})
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"))
} else {
loadData(user)
}
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
mRecyclerView = findViewById(R.id.my_recycler_view) as RecyclerView
mRecyclerView!!.setHasFixedSize(true)
val rParams:CoordinatorLayout.LayoutParams = CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT)
mRecyclerView!!.layoutParams = rParams
mLayoutManager = LinearLayoutManager(getContext())
mRecyclerView!!.layoutManager = mLayoutManager
mLayoutManager!!.setMeasuredDimension(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT)
mAdapter = GroupAdapter(ArrayList<Group>(), mRecyclerView, getMainActivity())
mRecyclerView!!.adapter = mAdapter
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener { view ->
val intent: Intent = Intent(baseContext, SignUpActivity::class.java)
intent.putExtra("USER_ID", user!!.uid)
startActivity(intent)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu items for use in the action bar
val inflater = menuInflater
inflater.inflate(R.menu.main_activity_actions, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle presses on the action bar items
when (item.itemId) {
R.id.action_signout -> {
LoginManager.getInstance().logOut()
applicationContext.startActivity(Intent(applicationContext, LoginActivity::class.java))
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
/** Called when the user touches the button */
fun goTest(group: String) {
val intent:Intent = Intent(getBaseContext(), GroupActivity::class.java)
intent.putExtra("GROUP_ID", group)
startActivity(intent)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
callbackManager.onActivityResult(requestCode, resultCode, data)
}
}
| apache-2.0 | 3854d25c4ebc6befd27a444fb7969a74 | 39.153846 | 173 | 0.584624 | 5.376623 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/util/Listeners.kt | 1 | 1773 | /*
ParaTask Copyright (C) 2017 Nick Robinson>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.util
import java.lang.ref.WeakReference
import java.util.concurrent.CopyOnWriteArrayList
open class Listeners<T : Any> : Iterable<T> {
private var listeners = CopyOnWriteArrayList<WeakReference<T>>()
private var strongListeners = CopyOnWriteArrayList<T>()
val size: Int
get() = listeners.size
fun add(listener: T, weak: Boolean = true) {
listeners.add(WeakReference(listener))
if (!weak) {
strongListeners.add(listener)
}
}
open fun remove(listener: T) {
listeners.forEach {
if (it.get() === listener) {
listeners.remove(it)
}
}
strongListeners.remove(listener)
}
open fun forEach(action: (T) -> Unit) {
listeners.forEach {
val listener = it.get()
if (listener == null) {
listeners.remove(it)
} else {
action(listener)
}
}
}
override fun iterator(): Iterator<T> = listeners.map { it.get() }.filterNotNull().iterator()
}
| gpl-3.0 | 50a25c577957122e42fd2cb84b83b51b | 28.55 | 96 | 0.649182 | 4.388614 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/compound/ResourceParameter.kt | 1 | 3314 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.parameters.compound
import uk.co.nickthecoder.paratask.parameters.*
import uk.co.nickthecoder.paratask.util.Resource
import uk.co.nickthecoder.paratask.util.uncamel
import java.net.URL
class ResourceParameter(
name: String,
label: String = name.uncamel(),
description: String = "",
value: Resource? = null,
val expectFile: Boolean? = null,
required: Boolean = true)
: CompoundParameter<Resource?>(
name = name,
label = label,
description = description) {
val fileP = FileParameter(name + "_file", label = "File", required = required, expectFile = expectFile)
var file by fileP
val urlP = StringParameter(name + "_url", label = "URL", required = required)
var url by urlP
val fileOrUrlP = OneOfParameter(name + "_fileOrUrl", label = "", value = fileP, choiceLabel = "")
.addChoices(fileP, urlP)
var fileOrUrl by fileOrUrlP
override var value: Resource?
get() {
if (fileOrUrl == fileP) {
return file?.let { Resource(it) }
} else if (fileOrUrl == urlP) {
if (url.isNotBlank()) {
return Resource(url)
}
}
return null
}
set(v) {
if (v == null) {
fileOrUrl = fileP
file = null
url = ""
} else {
if (v.isFileOrDirectory()) {
fileOrUrl = fileP
file = v.file
} else {
fileOrUrl = urlP
url = v.url.toString()
}
}
}
override val converter = Resource.converter
init {
addParameters(fileOrUrlP, fileP, urlP)
asHorizontal(LabelPosition.NONE)
this.value = value
}
override fun errorMessage(v: Resource?): String? {
if (fileP.required && v == null) {
return "Required"
}
return null
}
override fun errorMessage(): String? {
if (fileOrUrl == null && fileP.required) {
return "Required"
}
if (fileOrUrl == urlP) {
try {
URL(url)
} catch (e: Exception) {
return "Invalid URL"
}
}
return null
}
override fun toString() = "Resource" + super.toString()
override fun copy() = ResourceParameter(name = name, label = label, description = description, value = value,
expectFile = expectFile, required = fileP.required)
}
| gpl-3.0 | 9794afd4735816c27736ba7943feba0d | 28.855856 | 113 | 0.574834 | 4.490515 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise | buildSrc/src/main/kotlin/com/engineer/plugin/PhoenixPlugin.kt | 1 | 2102 | package com.engineer.plugin
import com.android.build.gradle.AppExtension
import com.engineer.plugin.actions.CalculateAction
import com.engineer.plugin.actions.RenameAction
import com.engineer.plugin.actions.TaskTimeAction
import com.engineer.plugin.extensions.PhoenixExtension
import com.engineer.plugin.transforms.FooTransform
import com.engineer.plugin.transforms.cat.CatTransform
import com.engineer.plugin.transforms.tiger.TigerTransform
import com.engineer.plugin.transforms.track.TrackTransform
//import com.engineer.plugin.utils.GitTool
//import com.engineer.plugin.utils.JsonTool
import org.gradle.api.Plugin
import org.gradle.api.Project
/**
* @author rookie
* @since 11-29-2019
*/
class PhoenixPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.extensions.create("phoenix", PhoenixExtension::class.java, project.objects)
project.afterEvaluate {
println()
println("===================================PhoenixPlugin===============begin==================")
println()
RenameAction.apply(project)
TaskTimeAction(project).apply()
CalculateAction(project).apply()
println()
println("===================================PhoenixPlugin===============end==================")
println()
// JsonTool.test()
// GitTool.getGitBranch(project)
}
registerTransform(project)
}
private fun registerTransform(project: Project) {
val appExtension = project.extensions.getByName("android")
if (appExtension is AppExtension) {
appExtension.registerTransform(CatTransform(project))
val fooTransform = FooTransform(project)
if (fooTransform.isEnabled()) {
appExtension.registerTransform(fooTransform)
} else {
println("FooTransform disabled")
}
appExtension.registerTransform(TigerTransform(project))
appExtension.registerTransform(TrackTransform(project))
}
}
} | apache-2.0 | 888d118aec318e91e44c4247f89b1fe6 | 30.863636 | 109 | 0.639391 | 4.76644 | false | false | false | false |
cashapp/sqldelight | drivers/sqljs-driver/src/main/kotlin/app/cash/sqldelight/driver/sqljs/JsSqlDriver.kt | 1 | 5250 | package app.cash.sqldelight.driver.sqljs
import app.cash.sqldelight.Query
import app.cash.sqldelight.Transacter
import app.cash.sqldelight.TransacterImpl
import app.cash.sqldelight.db.QueryResult
import app.cash.sqldelight.db.SqlCursor
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.db.SqlPreparedStatement
import app.cash.sqldelight.db.SqlSchema
import org.khronos.webgl.Int8Array
import org.khronos.webgl.Uint8Array
import kotlin.js.Promise
fun Promise<Database>.driver(): Promise<SqlDriver> = then { JsSqlDriver(it) }
fun Promise<SqlDriver>.withSchema(schema: SqlSchema? = null): Promise<SqlDriver> = then {
schema?.create(it)
it
}
fun Promise<SqlDriver>.transacter(): Promise<Transacter> = then { object : TransacterImpl(it) {} }
fun initSqlDriver(schema: SqlSchema? = null): Promise<SqlDriver> = initDb().driver().withSchema(schema)
class JsSqlDriver(private val db: Database) : SqlDriver {
private val statements = mutableMapOf<Int, Statement>()
private var transaction: Transacter.Transaction? = null
private val listeners = mutableMapOf<String, MutableSet<Query.Listener>>()
override fun addListener(listener: Query.Listener, queryKeys: Array<String>) {
queryKeys.forEach {
listeners.getOrPut(it, { mutableSetOf() }).add(listener)
}
}
override fun removeListener(listener: Query.Listener, queryKeys: Array<String>) {
queryKeys.forEach {
listeners[it]?.remove(listener)
}
}
override fun notifyListeners(queryKeys: Array<String>) {
queryKeys.flatMap { listeners[it].orEmpty() }
.distinct()
.forEach(Query.Listener::queryResultsChanged)
}
override fun <R> executeQuery(
identifier: Int?,
sql: String,
mapper: (SqlCursor) -> R,
parameters: Int,
binders: (SqlPreparedStatement.() -> Unit)?,
): QueryResult<R> {
val cursor = createOrGetStatement(identifier, sql).run {
bind(parameters, binders)
JsSqlCursor(this)
}
return try {
QueryResult.Value(mapper(cursor))
} finally {
cursor.close()
}
}
override fun execute(identifier: Int?, sql: String, parameters: Int, binders: (SqlPreparedStatement.() -> Unit)?): QueryResult<Long> =
createOrGetStatement(identifier, sql).run {
bind(parameters, binders)
step()
freemem()
return QueryResult.Value(0)
}
private fun Statement.bind(parameters: Int, binders: (SqlPreparedStatement.() -> Unit)?) = binders?.let {
if (parameters > 0) {
val bound = JsSqlPreparedStatement(parameters)
binders(bound)
bind(bound.parameters.toTypedArray())
}
}
private fun createOrGetStatement(identifier: Int?, sql: String): Statement = if (identifier == null) {
db.prepare(sql)
} else {
statements.getOrPut(identifier, { db.prepare(sql) }).apply { reset() }
}
override fun newTransaction(): QueryResult<Transacter.Transaction> {
val enclosing = transaction
val transaction = Transaction(enclosing)
this.transaction = transaction
if (enclosing == null) {
db.run("BEGIN TRANSACTION")
}
return QueryResult.Value(transaction)
}
override fun currentTransaction() = transaction
override fun close() = db.close()
private inner class Transaction(
override val enclosingTransaction: Transacter.Transaction?,
) : Transacter.Transaction() {
override fun endTransaction(successful: Boolean): QueryResult<Unit> {
if (enclosingTransaction == null) {
if (successful) {
db.run("END TRANSACTION")
} else {
db.run("ROLLBACK TRANSACTION")
}
}
transaction = enclosingTransaction
return QueryResult.Unit
}
}
}
private class JsSqlCursor(private val statement: Statement) : SqlCursor {
override fun next(): Boolean = statement.step()
override fun getString(index: Int): String? = statement.get()[index]
override fun getLong(index: Int): Long? = (statement.get()[index] as? Double)?.toLong()
override fun getBytes(index: Int): ByteArray? = (statement.get()[index] as? Uint8Array)?.let {
Int8Array(it.buffer).unsafeCast<ByteArray>()
}
override fun getDouble(index: Int): Double? = statement.get()[index]
override fun getBoolean(index: Int): Boolean? {
val double = (statement.get()[index] as? Double)
return if (double == null) null
else double.toLong() == 1L
}
fun close() { statement.freemem() }
}
internal class JsSqlPreparedStatement(parameters: Int) : SqlPreparedStatement {
val parameters = MutableList<Any?>(parameters) { null }
override fun bindBytes(index: Int, bytes: ByteArray?) {
parameters[index] = bytes?.toTypedArray()
}
override fun bindLong(index: Int, long: Long?) {
// We convert Long to Double because Kotlin's Double is mapped to JS number
// whereas Kotlin's Long is implemented as a JS object
parameters[index] = long?.toDouble()
}
override fun bindDouble(index: Int, double: Double?) {
parameters[index] = double
}
override fun bindString(index: Int, string: String?) {
parameters[index] = string
}
override fun bindBoolean(index: Int, boolean: Boolean?) {
parameters[index] = when (boolean) {
null -> null
true -> 1.0
false -> 0.0
}
}
}
| apache-2.0 | 23aeb8eb79841824cc5e52a8591d7476 | 30.065089 | 136 | 0.690286 | 4.101563 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/android/support/v7/widget/TwidereToolbar.kt | 1 | 3044 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[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 android.support.v7.widget
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.Menu
import android.view.View
import android.widget.ImageView
import de.vanita5.twittnuker.extension.findFieldByTypes
import de.vanita5.twittnuker.extension.get
import de.vanita5.twittnuker.util.ThemeUtils
class TwidereToolbar(context: Context, attrs: AttributeSet?) : Toolbar(context, attrs) {
private var itemColor: Int = 0
override fun getMenu(): Menu {
val menu = super.getMenu()
ThemeUtils.setActionBarOverflowColor(this, itemColor)
val menuViewField = try {
Toolbar::class.java.findFieldByTypes(ActionMenuView::class.java)
} catch (e: Exception) {
null
} ?: return menu
val menuView = this[menuViewField] as? ActionMenuView ?: return menu
val presenterField = try {
ActionMenuView::class.java.findFieldByTypes(ActionMenuPresenter::class.java)
} catch (e: Exception) {
null
} ?: return menu
val presenter = menuView[presenterField] as? ActionMenuPresenter ?: return menu
setActionBarOverflowColor(presenter, itemColor)
return menu
}
override fun setNavigationIcon(icon: Drawable?) {
if (icon != null && itemColor != 0) {
icon.setColorFilter(itemColor, PorterDuff.Mode.SRC_ATOP)
}
super.setNavigationIcon(icon)
}
fun setItemColor(itemColor: Int) {
this.itemColor = itemColor
navigationIcon = navigationIcon
}
companion object {
private fun setActionBarOverflowColor(presenter: ActionMenuPresenter, itemColor: Int) {
val viewField = try {
ActionMenuPresenter::class.java.findFieldByTypes(ActionMenuView.ActionMenuChildView::class.java, View::class.java)
} catch (e: Exception) {
null
} ?: return
val view = presenter[viewField] as? ImageView ?: return
view.setColorFilter(itemColor, PorterDuff.Mode.SRC_ATOP)
}
}
} | gpl-3.0 | e149fc52e95322b172bfe151b2573cb9 | 35.686747 | 130 | 0.691196 | 4.430859 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/api/TwitterConverterFactory.kt | 1 | 3596 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.util.api
import android.support.v4.util.SimpleArrayMap
import com.bluelinelabs.logansquare.JsonMapper
import com.bluelinelabs.logansquare.ParameterizedType
import org.mariotaku.commons.logansquare.LoganSquareMapperFinder
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.mastodon.model.LinkHeaderList
import de.vanita5.microblog.library.twitter.model.ResponseCode
import de.vanita5.microblog.library.twitter.model.TwitterResponse
import de.vanita5.microblog.library.twitter.util.OAuthTokenResponseConverter
import org.mariotaku.restfu.RestConverter
import org.mariotaku.restfu.http.HttpResponse
import org.mariotaku.restfu.http.mime.Body
import org.mariotaku.restfu.http.mime.SimpleBody
import org.mariotaku.restfu.logansqaure.LoganSquareConverterFactory
import org.mariotaku.restfu.oauth.OAuthToken
import java.lang.reflect.Type
/**
* Convert JSON responses
*/
object TwitterConverterFactory : LoganSquareConverterFactory<MicroBlogException>() {
private val responseConverters = SimpleArrayMap<Type, RestConverter<HttpResponse, *, MicroBlogException>>()
private val bodyConverters = SimpleArrayMap<Type, RestConverter<*, Body, MicroBlogException>>()
init {
responseConverters.put(ResponseCode::class.java, ResponseCode.ResponseConverter())
responseConverters.put(OAuthToken::class.java, OAuthTokenResponseConverter())
}
override fun <T : Any?> mapperFor(type: ParameterizedType<T>): JsonMapper<T> {
return LoganSquareMapperFinder.mapperFor(type)
}
override fun <T : Any?> mapperFor(type: Class<T>): JsonMapper<T> {
return LoganSquareMapperFinder.mapperFor(type)
}
@Throws(RestConverter.ConvertException::class)
override fun forResponse(type: Type): RestConverter<HttpResponse, *, MicroBlogException> {
val converter = responseConverters.get(type)
if (converter != null) {
return converter
}
return super.forResponse(type)
}
@Throws(RestConverter.ConvertException::class)
override fun forRequest(type: Type): RestConverter<*, Body, MicroBlogException> {
val converter = bodyConverters.get(type)
if (converter != null) {
return converter
}
if (SimpleBody.supports(type)) {
return SimpleBodyConverter<MicroBlogException>(type)
}
return super.forRequest(type)
}
override fun processParsedObject(obj: Any, httpResponse: HttpResponse) {
when (obj) {
is TwitterResponse -> obj.processResponseHeader(httpResponse)
is LinkHeaderList<*> -> obj.processResponseHeader(httpResponse)
}
}
} | gpl-3.0 | 485b95ded12421e32b243c4a6aa57bfd | 38.097826 | 111 | 0.743882 | 4.337756 | false | false | false | false |
stripe/stripe-android | link/src/main/java/com/stripe/android/link/ui/wallet/PaymentDetails.kt | 1 | 9478 | package com.stripe.android.link.ui.wallet
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.RadioButton
import androidx.compose.material.RadioButtonDefaults
import androidx.compose.material.TabRowDefaults
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.stripe.android.link.R
import com.stripe.android.link.model.icon
import com.stripe.android.link.theme.MinimumTouchTargetSize
import com.stripe.android.link.theme.linkColors
import com.stripe.android.link.theme.linkShapes
import com.stripe.android.link.ui.ErrorText
import com.stripe.android.link.ui.ErrorTextStyle
import com.stripe.android.model.ConsumerPaymentDetails
import com.stripe.android.model.ConsumerPaymentDetails.Card
@Composable
internal fun PaymentDetailsListItem(
paymentDetails: ConsumerPaymentDetails.PaymentDetails,
enabled: Boolean,
isSupported: Boolean,
isSelected: Boolean,
isUpdating: Boolean,
onClick: () -> Unit,
onMenuButtonClick: () -> Unit
) {
Row(
modifier = Modifier
.fillMaxWidth()
.defaultMinSize(minHeight = 56.dp)
.clickable(enabled = enabled && isSupported, onClick = onClick),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = isSelected,
onClick = null,
modifier = Modifier.padding(start = 20.dp, end = 6.dp),
colors = RadioButtonDefaults.colors(
selectedColor = MaterialTheme.linkColors.actionLabelLight,
unselectedColor = MaterialTheme.linkColors.disabledText
)
)
Column(
modifier = Modifier
.padding(vertical = 8.dp)
.weight(1f)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
PaymentDetails(paymentDetails = paymentDetails, enabled = isSupported)
if (paymentDetails.isDefault) {
Box(
modifier = Modifier
.background(
color = MaterialTheme.colors.secondary,
shape = MaterialTheme.linkShapes.extraSmall
),
contentAlignment = Alignment.Center
) {
Text(
text = stringResource(id = R.string.wallet_default),
modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp),
color = MaterialTheme.linkColors.disabledText,
fontSize = 12.sp,
fontWeight = FontWeight.Medium
)
}
}
val showWarning = (paymentDetails as? Card)?.isExpired ?: false
if (showWarning && !isSelected) {
Icon(
painter = painterResource(R.drawable.ic_link_error),
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = MaterialTheme.linkColors.errorText
)
}
}
if (!isSupported) {
ErrorText(
text = stringResource(id = R.string.wallet_unavailable),
style = ErrorTextStyle.Small,
modifier = Modifier.padding(start = 8.dp, top = 8.dp, end = 8.dp)
)
}
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.size(MinimumTouchTargetSize)
.padding(end = 12.dp)
) {
if (isUpdating) {
CircularProgressIndicator(
modifier = Modifier.size(24.dp),
strokeWidth = 2.dp
)
} else {
IconButton(
onClick = onMenuButtonClick,
enabled = enabled
) {
Icon(
imageVector = Icons.Filled.MoreVert,
contentDescription = stringResource(R.string.edit),
tint = MaterialTheme.linkColors.actionLabelLight,
modifier = Modifier.size(24.dp)
)
}
}
}
}
TabRowDefaults.Divider(
modifier = Modifier.padding(horizontal = 20.dp),
color = MaterialTheme.linkColors.componentDivider,
thickness = 1.dp
)
}
@Composable
internal fun RowScope.PaymentDetails(
paymentDetails: ConsumerPaymentDetails.PaymentDetails,
enabled: Boolean
) {
when (paymentDetails) {
is Card -> {
CardInfo(card = paymentDetails, enabled = enabled)
}
is ConsumerPaymentDetails.BankAccount -> {
BankAccountInfo(bankAccount = paymentDetails, enabled = enabled)
}
}
}
@Composable
internal fun RowScope.CardInfo(
card: Card,
enabled: Boolean
) {
CompositionLocalProvider(LocalContentAlpha provides if (enabled) 1f else 0.6f) {
Row(
modifier = Modifier.weight(1f),
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = card.brand.icon),
contentDescription = card.brand.displayName,
modifier = Modifier
.width(38.dp)
.padding(horizontal = 6.dp),
alignment = Alignment.Center,
alpha = LocalContentAlpha.current
)
Text(
text = "•••• ",
color = MaterialTheme.colors.onPrimary
.copy(alpha = LocalContentAlpha.current)
)
Text(
text = card.last4,
color = MaterialTheme.colors.onPrimary
.copy(alpha = LocalContentAlpha.current),
style = MaterialTheme.typography.h6
)
}
}
}
@Composable
internal fun RowScope.BankAccountInfo(
bankAccount: ConsumerPaymentDetails.BankAccount,
enabled: Boolean
) {
CompositionLocalProvider(LocalContentAlpha provides if (enabled) 1f else 0.6f) {
Row(
modifier = Modifier.weight(1f),
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(bankAccount.icon),
contentDescription = null,
modifier = Modifier
.width(38.dp)
.padding(horizontal = 6.dp),
alignment = Alignment.Center,
alpha = LocalContentAlpha.current,
colorFilter = ColorFilter.tint(MaterialTheme.linkColors.actionLabelLight)
)
Column(horizontalAlignment = Alignment.Start) {
Text(
text = bankAccount.bankName,
color = MaterialTheme.colors.onPrimary
.copy(alpha = LocalContentAlpha.current),
overflow = TextOverflow.Ellipsis,
maxLines = 1,
style = MaterialTheme.typography.h6
)
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = "•••• ",
color = MaterialTheme.colors.onSecondary
.copy(alpha = LocalContentAlpha.current),
style = MaterialTheme.typography.body2
)
Text(
text = bankAccount.last4,
color = MaterialTheme.colors.onSecondary
.copy(alpha = LocalContentAlpha.current),
style = MaterialTheme.typography.body2
)
}
}
}
}
}
| mit | 7d1da487b3c7e3cd15845d920397d9e4 | 36.848 | 92 | 0.574403 | 5.472527 | false | false | false | false |
izmajlowiczl/Expensive | storage/src/main/java/pl/expensive/storage/DBOs.kt | 1 | 1503 | package pl.expensive.storage
import java.math.BigDecimal
import java.util.*
private const val col_uuid = "uuid"
typealias Id = UUID
//region TransactionDbo
const val tbl_label = "tbl_label"
const val tbl_label_col_id = col_uuid
const val tbl_label_col_name = "name"
data class LabelDbo(val id: Id,
val name: String)
//endregion
//region CurrencyDbo
const val tbl_currency = "tbl_currency"
const val tbl_currency_col_code = "code"
const val tbl_currency_col_format = "format"
data class CurrencyDbo(val code: String, val format: String)
//endregion
//region TransactionDbo
const val tbl_transaction = "tbl_transaction"
const val tbl_transaction_col_id = col_uuid
const val tbl_transaction_col_amount = "amount"
const val tbl_transaction_col_currency = "currency"
const val tbl_transaction_col_date = "date"
const val tbl_transaction_col_description = "description"
data class TransactionDbo(val uuid: UUID,
val amount: BigDecimal,
val currency: CurrencyDbo,
val date: Long, // time in millis
val description: String)
fun withdrawal(uuid: UUID = UUID.randomUUID(),
amount: BigDecimal,
currency: CurrencyDbo,
time: Long = Date().time,
desc: String = "") =
TransactionDbo(uuid, amount.negate(), currency, time, desc)
fun String.asBigDecimalWithdrawal(): BigDecimal = BigDecimal(this).negate()
//endregion
| gpl-3.0 | 505e60589d08d3d72dc54c62de675b09 | 30.3125 | 75 | 0.662009 | 3.873711 | false | false | false | false |
stripe/stripe-android | camera-core/src/main/java/com/stripe/android/camera/framework/Loop.kt | 1 | 10533 | package com.stripe.android.camera.framework
import androidx.annotation.RestrictTo
import com.stripe.android.camera.framework.time.Clock
import com.stripe.android.camera.framework.time.ClockMark
import com.stripe.android.camera.framework.time.Duration
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
internal object NoAnalyzersAvailableException : Exception()
internal object AlreadySubscribedException : Exception()
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
interface AnalyzerLoopErrorListener {
/**
* A failure occurred during frame analysis. If this returns true, the loop will terminate. If
* this returns false, the loop will continue to execute on new data.
*/
fun onAnalyzerFailure(t: Throwable): Boolean
/**
* A failure occurred while collecting the result of frame analysis. If this returns true, the
* loop will terminate. If this returns false, the loop will continue to execute on new data.
*/
fun onResultFailure(t: Throwable): Boolean
}
/**
* A loop to execute repeated analysis. The loop uses coroutines to run the [Analyzer.analyze]
* method. If the [Analyzer] is threadsafe, multiple coroutines will be used. If not, a single
* coroutine will be used.
*
* Any data enqueued while the analyzers are at capacity will be dropped.
*
* This will process data until the result aggregator returns true.
*
* Note: an analyzer loop can only be started once. Once it terminates, it cannot be restarted.
*
* @param analyzerPool: A pool of analyzers to use in this loop.
* @param analyzerLoopErrorListener: An error handler for this loop
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
sealed class AnalyzerLoop<DataFrame, State, Output>(
private val analyzerPool: AnalyzerPool<DataFrame, in State, Output>,
private val analyzerLoopErrorListener: AnalyzerLoopErrorListener,
private val statsName: String? = null
) : ResultHandler<DataFrame, Output, Boolean> {
private val started = AtomicBoolean(false)
protected var startedAt: ClockMark? = null
private var finished: Boolean = false
private val cancelMutex = Mutex()
private var workerJob: Job? = null
protected fun subscribeToFlow(
flow: Flow<DataFrame>,
processingCoroutineScope: CoroutineScope
): Job? {
if (!started.getAndSet(true)) {
startedAt = Clock.markNow()
} else {
analyzerLoopErrorListener.onAnalyzerFailure(AlreadySubscribedException)
return null
}
if (analyzerPool.analyzers.isEmpty()) {
analyzerLoopErrorListener.onAnalyzerFailure(NoAnalyzersAvailableException)
return null
}
workerJob = processingCoroutineScope.launch {
// This should be using analyzerPool.analyzers.forEach, but doing so seems to require
// API 24. It's unclear why this won't use the kotlin.collections version of `forEach`,
// but it's not during compile.
for (it in analyzerPool.analyzers) {
launch(Dispatchers.Default) {
startWorker(flow, it)
}
}
}
return workerJob
}
protected suspend fun unsubscribeFromFlow() = cancelMutex.withLock {
workerJob?.apply { if (isActive) { cancel() } }
workerJob = null
started.set(false)
finished = false
}
/**
* Launch a worker coroutine that has access to the analyzer's `analyze` method and the result
* handler
*/
private suspend fun startWorker(
flow: Flow<DataFrame>,
analyzer: Analyzer<DataFrame, in State, Output>
) {
flow.collect { frame ->
val stat = statsName?.let { Stats.trackRepeatingTask(it) }
try {
val analyzerResult = analyzer.analyze(frame, getState())
try {
finished = onResult(analyzerResult, frame)
} catch (t: Throwable) {
stat?.trackResult("result_failure")
handleResultFailure(t)
}
} catch (t: Throwable) {
stat?.trackResult("analyzer_failure")
handleAnalyzerFailure(t)
}
if (finished) {
unsubscribeFromFlow()
}
stat?.trackResult("success")
}
}
private suspend fun handleAnalyzerFailure(t: Throwable) {
if (withContext(Dispatchers.Main) { analyzerLoopErrorListener.onAnalyzerFailure(t) }) {
unsubscribeFromFlow()
}
}
private suspend fun handleResultFailure(t: Throwable) {
if (withContext(Dispatchers.Main) { analyzerLoopErrorListener.onResultFailure(t) }) {
unsubscribeFromFlow()
}
}
abstract fun getState(): State
}
/**
* This kind of [AnalyzerLoop] will process data until the result handler indicates that it has
* reached a terminal state and is no longer listening.
*
* Data can be added to a queue for processing by a camera or other producer. It will be consumed by
* FILO. If no data is available, the analyzer pauses until data becomes available.
*
* If the enqueued data exceeds the allowed memory size, the bottom of the data stack will be
* dropped and will not be processed. This alleviates memory pressure when producers are faster than
* the consuming analyzer.
*
* @param analyzerPool: A pool of analyzers to use in this loop.
* @param resultHandler: A result handler that will be called with the results from the analyzers in
* this loop.
* @param analyzerLoopErrorListener: An error handler for this loop
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class ProcessBoundAnalyzerLoop<DataFrame, State, Output>(
private val analyzerPool: AnalyzerPool<DataFrame, in State, Output>,
private val resultHandler: StatefulResultHandler<DataFrame, out State, Output, Boolean>,
analyzerLoopErrorListener: AnalyzerLoopErrorListener,
statsName: String? = null
) : AnalyzerLoop<DataFrame, State, Output>(
analyzerPool,
analyzerLoopErrorListener,
statsName
) {
/**
* Subscribe to a flow. Loops can only subscribe to a single flow at a time.
*/
fun subscribeTo(flow: Flow<DataFrame>, processingCoroutineScope: CoroutineScope) =
subscribeToFlow(flow, processingCoroutineScope)
/**
* Unsubscribe from the flow.
*/
fun unsubscribe() = runBlocking { unsubscribeFromFlow() }
override suspend fun onResult(result: Output, data: DataFrame) =
resultHandler.onResult(result, data)
override fun getState(): State = resultHandler.state
}
/**
* This kind of [AnalyzerLoop] will process data provided as part of its constructor. Data will be
* processed in the order provided.
*
* @param analyzerPool: A pool of analyzers to use in this loop.
* @param resultHandler: A result handler that will be called with the results from the analyzers in
* this loop.
* @param analyzerLoopErrorListener: An error handler for this loop
* @param timeLimit: If specified, this is the maximum allowed time for the loop to run. If the loop
* exceeds this duration, the loop will terminate
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class FiniteAnalyzerLoop<DataFrame, State, Output>(
private val analyzerPool: AnalyzerPool<DataFrame, in State, Output>,
private val resultHandler: TerminatingResultHandler<DataFrame, out State, Output>,
analyzerLoopErrorListener: AnalyzerLoopErrorListener,
private val timeLimit: Duration = Duration.INFINITE,
statsName: String? = null
) : AnalyzerLoop<DataFrame, State, Output>(
analyzerPool,
analyzerLoopErrorListener,
statsName
) {
private val framesProcessed: AtomicInteger = AtomicInteger(0)
private var framesToProcess = 0
fun process(frames: Collection<DataFrame>, processingCoroutineScope: CoroutineScope): Job? {
val channel = Channel<DataFrame>(capacity = frames.size)
framesToProcess = frames.map { channel.trySend(it) }.count { it.isSuccess }
return if (framesToProcess > 0) {
subscribeToFlow(channel.receiveAsFlow(), processingCoroutineScope)
} else {
processingCoroutineScope.launch { resultHandler.onAllDataProcessed() }
}
}
fun cancel() = runBlocking { unsubscribeFromFlow() }
override suspend fun onResult(result: Output, data: DataFrame): Boolean {
val framesProcessed = this.framesProcessed.incrementAndGet()
val timeElapsed = startedAt?.elapsedSince() ?: Duration.ZERO
resultHandler.onResult(result, data)
if (framesProcessed >= framesToProcess) {
resultHandler.onAllDataProcessed()
unsubscribeFromFlow()
} else if (timeElapsed > timeLimit) {
resultHandler.onTerminatedEarly()
unsubscribeFromFlow()
}
val allFramesProcessed = framesProcessed >= framesToProcess
val exceededTimeLimit = timeElapsed > timeLimit
return allFramesProcessed || exceededTimeLimit
}
override fun getState(): State = resultHandler.state
}
/**
* Consume this [Flow] using a channelFlow with no buffer. Elements emitted from [this] flow are
* offered to the underlying [channelFlow]. If the consumer is not currently suspended and waiting
* for the next element, the element is dropped.
*
* example:
* ```
* flow {
* (0..100).forEach {
* emit(it)
* delay(100)
* }
* }.backPressureDrop().collect {
* delay(1000)
* println(it)
* }
* ```
*
* @return a flow that only emits elements when the downstream [Flow.collect] is waiting for the
* next element
*/
@ExperimentalCoroutinesApi
internal suspend fun <T> Flow<T>.backPressureDrop(): Flow<T> =
channelFlow { [email protected] { trySend(it) } }
.buffer(capacity = Channel.RENDEZVOUS)
| mit | 917bfef784f9f2bcec445c76cef3435c | 36.088028 | 100 | 0.696573 | 4.633964 | false | false | false | false |
stripe/stripe-android | camera-core/src/main/java/com/stripe/android/camera/CameraAdapter.kt | 1 | 5972 | package com.stripe.android.camera
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.PointF
import android.util.Log
import android.view.Surface
import androidx.annotation.CheckResult
import androidx.annotation.IntDef
import androidx.annotation.MainThread
import androidx.annotation.RestrictTo
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ClosedSendChannelException
import kotlinx.coroutines.channels.onClosed
import kotlinx.coroutines.channels.onFailure
import kotlinx.coroutines.channels.onSuccess
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.runBlocking
/**
* Valid integer rotation values.
*/
@IntDef(
Surface.ROTATION_0,
Surface.ROTATION_90,
Surface.ROTATION_180,
Surface.ROTATION_270
)
@Retention(AnnotationRetention.SOURCE)
internal annotation class RotationValue
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
abstract class CameraAdapter<CameraOutput> : LifecycleEventObserver {
// TODO: change this to be a channelFlow once it's no longer experimental, add some capacity and use a backpressure drop strategy
private val imageChannel = Channel<CameraOutput>(capacity = Channel.RENDEZVOUS)
private var lifecyclesBound = 0
abstract val implementationName: String
companion object {
/**
* Determine if the device supports the camera features used by this SDK.
*/
@JvmStatic
fun isCameraSupported(context: Context): Boolean =
(context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)).also {
if (!it) Log.e(logTag, "System feature 'FEATURE_CAMERA_ANY' is unavailable")
}
/**
* Calculate degrees from a [RotationValue].
*/
@CheckResult
fun Int.rotationToDegrees(): Int = this * 90
val logTag: String = CameraAdapter::class.java.simpleName
}
protected fun sendImageToStream(image: CameraOutput) = try {
imageChannel.trySend(image).onClosed {
Log.w(logTag, "Attempted to send image to closed channel", it)
}.onFailure {
if (it != null) {
Log.w(logTag, "Failure when sending image to channel", it)
} else {
Log.v(logTag, "No analyzers available to process image")
}
}.onSuccess {
Log.v(logTag, "Successfully sent image to be processed")
}
} catch (e: ClosedSendChannelException) {
Log.w(logTag, "Attempted to send image to closed channel")
} catch (t: Throwable) {
Log.e(logTag, "Unable to send image to channel", t)
}
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
when (event) {
Lifecycle.Event.ON_DESTROY -> onDestroyed()
Lifecycle.Event.ON_PAUSE -> onPause()
Lifecycle.Event.ON_CREATE -> onCreate()
Lifecycle.Event.ON_START -> onStart()
Lifecycle.Event.ON_RESUME -> onResume()
Lifecycle.Event.ON_STOP -> onStop()
Lifecycle.Event.ON_ANY -> onAny()
}
}
protected open fun onDestroyed() {
runBlocking { imageChannel.close() }
}
protected open fun onPause() {
// support onPause events.
}
protected open fun onCreate() {
// support onCreate events.
}
protected open fun onStart() {
// support onStart events.
}
protected open fun onResume() {
// support onResume events.
}
protected open fun onStop() {
// support onStop events.
}
protected open fun onAny() {
// support onAny events.
}
/**
* Bind this camera manager to a lifecycle.
*/
open fun bindToLifecycle(lifecycleOwner: LifecycleOwner) {
lifecycleOwner.lifecycle.addObserver(this)
lifecyclesBound++
}
/**
* Unbind this camera from a lifecycle. This will pause the camera.
*/
open fun unbindFromLifecycle(lifecycleOwner: LifecycleOwner) {
lifecycleOwner.lifecycle.removeObserver(this)
lifecyclesBound--
if (lifecyclesBound < 0) {
Log.e(logTag, "Bound lifecycle count $lifecyclesBound is below 0")
lifecyclesBound = 0
}
this.onPause()
}
/**
* Determine if the adapter is currently bound.
*/
open fun isBoundToLifecycle() = lifecyclesBound > 0
/**
* Execute a task with flash support.
*/
abstract fun withFlashSupport(task: (Boolean) -> Unit)
/**
* Turn the camera torch on or off.
*/
abstract fun setTorchState(on: Boolean)
/**
* Determine if the torch is currently on.
*/
abstract fun isTorchOn(): Boolean
/**
* Determine if the device has multiple cameras.
*/
abstract fun withSupportsMultipleCameras(task: (Boolean) -> Unit)
/**
* Change to a new camera.
*/
abstract fun changeCamera()
/**
* Determine which camera is currently in use.
*/
abstract fun getCurrentCamera(): Int
/**
* Set the focus on a particular point on the screen.
*/
abstract fun setFocus(point: PointF)
/**
* Get the stream of images from the camera. This is a hot [Flow] of images with a back pressure strategy DROP.
* Images that are not read from the flow are dropped. This flow is backed by a [Channel].
*/
fun getImageStream(): Flow<CameraOutput> = imageChannel.receiveAsFlow()
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
interface CameraErrorListener {
@MainThread
fun onCameraOpenError(cause: Throwable?)
@MainThread
fun onCameraAccessError(cause: Throwable?)
@MainThread
fun onCameraUnsupportedError(cause: Throwable?)
}
| mit | c8345e152c851a3e9a0d3fa84e87a602 | 28.27451 | 133 | 0.660918 | 4.665625 | false | false | false | false |
mswift42/apg | Wo4/app/src/main/java/mswift42/com/github/wo4/WorkoutListFragment.kt | 1 | 1540 | package mswift42.com.github.wo4
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.ListFragment
import android.support.v4.widget.ListViewAutoScrollHelper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
/**
* A simple [Fragment] subclass.
*/
class WorkoutListFragment : ListFragment() {
internal interface WorkoutListListener {
fun itemClicked(id: Long)
}
private var listener: WorkoutListListener? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val names = arrayOfNulls<String>(Workout.workouts.size)
for (i in names.indices) {
names[i] = Workout.workouts[i].name
}
val adapter = ArrayAdapter<String>(
inflater!!.context, android.R.layout.simple_list_item_1, names)
listAdapter = adapter
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onAttach(context: Context?) {
super.onAttach(context)
this.listener = context as WorkoutListListener?
}
override fun onListItemClick(l: ListView?, v: View?, position: Int, id: Long) {
if (listener != null) {
listener!!.itemClicked(id)
}
}
}// Required empty public constructor
| gpl-3.0 | fd8feecbea0ec40654068fb0b440d6b5 | 29.196078 | 83 | 0.690909 | 4.489796 | false | false | false | false |
Undin/intellij-rust | toml/src/main/kotlin/org/rust/toml/completion/CratesIoCargoTomlDependencyCompletionProviders.kt | 3 | 3854 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.toml.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.util.ProcessingContext
import org.rust.lang.core.psi.ext.ancestorStrict
import org.rust.toml.CargoTomlPsiPattern
import org.rust.toml.StringValueInsertionHandler
import org.toml.lang.psi.TomlKeyValue
import org.toml.lang.psi.TomlKeySegment
import org.toml.lang.psi.TomlTable
/** @see CargoTomlPsiPattern.inDependencyKeyValue */
class CratesIoCargoTomlDependencyCompletionProvider : TomlKeyValueCompletionProviderBase() {
override fun completeKey(keyValue: TomlKeyValue, result: CompletionResultSet) {
val key = keyValue.key.segments.singleOrNull() ?: return
val variants = searchCrate(key).map { it.dependencyLine }
result.addAllElements(variants.map(LookupElementBuilder::create))
}
override fun completeValue(keyValue: TomlKeyValue, result: CompletionResultSet) {
val key = keyValue.key.segments.singleOrNull() ?: return
val version = getCrateLastVersion(key) ?: return
result.addElement(
LookupElementBuilder.create(version)
.withInsertHandler(StringValueInsertionHandler(keyValue))
)
}
}
/** @see CargoTomlPsiPattern.inSpecificDependencyHeaderKey */
class CratesIoCargoTomlSpecificDependencyHeaderCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val key = parameters.position.parent as? TomlKeySegment ?: return
val variants = searchCrate(key)
val elements = variants.map { variant ->
LookupElementBuilder.create(variant.name)
.withPresentableText(variant.dependencyLine)
.withInsertHandler { context, _ ->
val table = key.ancestorStrict<TomlTable>() ?: return@withInsertHandler
if (table.entries.isEmpty()) {
context.document.insertString(
context.selectionEndOffset + 1,
"\nversion = \"${variant.maxVersion}\""
)
}
}
}
result.addAllElements(elements)
}
}
/** @see CargoTomlPsiPattern.inSpecificDependencyKeyValue */
class CratesIoCargoTomlSpecificDependencyVersionCompletionProvider : TomlKeyValueCompletionProviderBase() {
override fun completeKey(keyValue: TomlKeyValue, result: CompletionResultSet) {
val dependencyNameKey = getDependencyKeyFromTableHeader(keyValue)
val version = getCrateLastVersion(dependencyNameKey) ?: return
result.addElement(LookupElementBuilder.create("version = \"$version\""))
}
override fun completeValue(keyValue: TomlKeyValue, result: CompletionResultSet) {
val dependencyNameKey = getDependencyKeyFromTableHeader(keyValue)
val version = getCrateLastVersion(dependencyNameKey) ?: return
result.addElement(
LookupElementBuilder.create(version)
.withInsertHandler(StringValueInsertionHandler(keyValue))
)
}
private fun getDependencyKeyFromTableHeader(keyValue: TomlKeyValue): TomlKeySegment {
val table = keyValue.parent as? TomlTable
?: error("PsiElementPattern must not allow keys outside of TomlTable")
return table.header.key?.segments?.lastOrNull()
?: error("PsiElementPattern must not allow KeyValues in tables without header")
}
}
| mit | 4f1090045446c4b40d3855510eeebb88 | 42.795455 | 124 | 0.712766 | 5.27223 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/facade/src/test/kotlin/com/teamwizardry/librarianlib/facade/test/screens/pastry/tests/PastryTestTooltips.kt | 1 | 3568 | package com.teamwizardry.librarianlib.facade.test.screens.pastry.tests
import com.teamwizardry.librarianlib.facade.layer.GuiLayer
import com.teamwizardry.librarianlib.facade.layers.RectLayer
import com.teamwizardry.librarianlib.facade.layers.TextLayer
import com.teamwizardry.librarianlib.facade.layers.minecraft.ItemStackLayer
import com.teamwizardry.librarianlib.facade.test.screens.pastry.PastryTestBase
import com.teamwizardry.librarianlib.core.util.vec
import com.teamwizardry.librarianlib.facade.layers.text.TextFit
import com.teamwizardry.librarianlib.facade.pastry.layers.*
import net.minecraft.item.ItemStack
import net.minecraft.item.Items
import java.awt.Color
class PastryTestTooltips: PastryTestBase() {
init {
this.stack.add(PastryButton("Truncated text", 0, 0, 50).also {
it.tooltipText = "Tooltips!"
})
this.stack.add(PastryButton("Short text", 0, 0, 100).also {
it.tooltipText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Duis ultricies sit amet purus vel sagittis. Nunc commodo est est."
})
this.stack.add(PastryButton("Complex", 0, 0, 100).also {
it.tooltip = ComplexTooltip(
ItemStack(Items.GOLDEN_APPLE),
"To eat a golden apple, press and hold use while it is selected in the hotbar. " +
"Both restore 4 points of hunger and 9.6 hunger saturation."
)
})
this.stack.add(PastryButton("Vanilla", 0, 0, 100).also {
val tt = VanillaTooltip()
it.tooltip = tt
tt.lines = listOf(
"§6§nI'm important",
"Wheee! Such §evanilla§r, much §7plain",
"Many lines!"
)
})
this.stack.add(PastryButton("Faux vanilla", 0, 0, 100).also {
val tt = PastryBasicTooltip(vanilla = true)
it.tooltip = tt
tt.text = "§6§nI'm important\n§rWheee! Such §evanilla§r, much §7plain§r\nMany lines!"
})
this.stack.add(PastryButton("ItemStack", 0, 0, 100).also {
val tt = ItemStackTooltip()
it.tooltip = tt
val stack = ItemStack(Items.DIAMOND_AXE, 3)
tt.stack = stack
})
this.stack.add(GuiLayer(0, 0, 200, 50).also { outer ->
outer.add(RectLayer(Color.WHITE).also {
it.frame = outer.bounds
})
outer.add(GuiLayer(150, 10, 40, 30).also { inner ->
inner.add(RectLayer(Color.BLUE).also {
it.frame = inner.bounds
})
})
outer.tooltipText = "Outer tooltip"
outer.add(PastryButton("Short text", 10, 10, 100).also {
it.tooltipText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Duis ultricies sit amet purus vel sagittis. Nunc commodo est est."
})
})
}
}
class ComplexTooltip(val stack: ItemStack, val text: String): PastryTooltip() {
private val textLayer = TextLayer(18, 1)
private val itemStackLayer = ItemStackLayer(1, 1)
init {
contents.add(itemStackLayer, textLayer)
textLayer.color = Color.WHITE
itemStackLayer.stack = stack
textLayer.text = text
}
override fun layoutContents(maxWidth: Double) {
textLayer.width = maxWidth - 20
textLayer.fitToText(TextFit.VERTICAL_SHRINK)
contents.size = vec(textLayer.frame.maxX + 2, textLayer.height + 2)
}
}
| lgpl-3.0 | d190e4bc16b961c8c7bcbd4bfae90201 | 38.955056 | 98 | 0.61333 | 4.087356 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/fixes/ChangeRefToMutableFix.kt | 3 | 1299 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.fixes
import com.intellij.codeInspection.LocalQuickFixOnPsiElement
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.RsUnaryExpr
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.UnaryOperator
import org.rust.lang.core.psi.ext.operatorType
/**
* Fix that converts the given immutable reference to a mutable reference.
* @param expr An element, that represents an immutable reference.
*/
class ChangeRefToMutableFix(expr: RsElement) : LocalQuickFixOnPsiElement(expr) {
override fun getText() = "Change reference to mutable"
override fun getFamilyName() = text
override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) {
val ref = startElement as? RsUnaryExpr ?: return
if (ref.operatorType != UnaryOperator.REF) return
val innerExpr = ref.expr ?: return
val mutableExpr = RsPsiFactory(project).tryCreateExpression("&mut ${innerExpr.text}") ?: return
startElement.replace(mutableExpr)
}
}
| mit | 5d23b3f6488101b872db6c0b29385942 | 36.114286 | 108 | 0.756736 | 4.23127 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsConstantConditionIfInspection.kt | 2 | 4502 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.prevLeaf
import org.rust.ide.inspections.fixes.SubstituteTextFix
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.types.consts.asBool
import org.rust.lang.utils.evaluation.evaluate
/** See also [RsRedundantElseInspection]. */
class RsConstantConditionIfInspection : RsLocalInspectionTool() {
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor =
object : RsVisitor() {
override fun visitIfExpr(ifExpr: RsIfExpr) {
val condition = ifExpr.condition ?: return
if (condition.expr?.descendantOfTypeOrSelf<RsLetExpr>() != null) return
val conditionValue = condition.expr?.evaluate()?.asBool() ?: return
val isUsedAsExpression = ifExpr.isUsedAsExpression()
val fix = if (!conditionValue && ifExpr.elseBranch == null) {
val isInsideCascadeIf = ifExpr.isInsideCascadeIf
if (isUsedAsExpression && !isInsideCascadeIf) return
createDeleteElseBranchFix(ifExpr, isInsideCascadeIf)
} else {
SimplifyFix(conditionValue)
}
holder.registerProblem(condition, "Condition is always ''$conditionValue''", fix)
}
}
private fun createDeleteElseBranchFix(ifExpr: RsIfExpr, isInsideCascadeIf: Boolean): SubstituteTextFix {
val ifRange = ifExpr.rangeWithPrevSpace
val deletionRange = if (isInsideCascadeIf) {
val parentElse = (ifExpr.parent as RsElseBranch).`else`
val elseRange = parentElse.rangeWithPrevSpace(parentElse.prevLeaf())
elseRange.union(ifRange)
} else {
ifRange
}
return SubstituteTextFix.delete(
"Delete expression",
ifExpr.containingFile,
deletionRange
)
}
}
private class SimplifyFix(
private val conditionValue: Boolean,
) : LocalQuickFix {
override fun getFamilyName(): String = name
override fun getName(): String = "Simplify expression"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val ifExpr = descriptor.psiElement.ancestorStrict<RsIfExpr>() ?: return
// `if false {} else if ... {} else ...`
ifExpr.elseBranch?.ifExpr?.let { elseIfExpr ->
if (!conditionValue) {
ifExpr.replace(elseIfExpr)
return
}
}
val branch = (if (conditionValue) ifExpr.block else ifExpr.elseBranch?.block) ?: return
val replaced = ifExpr.replaceWithBlockContent(branch)
if (replaced != null) {
descriptor.findExistingEditor()?.caretModel?.moveToOffset(replaced.startOffset)
}
}
}
private fun RsIfExpr.isUsedAsExpression(): Boolean = parent !is RsExprStmt
private fun RsIfExpr.replaceWithBlockContent(branch: RsBlock): PsiElement? {
val parent = parent
val firstStmt = branch.lbrace.getNextNonWhitespaceSibling()!!
val lastStmt = branch.rbrace.getPrevNonWhitespaceSibling()!!
return if (parent is RsExprStmt) {
if (!parent.isTailStmt) {
// fn main() {
// if true { 1 } else { 0 }
// func();
// }
block?.syntaxTailStmt?.addSemicolon()
}
val ifStmt = parent as? RsExprStmt ?: this as RsElement
if (firstStmt != branch.rbrace) {
ifStmt.parent.addRangeAfter(firstStmt, lastStmt, ifStmt)
}
ifStmt.delete()
return null
} else {
val replaceWith = when {
isInsideCascadeIf -> branch
firstStmt == lastStmt && firstStmt is RsExprStmt && !firstStmt.hasSemicolon -> firstStmt.expr
else -> branch.wrapAsBlockExpr(RsPsiFactory(project))
}
replace(replaceWith)
}
}
private val RsIfExpr.isInsideCascadeIf get() = parent is RsElseBranch
private fun RsBlock.wrapAsBlockExpr(factory: RsPsiFactory): RsBlockExpr {
val blockExpr = factory.createBlockExpr("")
blockExpr.block.replace(this)
return blockExpr
}
| mit | 408bbd25a6fa96ac5969a6768f57a7b6 | 36.206612 | 108 | 0.645269 | 4.674974 | false | false | false | false |
androidx/androidx | camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/adapter/CameraFactoryAdapter.kt | 3 | 2975 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.integration.adapter
import android.content.Context
import androidx.annotation.RequiresApi
import androidx.camera.camera2.pipe.CameraId
import androidx.camera.camera2.pipe.core.Debug
import androidx.camera.camera2.pipe.core.Log.debug
import androidx.camera.camera2.pipe.core.Timestamps
import androidx.camera.camera2.pipe.core.Timestamps.formatMs
import androidx.camera.camera2.pipe.core.Timestamps.measureNow
import androidx.camera.camera2.pipe.integration.config.CameraAppComponent
import androidx.camera.camera2.pipe.integration.config.CameraAppConfig
import androidx.camera.camera2.pipe.integration.config.CameraConfig
import androidx.camera.camera2.pipe.integration.config.DaggerCameraAppComponent
import androidx.camera.core.CameraSelector
import androidx.camera.core.impl.CameraFactory
import androidx.camera.core.impl.CameraInternal
import androidx.camera.core.impl.CameraThreadConfig
import kotlinx.coroutines.runBlocking
/**
* The [CameraFactoryAdapter] is responsible for creating the root dagger component that is used
* to share resources across Camera instances.
*/
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
class CameraFactoryAdapter(
context: Context,
threadConfig: CameraThreadConfig,
availableCamerasSelector: CameraSelector?
) : CameraFactory {
private val appComponent: CameraAppComponent by lazy {
Debug.traceStart { "CameraFactoryAdapter#appComponent" }
val start = Timestamps.now()
val result = DaggerCameraAppComponent.builder()
.config(CameraAppConfig(context, threadConfig))
.build()
debug { "Created CameraFactoryAdapter in ${start.measureNow().formatMs()}" }
debug { "availableCamerasSelector: $availableCamerasSelector " }
Debug.traceStop()
result
}
init {
debug { "Created CameraFactoryAdapter" }
}
override fun getCamera(cameraId: String): CameraInternal =
appComponent.cameraBuilder()
.config(CameraConfig(CameraId(cameraId)))
.build()
.getCameraInternal()
override fun getAvailableCameraIds(): Set<String> =
runBlocking { appComponent.getCameraPipe().cameras().ids().map { it.value }.toSet() }
override fun getCameraManager(): Any? = appComponent
} | apache-2.0 | 0e08c6c8b85ace13b16d1b748c57aa69 | 40.333333 | 96 | 0.757311 | 4.487179 | false | true | false | false |
MoonlightOwl/Yui | src/main/kotlin/totoro/yui/util/api/HackerNews.kt | 1 | 3006 | package totoro.yui.util.api
import com.beust.klaxon.JsonArray
import com.beust.klaxon.JsonObject
import com.beust.klaxon.Parser
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.result.Result
import totoro.yui.util.LimitedHashMap
import totoro.yui.util.api.data.Story
object HackerNews {
private const val MAX_HISTORY_SIZE = 200
private fun stories(filter: String, success: (MutableList<Long>) -> Unit, failure: () -> Unit) {
"https://hacker-news.firebaseio.com/v0/${filter}stories.json".httpGet().responseString { _, _, result ->
when (result) {
is Result.Failure -> failure()
is Result.Success -> {
@Suppress("UNCHECKED_CAST")
val array = Parser().parse(StringBuilder(result.value)) as JsonArray<Long>
success(array.value)
}
}
}
}
private fun story(id: Long, success: (Story) -> Unit, failure: () -> Unit, then: () -> Unit) {
"https://hacker-news.firebaseio.com/v0/item/$id.json".httpGet().responseString { _, _, result ->
when (result) {
is Result.Failure -> failure()
is Result.Success -> {
val json = Parser().parse(StringBuilder(result.value)) as JsonObject
val score = json.int("score")
val title = json.string("title")
val url = json.string("url")
if (score != null && title != null && url != null) {
success(Story(score, title, url))
then()
} else failure()
}
}
}
}
private fun firstUnreadStory(filter: String, history: LimitedHashMap<Long, Boolean>,
success: (Story) -> Unit, failure: () -> Unit, then: () -> Unit) {
stories(filter,
{ list ->
val id = list.first { !history.contains(it) }
story(id,
{ story ->
history[id] = true
success(story)
}, failure, then
)
}, failure
)
}
private val topHistory = LimitedHashMap<Long, Boolean>(MAX_HISTORY_SIZE)
fun topStory(success: (Story) -> Unit, failure: () -> Unit, then: () -> Unit) =
firstUnreadStory("top", topHistory, success, failure, then)
private val bestHistory = LimitedHashMap<Long, Boolean>(MAX_HISTORY_SIZE)
fun bestStory(success: (Story) -> Unit, failure: () -> Unit, then: () -> Unit) =
firstUnreadStory("best", bestHistory, success, failure, then)
private val newHistory = LimitedHashMap<Long, Boolean>(MAX_HISTORY_SIZE)
fun newStory(success: (Story) -> Unit, failure: () -> Unit, then: () -> Unit) =
firstUnreadStory("new", newHistory, success, failure, then)
}
| mit | a68e0e2c025fb9ffd1fd78bff667d609 | 40.75 | 112 | 0.530605 | 4.466568 | false | false | false | false |
oleksiyp/mockk | mockk/common/src/main/kotlin/io/mockk/impl/recording/CommonCallRecorder.kt | 1 | 2782 | package io.mockk.impl.recording
import io.mockk.Invocation
import io.mockk.Matcher
import io.mockk.MockKGateway.*
import io.mockk.RecordedCall
import io.mockk.impl.instantiation.AbstractInstantiator
import io.mockk.impl.instantiation.AnyValueGenerator
import io.mockk.impl.log.Logger
import io.mockk.impl.log.SafeToString
import io.mockk.impl.recording.states.CallRecordingState
import io.mockk.impl.stub.StubRepository
import kotlin.reflect.KClass
class CommonCallRecorder(
val stubRepo: StubRepository,
val instantiator: AbstractInstantiator,
val signatureValueGenerator: SignatureValueGenerator,
val mockFactory: MockFactory,
val anyValueGenerator: AnyValueGenerator,
val safeToString: SafeToString,
val factories: CallRecorderFactories,
val initialState: (CommonCallRecorder) -> CallRecordingState,
val ack: VerificationAcknowledger
) : CallRecorder {
override val calls = mutableListOf<RecordedCall>()
var state: CallRecordingState = initialState(this)
var childHinter = factories.childHinter()
override fun startStubbing() {
state = factories.stubbingState(this)
log.trace { "Starting stubbing" }
}
override fun startVerification(params: VerificationParameters) {
state = factories.verifyingState(this, params)
log.trace { "Starting verification" }
}
override fun startExclusion(params: ExclusionParameters) {
state = factories.exclusionState(this, params)
log.trace { "Starting exclusion" }
}
override fun done() {
state = state.recordingDone()
}
override fun round(n: Int, total: Int) = state.round(n, total)
override fun nCalls() = state.nCalls()
override fun <T : Any> matcher(matcher: Matcher<*>, cls: KClass<T>): T = state.matcher(matcher, cls)
override fun call(invocation: Invocation) = state.call(invocation)
override fun answerOpportunity() = state.answerOpportunity()
override fun estimateCallRounds(): Int = state.estimateCallRounds()
override fun wasNotCalled(list: List<Any>) = state.wasNotCalled(list)
override fun hintNextReturnType(cls: KClass<*>, n: Int) = childHinter.hint(n, cls)
override fun discardLastCallRound() = state.discardLastCallRound()
override fun isLastCallReturnsNothing() = state.isLastCallReturnsNothing()
override fun reset() {
calls.clear()
childHinter = factories.childHinter()
state = initialState(this)
}
fun <T> safeExec(block: () -> T): T {
val prevState = state
try {
state = factories.safeLoggingState(this)
return block()
} finally {
state = prevState
}
}
companion object {
val log = Logger<CommonCallRecorder>()
}
}
| apache-2.0 | 6ccb2d01e96c525b1a44a1f3e81d3107 | 33.345679 | 104 | 0.706326 | 4.437002 | false | false | false | false |
jrgonzalezg/OpenLibraryApp | app/src/main/kotlin/com/github/jrgonzalezg/openlibrary/data/database/MyApplicationDatabase.kt | 1 | 1848 | /*
* Copyright (C) 2017 Juan Ramón González González (https://github.com/jrgonzalezg)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.jrgonzalezg.openlibrary.data.database
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.arch.persistence.room.TypeConverters
import android.content.Context
import com.github.jrgonzalezg.openlibrary.features.books.data.database.BookDao
import com.github.jrgonzalezg.openlibrary.features.books.data.database.BookEntity
import com.github.jrgonzalezg.openlibrary.features.books.data.database.BookSummaryEntity
@Database(entities = arrayOf(BookEntity::class, BookSummaryEntity::class), version = 1)
@TypeConverters(Converters::class)
abstract class MyApplicationDatabase : RoomDatabase() {
abstract fun bookDao(): BookDao
companion object {
private const val DB_NAME = "books.db"
fun createInMemoryDatabase(context: Context): MyApplicationDatabase
= Room.inMemoryDatabaseBuilder(context.applicationContext,
MyApplicationDatabase::class.java).build()
fun createPersistentDatabase(context: Context): MyApplicationDatabase
= Room.databaseBuilder(context.applicationContext, MyApplicationDatabase::class.java,
DB_NAME).build()
}
}
| apache-2.0 | 1cd7baf443fd0fc28de4ba03f38af8e9 | 40.931818 | 93 | 0.784824 | 4.42446 | false | false | false | false |
Sylvilagus/SylvaBBSClient | SylvaBBSClient/app/src/main/java/com/sylva/sylvabbsclient/view/activity/LoginActivity.kt | 1 | 2379 | package com.sylva.sylvabbsclient.view.activity
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.TextInputLayout
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import com.sylva.sylvabbsclient.R
import com.sylva.sylvabbsclient.global.find
import com.sylva.sylvabbsclient.presenter.impl.LoginPresenter
import com.sylva.sylvabbsclient.view.ILoginView
/**
* Created by sylva on 2016/3/20.
*/
class LoginActivity: BaseActivity(),ILoginView {
val mEtUserName:EditText by lazy {find<EditText>(R.id.login_userName)}
val mEtPassword:EditText by lazy {find<EditText>(R.id.login_password)}
val mCbRememberMe:CheckBox by lazy {find<CheckBox>(R.id.login_rememberme)}
val mBtnLogin: Button by lazy {find<Button>(R.id.login_submit)}
val mBtnRegister: View by lazy {find<View>(R.id.login_register)}
val mPresenter=LoginPresenter(this)
val mVgUserNameWrapper:TextInputLayout by lazy {findViewById(R.id.login_userNameWrapper) as TextInputLayout}
val mVgPasswordWrapper:TextInputLayout by lazy {findViewById(R.id.login_passwordWrapper) as TextInputLayout}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
mBtnLogin.setOnClickListener{mPresenter.login() }
}
override fun getUserName(): String =mEtUserName.text.toString()
override fun getPassword(): String =mEtPassword.text.toString()
override fun getRememberMe(): Boolean? =mCbRememberMe.isChecked
override fun setUserName(userName: String) {
mEtUserName.setText(userName)
}
override fun setPassword(password: String) {
mEtPassword.setText(password)
}
override fun setRememberMe(rememberMe: Boolean) {
mCbRememberMe.isChecked=rememberMe
}
override fun userNameError(msg: String) {
mVgUserNameWrapper.error=msg
}
override fun passwordError(msg: String) {
mVgPasswordWrapper.error=msg
}
override fun loginSuccess() {
startActivity(Intent(this,MainActivity::class.java))
}
override fun loginFailed(msg: String) {
throw UnsupportedOperationException()
}
override fun toggleInputUnits(enable: Boolean) {
throw UnsupportedOperationException()
}
} | apache-2.0 | b693d762788e266c943ee908674398b4 | 34 | 112 | 0.746532 | 4.032203 | false | false | false | false |
codehz/container | app/src/main/java/one/codehz/container/adapters/ComponentListAdapter.kt | 1 | 1632 | package one.codehz.container.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import one.codehz.container.R
import one.codehz.container.base.BaseAdapter
import one.codehz.container.base.BaseViewHolder
import one.codehz.container.ext.get
import one.codehz.container.models.ComponentInfoModel
class ComponentListAdapter(val hasCount: Boolean, val onClick: (Long, String, String) -> Unit) : BaseAdapter<ComponentListAdapter.ViewHolder, ComponentInfoModel>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(parent)
override fun onSetupViewHolder(holder: ViewHolder, data: ComponentInfoModel) = holder updateData data
inner class ViewHolder(parent: ViewGroup) : BaseViewHolder<ComponentInfoModel>(LayoutInflater.from(parent.context).inflate(R.layout.component_info_item, parent, false)) {
val typeView by lazy<TextView> { itemView[R.id.type_text] }
val titleView by lazy<TextView> { itemView[R.id.title] }
val countView by lazy<TextView> { itemView[R.id.count_text] }
var id: Long = 0
init {
itemView.setOnClickListener {
onClick(id, typeView.text.toString(), titleView.text.toString())
}
}
override fun updateData(data: ComponentInfoModel) {
typeView.text = data.type
titleView.text = data.name
id = data.id
if (hasCount)
countView.text = data.count
countView.visibility = if (hasCount) View.VISIBLE else View.GONE
}
}
} | gpl-3.0 | 623602c18ae9677019d578c01b414aaa | 40.871795 | 174 | 0.704044 | 4.387097 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/psi/impl/LuaLiteralExprMixin.kt | 2 | 2737 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.psi.impl
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.LiteralTextEscaper
import com.intellij.psi.PsiLanguageInjectionHost
import com.intellij.psi.stubs.IStubElementType
import com.intellij.psi.tree.IElementType
import com.tang.intellij.lua.lang.type.LuaString
import com.tang.intellij.lua.psi.LuaElementFactory
import com.tang.intellij.lua.psi.LuaLiteralExpr
import com.tang.intellij.lua.psi.LuaLiteralKind
import com.tang.intellij.lua.psi.kind
import com.tang.intellij.lua.stubs.LuaLiteralExprStub
import java.lang.StringBuilder
internal class TextEscaper(host: LuaLiteralExprMixin) : LiteralTextEscaper<LuaLiteralExprMixin>(host) {
override fun isOneLine(): Boolean {
return true
}
override fun decode(textRange: TextRange, builder: StringBuilder): Boolean {
val content = LuaString.getContent(myHost.text)
builder.append(content.value)
return true
}
override fun getOffsetInHost(offsetInDecoded: Int, range: TextRange): Int {
return offsetInDecoded + range.startOffset
}
}
abstract class LuaLiteralExprMixin
: LuaExprStubMixin<LuaLiteralExprStub>, PsiLanguageInjectionHost, LuaLiteralExpr {
constructor(stub: LuaLiteralExprStub, nodeType: IStubElementType<*, *>)
: super(stub, nodeType)
constructor(node: ASTNode) : super(node)
constructor(stub: LuaLiteralExprStub, nodeType: IElementType, node: ASTNode)
: super(stub, nodeType, node)
override fun updateText(text: String): PsiLanguageInjectionHost {
val expr = LuaElementFactory.createLiteral(project, text)
node.replaceChild(node.firstChildNode, expr.node.firstChildNode)
return this
}
override fun createLiteralTextEscaper(): LiteralTextEscaper<out PsiLanguageInjectionHost> {
return TextEscaper(this)
}
override fun isValidHost(): Boolean {
if (kind == LuaLiteralKind.String) {
val content = LuaString.getContent(text)
return content.start >= 2
}
return false
}
} | apache-2.0 | 6a92ccec320f04b17510036a9256b8e6 | 34.102564 | 103 | 0.738034 | 4.393258 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/secure/dto/SecureSmsNotification.kt | 1 | 2022 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.secure.dto
import com.google.gson.annotations.SerializedName
import kotlin.String
/**
* @param appId - Application ID
* @param date - Date when message has been sent in Unixtime
* @param id - Notification ID
* @param message - Messsage text
* @param userId - User ID
*/
data class SecureSmsNotification(
@SerializedName("app_id")
val appId: String? = null,
@SerializedName("date")
val date: String? = null,
@SerializedName("id")
val id: String? = null,
@SerializedName("message")
val message: String? = null,
@SerializedName("user_id")
val userId: String? = null
)
| mit | 265fa023e1d331960c732d9c998640f5 | 38.647059 | 81 | 0.676063 | 4.463576 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/dmsexplorer/view/dialog/SelectRendererDialog.kt | 1 | 2747 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.view.dialog
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import net.mm2d.dmsexplorer.R
import net.mm2d.dmsexplorer.Repository
import net.mm2d.dmsexplorer.databinding.RendererSelectDialogBinding
import net.mm2d.dmsexplorer.log.EventLogger
import net.mm2d.dmsexplorer.util.ItemSelectUtils
import net.mm2d.dmsexplorer.view.adapter.RendererListAdapter
/**
* 再生機器選択を行うダイアログ。
*
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class SelectRendererDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val activity = requireActivity()
val builder = AlertDialog.Builder(activity)
val model = Repository.get().controlPointModel
val cp = model.mrControlPoint
val rendererList = cp.deviceList
if (rendererList.isEmpty()) {
dismiss()
return builder.create()
}
val adapter = RendererListAdapter(activity, rendererList)
adapter.setOnItemClickListener { _, renderer ->
model.setSelectedMediaRenderer(renderer)
EventLogger.sendSelectRenderer()
ItemSelectUtils.sendSelectedRenderer(activity)
dismiss()
}
val inflater = LayoutInflater.from(activity)
val binding = DataBindingUtil.inflate<RendererSelectDialogBinding>(
inflater,
R.layout.renderer_select_dialog, null, false
)
binding.recyclerView.layoutManager = LinearLayoutManager(activity)
binding.recyclerView.addItemDecoration(
DividerItemDecoration(
activity,
DividerItemDecoration.VERTICAL
)
)
binding.recyclerView.adapter = adapter
builder.setTitle(R.string.dialog_title_select_device)
builder.setView(binding.root)
return builder.create()
}
companion object {
private fun newInstance(): SelectRendererDialog = SelectRendererDialog()
fun show(activity: FragmentActivity) {
if (activity.supportFragmentManager.isStateSaved) {
return
}
newInstance().show(activity.supportFragmentManager, "")
}
}
}
| mit | e4635c5370b54b175cb231a7a0aa2c14 | 33.628205 | 80 | 0.69863 | 4.857914 | false | false | false | false |
anlun/haskell-idea-plugin | generator/src/org/jetbrains/generator/ParserGenerator.kt | 1 | 8240 | package org.jetbrains.generator
import java.io.FileReader
import java.util.ArrayList
import org.jetbrains.generator.grammar.TokenDescription
import java.io.PrintStream
import java.io.File
import java.io.FileWriter
import org.jetbrains.generator.grammar.*
import java.util.HashMap
import java.util.HashSet
import java.util.TreeSet
/**
* Created by atsky on 11/7/14.
*/
class ParserGenerator(val grammar: Grammar) {
companion object {
val MAIN_PATH = "./plugin/gen/org/jetbrains/grammar/"
}
val tokens: Map<String, TokenDescription>
val rules: Map<String, AbstractRule>
val fakeRules: List<FakeRule>
init {
val tokens = HashMap<String, TokenDescription>()
val rules = HashMap<String, AbstractRule>()
val fakeRules = ArrayList<FakeRule>()
for (token in grammar.tokens) {
if (token.useText) {
tokens["'${token.text}'"] = token;
} else {
tokens[token.text] = token;
}
}
for (rule in grammar.rules) {
rules[rule.name] = rule
}
this.tokens = tokens;
this.rules = rules;
this.fakeRules = fakeRules;
}
fun generate() {
generateLexerTokens(grammar.tokens)
generateTokens()
generateParser();
}
fun generateLexerTokens(tokens: List<TokenDescription>) {
val result = TextGenerator()
with(result) {
line("package org.jetbrains.grammar;")
line()
line("import org.jetbrains.haskell.parser.HaskellTokenType;")
line()
line()
line("public interface HaskellLexerTokens {")
indent {
for (token in tokens) {
val name = token.name.toUpperCase()
line("public static HaskellTokenType ${name} = new HaskellTokenType(\"${token.text}\");");
}
}
line("}")
}
val parent = File(MAIN_PATH)
parent.mkdirs()
val writer = FileWriter(File(parent, "HaskellLexerTokens.java"))
writer.write(result.toString())
writer.close()
}
fun generateTokens() {
val result = TextGenerator()
val elementSet = TreeSet<String>()
for (token in grammar.rules) {
for (variant in token.variants) {
variant.fillElements(elementSet)
}
}
with(result) {
line("package org.jetbrains.grammar")
line()
line("import com.intellij.psi.tree.IElementType")
line("import org.jetbrains.haskell.parser.HaskellCompositeElementType")
line("import org.jetbrains.haskell.psi.*")
line()
line()
for (element in elementSet) {
line("public val ${camelCaseToUpperCase(element)} : IElementType = HaskellCompositeElementType(\"${element}\", ::${element})")
}
}
val parent = File(MAIN_PATH)
parent.mkdirs()
val writer = FileWriter(File(parent, "HaskellTokens.kt"))
writer.write(result.toString())
writer.close()
}
fun camelCaseToUpperCase(string: String): String {
val result = StringBuilder()
var first = true;
for (char in string) {
if (Character.isUpperCase(char)) {
if (!first) {
result.append("_")
}
result.append(char)
} else {
result.append(Character.toUpperCase(char))
}
first = false;
}
return result.toString();
}
fun generateParser() {
val result = TextGenerator()
with(result) {
line("package org.jetbrains.grammar;")
line()
line("import static org.jetbrains.grammar.HaskellLexerTokens.*;")
line("import com.intellij.lang.PsiBuilder;")
line("import org.jetbrains.annotations.NotNull;")
line("import org.jetbrains.grammar.dumb.*;")
line()
line("import java.util.*;")
line()
line("public class HaskellParser extends BaseHaskellParser {")
indent {
line("public HaskellParser(PsiBuilder builder) {")
line(" super(builder);")
line("}")
line()
line("@NotNull")
line("public Map<String, Rule> getGrammar() {")
indent {
line("Map<String, Rule> grammar = new HashMap<String, Rule>();")
for (rule in rules.values()) {
if (rule is Rule) {
generateRule(this, rule)
}
}
line("return grammar;");
}
line("}")
}
line("}")
}
val parent = File(MAIN_PATH)
parent.mkdirs()
val writer = FileWriter(File(parent, "HaskellParser.java"))
writer.write(result.toString())
writer.close()
}
fun generateRule(textGenerator: TextGenerator,
rule: Rule) {
with(textGenerator) {
line("{")
indent {
line("List<Variant> variants = new ArrayList<Variant>();")
line("List<Variant> left = new ArrayList<Variant>();")
for (varinant in rule.variants) {
generateVariant(this, rule, varinant);
}
line("grammar.put(\"${rule.name}\", new Rule(\"${rule.name}\", variants, left));")
}
line("}")
}
}
fun generateFakeRule(textGenerator: TextGenerator,
rule: FakeRule) {
with(textGenerator) {
line()
line("// Fake rule")
line("fun ${getParseFun(rule.name)}() : Boolean {")
indent {
line("throw FakeRuleException()")
}
line("}")
}
}
fun generateVariant(textGenerator: TextGenerator,
rule: Rule,
variant: Variant) {
with(textGenerator) {
val builder = StringBuilder()
fillVariant(builder, variant)
if (variant is NonFinalVariant && variant.atom.toString() == rule.name) {
line("addVar(left, ${builder});")
} else {
line("addVar(variants, ${builder});")
}
}
}
fun fillVariant(builder : StringBuilder, variant : Variant): StringBuilder {
if (variant is NonFinalVariant) {
if (variant.next.size() == 1) {
fillVariant(builder, variant.next.firstOrNull()!!)
val atom = variant.atom
if (tokens.containsKey(atom.toString())) {
val tokenDescription = tokens[atom.toString()]!!
builder.append(".add(" + tokenDescription.name.toUpperCase() + ")")
} else {
builder.append(".add(\"" + atom.text + "\")")
}
} else {
val atom = variant.atom
if (tokens.containsKey(atom.toString())) {
val tokenDescription = tokens[atom.toString()]!!
builder.append("many(" + tokenDescription.name.toUpperCase() + "")
} else {
builder.append("many(\"" + atom.text + "\"")
}
for (variant in variant.next) {
builder.append(", ")
fillVariant(builder, variant)
}
builder.append(")")
}
} else {
val elementName = (variant as FinalVariant).elementName
builder.append(if (elementName != null) {
"end(GrammarPackage.get${camelCaseToUpperCase(elementName)}())"
} else {
"end()"
})
}
return builder
}
fun getParseFun(name: String): String =
"parse" + Character.toUpperCase(name[0]) + name.substring(1)
}
| apache-2.0 | f06332e54caa185fb147a29e5a13ba8d | 30.692308 | 142 | 0.50449 | 4.966847 | false | false | false | false |
WonderBeat/vasilich | src/main/kotlin/com/vasilich/commands/monitoring/SystemMonitoringCommand.kt | 1 | 1296 | package com.vasilich.commands.monitoring
import com.vasilich.commands.api.Command
import org.springframework.stereotype.Component
import com.vasilich.system.Cpu
import com.vasilich.system.FileSystem
import com.vasilich.system.Size
/**
*
* @author Ilya_Mestnikov
* @date 11/18/13
* @time 2:08 AM
*/
Component
public class SystemMonitoringCommand (val cpu: Cpu = Cpu(), val fs: FileSystem = FileSystem()) : Command {
override fun execute(msg: String): String? {
val parts = msg.split("\\s?mon\\s")
if (parts.size > 1) {
when (parts.get(1).trim()) {
"cpu" -> {
val percent = Cpu().getSystemLoad() * 100;
return "Current cpu usage: %.2f%%".format(percent);
}
"disk" -> {
var output = "Disk Usage Statistics:"
val fs = FileSystem()
for (disk in fs.disks) {
output += "\n%-4s T:%5dGb U:%4dGb A:%4dGb".format(disk.name,
Size.Gb.get(disk.total), Size.Gb.get(disk.used), Size.Gb.get(disk.available));
}
return output
}
}
}
return "Usage help: Vasilich, mon <command>"
}
} | gpl-2.0 | 01aac86be612b4452434f523cb89e53a | 30.634146 | 110 | 0.52392 | 3.93921 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/address/AddAddressStreet.kt | 1 | 4515 | package de.westnordost.streetcomplete.quests.address
import de.westnordost.osmapi.map.MapDataWithGeometry
import de.westnordost.osmapi.map.data.Element
import de.westnordost.osmapi.map.data.Relation
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.meta.ALL_PATHS
import de.westnordost.streetcomplete.data.meta.ALL_ROADS
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPolylinesGeometry
import de.westnordost.streetcomplete.data.quest.AllCountriesExcept
import de.westnordost.streetcomplete.data.osm.osmquest.OsmElementQuestType
import de.westnordost.streetcomplete.ktx.arrayOfNotNull
import de.westnordost.streetcomplete.quests.road_name.data.RoadNameSuggestionEntry
import de.westnordost.streetcomplete.quests.road_name.data.RoadNameSuggestionsDao
import de.westnordost.streetcomplete.quests.road_name.data.toRoadNameByLanguage
class AddAddressStreet(
private val roadNameSuggestionsDao: RoadNameSuggestionsDao
) : OsmElementQuestType<AddressStreetAnswer> {
private val filter by lazy { """
nodes, ways, relations with
addr:housenumber and !addr:street and !addr:place and !addr:block_number
or addr:streetnumber and !addr:street
""".toElementFilterExpression() }
private val roadsWithNamesFilter by lazy { """
ways with
highway ~ ${(ALL_ROADS + ALL_PATHS).joinToString("|")}
and name
""".toElementFilterExpression()}
// #2112 - exclude indirect addr:street
private val excludedWaysFilter by lazy { """
ways with
addr:street and addr:interpolation
""".toElementFilterExpression() }
override val commitMessage = "Add street/place names to address"
override val icon = R.drawable.ic_quest_housenumber_street
override val wikiLink = "Key:addr"
// In Japan, housenumbers usually have block numbers, not streets
override val enabledInCountries = AllCountriesExcept("JP")
override fun getTitle(tags: Map<String, String>) = R.string.quest_address_street_title
override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>): Array<String> =
arrayOfNotNull(tags["addr:streetnumber"] ?: tags["addr:housenumber"])
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> {
val excludedWayNodeIds = mutableSetOf<Long>()
mapData.ways
.filter { excludedWaysFilter.matches(it) }
.flatMapTo(excludedWayNodeIds) { it.nodeIds }
val associatedStreetRelations = mapData.relations.filter {
val type = it.tags?.get("type")
type == "associatedStreet" || type == "street"
}
val addressesWithoutStreet = mapData.filter { address ->
filter.matches(address) &&
associatedStreetRelations.none { it.contains(address.type, address.id) }
&& address.id !in excludedWayNodeIds
}
if (addressesWithoutStreet.isNotEmpty()) {
val roadsWithNames = mapData.ways
.filter { roadsWithNamesFilter.matches(it) }
.mapNotNull {
val geometry = mapData.getWayGeometry(it.id) as? ElementPolylinesGeometry
val roadNamesByLanguage = it.tags?.toRoadNameByLanguage()
if (geometry != null && roadNamesByLanguage != null) {
RoadNameSuggestionEntry(it.id, roadNamesByLanguage, geometry.polylines.first())
} else null
}
roadNameSuggestionsDao.putRoads(roadsWithNames)
}
return addressesWithoutStreet
}
override fun createForm() = AddAddressStreetForm()
/* cannot be determined because of the associated street relations */
override fun isApplicableTo(element: Element): Boolean? = null
override fun applyAnswerTo(answer: AddressStreetAnswer, changes: StringMapChangesBuilder) {
val key = when(answer) {
is StreetName -> "addr:street"
is PlaceName -> "addr:place"
}
changes.add(key, answer.name)
}
override fun cleanMetadata() {
roadNameSuggestionsDao.cleanUp()
}
}
private fun Relation.contains(elementType: Element.Type, elementId: Long) : Boolean {
return members.any { it.type == elementType && it.ref == elementId }
}
| gpl-3.0 | f39869345fb63460cbe2a362aed793d7 | 42.413462 | 103 | 0.702769 | 4.737671 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/objects/kt2398.kt | 5 | 313 | class C {
public object Obj {
val o = "O"
object InnerObj {
fun k() = "K"
}
class D {
val ko = "KO"
}
}
}
fun box(): String {
val res = C.Obj.o + C.Obj.InnerObj.k() + C.Obj.D().ko
return if (res == "OKKO") "OK" else "Fail: $res"
}
| apache-2.0 | bd28f10ab1078a608c56fde409b028ce | 16.388889 | 58 | 0.412141 | 2.980952 | false | false | false | false |
garmax1/material-flashlight | app/src/main/java/co/garmax/materialflashlight/di/DataModule.kt | 1 | 1390 | package co.garmax.materialflashlight.di
import co.garmax.materialflashlight.features.LightManager
import co.garmax.materialflashlight.features.modes.ModeFactory
import co.garmax.materialflashlight.features.modules.ModuleFactory
import co.garmax.materialflashlight.repositories.SettingsRepository
import co.garmax.materialflashlight.utils.PostExecutionThread
import co.garmax.materialflashlight.widget.WidgetManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
val dataModule = module {
single<PostExecutionThread> {
object : PostExecutionThread {
override val scheduler get() = AndroidSchedulers.mainThread()
}
}
single { Schedulers.io() }
single {
LightManager(get(), androidContext()).apply {
val settingsRepository: SettingsRepository = get()
val moduleFactory: ModuleFactory = get()
val modeFactory: ModeFactory = get()
setModule(moduleFactory.getModule(settingsRepository.module))
setMode(modeFactory.getMode(settingsRepository.mode))
}
}
single { SettingsRepository(get()) }
single { WidgetManager(androidContext()) }
single { ModuleFactory(androidContext()) }
single { ModeFactory(get(), androidContext()) }
} | apache-2.0 | 10b4ef0825fa3edeb582adcc7eb1446b | 36.594595 | 73 | 0.741727 | 5.054545 | false | false | false | false |
suchaHassle/kotNES | src/Mappers/NROM.kt | 1 | 861 | package kotNES.mapper
import kotNES.Cartridge
import kotNES.Emulator
import kotNES.Mapper
class NROM(emulator: Emulator) : Mapper(emulator) {
private var cartridge: Cartridge = emulator.cartridge
init {
mirroringType = if (cartridge.mirroringMode == 1) VramMirroring.Vertical else VramMirroring.Horizontal
}
private fun toPrgROMAddress(address: Int): Int =
if (cartridge.data[4] == 1.toByte()) ((address - 0x8000) % 0x4000) else (address - 0x8000)
override fun read(address: Int): Int = when {
address >= 0x8000 -> cartridge.readPRGRom(toPrgROMAddress(address))
address <= 0x2000 -> cartridge.readCHRRom(address)
else -> 0
}
override fun write(address: Int, value: Int) = when(address) {
in 0x0000..0x1FFF -> cartridge.writeCHRRom(address, value)
else -> Unit
}
} | mit | 936574bc8d1657cff0c01a83f8d23a04 | 30.925926 | 110 | 0.671312 | 3.54321 | false | false | false | false |
google/filament | android/samples/sample-transparent-view/src/main/java/com/google/android/filament/transparentrendering/MainActivity.kt | 1 | 13580 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.filament.transparentrendering
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.opengl.Matrix
import android.os.Bundle
import android.view.Choreographer
import android.view.Gravity
import android.view.Surface
import android.view.SurfaceView
import android.view.animation.LinearInterpolator
import android.widget.FrameLayout
import android.widget.TextView
import com.google.android.filament.*
import com.google.android.filament.RenderableManager.*
import com.google.android.filament.VertexBuffer.*
import com.google.android.filament.android.DisplayHelper
import com.google.android.filament.android.UiHelper
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.Channels
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
class MainActivity : Activity() {
// Make sure to initialize Filament first
// This loads the JNI library needed by most API calls
companion object {
init {
Filament.init()
}
}
// The View we want to render into
private lateinit var surfaceView: SurfaceView
// UiHelper is provided by Filament to manage SurfaceView and SurfaceTexture
private lateinit var uiHelper: UiHelper
// DisplayHelper is provided by Filament to manage the display
private lateinit var displayHelper: DisplayHelper
// Choreographer is used to schedule new frames
private lateinit var choreographer: Choreographer
// Engine creates and destroys Filament resources
// Each engine must be accessed from a single thread of your choosing
// Resources cannot be shared across engines
private lateinit var engine: Engine
// A renderer instance is tied to a single surface (SurfaceView, TextureView, etc.)
private lateinit var renderer: Renderer
// A scene holds all the renderable, lights, etc. to be drawn
private lateinit var scene: Scene
// A view defines a viewport, a scene and a camera for rendering
private lateinit var view: View
// Should be pretty obvious :)
private lateinit var camera: Camera
private lateinit var material: Material
private lateinit var vertexBuffer: VertexBuffer
private lateinit var indexBuffer: IndexBuffer
// Filament entity representing a renderable object
@Entity private var renderable = 0
// A swap chain is Filament's representation of a surface
private var swapChain: SwapChain? = null
// Performs the rendering and schedules new frames
private val frameScheduler = FrameCallback()
private val animator = ValueAnimator.ofFloat(0.0f, 360.0f)
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
choreographer = Choreographer.getInstance()
displayHelper = DisplayHelper(this)
surfaceView = SurfaceView(this)
val textView = TextView(this).apply {
val d = resources.displayMetrics.density
text = "This TextView is under the Filament SurfaceView."
textSize = 32.0f
setPadding((16 * d).toInt(), 0, (16 * d).toInt(), 0)
}
setContentView(FrameLayout(this).apply {
addView(textView, FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT,
Gravity.CENTER_VERTICAL
))
addView(surfaceView)
})
setupSurfaceView()
setupFilament()
setupView()
setupScene()
}
private fun setupSurfaceView() {
uiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK)
uiHelper.renderCallback = SurfaceCallback()
// Make the render target transparent
uiHelper.isOpaque = false
uiHelper.attachTo(surfaceView)
}
private fun setupFilament() {
engine = Engine.create()
renderer = engine.createRenderer()
scene = engine.createScene()
view = engine.createView()
camera = engine.createCamera(engine.entityManager.create())
// clear the swapchain with transparent pixels
val options = renderer.clearOptions
options.clear = true
renderer.clearOptions = options
}
private fun setupView() {
// Tell the view which camera we want to use
view.camera = camera
// Tell the view which scene we want to render
view.scene = scene
}
private fun setupScene() {
loadMaterial()
createMesh()
// To create a renderable we first create a generic entity
renderable = EntityManager.get().create()
// We then create a renderable component on that entity
// A renderable is made of several primitives; in this case we declare only 1
RenderableManager.Builder(1)
// Overall bounding box of the renderable
.boundingBox(Box(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.01f))
// Sets the mesh data of the first primitive
.geometry(0, PrimitiveType.TRIANGLES, vertexBuffer, indexBuffer, 0, 3)
// Sets the material of the first primitive
.material(0, material.defaultInstance)
.build(engine, renderable)
// Add the entity to the scene to render it
scene.addEntity(renderable)
startAnimation()
}
private fun loadMaterial() {
readUncompressedAsset("materials/baked_color.filamat").let {
material = Material.Builder().payload(it, it.remaining()).build(engine)
}
}
private fun createMesh() {
val intSize = 4
val floatSize = 4
val shortSize = 2
// A vertex is a position + a color:
// 3 floats for XYZ position, 1 integer for color
val vertexSize = 3 * floatSize + intSize
// Define a vertex and a function to put a vertex in a ByteBuffer
data class Vertex(val x: Float, val y: Float, val z: Float, val color: Int)
fun ByteBuffer.put(v: Vertex): ByteBuffer {
putFloat(v.x)
putFloat(v.y)
putFloat(v.z)
putInt(v.color)
return this
}
// We are going to generate a single triangle
val vertexCount = 3
val a1 = PI * 2.0 / 3.0
val a2 = PI * 4.0 / 3.0
val vertexData = ByteBuffer.allocate(vertexCount * vertexSize)
// It is important to respect the native byte order
.order(ByteOrder.nativeOrder())
.put(Vertex(1.0f, 0.0f, 0.0f, 0xffff0000.toInt()))
.put(Vertex(cos(a1).toFloat(), sin(a1).toFloat(), 0.0f, 0xff00ff00.toInt()))
.put(Vertex(cos(a2).toFloat(), sin(a2).toFloat(), 0.0f, 0xff0000ff.toInt()))
// Make sure the cursor is pointing in the right place in the byte buffer
.flip()
// Declare the layout of our mesh
vertexBuffer = VertexBuffer.Builder()
.bufferCount(1)
.vertexCount(vertexCount)
// Because we interleave position and color data we must specify offset and stride
// We could use de-interleaved data by declaring two buffers and giving each
// attribute a different buffer index
.attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize)
.attribute(VertexAttribute.COLOR, 0, AttributeType.UBYTE4, 3 * floatSize, vertexSize)
// We store colors as unsigned bytes but since we want values between 0 and 1
// in the material (shaders), we must mark the attribute as normalized
.normalized(VertexAttribute.COLOR)
.build(engine)
// Feed the vertex data to the mesh
// We only set 1 buffer because the data is interleaved
vertexBuffer.setBufferAt(engine, 0, vertexData)
// Create the indices
val indexData = ByteBuffer.allocate(vertexCount * shortSize)
.order(ByteOrder.nativeOrder())
.putShort(0)
.putShort(1)
.putShort(2)
.flip()
indexBuffer = IndexBuffer.Builder()
.indexCount(3)
.bufferType(IndexBuffer.Builder.IndexType.USHORT)
.build(engine)
indexBuffer.setBuffer(engine, indexData)
}
private fun startAnimation() {
// Animate the triangle
animator.interpolator = LinearInterpolator()
animator.duration = 4000
animator.repeatMode = ValueAnimator.RESTART
animator.repeatCount = ValueAnimator.INFINITE
animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener {
val transformMatrix = FloatArray(16)
override fun onAnimationUpdate(a: ValueAnimator) {
Matrix.setRotateM(transformMatrix, 0, -(a.animatedValue as Float), 0.0f, 0.0f, 1.0f)
val tcm = engine.transformManager
tcm.setTransform(tcm.getInstance(renderable), transformMatrix)
}
})
animator.start()
}
override fun onResume() {
super.onResume()
choreographer.postFrameCallback(frameScheduler)
animator.start()
}
override fun onPause() {
super.onPause()
choreographer.removeFrameCallback(frameScheduler)
animator.cancel()
}
override fun onDestroy() {
super.onDestroy()
// Stop the animation and any pending frame
choreographer.removeFrameCallback(frameScheduler)
animator.cancel()
// Always detach the surface before destroying the engine
uiHelper.detach()
// Cleanup all resources
engine.destroyEntity(renderable)
engine.destroyRenderer(renderer)
engine.destroyVertexBuffer(vertexBuffer)
engine.destroyIndexBuffer(indexBuffer)
engine.destroyMaterial(material)
engine.destroyView(view)
engine.destroyScene(scene)
engine.destroyCameraComponent(camera.entity)
// Engine.destroyEntity() destroys Filament related resources only
// (components), not the entity itself
val entityManager = EntityManager.get()
entityManager.destroy(renderable)
entityManager.destroy(camera.entity)
// Destroying the engine will free up any resource you may have forgotten
// to destroy, but it's recommended to do the cleanup properly
engine.destroy()
}
inner class FrameCallback : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
// Schedule the next frame
choreographer.postFrameCallback(this)
// This check guarantees that we have a swap chain
if (uiHelper.isReadyToRender) {
// If beginFrame() returns false you should skip the frame
// This means you are sending frames too quickly to the GPU
if (renderer.beginFrame(swapChain!!, frameTimeNanos)) {
renderer.render(view)
renderer.endFrame()
}
}
}
}
inner class SurfaceCallback : UiHelper.RendererCallback {
override fun onNativeWindowChanged(surface: Surface) {
swapChain?.let { engine.destroySwapChain(it) }
swapChain = engine.createSwapChain(surface, uiHelper.swapChainFlags)
displayHelper.attach(renderer, surfaceView.display)
}
override fun onDetachedFromSurface() {
displayHelper.detach()
swapChain?.let {
engine.destroySwapChain(it)
// Required to ensure we don't return before Filament is done executing the
// destroySwapChain command, otherwise Android might destroy the Surface
// too early
engine.flushAndWait()
swapChain = null
}
}
override fun onResized(width: Int, height: Int) {
val zoom = 1.5
val aspect = width.toDouble() / height.toDouble()
camera.setProjection(Camera.Projection.ORTHO,
-aspect * zoom, aspect * zoom, -zoom, zoom, 0.0, 10.0)
view.viewport = Viewport(0, 0, width, height)
}
}
@Suppress("SameParameterValue")
private fun readUncompressedAsset(assetName: String): ByteBuffer {
assets.openFd(assetName).use { fd ->
val input = fd.createInputStream()
val dst = ByteBuffer.allocate(fd.length.toInt())
val src = Channels.newChannel(input)
src.read(dst)
src.close()
return dst.apply { rewind() }
}
}
}
| apache-2.0 | 4cf1a55f2a38d0bba2cae078368e6584 | 35.802168 | 104 | 0.636524 | 5.016624 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/entities/ProfileSwitch.kt | 1 | 2892 | package info.nightscout.androidaps.database.entities
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import info.nightscout.androidaps.database.TABLE_PROFILE_SWITCHES
import info.nightscout.androidaps.database.data.Block
import info.nightscout.androidaps.database.data.TargetBlock
import info.nightscout.androidaps.database.embedments.InsulinConfiguration
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.interfaces.DBEntryWithTimeAndDuration
import info.nightscout.androidaps.database.interfaces.TraceableDBEntry
import java.util.*
@Entity(
tableName = TABLE_PROFILE_SWITCHES,
foreignKeys = [ForeignKey(
entity = ProfileSwitch::class,
parentColumns = ["id"],
childColumns = ["referenceId"]
)],
indices = [
Index("referenceId"),
Index("timestamp"),
Index("isValid"),
Index("id"),
Index("nightscoutId")
]
)
data class ProfileSwitch(
@PrimaryKey(autoGenerate = true)
override var id: Long = 0,
override var version: Int = 0,
override var dateCreated: Long = -1,
override var isValid: Boolean = true,
override var referenceId: Long? = null,
@Embedded
override var interfaceIDs_backing: InterfaceIDs? = InterfaceIDs(),
override var timestamp: Long,
override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(),
var basalBlocks: List<Block>,
var isfBlocks: List<Block>,
var icBlocks: List<Block>,
var targetBlocks: List<TargetBlock>,
var glucoseUnit: GlucoseUnit,
var profileName: String,
var timeshift: Long, // [milliseconds]
var percentage: Int, // 1 ~ XXX [%]
override var duration: Long, // [milliseconds]
@Embedded
var insulinConfiguration: InsulinConfiguration
) : TraceableDBEntry, DBEntryWithTimeAndDuration {
private fun contentEqualsTo(other: ProfileSwitch): Boolean =
isValid == other.isValid &&
timestamp == other.timestamp &&
utcOffset == other.utcOffset &&
basalBlocks == other.basalBlocks &&
isfBlocks == other.isfBlocks &&
icBlocks == other.icBlocks &&
targetBlocks == other.targetBlocks &&
glucoseUnit == other.glucoseUnit &&
profileName == other.profileName &&
timeshift == other.timeshift &&
percentage == other.percentage &&
duration == other.duration
fun onlyNsIdAdded(previous: ProfileSwitch): Boolean =
previous.id != id &&
contentEqualsTo(previous) &&
previous.interfaceIDs.nightscoutId == null &&
interfaceIDs.nightscoutId != null
enum class GlucoseUnit {
MGDL,
MMOL;
companion object
}
} | agpl-3.0 | 0d118f3c2ee71172defdc1b6f9c255ad | 34.280488 | 87 | 0.681189 | 4.694805 | false | false | false | false |
saletrak/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/ModelsMappingExtensions.kt | 1 | 1739 | package io.github.feelfreelinux.wykopmobilny.models
import io.github.feelfreelinux.wykopmobilny.models.dataclass.*
import io.github.feelfreelinux.wykopmobilny.models.pojo.*
fun EntryResponse.mapToEntry() : Entry {
val commentList = ArrayList<Comment>()
comments?.mapTo(commentList, { it.mapToComment() })
return Entry(
id,
Author(
author,
authorAvatarMed,
authorGroup,
authorSex,
app
),
body,
date,
userVote > 0,
!(userFavorite == null || !userFavorite!!),
embed,
voteCount,
voters.map { Author(it.author, it.authorAvatarMed, it.authorGroup, it.authorSex, null) },
commentCount,
commentList.toList()
)
}
fun NotificationResponse.mapToNotification() : Notification
= Notification(
Author(author ?: "", authorAvatar, authorGroup, authorSex, null),
body,
date,
url,
new
)
fun CommentResponse.mapToComment() : Comment
= Comment(
id,
entryId,
Author(
author,
authorAvatarMed,
authorGroup,
authorSex,
app
),
body,
date,
userVote > 0,
embed,
voters.map { Author(it.author, it.authorAvatarMed, it.authorGroup, it.authorSex, null) },
voteCount
)
fun TagEntriesResponse.mapToTagEntries() : TagEntries
= TagEntries(meta.mapToTagMeta(), items.map { it.mapToEntry() })
fun TagMetaResponse.mapToTagMeta() : TagMeta
= TagMeta(tag, isObserved ?: false, isObserved ?: false) | mit | 9c1bdd9863172118a0ca1400b9aa50a2 | 27.064516 | 101 | 0.554342 | 4.576316 | false | false | false | false |
maiconhellmann/pomodoro | app/src/main/kotlin/br/com/maiconhellmann/pomodoro/data/local/Db.kt | 1 | 1678 | package br.com.maiconhellmann.pomodoro.data.local
import android.content.ContentValues
import android.database.Cursor
import br.com.maiconhellmann.pomodoro.data.model.Pomodoro
import br.com.maiconhellmann.pomodoro.data.model.PomodoroStatus
import br.com.maiconhellmann.pomodoro.util.extension.getLong
import java.util.*
object Db {
object PomodoroTable{
val TABLE_NAME = "pomodoro"
val COLUMN_ID = "_id"
val COLUMN_START_TIME = "dat_start_time"
val COLUMN_END_TIME = "dat_end_time"
val COLUMN_STATUS = "ind_status"
val CREATE = """
CREATE TABLE $TABLE_NAME(
$COLUMN_ID INTEGER PRIMARY KEY,
$COLUMN_START_TIME REAL NOT NULL,
$COLUMN_END_TIME REAL NOT NULL,
$COLUMN_STATUS INTEGER NOT NULL
)
"""
fun toContentValues(pomodoro: Pomodoro): ContentValues {
val values = ContentValues()
values.put(PomodoroTable.COLUMN_START_TIME, pomodoro.startDateTime.time)
values.put(PomodoroTable.COLUMN_END_TIME, pomodoro.endDateTime.time)
values.put(PomodoroTable.COLUMN_STATUS, pomodoro.status.id)
return values
}
fun parseCursor(cursor: Cursor): Pomodoro {
return Pomodoro(
id = cursor.getLong(COLUMN_ID),
startDateTime = Date(cursor.getLong(COLUMN_START_TIME)),
endDateTime = Date(cursor.getLong(COLUMN_END_TIME)),
status = PomodoroStatus.findById(cursor.getLong(COLUMN_STATUS)))
}
}
}
| apache-2.0 | ac143c3470e8644840bdcbce7224ab14 | 35.288889 | 84 | 0.600119 | 4.486631 | false | false | false | false |
Adventech/sabbath-school-android-2 | app/src/main/java/com/cryart/sabbathschool/ui/splash/SplashViewModel.kt | 1 | 2896 | /*
* Copyright (c) 2020. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.cryart.sabbathschool.ui.splash
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.ss.auth.AuthRepository
import app.ss.models.auth.SSUser
import com.cryart.sabbathschool.core.extensions.coroutines.DispatcherProvider
import com.cryart.sabbathschool.core.extensions.prefs.SSPrefs
import com.cryart.sabbathschool.reminder.DailyReminderManager
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SplashViewModel @Inject constructor(
private val ssPrefs: SSPrefs,
private val authRepository: AuthRepository,
private val dailyReminderManager: DailyReminderManager,
private val dispatcherProvider: DispatcherProvider
) : ViewModel() {
private val _launchState: MutableStateFlow<LaunchState> = MutableStateFlow(LaunchState.Loading)
val launchStateFlow: StateFlow<LaunchState> = _launchState
fun launch() = viewModelScope.launch(dispatcherProvider.default) {
val resource = authRepository.getUser()
val user = resource.data
if (user != null && ssPrefs.reminderEnabled() && ssPrefs.isReminderScheduled().not()) {
dailyReminderManager.scheduleReminder()
}
updateState(user)
}
private suspend fun updateState(user: SSUser?) {
val state = when {
user == null -> LaunchState.Login
ssPrefs.getLastQuarterlyIndex() != null && ssPrefs.isReadingLatestQuarterly() ->
LaunchState.Lessons(ssPrefs.getLastQuarterlyIndex()!!)
else -> LaunchState.Quarterlies
}
_launchState.emit(state)
}
}
| mit | b024cf3e0a6e7751ea10104073ae1c54 | 40.371429 | 99 | 0.751381 | 4.786777 | false | false | false | false |
geeteshk/Hyper | app/src/main/java/io/geeteshk/hyper/ui/fragment/analyze/AnalyzeFileFragment.kt | 1 | 8021 | /*
* Copyright 2016 Geetesh Kalakoti <[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 io.geeteshk.hyper.ui.fragment.analyze
import android.content.Context
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.DefaultValueFormatter
import com.github.mikephil.charting.formatter.IValueFormatter
import com.github.mikephil.charting.utils.ColorTemplate
import com.github.mikephil.charting.utils.ViewPortHandler
import io.geeteshk.hyper.R
import io.geeteshk.hyper.extensions.compatColor
import io.geeteshk.hyper.extensions.inflate
import io.geeteshk.hyper.util.Prefs.defaultPrefs
import io.geeteshk.hyper.util.Prefs.get
import io.geeteshk.hyper.util.project.ProjectManager
import kotlinx.android.synthetic.main.fragment_analyze_file.*
import java.io.File
import java.util.*
class AnalyzeFileFragment : Fragment() {
private lateinit var pieColors: ArrayList<Int>
private lateinit var projectDir: File
internal lateinit var activity: FragmentActivity
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
container?.inflate(R.layout.fragment_analyze_file)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val prefs = defaultPrefs(activity)
val darkTheme = prefs["dark_theme", false]!!
val lightColor = activity.compatColor(androidx.appcompat.R.color.abc_primary_text_material_light)
val darkColor = activity.compatColor(androidx.appcompat.R.color.abc_primary_text_material_dark)
projectDir = File(arguments!!.getString("project_file")!!)
pieColors = ArrayList()
for (c in ColorTemplate.VORDIPLOM_COLORS)
pieColors.add(c)
for (c in ColorTemplate.JOYFUL_COLORS)
pieColors.add(c)
for (c in ColorTemplate.COLORFUL_COLORS)
pieColors.add(c)
for (c in ColorTemplate.LIBERTY_COLORS)
pieColors.add(c)
pieColors.add(ColorTemplate.getHoloBlue())
pieChart.description.isEnabled = false
pieChart.setExtraOffsets(8f, 12f, 8f, 8f)
pieChart.dragDecelerationFrictionCoef = 0.95f
pieChart.isDrawHoleEnabled = true
pieChart.setHoleColor(0x00000000)
pieChart.setTransparentCircleColor(if (darkTheme) lightColor else darkColor)
pieChart.setTransparentCircleAlpha(110)
pieChart.holeRadius = 58f
pieChart.transparentCircleRadius = 61f
pieChart.rotationAngle = 0f
pieChart.isRotationEnabled = false
pieChart.isHighlightPerTapEnabled = true
var byteSize = 0L
projectDir.walkTopDown().forEach { byteSize += it.length() }
pieChart.centerText = ProjectManager.humanReadableByteCount(byteSize)
pieChart.setCenterTextSize(48f)
pieChart.setCenterTextColor(if (darkTheme) darkColor else lightColor)
pieChart.setDrawCenterText(true)
pieChart.setDrawEntryLabels(false)
setData(false)
val pieLegend = pieChart.legend
pieLegend.verticalAlignment = Legend.LegendVerticalAlignment.TOP
pieLegend.horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT
pieLegend.orientation = Legend.LegendOrientation.VERTICAL
pieLegend.setDrawInside(false)
pieLegend.xEntrySpace = 0f
pieLegend.yEntrySpace = 0f
pieLegend.yOffset = 10f
pieLegend.formSize = 12f
pieLegend.textSize = 12f
pieLegend.typeface = Typeface.DEFAULT_BOLD
pieLegend.textColor = if (darkTheme) darkColor else lightColor
switchFile.setOnCheckedChangeListener { _, b ->
if (b) {
sizeText!!.animate().alpha(1f)
countText!!.animate().alpha(0.4f)
setData(false)
} else {
countText!!.animate().alpha(1f)
sizeText!!.animate().alpha(0.4f)
setData(true)
}
}
}
private fun setData(isCount: Boolean) {
if (isCount) {
val entries = ArrayList<PieEntry>()
val files = projectDir.listFiles()
val filesAndCounts = HashMap<String, Int>()
files.map { it.extension }
.forEach {
if (filesAndCounts.containsKey(it)) {
filesAndCounts[it] = filesAndCounts[it]!!.plus(1)
} else {
filesAndCounts[it] = 1
}
}
for ((fileType, count) in filesAndCounts) {
entries.add(PieEntry(count.toFloat(), fileType))
}
val pieDataSet = PieDataSet(entries, "")
pieDataSet.setDrawIcons(false)
pieDataSet.sliceSpace = 3f
pieDataSet.selectionShift = 3f
pieDataSet.colors = pieColors
val pieData = PieData(pieDataSet)
pieData.setValueFormatter(DefaultValueFormatter(0))
pieData.setValueTextColor(-0x7b000000)
pieData.setValueTextSize(20f)
pieData.setValueTypeface(Typeface.DEFAULT_BOLD)
pieChart.data = pieData
} else {
val entries = ArrayList<PieEntry>()
val files = projectDir.listFiles()
val filesAndCounts = HashMap<String, Long>()
for (file in files) {
val extension = file.extension
if (filesAndCounts.containsKey(extension)) {
filesAndCounts[extension] = filesAndCounts[extension]!!.plus(file.length())
} else {
filesAndCounts[extension] = file.length()
}
}
for ((fileType, count) in filesAndCounts) {
entries.add(PieEntry(count.toFloat(), fileType))
}
val pieDataSet = PieDataSet(entries, "")
pieDataSet.setDrawIcons(false)
pieDataSet.sliceSpace = 3f
pieDataSet.selectionShift = 3f
pieDataSet.colors = pieColors
val pieData = PieData(pieDataSet)
pieData.setValueFormatter(SizeValueFormatter())
pieData.setValueTextColor(-0x7b000000)
pieData.setValueTextSize(16f)
pieData.setValueTypeface(Typeface.DEFAULT_BOLD)
pieChart.data = pieData
}
pieChart.highlightValues(null)
pieChart.invalidate()
pieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad)
}
private inner class SizeValueFormatter : IValueFormatter {
override fun getFormattedValue(value: Float, entry: Entry, dataSetIndex: Int, viewPortHandler: ViewPortHandler): String =
ProjectManager.humanReadableByteCount(value.toLong())
}
override fun onAttach(context: Context) {
super.onAttach(context)
activity = context as FragmentActivity
}
}
| apache-2.0 | fc831e58cafeb6cf05675cbbf4a2cdd9 | 37.936893 | 129 | 0.663259 | 4.583429 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinDeclarationScopeOptimizer.kt | 1 | 2796 | // 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.kotlin.idea.search.ideaExtensions
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.search.*
import com.intellij.psi.util.parentsOfType
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.search.excludeKotlinSources
import org.jetbrains.kotlin.idea.search.fileScope
import org.jetbrains.kotlin.idea.util.psiPackage
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinDeclarationScopeOptimizer : ScopeOptimizer {
override fun getRestrictedUseScope(element: PsiElement): SearchScope? {
val declaration = element.unwrapped?.safeAs<KtDeclaration>() ?: return null
val isPrivateDeclaration = declaration.isPrivate() ||
element.safeAs<PsiModifierListOwner>()?.hasModifier(JvmModifier.PRIVATE) == true
val privateClass = declaration.parentsOfType<KtClassOrObject>(withSelf = true).find(KtClassOrObject::isPrivate)
if (privateClass == null && !isPrivateDeclaration) return null
val containingFile = declaration.containingKtFile
val fileScope = containingFile.fileScope()
if (declaration !is KtClassOrObject && isPrivateDeclaration || privateClass?.isTopLevel() != true) return fileScope
// it is possible to create new kotlin private class from java - so have to look up in the same module as well
val minimalScope = findModuleOrLibraryScope(containingFile) ?: element.useScope
val scopeWithoutKotlin = minimalScope.excludeKotlinSources(containingFile.project)
val psiPackage = containingFile.psiPackage
val jvmScope = if (psiPackage != null && scopeWithoutKotlin is GlobalSearchScope)
PackageScope.packageScope(psiPackage, /* includeSubpackages = */ false, scopeWithoutKotlin)
else
scopeWithoutKotlin
return fileScope.union(jvmScope)
}
}
private fun findModuleOrLibraryScope(file: KtFile): GlobalSearchScope? {
val project = file.project
val projectFileIndex = ProjectFileIndex.getInstance(project)
val virtualFile = file.virtualFile ?: return null
val moduleScope = projectFileIndex.getModuleForFile(virtualFile)?.moduleScope
return when {
moduleScope != null -> moduleScope
projectFileIndex.isInLibrary(virtualFile) -> ProjectScope.getLibrariesScope(project)
else -> null
}
} | apache-2.0 | 1951f4eb9c26c387bd74e2c7520baff0 | 48.946429 | 123 | 0.765021 | 5.010753 | false | false | false | false |
Tandrial/Advent_of_Code | src/aoc2017/kot/Day24.kt | 1 | 1391 | package aoc2017.kot
import java.io.File
object Day24 {
fun solve(input: List<String>): Pair<Int, Int> {
val (pairs, doubles) = input.map { val (l, r) = it.split("/").map { it.toInt() }; l to r }.partition { it.first != it.second }
val (p1, p2) = dfs(listOf(0), pairs, doubles)
return Pair(p1, p2.second)
}
private fun dfs(bridge: List<Int>, pieces: List<Pair<Int, Int>>, doubles: List<Pair<Int, Int>>): Pair<Int, Pair<Int, Int>> {
val matchDbl = doubles.filter { bridge.contains(it.first) }
var strength = bridge.sumBy { it } + 2 * matchDbl.sumBy { it.first }
val length = bridge.size + 2 * matchDbl.size
var longest = Pair(length, strength)
for ((l, r) in pieces) {
if (l == bridge.last() || r == bridge.last()) {
val newLink = if (l == bridge.last()) listOf(l, r) else listOf(r, l)
val result = dfs(bridge + newLink, pieces.filter { it != Pair(l, r) }, doubles)
strength = maxOf(strength, result.first)
if (length > longest.first || (length == longest.first && strength > longest.second)) {
longest = Pair(length, strength)
}
}
}
return Pair(strength, longest)
}
}
fun main(args: Array<String>) {
val input = File("./input/2017/Day24_input.txt").readLines()
val (partOne, partTwo) = Day24.solve(input)
println("Part One = $partOne")
println("Part Two = $partTwo")
}
| mit | c732c1f7b270c022e650a492c3ce8adb | 36.594595 | 130 | 0.607477 | 3.219907 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/command/Command.kt | 1 | 3159 | /*
* 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.command
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.handler.EditorActionHandlerBase
import com.maddyhome.idea.vim.handler.MotionActionHandler
import com.maddyhome.idea.vim.handler.TextObjectActionHandler
import java.util.*
/**
* This represents a single Vim command to be executed (operator, motion, text object, etc.). It may optionally include
* an argument if appropriate for the command. The command has a count and a type.
*/
data class Command(
var rawCount: Int,
var action: EditorActionHandlerBase,
val type: Type,
var flags: EnumSet<CommandFlags>,
) {
constructor(rawCount: Int, register: Char) : this(
rawCount,
NonExecutableActionHandler,
Type.SELECT_REGISTER,
EnumSet.of(CommandFlags.FLAG_EXPECT_MORE)
) {
this.register = register
}
init {
action.process(this)
}
var count: Int
get() = rawCount.coerceAtLeast(1)
set(value) {
rawCount = value
}
var argument: Argument? = null
var register: Char? = null
fun isLinewiseMotion(): Boolean {
return when (action) {
is TextObjectActionHandler -> (action as TextObjectActionHandler).visualType == TextObjectVisualType.LINE_WISE
is MotionActionHandler -> (action as MotionActionHandler).motionType == MotionType.LINE_WISE
else -> error("Command is not a motion: $action")
}
}
enum class Type {
/**
* Represents commands that actually move the cursor and can be arguments to operators.
*/
MOTION,
/**
* Represents commands that insert new text into the editor.
*/
INSERT,
/**
* Represents commands that remove text from the editor.
*/
DELETE,
/**
* Represents commands that change text in the editor.
*/
CHANGE,
/**
* Represents commands that copy text in the editor.
*/
COPY,
PASTE,
/**
* Represents commands that select the register.
*/
SELECT_REGISTER,
OTHER_READONLY,
OTHER_WRITABLE,
/**
* Represent commands that don't require an outer read or write action for synchronization.
*/
OTHER_SELF_SYNCHRONIZED;
val isRead: Boolean
get() = when (this) {
MOTION, COPY, OTHER_READONLY -> true
else -> false
}
val isWrite: Boolean
get() = when (this) {
INSERT, DELETE, CHANGE, PASTE, OTHER_WRITABLE -> true
else -> false
}
}
}
private object NonExecutableActionHandler : EditorActionHandlerBase(false) {
override val type: Command.Type
get() = error("This action should not be executed")
override fun baseExecute(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
cmd: Command,
operatorArguments: OperatorArguments
): Boolean {
error("This action should not be executed")
}
}
| mit | ef4eb65d3cd7096559f462e0a465afcb | 24.071429 | 119 | 0.675847 | 4.280488 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/containers/BidirectionalLongSetMap.kt | 9 | 3149 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl.containers
import it.unimi.dsi.fastutil.longs.Long2ObjectMap
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap
import it.unimi.dsi.fastutil.longs.LongOpenHashSet
import it.unimi.dsi.fastutil.longs.LongSet
import kotlin.collections.component1
import kotlin.collections.component2
internal class BidirectionalLongSetMap<V> private constructor(
private val keyToValueMap: Long2ObjectOpenHashMap<V>,
private val valueToKeysMap: MutableMap<V, LongOpenHashSet>
) {
constructor() : this(Long2ObjectOpenHashMap<V>(), HashMap<V, LongOpenHashSet>())
fun put(key: Long, value: V): V? {
val oldValue = keyToValueMap.put(key, value)
if (oldValue != null) {
if (oldValue == value) {
return oldValue
}
val array = valueToKeysMap[oldValue]!!
array.remove(key)
if (array.isEmpty()) {
valueToKeysMap.remove(oldValue)
}
}
val array = valueToKeysMap.computeIfAbsent(value) { LongOpenHashSet() }
array.add(key)
return oldValue
}
fun clear() {
keyToValueMap.clear()
valueToKeysMap.clear()
}
fun getKeysByValue(value: V): LongSet? {
return valueToKeysMap[value]
}
val keys: LongSet
get() = keyToValueMap.keys
val size: Int
get() = keyToValueMap.size
fun isEmpty(): Boolean {
return keyToValueMap.isEmpty()
}
fun containsKey(key: Long): Boolean {
return keyToValueMap.containsKey(key)
}
fun containsValue(value: V): Boolean {
return valueToKeysMap.containsKey(value)
}
operator fun get(key: Long): V? = keyToValueMap[key]
fun removeValue(v: V) {
val ks: LongOpenHashSet? = valueToKeysMap.remove(v)
if (ks != null) {
val longIterator = ks.longIterator()
while (longIterator.hasNext()) {
val k = longIterator.nextLong()
keyToValueMap.remove(k)
}
}
}
fun remove(key: Long): V? {
val value = keyToValueMap.remove(key)
val ks: LongOpenHashSet? = valueToKeysMap[value]
if (ks != null) {
if (ks.size > 1) {
ks.remove(key)
}
else {
valueToKeysMap.remove(value)
}
}
return value
}
fun putAll(from: BidirectionalLongSetMap<V>) {
from.keyToValueMap.long2ObjectEntrySet().forEach { entry ->
put(entry.longKey, entry.value)
}
}
val values: MutableSet<V>
get() = valueToKeysMap.keys
//val entries: MutableSet<MutableMap.MutableEntry<K, V>>
// get() = keyToValueMap.entries
//
fun copy(): BidirectionalLongSetMap<V> {
val valueToKeys = HashMap<V, LongOpenHashSet>(valueToKeysMap.size)
valueToKeysMap.forEach { (key, value) -> valueToKeys[key] = LongOpenHashSet(value) }
return BidirectionalLongSetMap(keyToValueMap.clone(), valueToKeys)
}
fun forEach(action: (Long2ObjectMap.Entry<V>) -> Unit) {
keyToValueMap.long2ObjectEntrySet().forEach { entry ->
action(entry)
}
}
override fun toString(): String {
return keyToValueMap.toString()
}
}
| apache-2.0 | 446e0988a7f9abd583dff9d9b5ef454c | 25.91453 | 140 | 0.678946 | 4.001271 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/ir/buildsystem/DependencyIR.kt | 1 | 7414 | // 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.ir.buildsystem
import org.jetbrains.kotlin.tools.projectWizard.core.service.WizardKotlinVersion
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.GradleIR
import org.jetbrains.kotlin.tools.projectWizard.library.LibraryArtifact
import org.jetbrains.kotlin.tools.projectWizard.library.MavenArtifact
import org.jetbrains.kotlin.tools.projectWizard.library.NpmArtifact
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.BuildFilePrinter
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.MavenPrinter
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.ModulePath
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.SourcesetType
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
import java.util.*
interface DependencyIR : BuildSystemIR {
val dependencyType: DependencyType
fun withDependencyType(type: DependencyType): DependencyIR
}
data class ModuleDependencyIR(
val path: ModulePath,
val pomIR: PomIR,
override val dependencyType: DependencyType
) : DependencyIR {
override fun withDependencyType(type: DependencyType): DependencyIR = copy(dependencyType = type)
override fun BuildFilePrinter.render() = when (this) {
is GradlePrinter -> call(dependencyType.getGradleName(DependencyKind.implementation)) {
call("project", forceBrackets = true) {
+path.parts.joinToString(separator = "") { ":$it" }.quotified
}
}
is MavenPrinter -> node("dependency") {
pomIR.render(this)
}
else -> Unit
}
}
data class GradleRootProjectDependencyIR(
override val dependencyType: DependencyType
) : DependencyIR, GradleIR {
override fun withDependencyType(type: DependencyType): GradleRootProjectDependencyIR =
copy(dependencyType = type)
override fun GradlePrinter.renderGradle() {
+"rootProject"
}
}
interface LibraryDependencyIR : DependencyIR {
val artifact: LibraryArtifact
val version: Version
}
enum class DependencyType {
MAIN, TEST
}
fun SourcesetType.toDependencyType() = when (this) {
SourcesetType.main -> DependencyType.MAIN
SourcesetType.test -> DependencyType.TEST
}
fun DependencyType.getGradleName(kind: DependencyKind) = when (this) {
DependencyType.MAIN -> kind.text
DependencyType.TEST -> "test${kind.text.capitalize(Locale.US)}"
}
data class ArtifactBasedLibraryDependencyIR(
override val artifact: LibraryArtifact,
override val version: Version,
override val dependencyType: DependencyType,
val dependencyKind: DependencyKind = DependencyKind.implementation
) : LibraryDependencyIR {
override fun withDependencyType(type: DependencyType): ArtifactBasedLibraryDependencyIR =
copy(dependencyType = type)
fun withDependencyKind(kind: DependencyKind): ArtifactBasedLibraryDependencyIR = copy(dependencyKind = kind)
override fun BuildFilePrinter.render() = when (this) {
is GradlePrinter -> call(dependencyType.getGradleName(dependencyKind)) {
with(artifact) {
when (this) {
is MavenArtifact -> +"$groupId:$artifactId:${version}".quotified
is NpmArtifact -> {
+"npm(${name.quotified}"
+","
+version.toString().quotified
+")"
}
}
}
}
is MavenPrinter -> {
node("dependency") {
with(artifact as MavenArtifact) {
singleLineNode("groupId") { +groupId }
singleLineNode("artifactId") { +artifactId }
}
singleLineNode("version") { +version.toString() }
if (dependencyType == DependencyType.TEST) {
singleLineNode("scope") { +"test" }
}
}
}
else -> Unit
}
}
abstract class KotlinLibraryDependencyIR(
val artifactName: String,
override val dependencyType: DependencyType
) : LibraryDependencyIR {
abstract val kotlinVersion: WizardKotlinVersion
final override val version: Version get() = kotlinVersion.version
abstract val isInMppModule: Boolean
override val artifact: LibraryArtifact
get() = MavenArtifact(
kotlinVersion.repository,
"org.jetbrains.kotlin",
"kotlin-$artifactName"
)
override fun BuildFilePrinter.render() {
when (this) {
is GradlePrinter -> call(dependencyType.getGradleName(DependencyKind.implementation)) {
if (GradlePrinter.GradleDsl.KOTLIN == dsl || isInMppModule) {
+"kotlin("
+artifactName.quotified
+")"
} else {
+"org.jetbrains.kotlin:kotlin-$artifactName".quotified
}
}
is MavenPrinter -> node("dependency") {
singleLineNode("groupId") { +"org.jetbrains.kotlin" }
singleLineNode("artifactId") {
+"kotlin-"
+artifactName
}
singleLineNode("version") { +version.toString() }
if (dependencyType == DependencyType.TEST) {
singleLineNode("scope") { +"test" }
}
}
}
}
}
data class KotlinStdlibDependencyIR(
val type: StdlibType,
override val isInMppModule: Boolean,
override val kotlinVersion: WizardKotlinVersion,
override val dependencyType: DependencyType
) : KotlinLibraryDependencyIR(type.artifact, dependencyType) {
override fun withDependencyType(type: DependencyType): KotlinStdlibDependencyIR = copy(dependencyType = type)
}
data class KotlinArbitraryDependencyIR(
val name: String,
override val isInMppModule: Boolean,
override val kotlinVersion: WizardKotlinVersion,
override val dependencyType: DependencyType
) : KotlinLibraryDependencyIR(name, dependencyType) {
override fun withDependencyType(type: DependencyType): KotlinArbitraryDependencyIR = copy(dependencyType = type)
}
data class CustomGradleDependencyDependencyIR(
val dependency: String,
override val dependencyType: DependencyType,
val dependencyKind: DependencyKind
) : DependencyIR, GradleIR {
override fun withDependencyType(type: DependencyType): CustomGradleDependencyDependencyIR = copy(dependencyType = type)
override fun GradlePrinter.renderGradle() {
call(dependencyType.getGradleName(dependencyKind)) {
+dependency
}
}
}
enum class DependencyKind(val text: String) {
implementation("implementation"),
api("api"),
runtimeOnly("runtimeOnly"),
compileOnly("compileOnly")
}
enum class StdlibType(val artifact: String) {
StdlibJdk7("stdlib-jdk7"),
StdlibJdk8("stdlib-jdk8"),
StdlibJs("stdlib-js"),
StdlibCommon("stdlib-common"),
}
val LibraryDependencyIR.isKotlinStdlib
get() = this is KotlinStdlibDependencyIR
| apache-2.0 | 186845f0108be1f9112421013f57c9b5 | 35.522167 | 158 | 0.670353 | 4.952572 | false | false | false | false |
benjamin-bader/thrifty | thrifty-schema/src/main/kotlin/com/microsoft/thrifty/schema/SetType.kt | 1 | 2466 | /*
* Thrifty
*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE,
* FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.thrifty.schema
/**
* Represents a Thrift `set<T>`.
*
* @property elementType The type of value contained by instances of this type.
*/
class SetType internal constructor(
val elementType: ThriftType,
override val annotations: Map<String, String> = emptyMap()
) : ThriftType("set<" + elementType.name + ">") {
override val isSet: Boolean = true
override fun <T> accept(visitor: ThriftType.Visitor<T>): T = visitor.visitSet(this)
override fun withAnnotations(annotations: Map<String, String>): ThriftType {
return SetType(elementType, mergeAnnotations(this.annotations, annotations))
}
/**
* Creates a [Builder] initialized with this type's values.
*/
fun toBuilder(): Builder = Builder(this)
/**
* An object that can create new [SetType] instances.
*/
class Builder(
private var elementType: ThriftType,
private var annotations: Map<String, String>
) {
internal constructor(type: SetType) : this(type, type.annotations) {
this.elementType = type
this.annotations = type.annotations
}
/**
* Use the given [elementType] with the set type under construction.
*/
fun elementType(elementType: ThriftType): Builder = apply {
this.elementType = elementType
}
/**
* Use the given [annotations] with the set type under construction.
*/
fun annotations(annotations: Map<String, String>): Builder = apply {
this.annotations = annotations
}
/**
* Creates a new [SetType] instance.
*/
fun build(): SetType = SetType(elementType, annotations)
}
}
| apache-2.0 | 7b907f36081a9b4046f1ada23eaf75d6 | 31.025974 | 116 | 0.654501 | 4.549815 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddConstructorParameterFromSuperTypeCallFix.kt | 1 | 3912 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class AddConstructorParameterFromSuperTypeCallFix(
constructor: KtValueArgumentList,
private val parameterName: String,
parameterType: KotlinType
) : KotlinQuickFixAction<KtValueArgumentList>(constructor) {
private val parameterTypeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(parameterType)
override fun getText() = KotlinBundle.message("fix.add.constructor.parameter", parameterName)
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val superTypeCallArgList = element ?: return
val constructorParamList = superTypeCallArgList.containingClass()?.createPrimaryConstructorIfAbsent()?.valueParameterList ?: return
val psiFactory = KtPsiFactory(superTypeCallArgList)
val constructorParam = constructorParamList.addParameter(psiFactory.createParameter("$parameterName: $parameterTypeSourceCode"))
val superTypeCallArg = superTypeCallArgList.addArgument(psiFactory.createArgument(parameterName))
ShortenReferences.DEFAULT.process(constructorParam)
editor?.caretModel?.moveToOffset(superTypeCallArg.endOffset)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtValueArgumentList>? {
val superTypeCallArgList = diagnostic.psiElement as? KtValueArgumentList ?: return null
val superTypeCall = superTypeCallArgList.parent as? KtSuperTypeCallEntry ?: return null
val containingClass = superTypeCall.containingClass() ?: return null
val parameter = DiagnosticFactory.cast(diagnostic, Errors.NO_VALUE_FOR_PARAMETER).a
val parameterIndex = parameter.index
if (parameterIndex != superTypeCallArgList.arguments.size) return null
val parameterName = parameter.name.render()
val context = superTypeCallArgList.analyze(BodyResolveMode.PARTIAL)
val constructor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, containingClass]?.safeAs<ClassDescriptor>()
?.constructors?.firstOrNull() ?: return null
if (constructor.valueParameters.any { it.name.asString() == parameterName }) return null
val superTypeCallParameters = superTypeCall.getResolvedCall(context)?.resultingDescriptor?.valueParameters
val parameterType = superTypeCallParameters?.getOrNull(parameterIndex)?.type ?: parameter.type
return AddConstructorParameterFromSuperTypeCallFix(superTypeCallArgList, parameterName, parameterType)
}
}
} | apache-2.0 | 43ca1a42516be6457d48a36ee42682c0 | 57.402985 | 158 | 0.785532 | 5.3297 | false | false | false | false |
consp1racy/android-support-preference | gradle/plugins/publish/src/main/java/net/xpece/gradle/publish/PublishSonatypePlugin.kt | 1 | 3528 | package net.xpece.gradle.publish
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.publish.PublishingExtension
import org.gradle.kotlin.dsl.*
import org.gradle.plugins.signing.SigningExtension
import java.io.BufferedInputStream
import java.util.*
class PublishSonatypePlugin : Plugin<Project> {
override fun apply(target: Project) {
target.plugins.findPlugin(PublishPlugin::class)
?: target.apply<PublishPlugin>()
target.plugins.findPlugin("signing")
?: target.apply(plugin = "signing")
val publishing = target.extensions.getByName<PublishingExtension>("publishing")
val signing = target.extensions.getByName<SigningExtension>("signing")
signing.sign(publishing.publications)
if (System.getenv("CI") == null) {
signing.useGpgCmd()
}
val extension = target.extensions.getByType<PublishExtension>()
extension.releaseFromDefaultComponent()
val signingProps by lazy {
Properties().apply {
target.rootProject.file("publishing.properties")
.inputStream().buffered().use(this::load)
}
}
extension.pom {
name.set(target.name)
description.set(target.description ?: "Material theme for preference widgets.")
url.set("https://github.com/consp1racy/android-support-preference")
licenses {
license {
name.set("The Apache Software License, Version 2.0")
url.set("http://www.apache.org/licenses/LICENSE-2.0.txt")
}
}
developers {
developer {
name.set("Eugen Pechanec")
email.set("[email protected]")
url.set("https://github.com/consp1racy")
}
}
scm {
connection.set("scm:git:https://github.com/consp1racy/android-support-preference.git")
developerConnection.set("scm:git:ssh://[email protected]/consp1racy/android-support-preference.git")
url.set("https://github.com/consp1racy/android-support-preference")
}
}
extension.repositories { version ->
when {
version.endsWith("-SNAPSHOT") -> {
maven("https://s01.oss.sonatype.org/content/repositories/snapshots/") {
name = "ossrh"
credentials {
username = System.getProperty("OSSRH_USERNAME")
?: signingProps.getProperty("OSSRH_USERNAME")
password = System.getProperty("OSSRH_PASSWORD")
?: signingProps.getProperty("OSSRH_PASSWORD")
}
}
}
else -> {
maven("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") {
name = "ossrh"
credentials {
username = System.getProperty("OSSRH_USERNAME")
?: signingProps.getProperty("OSSRH_USERNAME")
password = System.getProperty("OSSRH_PASSWORD")
?: signingProps.getProperty("OSSRH_PASSWORD")
}
}
}
}
}
}
} | apache-2.0 | ff74e93db93e93dfbebd5d7fbd2cbef9 | 36.542553 | 113 | 0.528628 | 4.906815 | false | false | false | false |
caarmen/FRCAndroidWidget | app/src/main/kotlin/ca/rmen/android/frcwidget/render/FRCRenderApi16.kt | 1 | 3000 | /*
* French Revolutionary Calendar Android Widget
* Copyright (C) 2011 - 2014, 2017 Carmen Alvarez
*
* 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 ca.rmen.android.frcwidget.render
import android.annotation.TargetApi
import android.appwidget.AppWidgetManager
import android.content.Context
import android.util.Log
import android.widget.TextView
import ca.rmen.android.frccommon.Constants
/**
* Provides methods used to render widgets. These methods are available only on api level 16+
*
* @author calvarez
*/
object FRCRenderApi16 {
private val TAG = Constants.TAG + FRCRenderApi16::class.java.simpleName
/**
* @return Looks at the size of the given widget, and returns the scale factor based on this widget's default size. All the widget's default dimensions
* should be multiplied by this scale factor when rendering the widget.
*/
@TargetApi(16)
fun getScaleFactor(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int, defaultWidgetWidth: Float, defaultWidgetHeight: Float): Float {
Log.v(TAG, "getScaleFactor for widget " + appWidgetId)
val widgetOptions = appWidgetManager.getAppWidgetOptions(appWidgetId)
val keys = widgetOptions.keySet()
Log.v(TAG, "getScaleFactor: widget option keys: " + keys)
val minWidth = widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)
val minHeight = widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT)
val maxWidth = widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH)
val maxHeight = widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT)
Log.v(TAG, "getScaleFactor: min:" + minWidth + "x" + minHeight + ", max:" + maxWidth + "x" + maxHeight + ", default:" + defaultWidgetWidth + "x" + defaultWidgetHeight)
if (maxWidth <= 0 || maxHeight <= 0) {
return FRCRenderApi13.getMaxScaleFactor(context, defaultWidgetWidth, defaultWidgetHeight)
}
return Math.max(maxWidth / defaultWidgetWidth, maxHeight / defaultWidgetHeight)
}
@TargetApi(16)
fun scaleShadow(textView: TextView, scaleFactor: Float) =
textView.setShadowLayer(textView.shadowRadius * scaleFactor,
textView.shadowDx * scaleFactor,
textView.shadowDy * scaleFactor,
textView.shadowColor)
}
| gpl-3.0 | 60d21f1bf4bf2d10e1cc900e5ad302a6 | 45.875 | 175 | 0.723 | 4.405286 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesOrDirectories/MoveKotlinFileHandler.kt | 4 | 6553 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.move.moveFilesOrDirectories
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiCompiledElement
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.light.LightElement
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFileHandler
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix
import org.jetbrains.kotlin.idea.core.packageMatchesDirectoryOrImplicit
import org.jetbrains.kotlin.idea.refactoring.hasIdentifiersOnly
import org.jetbrains.kotlin.idea.refactoring.move.ContainerChangeInfo
import org.jetbrains.kotlin.idea.refactoring.move.ContainerInfo
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.*
import org.jetbrains.kotlin.idea.refactoring.move.updatePackageDirective
import org.jetbrains.kotlin.idea.roots.isOutsideKotlinAwareSourceRoot
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.UserDataProperty
internal var KtFile.allElementsToMove: List<PsiElement>? by UserDataProperty(Key.create("SCOPE_TO_MOVE"))
class MoveKotlinFileHandler : MoveFileHandler() {
internal class FileInfo(file: KtFile) : UsageInfo(file)
// This is special 'PsiElement' whose purpose is to wrap MoveKotlinTopLevelDeclarationsProcessor
// so that it can be kept in the usage info list
private class MoveContext(
val file: PsiFile,
val declarationMoveProcessor: MoveKotlinDeclarationsProcessor
) : LightElement(file.manager, KotlinLanguage.INSTANCE) {
override fun toString() = ""
}
private fun KtFile.getPackageNameInfo(newParent: PsiDirectory?, clearUserData: Boolean): ContainerChangeInfo? {
val shouldUpdatePackageDirective = updatePackageDirective ?: packageMatchesDirectoryOrImplicit()
updatePackageDirective = if (clearUserData) null else shouldUpdatePackageDirective
if (!shouldUpdatePackageDirective) return null
val oldPackageName = packageFqName
val newPackageName = newParent?.getFqNameWithImplicitPrefix() ?: return ContainerChangeInfo(
ContainerInfo.Package(oldPackageName),
ContainerInfo.UnknownPackage
)
if (oldPackageName.asString() == newPackageName.asString()
&& ModuleUtilCore.findModuleForPsiElement(this) == ModuleUtilCore.findModuleForPsiElement(newParent)
) return null
if (!newPackageName.hasIdentifiersOnly()) return null
return ContainerChangeInfo(ContainerInfo.Package(oldPackageName), ContainerInfo.Package(newPackageName))
}
fun initMoveProcessor(psiFile: PsiFile, newParent: PsiDirectory?, withConflicts: Boolean): MoveKotlinDeclarationsProcessor? {
if (psiFile !is KtFile) return null
val packageNameInfo = psiFile.getPackageNameInfo(newParent, false) ?: return null
val project = psiFile.project
val moveTarget = when (val newPackage = packageNameInfo.newContainer) {
ContainerInfo.UnknownPackage -> EmptyKotlinMoveTarget
else -> if (newParent == null) {
return null
} else {
KotlinMoveTargetForDeferredFile(newPackage.fqName!!, newParent.virtualFile) {
MoveFilesOrDirectoriesUtil.doMoveFile(psiFile, newParent)
val file = newParent.findFile(psiFile.name) ?: error("Lost file after move")
file as KtFile
}
}
}
return MoveKotlinDeclarationsProcessor(
MoveDeclarationsDescriptor(
project = project,
moveSource = MoveSource(psiFile),
moveTarget = moveTarget,
delegate = MoveDeclarationsDelegate.TopLevel,
allElementsToMove = psiFile.allElementsToMove,
analyzeConflicts = withConflicts
)
)
}
override fun canProcessElement(element: PsiFile?): Boolean {
if (element is PsiCompiledElement || element !is KtFile) return false
return !isOutsideKotlinAwareSourceRoot(element)
}
override fun findUsages(
psiFile: PsiFile,
newParent: PsiDirectory?,
searchInComments: Boolean,
searchInNonJavaFiles: Boolean
): List<UsageInfo> {
return findUsages(psiFile, newParent, true)
}
fun findUsages(
psiFile: PsiFile,
newParent: PsiDirectory?,
withConflicts: Boolean
): List<UsageInfo> {
if (psiFile !is KtFile) return emptyList()
val usages = arrayListOf<UsageInfo>(FileInfo(psiFile))
initMoveProcessor(psiFile, newParent, withConflicts)?.let {
usages += it.findUsages()
usages += it.getConflictsAsUsages()
}
return usages
}
override fun prepareMovedFile(file: PsiFile, moveDestination: PsiDirectory, oldToNewMap: MutableMap<PsiElement, PsiElement>) {
if (file !is KtFile) return
val moveProcessor = initMoveProcessor(file, moveDestination, false) ?: return
val moveContext = MoveContext(file, moveProcessor)
oldToNewMap[moveContext] = moveContext
val packageNameInfo = file.getPackageNameInfo(moveDestination, true) ?: return
val newFqName = packageNameInfo.newContainer.fqName
if (newFqName != null) {
file.packageDirective?.fqName = newFqName.quoteIfNeeded()
}
}
override fun updateMovedFile(file: PsiFile) {
}
override fun retargetUsages(usageInfos: List<UsageInfo>?, oldToNewMap: Map<PsiElement, PsiElement>) {
val currentFile = (usageInfos?.firstOrNull() as? FileInfo)?.element
val moveContext = oldToNewMap.keys.firstOrNull { it is MoveContext && it.file == currentFile } as? MoveContext ?: return
retargetUsages(usageInfos, moveContext.declarationMoveProcessor)
}
fun retargetUsages(usageInfos: List<UsageInfo>?, moveDeclarationsProcessor: MoveKotlinDeclarationsProcessor) {
usageInfos?.let { moveDeclarationsProcessor.doPerformRefactoring(it) }
}
}
| apache-2.0 | af3045560fc966f9a819d3fd414aef9f | 43.277027 | 158 | 0.720586 | 5.250801 | false | false | false | false |
GunoH/intellij-community | plugins/devkit/intellij.devkit.workspaceModel/tests/testData/finalProperty/after/gen/FinalFieldsEntityImpl.kt | 2 | 6394 | package com.intellij.workspaceModel.test.api
import com.intellij.workspaceModel.deft.api.annotations.Default
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.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class FinalFieldsEntityImpl(val dataSource: FinalFieldsEntityData) : FinalFieldsEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val descriptor: AnotherDataClass
get() = dataSource.descriptor
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: FinalFieldsEntityData?) : ModifiableWorkspaceEntityBase<FinalFieldsEntity, FinalFieldsEntityData>(
result), FinalFieldsEntity.Builder {
constructor() : this(FinalFieldsEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity FinalFieldsEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// 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().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDescriptorInitialized()) {
error("Field FinalFieldsEntity#descriptor should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as FinalFieldsEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.descriptor != dataSource.descriptor) this.descriptor = dataSource.descriptor
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var descriptor: AnotherDataClass
get() = getEntityData().descriptor
set(value) {
checkModificationAllowed()
getEntityData(true).descriptor = value
changedProperty.add("descriptor")
}
override fun getEntityClass(): Class<FinalFieldsEntity> = FinalFieldsEntity::class.java
}
}
class FinalFieldsEntityData : WorkspaceEntityData<FinalFieldsEntity>() {
lateinit var descriptor: AnotherDataClass
fun isDescriptorInitialized(): Boolean = ::descriptor.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<FinalFieldsEntity> {
val modifiable = FinalFieldsEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): FinalFieldsEntity {
return getCached(snapshot) {
val entity = FinalFieldsEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return FinalFieldsEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return FinalFieldsEntity(descriptor, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as FinalFieldsEntityData
if (this.entitySource != other.entitySource) return false
if (this.descriptor != other.descriptor) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as FinalFieldsEntityData
if (this.descriptor != other.descriptor) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + descriptor.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + descriptor.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.add(AnotherDataClass::class.java)
collector.sameForAllEntities = true
}
}
| apache-2.0 | dba8bfd4c2b879e6fa87e0ad9161e997 | 31.789744 | 122 | 0.738036 | 5.483705 | false | false | false | false |
himikof/intellij-rust | src/main/kotlin/org/rust/cargo/toolchain/impl/CargoMetadata.kt | 1 | 6614 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.toolchain.impl
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtil
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.utils.findFileByMaybeRelativePath
/**
* Classes mirroring JSON output of `cargo metadata`.
* Attribute names and snake_case are crucial.
*
* Some information available in JSON is not represented here
*/
object CargoMetadata {
data class Project(
/**
* All packages, including dependencies
*/
val packages: List<Package>,
/**
* A graph of dependencies
*/
val resolve: Resolve,
/**
* Version of the format (currently 1)
*/
val version: Int,
/**
* Ids of packages that are members of the cargo workspace
*/
val workspace_members: List<String>?
)
data class Package(
val name: String,
/**
* SemVer version
*/
val version: String,
/**
* Where did this package comes from? Local file system, crates.io, github repository.
*
* Will be `null` for the root package and path dependencies.
*/
val source: String?,
/**
* A unique id.
* There may be several packages with the same name, but different version/source.
* The triple (name, version, source) is unique.
*/
val id: String,
/**
* Path to Cargo.toml
*/
val manifest_path: String,
/**
* Artifacts that can be build from this package.
* This is a list of crates that can be build from the package.
*/
val targets: List<Target>
)
data class Target(
/**
* Kind of a target. Can be a singleton list ["bin"],
* ["example], ["test"], ["example"], ["custom-build"], ["bench"].
*
* Can also be a list of one or more of "lib", "rlib", "dylib", "staticlib"
*/
val kind: List<String>,
/**
* Name
*/
val name: String,
/**
* Path to the root module of the crate (aka crate root)
*/
val src_path: String
) {
val cleanKind: CargoWorkspace.TargetKind get() = when (kind.singleOrNull()) {
"bin" -> CargoWorkspace.TargetKind.BIN
"example" -> CargoWorkspace.TargetKind.EXAMPLE
"test" -> CargoWorkspace.TargetKind.TEST
"bench" -> CargoWorkspace.TargetKind.BENCH
"proc-macro" -> CargoWorkspace.TargetKind.LIB
else ->
if (kind.any { it.endsWith("lib") })
CargoWorkspace.TargetKind.LIB
else
CargoWorkspace.TargetKind.UNKNOWN
}
}
/**
* A rooted graph of dependencies, represented as adjacency list
*/
data class Resolve(
val nodes: List<ResolveNode>
)
data class ResolveNode(
val id: String,
/**
* id's of dependent packages
*/
val dependencies: List<String>
)
// The next two things do not belong here,
// see `machine_message` in Cargo.
data class Artifact(
val target: Target,
val profile: Profile,
val filenames: List<String>
) {
companion object {
fun fromJson(json: JsonObject): Artifact? {
if (json.getAsJsonPrimitive("reason").asString != "compiler-artifact") {
return null
}
return Gson().fromJson(json, Artifact::class.java)
}
}
}
data class Profile(
val test: Boolean
)
fun clean(project: Project): CleanCargoMetadata {
val packageIdToIndex: (String) -> Int = project.packages.mapIndexed { i, p -> p.id to i }.toMap().let { pkgs ->
{ pkgs[it] ?: error("Cargo metadata references an unlisted package: `$it`") }
}
val fs = LocalFileSystem.getInstance()
val members = project.workspace_members
?: error("No `members` key in the `cargo metadata` output.\n" +
"Your version of Cargo is no longer supported, please upgrade Cargo.")
return CleanCargoMetadata(
project.packages.mapNotNull { it.clean(fs, it.id in members) },
project.resolve.nodes.map { (id, dependencies) ->
CleanCargoMetadata.DependencyNode(
packageIdToIndex(id),
dependencies.map { packageIdToIndex(it) }
)
}
)
}
private fun Package.clean(fs: LocalFileSystem, isWorkspaceMember: Boolean): CleanCargoMetadata.Package? {
val root = checkNotNull(fs.refreshAndFindFileByPath(PathUtil.getParentPath(manifest_path))) {
"`cargo metadata` reported a package which does not exist at `$manifest_path`"
}
return CleanCargoMetadata.Package(
id,
root.url,
name,
version,
targets.mapNotNull { it.clean(root) },
source,
manifest_path,
isWorkspaceMember
)
}
private fun Target.clean(root: VirtualFile): CleanCargoMetadata.Target? {
val mainFile = root.findFileByMaybeRelativePath(src_path)
return mainFile?.let { CleanCargoMetadata.Target(it.url, name, cleanKind) }
}
}
/**
* A POD-style representation of [CargoWorkspace] used as an intermediate representation
* between `cargo metadata` JSON and [CargoWorkspace] object graph.
*
* Dependency graph is represented via adjacency list, where `Index` is the order of a particular
* package in `packages` list.
*/
data class CleanCargoMetadata(
val packages: List<Package>,
val dependencies: List<DependencyNode>
) {
data class DependencyNode(
val packageIndex: Int,
val dependenciesIndexes: Collection<Int>
)
data class Package(
val id: String,
val url: String,
val name: String,
val version: String,
val targets: Collection<Target>,
val source: String?,
val manifestPath: String,
val isWorkspaceMember: Boolean
)
data class Target(
val url: String,
val name: String,
val kind: CargoWorkspace.TargetKind
)
}
| mit | 90b24728807df96873cda89d7d93785b | 27.756522 | 119 | 0.578319 | 4.667608 | false | false | false | false |
brianwernick/PlaylistCore | demo/src/main/java/com/devbrackets/android/playlistcoredemo/ui/activity/AudioPlayerActivity.kt | 1 | 11784 | package com.devbrackets.android.playlistcoredemo.ui.activity
import android.os.Bundle
import android.text.format.DateUtils
import android.view.View
import android.widget.*
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.appcompat.app.AppCompatActivity
import androidx.mediarouter.app.MediaRouteButton
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.devbrackets.android.playlistcore.data.MediaProgress
import com.devbrackets.android.playlistcore.data.PlaybackState
import com.devbrackets.android.playlistcore.listener.PlaylistListener
import com.devbrackets.android.playlistcore.listener.ProgressListener
import com.devbrackets.android.playlistcoredemo.App
import com.devbrackets.android.playlistcoredemo.R
import com.devbrackets.android.playlistcoredemo.data.MediaItem
import com.devbrackets.android.playlistcoredemo.data.Samples
import com.devbrackets.android.playlistcoredemo.manager.PlaylistManager
import com.google.android.gms.cast.framework.CastButtonFactory
import java.util.*
/**
* An example activity to show how to implement and audio UI
* that interacts with the [com.devbrackets.android.playlistcore.service.BasePlaylistService]
* and [com.devbrackets.android.playlistcore.manager.ListPlaylistManager]
* classes.
*/
class AudioPlayerActivity : AppCompatActivity(), PlaylistListener<MediaItem>, ProgressListener {
private var loadingBar: ProgressBar? = null
private var artworkView: ImageView? = null
private var currentPositionView: TextView? = null
private var durationView: TextView? = null
private var seekBar: SeekBar? = null
private var shouldSetDuration = false
private var userInteracting = false
private var titleTextView: TextView? = null
private var subtitleTextView: TextView? = null
private var descriptionTextView: TextView? = null
private var previousButton: ImageButton? = null
private var playPauseButton: ImageButton? = null
private var nextButton: ImageButton? = null
private var castButton: MediaRouteButton? = null
protected val playlistManager: PlaylistManager by lazy {
(applicationContext as App).playlistManager
}
private var selectedPosition = 0
private var glide: RequestManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.audio_player_activity)
retrieveExtras()
init()
}
override fun onPause() {
super.onPause()
playlistManager.unRegisterPlaylistListener(this)
playlistManager.unRegisterProgressListener(this)
}
override fun onResume() {
super.onResume()
playlistManager.registerPlaylistListener(this)
playlistManager.registerProgressListener(this)
//Makes sure to retrieve the current playback information
updateCurrentPlaybackInformation()
}
override fun onPlaylistItemChanged(currentItem: MediaItem?, hasNext: Boolean, hasPrevious: Boolean): Boolean {
shouldSetDuration = true
//Updates the button states
nextButton!!.isEnabled = hasNext
previousButton!!.isEnabled = hasPrevious
//Loads the new image
if (currentItem != null) {
artworkView?.let { view ->
glide?.load(currentItem.artworkUrl)?.into(view)
}
}
// Updates the title, subtitle, and description
titleTextView!!.text = currentItem?.title.orEmpty()
subtitleTextView!!.text = currentItem?.album.orEmpty()
descriptionTextView!!.text = currentItem?.artist.orEmpty()
return true
}
override fun onPlaybackStateChanged(playbackState: PlaybackState): Boolean {
when (playbackState) {
PlaybackState.STOPPED -> finish()
PlaybackState.RETRIEVING, PlaybackState.PREPARING, PlaybackState.SEEKING -> restartLoading()
PlaybackState.PLAYING -> doneLoading(true)
PlaybackState.PAUSED -> doneLoading(false)
else -> {}
}
return true
}
override fun onProgressUpdated(progress: MediaProgress): Boolean {
if (shouldSetDuration && progress.duration > 0) {
shouldSetDuration = false
setDuration(progress.duration)
}
if (!userInteracting) {
seekBar!!.secondaryProgress = (progress.duration * progress.bufferPercentFloat).toInt()
seekBar!!.progress = progress.position.toInt()
currentPositionView!!.text = formatMs(progress.position)
}
return true
}
/**
* Makes sure to update the UI to the current playback item.
*/
private fun updateCurrentPlaybackInformation() {
val itemChange = playlistManager.currentItemChange
if (itemChange != null) {
onPlaylistItemChanged(itemChange.currentItem, itemChange.hasNext, itemChange.hasPrevious)
}
val currentPlaybackState = playlistManager.currentPlaybackState
if (currentPlaybackState !== PlaybackState.STOPPED) {
onPlaybackStateChanged(currentPlaybackState)
}
val mediaProgress = playlistManager.currentProgress
mediaProgress?.let { onProgressUpdated(it) }
}
/**
* Retrieves the extra associated with the selected playlist index
* so that we can start playing the correct item.
*/
private fun retrieveExtras() {
val extras = intent.extras
selectedPosition = extras!!.getInt(EXTRA_INDEX, 0)
}
/**
* Performs the initialization of the views and any other
* general setup
*/
private fun init() {
retrieveViews()
setupListeners()
glide = Glide.with(this)
CastButtonFactory.setUpMediaRouteButton(applicationContext, castButton!!)
val generatedPlaylist = setupPlaylistManager()
startPlayback(generatedPlaylist)
}
/**
* Called when we receive a notification that the current item is
* done loading. This will then update the view visibilities and
* states accordingly.
*
* @param isPlaying True if the audio item is currently playing
*/
private fun doneLoading(isPlaying: Boolean) {
loadCompleted()
updatePlayPauseImage(isPlaying)
}
/**
* Updates the Play/Pause image to represent the correct playback state
*
* @param isPlaying True if the audio item is currently playing
*/
private fun updatePlayPauseImage(isPlaying: Boolean) {
val resId = if (isPlaying) R.drawable.ic_pause_black_24dp else R.drawable.ic_play_black_24dp
playPauseButton!!.setImageResource(resId)
}
/**
* Used to inform the controls to finalize their setup. This
* means replacing the loading animation with the PlayPause button
*/
fun loadCompleted() {
playPauseButton!!.visibility = View.VISIBLE
previousButton!!.visibility = View.VISIBLE
nextButton!!.visibility = View.VISIBLE
loadingBar!!.visibility = View.INVISIBLE
}
/**
* Used to inform the controls to return to the loading stage.
* This is the opposite of [.loadCompleted]
*/
fun restartLoading() {
playPauseButton!!.visibility = View.INVISIBLE
previousButton!!.visibility = View.INVISIBLE
nextButton!!.visibility = View.INVISIBLE
loadingBar!!.visibility = View.VISIBLE
}
/**
* Sets the [.seekBar]s max and updates the duration text
*
* @param duration The duration of the media item in milliseconds
*/
private fun setDuration(duration: Long) {
seekBar!!.max = duration.toInt()
durationView!!.text = formatMs(duration)
}
/**
* Retrieves the playlist instance and performs any generation
* of content if it hasn't already been performed.
*
* @return True if the content was generated
*/
private fun setupPlaylistManager(): Boolean {
//There is nothing to do if the currently playing values are the same
if (playlistManager.id == PLAYLIST_ID.toLong()) {
return false
}
val mediaItems: MutableList<MediaItem> = LinkedList()
for (sample in Samples.audio) {
val mediaItem = MediaItem(sample, true)
mediaItems.add(mediaItem)
}
playlistManager.setParameters(mediaItems, selectedPosition)
playlistManager.id = PLAYLIST_ID.toLong()
return true
}
/**
* Populates the class variables with the views created from the
* xml layout file.
*/
private fun retrieveViews() {
loadingBar = findViewById(R.id.audio_player_loading)
artworkView = findViewById(R.id.audio_player_image)
currentPositionView = findViewById(R.id.audio_player_position)
durationView = findViewById(R.id.audio_player_duration)
seekBar = findViewById(R.id.audio_player_seek)
titleTextView = findViewById(R.id.title_text_view)
subtitleTextView = findViewById(R.id.subtitle_text_view)
descriptionTextView = findViewById(R.id.description_text_view)
previousButton = findViewById(R.id.audio_player_previous)
playPauseButton = findViewById(R.id.audio_player_play_pause)
nextButton = findViewById(R.id.audio_player_next)
castButton = findViewById(R.id.media_route_button)
}
/**
* Links the SeekBarChanged to the [.seekBar] and
* onClickListeners to the media buttons that call the appropriate
* invoke methods in the [.playlistManager]
*/
private fun setupListeners() {
seekBar!!.setOnSeekBarChangeListener(SeekBarChanged())
previousButton!!.setOnClickListener { playlistManager.invokePrevious() }
playPauseButton!!.setOnClickListener { playlistManager.invokePausePlay() }
nextButton!!.setOnClickListener { playlistManager.invokeNext() }
}
/**
* Starts the audio playback if necessary.
*
* @param forceStart True if the audio should be started from the beginning even if it is currently playing
*/
private fun startPlayback(forceStart: Boolean) {
//If we are changing audio files, or we haven't played before then start the playback
if (forceStart || playlistManager.currentPosition != selectedPosition) {
playlistManager.currentPosition = selectedPosition
playlistManager.play(0, false)
}
}
/**
* Listens to the seek bar change events and correctly handles the changes
*/
private inner class SeekBarChanged : OnSeekBarChangeListener {
private var seekPosition = -1
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (!fromUser) {
return
}
seekPosition = progress
currentPositionView!!.text = formatMs(progress.toLong())
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
userInteracting = true
seekPosition = seekBar.progress
playlistManager.invokeSeekStarted()
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
userInteracting = false
playlistManager.invokeSeekEnded(seekPosition.toLong())
seekPosition = -1
}
}
companion object {
const val EXTRA_INDEX = "EXTRA_INDEX"
const val PLAYLIST_ID = 4 //Arbitrary, for the example
private val formatBuilder = StringBuilder()
private val formatter = Formatter(formatBuilder, Locale.getDefault())
/**
* Formats the specified milliseconds to a human readable format
* in the form of (Hours : Minutes : Seconds). If the specified
* milliseconds is less than 0 the resulting format will be
* "--:--" to represent an unknown time
*
* @param milliseconds The time in milliseconds to format
* @return The human readable time
*/
fun formatMs(milliseconds: Long): String {
if (milliseconds < 0) {
return "--:--"
}
val seconds = milliseconds % DateUtils.MINUTE_IN_MILLIS / DateUtils.SECOND_IN_MILLIS
val minutes = milliseconds % DateUtils.HOUR_IN_MILLIS / DateUtils.MINUTE_IN_MILLIS
val hours = milliseconds % DateUtils.DAY_IN_MILLIS / DateUtils.HOUR_IN_MILLIS
formatBuilder.setLength(0)
return if (hours > 0) {
formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString()
} else formatter.format("%02d:%02d", minutes, seconds).toString()
}
}
} | apache-2.0 | 8550a50835008a47111cafbd06989bfb | 34.496988 | 112 | 0.728021 | 4.742052 | false | false | false | false |
mdanielwork/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/type/PrecisionUtil.kt | 9 | 4041 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInspection.type
import com.intellij.psi.PsiType
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrUnaryExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypeConstants.*
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl
import java.math.BigDecimal
import java.math.BigInteger
object PrecisionUtil {
//see org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.checkPossibleLooseOfPrecision()
fun isPossibleLooseOfPrecision(targetType: PsiType, actualType: PsiType, expression: GrExpression): Boolean {
val targetRank = getTypeRank(targetType)
val actualRank = getTypeRank(actualType)
if (targetRank == CHARACTER_RANK || actualRank == CHARACTER_RANK || targetRank == BIG_DECIMAL_RANK) return false
if (actualRank == 0 || targetRank == 0 || actualRank <= targetRank) return false
val value = extractLiteralValue(expression) ?: return true
when (targetRank) {
BYTE_RANK -> {
val byteVal = value.toByte()
if (value is Short) {
return java.lang.Short.valueOf(byteVal.toShort()) != value
}
if (value is Int) {
return Integer.valueOf(byteVal.toInt()) != value
}
if (value is Long) {
return java.lang.Long.valueOf(byteVal.toLong()) != value
}
return if (value is Float) {
java.lang.Float.valueOf(byteVal.toFloat()) != value
}
else java.lang.Double.valueOf(byteVal.toDouble()) != value
}
SHORT_RANK -> {
val shortVal = value.toShort()
if (value is Int) {
return Integer.valueOf(shortVal.toInt()) != value
}
if (value is Long) {
return java.lang.Long.valueOf(shortVal.toLong()) != value
}
return if (value is Float) {
java.lang.Float.valueOf(shortVal.toFloat()) != value
}
else java.lang.Double.valueOf(shortVal.toDouble()) != value
}
INTEGER_RANK -> {
val intVal = value.toInt()
if (value is Long) {
return java.lang.Long.valueOf(intVal.toLong()) != value
}
return if (value is Float) {
java.lang.Float.valueOf(intVal.toFloat()) != value
}
else java.lang.Double.valueOf(intVal.toDouble()) != value
}
LONG_RANK -> {
val longVal = value.toLong()
return if (value is Float) {
java.lang.Float.valueOf(longVal.toFloat()) != value
}
else java.lang.Double.valueOf(longVal.toDouble()) != value
}
FLOAT_RANK -> {
val floatVal = value.toFloat()
return java.lang.Double.valueOf(floatVal.toDouble()) != value
}
else -> return false
}
}
private fun extractLiteralValue(expression: GrExpression?): Number? {
var negativeNumber = false
var valueExpression = expression
if (expression is GrUnaryExpression) {
val operationTokenType = expression.operationTokenType
if (operationTokenType in listOf(GroovyTokenTypes.mPLUS, GroovyTokenTypes.mMINUS)) {
negativeNumber = operationTokenType == GroovyTokenTypes.mMINUS
valueExpression = expression.operand
}
}
val literalValue = (valueExpression as? GrLiteralImpl)?.value ?: return null
return (literalValue as? Number)?.let { if (negativeNumber) commonNegate(it) else it }
}
private fun commonNegate(num: Number): Number? {
return when (num) {
is Byte -> -num
is Short -> -num
is Int -> -num
is Long -> -num
is BigInteger -> -num
is Float -> -num
is Double -> -num
is BigDecimal -> -num
else -> null
}
}
} | apache-2.0 | 553d80ffa13a5a5b8909058829024e0f | 36.082569 | 140 | 0.652561 | 4.209375 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/uhabits/utils/DatabaseUtils.kt | 1 | 2683 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.utils
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import org.isoron.uhabits.HabitsApplication.Companion.isTestMode
import org.isoron.uhabits.HabitsDatabaseOpener
import org.isoron.uhabits.core.DATABASE_FILENAME
import org.isoron.uhabits.core.DATABASE_VERSION
import org.isoron.uhabits.core.utils.DateFormats.Companion.getBackupDateFormat
import org.isoron.uhabits.core.utils.DateUtils.Companion.getLocalTime
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
object DatabaseUtils {
private var opener: HabitsDatabaseOpener? = null
@JvmStatic
fun getDatabaseFile(context: Context): File {
val databaseFilename = databaseFilename
val root = context.filesDir.path
return File("$root/../databases/$databaseFilename")
}
private val databaseFilename: String
get() {
var databaseFilename: String = DATABASE_FILENAME
if (isTestMode()) databaseFilename = "test.db"
return databaseFilename
}
fun initializeDatabase(context: Context?) {
opener = HabitsDatabaseOpener(
context!!,
databaseFilename,
DATABASE_VERSION
)
}
@JvmStatic
@Throws(IOException::class)
fun saveDatabaseCopy(context: Context, dir: File): String {
val dateFormat: SimpleDateFormat = getBackupDateFormat()
val date = dateFormat.format(getLocalTime())
val filename = "${dir.absolutePath}/Loop Habits Backup $date.db"
Log.i("DatabaseUtils", "Writing: $filename")
val db = getDatabaseFile(context)
val dbCopy = File(filename)
db.copyTo(dbCopy)
return dbCopy.absolutePath
}
fun openDatabase(): SQLiteDatabase {
checkNotNull(opener)
return opener!!.writableDatabase
}
}
| gpl-3.0 | 9976666ce73a2e4792c99a0a1efa279b | 34.76 | 78 | 0.713274 | 4.48495 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/completion/tests/testData/basic/common/ExtensionWithGenericReceiver.kt | 8 | 653 | // FIR_IDENTICAL
// FIR_COMPARISON
open class Base
open class SubBase:Base()
open class SubSubBase:SubBase()
open class OtherBase
fun <T: Base> T.extensionSomeBase() = 12
fun <T: SubBase> T.extensionSomeSubBase() = 12
fun <T: SubSubBase> T.extensionSomeSubSubBase() = 12
fun <T: Base> T?.extensionSomeNull() = 12
fun <T: Base?> T.extensionSomeNullParam() = 12
fun <T: OtherBase> T.extensionSomeOtherBase() = 12
fun some() {
SubBase().extensionSome<caret>
}
// EXIST: extensionSomeBase
// EXIST: extensionSomeSubBase
// EXIST: extensionSomeNull
// EXIST: extensionSomeNullParam
// ABSENT: extensionSomeOtherBase
// ABSENT: extensionSomeSubSubBase
| apache-2.0 | 8ed50a7c2c4ded81532b5115c896c049 | 26.208333 | 52 | 0.74732 | 3.265 | false | false | false | false |
spotify/heroic | heroic-component/src/main/java/com/spotify/heroic/common/FeatureSet.kt | 1 | 2795 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.spotify.heroic.common
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonValue
/**
* A set of enabled and disabled features.
*/
data class FeatureSet(
val enabled: Set<Feature> = emptySet(),
val disabled: Set<Feature> = emptySet()
) {
@JsonCreator
constructor(features: Set<String>): this(
enabled = features.filterNot { it.startsWith("-") }
.map(Feature::create)
.toSet(),
disabled = features.filter { it.startsWith("-") }
.map { Feature.create(it.substring(1)) }
.toSet()
)
@JsonValue
fun value(): List<String> {
val features = mutableListOf<String>()
enabled.forEach { features.add(it.id()) }
disabled.forEach { features.add("-" + it.id()) }
return features
}
fun isEmpty(): Boolean {
return enabled.isEmpty() && disabled.isEmpty()
}
/**
* Combine this feature set with another.
*
* @param other Other set to combine with.
* @return a new feature set.
*/
fun combine(other: FeatureSet): FeatureSet {
val enabled = mutableSetOf<Feature>()
enabled.addAll(this.enabled)
enabled.addAll(other.enabled)
val disabled = mutableSetOf<Feature>()
disabled.addAll(this.disabled)
disabled.addAll(other.disabled)
return FeatureSet(enabled, disabled)
}
companion object {
/**
* Create an empty feature set.
*
* @return a new feature set.
*/
@JvmStatic
fun empty() = FeatureSet()
/**
* Create a new feature set with the given features enabled.
*
* @param features Features to enable in the new set.
* @return a new feature set.
*/
@JvmStatic
fun of(vararg features: Feature) = FeatureSet(enabled = features.toSet())
}
}
| apache-2.0 | 1bbe1a69babe3b7ba3b50819e7de617d | 29.380435 | 81 | 0.634347 | 4.394654 | false | false | false | false |
mikepenz/FastAdapter | fastadapter-extensions-ui/src/main/java/com/mikepenz/fastadapter/ui/utils/FixStateListDrawable.kt | 1 | 1608 | package com.mikepenz.fastadapter.ui.utils
import android.R
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
/**
* http://stackoverflow.com/questions/7979440/android-cloning-a-drawable-in-order-to-make-a-statelistdrawable-with-filters
* http://stackoverflow.com/users/2075875/malachiasz
*/
@SuppressLint("InlinedApi")
class FixStateListDrawable : StateListDrawable {
var color: ColorStateList?
constructor(drawable: Drawable, color: ColorStateList?) : super() {
var drawable = drawable
drawable = drawable.mutate()
addState(intArrayOf(R.attr.state_selected), drawable)
addState(intArrayOf(), drawable)
this.color = color
}
constructor(drawable: Drawable, selectedDrawable: Drawable, color: ColorStateList?) : super() {
var drawable = drawable
var selectedDrawable = selectedDrawable
drawable = drawable.mutate()
selectedDrawable = selectedDrawable.mutate()
addState(intArrayOf(R.attr.state_selected), selectedDrawable)
addState(intArrayOf(), drawable)
this.color = color
}
override fun onStateChange(states: IntArray): Boolean {
val color = color
if (color != null) {
super.setColorFilter(color.getColorForState(states, color.defaultColor), PorterDuff.Mode.SRC_IN)
}
return super.onStateChange(states)
}
override fun isStateful(): Boolean {
return true
}
} | apache-2.0 | 2b47f44344186030786bcf13b7bca307 | 33.234043 | 122 | 0.709577 | 4.516854 | false | false | false | false |
spoptchev/kotlin-preconditions | src/main/kotlin/com/github/spoptchev/kotlin/preconditions/matcher/ComparableMatcher.kt | 1 | 1755 | package com.github.spoptchev.kotlin.preconditions.matcher
import com.github.spoptchev.kotlin.preconditions.Condition
import com.github.spoptchev.kotlin.preconditions.Matcher
import com.github.spoptchev.kotlin.preconditions.PreconditionBlock
fun <T> PreconditionBlock<T>.isLt(other: T) = isLessThan(other)
fun <T> PreconditionBlock<T>.isLessThan(other: T) = object : Matcher<Comparable<T>>() {
override fun test(condition: Condition<Comparable<T>>) = condition.test {
withResult(value < other) { "$expectedTo be < $other" }
}
}
fun <T> PreconditionBlock<T>.isLte(other: T) = isLessThanOrEqualTo(other)
fun <T> PreconditionBlock<T>.isLessThanOrEqualTo(other: T) = object : Matcher<Comparable<T>>() {
override fun test(condition: Condition<Comparable<T>>) = condition.test {
withResult(value <= other) { "$expectedTo be <= $other" }
}
}
fun <T> PreconditionBlock<T>.isGt(other: T) = isGreaterThan(other)
fun <T> PreconditionBlock<T>.isGreaterThan(other: T) = object : Matcher<Comparable<T>>() {
override fun test(condition: Condition<Comparable<T>>) = condition.test {
withResult(value > other) { "$expectedTo be > $other" }
}
}
fun <T> PreconditionBlock<T>.isGte(other: T) = isGreaterThanOrEqualTo(other)
fun <T> PreconditionBlock<T>.isGreaterThanOrEqualTo(other: T) = object : Matcher<Comparable<T>>() {
override fun test(condition: Condition<Comparable<T>>) = condition.test {
withResult(value >= other) { "$expectedTo be >= $other" }
}
}
fun <T : Comparable<T>> PreconditionBlock<T>.isBetween(range: ClosedRange<T>) = object : Matcher<T>() {
override fun test(condition: Condition<T>) = condition.test {
withResult(value in range) { "$expectedTo be in $range" }
}
}
| mit | 4377b17d4b63dc6dbf1f4f2caad2b034 | 41.804878 | 103 | 0.704274 | 3.475248 | false | true | false | false |
ranmocy/rCaltrain | android/app/src/main/java/me/ranmocy/rcaltrain/Events.kt | 1 | 1851 | package me.ranmocy.rcaltrain
import android.os.Bundle
import me.ranmocy.rcaltrain.database.ScheduleDao
/** Events used for FirebaseAnalytics */
internal object Events {
internal val EVENT_SCHEDULE = "event_schedule"
internal val EVENT_ON_CLICK = "event_on_click"
private val PARAM_DEPARTURE = "param_departure"
private val PARAM_ARRIVAL = "param_arrival"
private val PARAM_SCHEDULE = "param_schedule"
private val PARAM_CLICKED_ELEM = "param_clicked_elem"
private val VALUE_CLICK_DEPARTURE = "value_click_departure"
private val VALUE_CLICK_ARRIVAL = "value_click_arrival"
private val VALUE_CLICK_SWITCH = "value_click_switch"
private val VALUE_CLICK_SCHEDULE = "value_click_schedule"
fun getScheduleEvent(departure: String, arrival: String, @ScheduleDao.ServiceType schedule: Int): Bundle {
val data = Bundle()
data.putString(PARAM_DEPARTURE, departure)
data.putString(PARAM_ARRIVAL, arrival)
data.putInt(PARAM_SCHEDULE, schedule)
return data
}
val clickDepartureEvent: Bundle
get() {
val data = Bundle()
data.putString(PARAM_CLICKED_ELEM, VALUE_CLICK_DEPARTURE)
return data
}
val clickArrivalEvent: Bundle
get() {
val data = Bundle()
data.putString(PARAM_CLICKED_ELEM, VALUE_CLICK_ARRIVAL)
return data
}
val clickSwitchEvent: Bundle
get() {
val data = Bundle()
data.putString(PARAM_CLICKED_ELEM, VALUE_CLICK_SWITCH)
return data
}
fun getClickScheduleEvent(@ScheduleDao.ServiceType scheduleType: Int): Bundle {
val data = Bundle()
data.putString(PARAM_CLICKED_ELEM, VALUE_CLICK_SCHEDULE)
data.putInt(PARAM_SCHEDULE, scheduleType)
return data
}
}
| mit | e99e6f3042ffdb5ce4e2fdc79553b632 | 31.473684 | 110 | 0.657482 | 4.086093 | false | false | false | false |
chrislo27/Tickompiler | src/main/kotlin/rhmodding/tickompiler/cli/CompileCommand.kt | 2 | 6174 | package rhmodding.tickompiler.cli
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import picocli.CommandLine
import rhmodding.tickompiler.DSFunctions
import rhmodding.tickompiler.MegamixFunctions
import rhmodding.tickompiler.compiler.Compiler
import rhmodding.tickompiler.util.getDirectories
import java.io.File
import java.io.FileOutputStream
import java.nio.ByteOrder
@CommandLine.Command(name = "compile", aliases = ["c"], description = ["Compile tickflow file(s) and output them as a binary to the file/directory specified.",
"Files must be with the file extension .tickflow",
"Files will be overwritten without warning.",
"Use the --objectify/-o optional parameter to create a .tfobj (tickflow object) file, which contains the compiled data along with the tempo files required.",
"If the output is not specified, the file will be a (little-endian) .bin file with the same name.",
"If the output is not specified AND --objectify was used, the output file MUST be specified!"],
mixinStandardHelpOptions = true)
class CompileCommand : Runnable {
@CommandLine.Option(names = ["-c"], description = ["Continue even with errors."])
var continueWithErrors: Boolean = false
@CommandLine.Option(names = ["-m", "--megamix"], description = ["Compile with Megamix functions. (default true)"])
var megamixFunctions: Boolean = true
@CommandLine.Option(names = ["--ds"], description = ["Compile with RHDS functions."])
var dsFunctions: Boolean = false
@CommandLine.Option(names = ["-o", "--objectify"], paramLabel = "tempo files directory",
description = ["Compile as a .tfobj (tickflow object) file. Provide the directory where required .tempo files are located."])
var objectify: File? = null
@CommandLine.Parameters(index = "0", arity = "1", description = ["Input file or directory."])
lateinit var inputFile: File
@CommandLine.Parameters(index = "1", arity = "0..1", description = ["Output file or directory. If --objectify is used, this is NOT optional and must be a file."])
var outputFile: File? = null
override fun run() {
val nanoStart: Long = System.nanoTime()
val tempoLoc = objectify
if (tempoLoc != null && !tempoLoc.isDirectory) {
throw IllegalArgumentException("--objectify was used but the path given was not a directory: ${tempoLoc.path}")
} else if (tempoLoc != null) {
if (outputFile == null) {
throw IllegalArgumentException("--objectify was used but the output file was not specified or is not a file. It must be specified and must be a file.")
}
outputFile!!.createNewFile()
}
val objectifying = tempoLoc != null
val dirs = getDirectories(inputFile, outputFile, { s -> s.endsWith(".tickflow") }, if (objectifying) "tfobj" else "bin", objectifying)
val functions = when {
dsFunctions -> DSFunctions
megamixFunctions -> MegamixFunctions
else -> MegamixFunctions
}
val tempoFiles: List<File> = if (tempoLoc != null) tempoLoc.listFiles { f -> f.name.endsWith(".tempo") }!!.toList() else listOf()
println("Compiling ${dirs.input.size} file(s)${if (objectifying) " with ${tempoFiles.size} tempo files" else ""} ")
val outputBinFiles: List<Pair<File, File>> = if (!objectifying) {
dirs.input.mapIndexed { i, f -> f to dirs.output[i] }
} else {
dirs.input.map { it to File.createTempFile("Tickompiler_tmp-", ".bin").apply { deleteOnExit() } }
}
val coroutines: MutableList<Deferred<Boolean>> = mutableListOf()
dirs.input.forEachIndexed { index, file ->
coroutines += GlobalScope.async {
val compiler = Compiler(file, functions)
try {
println("Compiling ${file.path}")
val result = compiler.compile(ByteOrder.LITTLE_ENDIAN)
if (result.success) {
val out = outputBinFiles[index].second
out.createNewFile()
val fos = FileOutputStream(out)
fos.write(result.data.array())
fos.close()
println("Compiled ${file.path} -> ${result.timeMs} ms")
return@async true
}
} catch (e: Exception) {
if (continueWithErrors) {
println("FAILED to compile ${file.path}")
e.printStackTrace()
} else {
throw e
}
}
return@async false
}
}
runBlocking {
val numSuccessful = coroutines
.map { it.await() }
.count { it }
if (objectifying) {
if (numSuccessful != dirs.input.size) {
println("""
+====================+
| COMPILATION FAILED |
+====================+
Only $numSuccessful / ${dirs.input.size} were compiled successfully. (Took ${(System.nanoTime() - nanoStart) / 1_000_000.0} ms)
All must compile successfully to build a tickflow object.""")
} else {
val objOut = outputFile!!
println("""
+========================+
| COMPILATION SUCCESSFUL |
+========================+
All $numSuccessful targets were compiled successfully. (Took ${(System.nanoTime() - nanoStart) / 1_000_000.0} ms)
Building object file ${objOut.name}...""")
rhmodding.tickompiler.objectify.objectify(objOut, outputBinFiles.map { it.second }, tempoFiles)
println("Succeeded.")
}
} else {
println("""
+======================+
| COMPILATION COMPLETE |
+======================+
$numSuccessful / ${dirs.input.size} compiled successfully in ${(System.nanoTime() - nanoStart) / 1_000_000.0} ms""")
}
}
}
}
| mit | 71d1c15843536783d4d13fcb76bb39b9 | 43.417266 | 167 | 0.586978 | 4.617801 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/creator/MinecraftModuleBuilder.kt | 1 | 3908 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.creator
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.platform.MinecraftModuleType
import com.intellij.ide.util.projectWizard.JavaModuleBuilder
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.JavaModuleType
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.project.DumbAwareRunnable
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.SdkTypeId
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.ui.configuration.ModulesProvider
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
class MinecraftModuleBuilder : JavaModuleBuilder() {
private val creator = MinecraftProjectCreator()
override fun getPresentableName() = MinecraftModuleType.NAME
override fun getNodeIcon() = PlatformAssets.MINECRAFT_ICON
override fun getGroupName() = MinecraftModuleType.NAME
override fun getWeight() = JavaModuleBuilder.BUILD_SYSTEM_WEIGHT - 1
override fun getBuilderId() = "MINECRAFT_MODULE"
override fun isSuitableSdkType(sdk: SdkTypeId?) = sdk === JavaSdk.getInstance()
override fun setupRootModel(modifiableRootModel: ModifiableRootModel) {
val project = modifiableRootModel.project
val root = createAndGetRoot() ?: return
modifiableRootModel.addContentEntry(root)
if (moduleJdk != null) {
modifiableRootModel.sdk = moduleJdk
}
val r = DumbAwareRunnable {
creator.create(root, modifiableRootModel.module)
}
if (project.isDisposed) {
return
}
if (
ApplicationManager.getApplication().isUnitTestMode ||
ApplicationManager.getApplication().isHeadlessEnvironment
) {
r.run()
return
}
if (!project.isInitialized) {
StartupManager.getInstance(project).registerPostStartupActivity(r)
return
}
DumbService.getInstance(project).runWhenSmart(r)
}
private fun createAndGetRoot(): VirtualFile? {
val temp = contentEntryPath ?: return null
val path = FileUtil.toSystemIndependentName(temp)
return try {
Files.createDirectories(Paths.get(path))
LocalFileSystem.getInstance().refreshAndFindFileByPath(path)
} catch (e: IOException) {
null
}
}
override fun getModuleType(): ModuleType<*> = JavaModuleType.getModuleType()
override fun getParentGroup() = MinecraftModuleType.NAME
override fun createWizardSteps(
wizardContext: WizardContext,
modulesProvider: ModulesProvider
): Array<ModuleWizardStep> {
return arrayOf(
BuildSystemWizardStep(creator),
BukkitProjectSettingsWizard(creator),
SpongeProjectSettingsWizard(creator),
ForgeProjectSettingsWizard(creator),
LiteLoaderProjectSettingsWizard(creator),
BungeeCordProjectSettingsWizard(creator)
)
}
override fun getCustomOptionsStep(context: WizardContext?, parentDisposable: Disposable?) =
ProjectChooserWizardStep(creator)
override fun validate(current: Project?, dest: Project?) = true
}
| mit | d037130663661c836a51f43ed8b14f92 | 32.982609 | 95 | 0.72262 | 5.183024 | false | false | false | false |
google/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/templates/compose/ComposeJvmDesktopTemplate.kt | 2 | 4532 | // 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.templates.compose
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.Versions
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.*
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.GradleImportIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.irsList
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.moduleType
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleType
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind
import org.jetbrains.kotlin.tools.projectWizard.plugins.pomIR
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.*
import org.jetbrains.kotlin.tools.projectWizard.settings.javaPackage
import org.jetbrains.kotlin.tools.projectWizard.templates.*
class ComposeJvmDesktopTemplate : Template() {
@NonNls
override val id: String = "composeDesktopTemplate"
override val title: String = KotlinNewProjectWizardBundle.message("module.template.compose.desktop.title")
override val description: String = KotlinNewProjectWizardBundle.message("module.template.compose.desktop.description")
override fun isApplicableTo(module: Module, projectKind: ProjectKind, reader: Reader): Boolean =
module.configurator.moduleType == ModuleType.jvm && projectKind == ProjectKind.COMPOSE
&& (module.kind == ModuleKind.singlePlatformJvm || module.kind == ModuleKind.target)
override fun Writer.getIrsToAddToBuildFile(
module: ModuleIR
) = irsList {
+RepositoryIR(Repositories.JETBRAINS_COMPOSE_DEV)
+RepositoryIR(DefaultRepository.GOOGLE)
+GradleOnlyPluginByNameIR("org.jetbrains.compose", version = Versions.JETBRAINS_COMPOSE)
+GradleImportIR("org.jetbrains.compose.desktop.application.dsl.TargetFormat")
"compose.desktop" {
"application" {
"mainClass" assign const("MainKt")
"nativeDistributions" {
"targetFormats"(raw("TargetFormat.Dmg"), raw("TargetFormat.Msi"), raw("TargetFormat.Deb"))
"packageName" assign const(module.name)
"packageVersion" assign const("1.0.0")
}
}
}
+GradleImportIR("org.jetbrains.compose.compose")
}
override fun Writer.getRequiredLibraries(module: ModuleIR): List<DependencyIR> = listOf(
CustomGradleDependencyDependencyIR("compose.desktop.currentOs", dependencyType = DependencyType.MAIN, DependencyKind.implementation)
)
override fun Writer.runArbitratyTask(module: ModuleIR): TaskResult<Unit> =
BuildSystemPlugin.pluginRepositoreis.addValues(Repositories.JETBRAINS_COMPOSE_DEV, DefaultRepository.GOOGLE)
override fun Reader.getFileTemplates(module: ModuleIR) = buildList<FileTemplateDescriptorWithPath> {
val dependsOnMppModule: Module? =
module.originalModule.dependencies.map { moduleByReference(it) }.firstOrNull { it.template is ComposeMppModuleTemplate }
if (dependsOnMppModule == null) {
+(FileTemplateDescriptor("$id/main.kt", "Main.kt".asPath()) asSrcOf SourcesetType.main)
} else {
val javaPackage = dependsOnMppModule.javaPackage(pomIR()).asCodePackage()
+(FileTemplateDescriptor("composeMpp/main.kt.vm", "Main.kt".asPath())
asSrcOf SourcesetType.main
withSettings ("sharedPackage" to javaPackage)
)
}
}
}
class ComposeCommonDesktopTemplate : Template() {
@NonNls
override val id: String = "composeCommonDesktopTemplate"
override val title: String = KotlinNewProjectWizardBundle.message("module.template.compose.desktop.title")
override val description: String = KotlinNewProjectWizardBundle.message("module.template.compose.desktop.description")
override fun isApplicableTo(module: Module, projectKind: ProjectKind, reader: Reader): Boolean =
module.configurator.moduleType == ModuleType.jvm && projectKind == ProjectKind.COMPOSE
} | apache-2.0 | a59185cd6d2d92c0378ff2af5062c1d6 | 51.103448 | 158 | 0.740512 | 4.800847 | false | false | false | false |
google/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/util/RightTextCellRenderer.kt | 10 | 2256 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.util
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.UIUtil.getListSelectionForeground
import java.awt.BorderLayout
import java.awt.Component
import javax.swing.JList
import javax.swing.JPanel
import javax.swing.ListCellRenderer
/**
* This renderer adds grey text aligned to the right of whatever component returned by [baseRenderer]
*
* @see com.intellij.ide.util.PsiElementModuleRenderer
*/
class RightTextCellRenderer<T>(
private val baseRenderer: ListCellRenderer<in T>,
private val text: (T) -> String?
) : ListCellRenderer<T> {
private val label = JBLabel().apply {
isOpaque = true
border = JBUI.Borders.emptyRight(UIUtil.getListCellHPadding())
}
private val spacer = JPanel().apply {
border = JBUI.Borders.empty(0, 2)
}
private val layout = BorderLayout()
private val rendererComponent = JPanel(layout).apply {
add(spacer, BorderLayout.CENTER)
add(label, BorderLayout.EAST)
}
override fun getListCellRendererComponent(list: JList<out T>?,
value: T?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
val originalComponent = baseRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
if (value == null || list == null || originalComponent == null) return originalComponent
val text = text(value) ?: return originalComponent
val bg = if (isSelected) UIUtil.getListSelectionBackground(true) else originalComponent.background
label.text = text
label.background = bg
label.foreground = if (isSelected) getListSelectionForeground(true) else UIUtil.getInactiveTextColor()
spacer.background = bg
layout.getLayoutComponent(BorderLayout.WEST)?.let(rendererComponent::remove)
rendererComponent.add(originalComponent, BorderLayout.WEST)
return rendererComponent
}
}
| apache-2.0 | d019f445496b3fdddfaf13c72ebef943 | 34.809524 | 140 | 0.700798 | 4.709812 | false | false | false | false |
RuneSuite/client | api/src/main/java/org/runestar/client/api/game/SceneElement.kt | 1 | 6641 | package org.runestar.client.api.game
import org.runestar.client.api.game.live.Scene
import org.runestar.client.api.util.cascadingListOf
import org.runestar.client.raw.access.XWall
import org.runestar.client.raw.access.XEntity
import org.runestar.client.raw.access.XFloorDecoration
import org.runestar.client.raw.access.XModel
import org.runestar.client.raw.access.XNode
import org.runestar.client.raw.access.XObj
import org.runestar.client.raw.access.XObjStack
import org.runestar.client.raw.access.XScenery
import org.runestar.client.raw.access.XWallDecoration
import org.runestar.client.raw.base.Accessor
abstract class SceneElement(accessor: Accessor) : Wrapper(accessor) {
private companion object {
fun xModelFromEntity(e: XEntity?): XModel? {
return e as? XModel ?: e?.model
}
inline fun makeModel(e: XEntity?, f: (XModel) -> Model): Model? {
return xModelFromEntity(e)?.let(f)
}
}
abstract val plane: Int
abstract val tag: SceneElementTag
val x: Int get() = tag.x
val y: Int get() = tag.y
val location: SceneTile get() = SceneTile(x, y, plane)
val isLoc: Boolean get() = tag.kind == SceneElementKind.LOC
// todo
// val baseOrientation: Angle get() = Angle.of(((flags shr 6) and 3) * 512)
abstract val dynamicOrientation: Angle
// val orientation: Angle get() = baseOrientation + dynamicOrientation
abstract val modelPosition: Position
protected abstract val entity: XEntity?
val model: Model? get() = makeModel(entity) { Model(it, modelPosition, dynamicOrientation) }
open val models: List<Model> get() = cascadingListOf(model)
abstract class TwoModels(
accessor: Accessor
) : SceneElement(accessor) {
protected abstract val entity2: XEntity?
abstract val modelPosition2: Position
val model2: Model? get() = makeModel(entity2) { Model(it, modelPosition2, dynamicOrientation) }
override val models: List<Model> get() = cascadingListOf(model, model2)
}
abstract class ThreeModels(
accessor: Accessor
) : TwoModels(accessor) {
protected abstract val entity3: XEntity?
abstract val modelPosition3: Position
val model3: Model? get() = makeModel(entity3) { Model(it, modelPosition3, dynamicOrientation) }
override val models: List<Model> get() = cascadingListOf(model, model2, model3)
}
class Scenery(
override val accessor: XScenery
) : SceneElement(accessor) {
override val dynamicOrientation: Angle get() = Angle.of(accessor.orientation)
override val modelPosition: Position get() = Position(accessor.centerX, accessor.centerY, heightOffset, plane)
val heightOffset: Int get() = Scene.getTileHeight(accessor.centerX, accessor.centerY, plane) - accessor.height
override val entity: XEntity? get() = accessor.entity
override val plane: Int get() = accessor.plane
override val tag get() = SceneElementTag(accessor.tag)
override fun toString(): String = "SceneElement.Scenery($tag)"
}
class FloorDecoration(
override val accessor: XFloorDecoration,
override val plane: Int
) : SceneElement(accessor) {
override val dynamicOrientation: Angle get() = Angle.ZERO
override val modelPosition: Position get() = Position.centerOfTile(x, y, 0, plane)
override val entity: XEntity? get() = accessor.entity
override val tag get() = SceneElementTag(accessor.tag)
override fun toString(): String = "SceneElement.FloorDecoration($tag)"
}
class WallDecoration(
override val accessor: XWallDecoration,
override val plane: Int
) : TwoModels(accessor) {
override val dynamicOrientation: Angle get() = Angle.ZERO
override val modelPosition: Position get() = Position(
LocalValue(x, LocalValue.MID_SUB).value + accessor.xOffset,
LocalValue(y, LocalValue.MID_SUB).value + accessor.yOffset,
0,
plane
)
override val entity: XEntity? get() = accessor.entity1
override val modelPosition2: Position get() = Position.centerOfTile(x, y, 0, plane)
override val entity2: XEntity? get() = accessor.entity2
override val tag get() = SceneElementTag(accessor.tag)
override fun toString(): String = "SceneElement.WallDecoration($tag)"
}
class Wall(
override val accessor: XWall,
override val plane: Int
) : TwoModels(accessor) {
override val dynamicOrientation: Angle get() = Angle.ZERO
override val modelPosition: Position get() = Position.centerOfTile(x, y, 0, plane)
override val modelPosition2: Position get() = modelPosition
override val entity: XEntity? get() = accessor.entity1
override val entity2: XEntity? get() = accessor.entity2
override val tag get() = SceneElementTag(accessor.tag)
override fun toString(): String = "SceneElement.Wall($tag)"
}
class ObjStack(
override val accessor: XObjStack,
override val plane: Int
) : ThreeModels(accessor), Iterable<GroundItem> {
override val tag get() = SceneElementTag(accessor.tag)
override val dynamicOrientation: Angle get() = Angle.ZERO
override val entity: XEntity? get() = accessor.first
override val modelPosition: Position get() = Position.centerOfTile(x, y, accessor.height, plane)
override val entity2: XEntity? get() = accessor.second
override val modelPosition2: Position get() = modelPosition
override val entity3: XEntity? get() = accessor.third
override val modelPosition3: Position get() = modelPosition
val first: GroundItem? get() = accessor.first?.let { GroundItem(it as XObj, modelPosition) }
val second: GroundItem? get() = accessor.second?.let { GroundItem(it as XObj, modelPosition) }
val third: GroundItem? get() = accessor.third?.let { GroundItem(it as XObj, modelPosition) }
override fun iterator(): Iterator<GroundItem> = object : AbstractIterator<GroundItem>() {
private val position = modelPosition
private var cur: XNode? = accessor.first
override fun computeNext() {
val gi = cur as? XObj ?: return done()
setNext(GroundItem(gi, position))
cur = gi.previous
}
}
override fun toString(): String = "SceneElement.ObjStack($tag)"
}
} | mit | acd87a9fde6fcce61306bc5245f88ff5 | 31.558824 | 118 | 0.661346 | 4.238034 | false | false | false | false |
Atsky/haskell-idea-plugin | generator/src/org/jetbrains/generator/Main.kt | 1 | 1946 | package org.jetbrains.generator
import java.io.FileReader
import java.util.ArrayList
import org.jetbrains.generator.grammar.Grammar
import org.jetbrains.generator.grammar.Rule
import org.jetbrains.generator.grammar.Variant
import java.util.HashMap
import org.jetbrains.generator.grammar.NonFinalVariant
import org.jetbrains.generator.grammar.RuleRef
/**
* Created by atsky on 11/7/14.
*/
private fun getTokens(lexer : GrammarLexer) : List<Token> {
val list = ArrayList<Token>()
while (true) {
val tokenType = lexer.yylex()
if (tokenType == null) {
break
}
if (tokenType == TokenType.BLOCK_COMMENT) {
continue
}
if (tokenType == TokenType.EOL_COMMENT) {
continue
}
list.add(Token(tokenType, lexer.yytext()))
}
return list
}
fun main(args : Array<String>) {
val lexer = GrammarLexer(FileReader("./plugin/haskell.grm"))
val grammarParser = GrammarParser(getTokens(lexer))
val grammar = grammarParser.parseGrammar()!!
val generator = ParserGenerator(mergeGrammar(grammar))
generator.generate()
}
fun mergeGrammar(grammar: Grammar): Grammar {
val newRules = ArrayList<Rule>()
for (rule in grammar.rules) {
newRules.add(Rule(rule.name, merge(rule.variants)))
}
return Grammar(grammar.tokens, newRules)
}
fun merge(variants: List<Variant>): List<Variant> {
val result = ArrayList<Variant>()
val map = HashMap<RuleRef, ArrayList<Variant>>()
for (variant in variants) {
if (variant is NonFinalVariant) {
val name = variant.atom
if (!map.contains(name)) {
map[name] = ArrayList<Variant>()
}
map[name]!!.addAll(variant.next)
} else {
result.add(variant)
}
}
for ((name, vars) in map) {
result.add(NonFinalVariant(name, merge(vars)))
}
return result
} | apache-2.0 | a735ae8729c1d59191251c9dd6b6df6b | 26.422535 | 64 | 0.636177 | 4.028986 | false | false | false | false |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/contentprovider/RSSContentProvider.kt | 1 | 2935 | package com.nononsenseapps.feeder.contentprovider
import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import com.nononsenseapps.feeder.FeederApplication
import com.nononsenseapps.feeder.db.room.FeedDao
import com.nononsenseapps.feeder.db.room.FeedItemDao
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.instance
class RSSContentProvider : ContentProvider(), DIAware {
override val di: DI by lazy {
val application = context!!.applicationContext as FeederApplication
application.di
}
private val feedDao: FeedDao by instance()
private val feedItemDao: FeedItemDao by instance()
private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {
addURI(AUTHORITY, RssContentProviderContract.feedsUriPathList, URI_FEED_LIST)
addURI(
AUTHORITY,
RssContentProviderContract.articlesUriPathList,
URI_ARTICLE_LIST
)
addURI(
AUTHORITY,
RssContentProviderContract.articlesUriPathItem,
URI_ARTICLE_IN_FEED_LIST
)
}
override fun onCreate(): Boolean {
return true
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
throw UnsupportedOperationException("Not implemented")
}
override fun getType(uri: Uri): String? = when (uriMatcher.match(uri)) {
URI_FEED_LIST -> RssContentProviderContract.feedsMimeTypeList
URI_ARTICLE_LIST -> RssContentProviderContract.articlesMimeTypeList
URI_ARTICLE_IN_FEED_LIST -> RssContentProviderContract.articlesMimeTypeItem
else -> null
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
throw UnsupportedOperationException("Not implemented")
}
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<out String>?
): Int {
throw UnsupportedOperationException("Not implemented")
}
override fun query(
uri: Uri,
projection: Array<out String>?,
selection: String?,
selectionArgs: Array<out String>?,
sortOrder: String?
): Cursor? {
return when (uriMatcher.match(uri)) {
URI_FEED_LIST -> feedDao.loadFeedsForContentProvider()
URI_ARTICLE_LIST -> feedItemDao.loadFeedItemsForContentProvider()
URI_ARTICLE_IN_FEED_LIST -> feedItemDao.loadFeedItemsInFeedForContentProvider(uri.lastPathSegment!!.toLong())
else -> null
}
}
companion object {
private const val AUTHORITY = "com.nononsenseapps.feeder.rssprovider"
private const val URI_FEED_LIST = 1
private const val URI_ARTICLE_LIST = 2
private const val URI_ARTICLE_IN_FEED_LIST = 3
}
}
| gpl-3.0 | e377e9f1219687e65afe2d67e955f168 | 32.735632 | 121 | 0.682112 | 4.795752 | false | false | false | false |
customerly/Customerly-Android-SDK | customerly-android-sdk/src/main/java/io/customerly/utils/ui/RvDividerDecoration.kt | 1 | 6903 | package io.customerly.utils.ui
/*
* Copyright (C) 2017 Customerly
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import io.customerly.R
import io.customerly.sxdependencies.SXContextCompat
import io.customerly.sxdependencies.SXRecyclerView
import io.customerly.sxdependencies.SXRecyclerViewItemDecoration
import io.customerly.sxdependencies.SXRecyclerViewLayoutParams
import io.customerly.sxdependencies.annotations.SXColorInt
import io.customerly.sxdependencies.annotations.SXColorRes
import io.customerly.sxdependencies.annotations.SXIntDef
import io.customerly.utils.ggkext.dp2px
import kotlin.math.max
/**
* Created by Gianni on 24/06/15.
* Project: Customerly Android SDK
*/
//internal const val RVDIVIDER_H_LEFT = 0
//internal const val RVDIVIDER_H_CENTER = 1
//internal const val RVDIVIDER_H_RIGHT = 2
//internal const val RVDIVIDER_H_BOTH = 3
//
//@SXIntDef(RVDIVIDER_H_LEFT, RVDIVIDER_H_CENTER, RVDIVIDER_H_RIGHT, RVDIVIDER_H_BOTH)
//@Retention(AnnotationRetention.SOURCE)
//internal annotation class RvDividerHorizontal
internal const val RVDIVIDER_V_TOP = 0
internal const val RVDIVIDER_V_CENTER = 1
internal const val RVDIVIDER_V_BOTTOM = 2
internal const val RVDIVIDER_V_BOTH = 3
@SXIntDef(RVDIVIDER_V_TOP, RVDIVIDER_V_CENTER, RVDIVIDER_V_BOTTOM, RVDIVIDER_V_BOTH)
@Retention(AnnotationRetention.SOURCE)
internal annotation class RvDividerVertical
private val dp1 = max(1f, 1f.dp2px)
@SXColorRes
private val DEFAULT_COLOR_RES = R.color.io_customerly__grey_cc
internal sealed class RvDividerDecoration(@SXColorInt colorInt: Int) : SXRecyclerViewItemDecoration() {
protected val paint : Paint = Paint().apply {
color = colorInt
style = Paint.Style.FILL
}
internal class Vertical(
@SXColorInt colorInt: Int,
@RvDividerVertical private val where : Int = RVDIVIDER_V_CENTER
) : RvDividerDecoration(colorInt = colorInt) {
internal constructor(
context: Context,
@SXColorRes colorRes: Int = DEFAULT_COLOR_RES,
@RvDividerVertical where : Int = RVDIVIDER_V_CENTER
): this(colorInt = SXContextCompat.getColor(context, colorRes), where = where)
override fun onDrawOver(c: Canvas, parent: SXRecyclerView) {
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
(0 until if (this.where == RVDIVIDER_V_CENTER) {
parent.childCount - 1
} else {
parent.childCount
})
.asSequence()
.map { parent.getChildAt(it) }
.forEach { child ->
when (this.where) {
RVDIVIDER_V_BOTTOM, RVDIVIDER_V_CENTER -> {
val top = child.bottom + (child.layoutParams as SXRecyclerViewLayoutParams).bottomMargin
c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), top + dp1, this.paint)
}
RVDIVIDER_V_BOTH -> {
var top = child.bottom + (child.layoutParams as SXRecyclerViewLayoutParams).bottomMargin
c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), top + dp1, this.paint)
top = child.top - (child.layoutParams as SXRecyclerViewLayoutParams).topMargin
c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), top + dp1, this.paint)
}
/*RVDIVIDER_V_TOP,*/else -> {
val top = child.top - (child.layoutParams as SXRecyclerViewLayoutParams).topMargin
c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), top + dp1, this.paint)
}
}
}
}
}
// internal class Horizontal(
// @SXColorInt colorInt: Int,
// @RvDividerHorizontal private val where : Int = RVDIVIDER_H_CENTER
// ) : RvDividerDecoration(colorInt = colorInt) {
//
// internal constructor(
// context: Context,
// @SXColorRes colorRes: Int = DEFAULT_COLOR_RES,
// @RvDividerHorizontal where : Int = RVDIVIDER_H_CENTER
// ): this(colorInt = ContextCompat.getColor(context, colorRes), where = where)
//
// override fun onDrawOver(c: Canvas, parent: RecyclerView) {
// val top = parent.paddingTop
// val bottom = parent.height - parent.paddingBottom
//
// (0 until if (this.where == RVDIVIDER_H_CENTER) {
// parent.childCount - 1
// } else {
// parent.childCount
// })
// .asSequence()
// .map { parent.getChildAt(it) }
// .forEach { child ->
// when (this.where) {
// RVDIVIDER_H_RIGHT, RVDIVIDER_H_CENTER -> {
// val left = child.right + (child.layoutParams as SXRecyclerViewLayoutParams).rightMargin
// c.drawRect(left.toFloat(), top.toFloat(), left + dp1, bottom.toFloat(), this.paint)
// }
// RVDIVIDER_H_BOTH -> {
// var left = child.right + (child.layoutParams as SXRecyclerViewLayoutParams).rightMargin
// c.drawRect(left.toFloat(), top.toFloat(), left + dp1, bottom.toFloat(), this.paint)
// left = child.left - (child.layoutParams as SXRecyclerViewLayoutParams).leftMargin
// c.drawRect(left.toFloat(), top.toFloat(), left + dp1, bottom.toFloat(), this.paint)
// }
// /*RVDIVIDER_H_LEFT,*/else -> {
// val left = child.left - (child.layoutParams as SXRecyclerViewLayoutParams).leftMargin
// c.drawRect(left.toFloat(), top.toFloat(), left + dp1, bottom.toFloat(), this.paint)
// }
// }
// }
// }
// }
} | apache-2.0 | 51b1f1fc719901ebcafa31a1e7fb846a | 44.721854 | 121 | 0.584384 | 4.482468 | false | false | false | false |
allotria/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/left/PackagesSmartItemPopup.kt | 1 | 5909 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.left
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.ide.CopyPasteManager
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.looksLikeGradleVariable
import com.jetbrains.packagesearch.intellij.plugin.ui.RiderUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.InfoLink.CODE_OF_CONDUCT
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.InfoLink.GITHUB
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.InfoLink.README
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageOperationUtility
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageSearchDependency
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageSearchToolWindowModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.asList
import icons.PackageSearchIcons
import java.awt.datatransfer.StringSelection
import javax.swing.JPopupMenu
class PackagesSmartItemPopup(viewModel: PackageSearchToolWindowModel, private val meta: PackageSearchDependency) :
JPopupMenu() {
private val packageOperationUtility = PackageOperationUtility(viewModel)
init {
// Build actions
val selectedDependency = viewModel.searchResults.value[viewModel.selectedPackage.value]
val selectedDependencyRemoteInfo = selectedDependency?.remoteInfo
val selectedProjectModule = viewModel.selectedProjectModule.value
val currentSelectedRemoteRepository = viewModel.selectedRemoteRepository.value
val projectModules = if (selectedProjectModule != null) {
// Selected module
listOf(selectedProjectModule)
} else {
// All modules
viewModel.projectModules.value
}.filter {
// Make sure the dependency is supported by the available project module(s)
if (selectedDependencyRemoteInfo != null) {
it.moduleType.providesSupportFor(selectedDependencyRemoteInfo)
} else {
true
}
}
val packageOperationTargets = if (selectedDependency != null) {
val preparedTargets = viewModel.preparePackageOperationTargetsFor(projectModules, selectedDependency, currentSelectedRemoteRepository)
val installables = preparedTargets.filter { it.version.isBlank() }
val updateables = preparedTargets.filter { it.version.isNotBlank() && !looksLikeGradleVariable(it.version) }
if (updateables.isNotEmpty()) {
updateables
} else {
installables
}
} else {
emptyList()
}
// Build menu entries for actions
val operationTargetVersion = meta.getLatestAvailableVersion(
viewModel.selectedOnlyStable.value, currentSelectedRemoteRepository.asList()) ?: ""
val operations = listOfNotNull(
packageOperationUtility.getApplyOperation(packageOperationTargets, operationTargetVersion),
packageOperationUtility.getRemoveOperation(packageOperationTargets)
)
operations.forEach { operation ->
val projectsMessage = when (packageOperationTargets.size) {
1 -> packageOperationTargets.first().projectModuleTitle
else -> PackageSearchBundle.message("packagesearch.ui.toolwindow.selectedModules").toLowerCase()
}
@Suppress("HardCodedStringLiteral") // Formatting into a non-locale-specific format
val message = operation.htmlDescription.replace("</html>", " - <b>$projectsMessage</b></html>")
add(RiderUI.menuItem(message, operation.icon) {
packageOperationUtility.doOperation(operation, packageOperationTargets, operationTargetVersion)
})
}
if (operations.isNotEmpty()) {
addSeparator()
}
// All links on package
val links = meta.getAllLinks()
// Encourage using Package Search website!
links.remove(README)
links.remove(CODE_OF_CONDUCT)
add(RiderUI.menuItem(PackageSearchBundle.message("packagesearch.ui.popup.show.online"), PackageSearchIcons.Artifact) {
BrowserUtil.browse(PackageSearchBundle.message("packagesearch.wellknown.url.jb.packagesearch.details", meta.identifier))
})
addSeparator()
meta.remoteInfo?.gitHub?.let {
val gitHubLink = links.remove(GITHUB) ?: return@let
add(RiderUI.menuItem(PackageSearchBundle.message("packagesearch.ui.popup.open.github"), AllIcons.Vcs.Vendors.Github) {
BrowserUtil.browse(gitHubLink)
})
}
meta.remoteInfo?.gitHub?.communityProfile?.files?.license?.let {
val licenseUrl = it.htmlUrl ?: it.url
val licenseName = it.name ?: PackageSearchBundle.message("packagesearch.terminology.license.unknown")
if (!licenseUrl.isNullOrEmpty()) {
add(RiderUI.menuItem(PackageSearchBundle.message("packagesearch.ui.popup.open.license", licenseName), null) {
BrowserUtil.browse(licenseUrl)
})
}
}
links.forEach {
add(RiderUI.menuItem(PackageSearchBundle.message("packagesearch.ui.popup.browse.thing", it.key.displayName), null) {
BrowserUtil.browse(it.value)
})
}
// Other entries
addSeparator()
add(RiderUI.menuItem(PackageSearchBundle.message("packagesearch.ui.popup.copy.identifier"), null) {
CopyPasteManager.getInstance().setContents(StringSelection(meta.identifier))
})
}
}
| apache-2.0 | 7f89a174d31210176b3c76be509a671c | 47.434426 | 146 | 0.694872 | 5.210758 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/fileTypes/UpdateComponentWatcher.kt | 2 | 5336 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.fileTypes
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PermanentInstallationID
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.editor.ex.EditorEventMulticasterEx
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.FocusChangeListener
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ObjectUtils
import com.intellij.util.io.HttpRequests
import org.jdom.JDOMException
import java.io.IOException
import java.net.URLEncoder
import java.net.UnknownHostException
import java.util.*
import java.util.concurrent.TimeUnit
private val EP_NAME = ExtensionPointName<FileTypeStatisticProvider>("com.intellij.fileTypeStatisticProvider")
@Service
private class UpdateComponentWatcher : Disposable {
init {
// rely on fact that service will be initialized only once
// TODO: Use message bus once it will be provided by platform
val multicaster = EditorFactory.getInstance().eventMulticaster
if (multicaster is EditorEventMulticasterEx) {
multicaster.addFocusChangeListener(object : FocusChangeListener {
override fun focusGained(editor: Editor) {
scheduleUpdate(editor)
}
}, this)
}
}
fun scheduleUpdate(editor: Editor) {
val fileType = (editor as EditorEx).virtualFile?.fileType ?: return
// TODO: `accept` can be slow (CloudFormationFileTypeStatisticProvider), we should not call it synchronously
val ep = EP_NAME.findFirstSafe { it.accept(editor, fileType) } ?: return
// TODO: Use PluginAware EP
val plugin = EP_NAME.computeIfAbsent(ep, UpdateComponentWatcher::class.java) {
Optional.ofNullable(PluginManagerCore.getPlugin(PluginId.getId(ep.pluginId)))
}
val pluginIdString = ep.pluginId
if (!plugin.isPresent) {
LOG.error("Unknown plugin id: $pluginIdString is reported by ${ep::class.java}")
return
}
val pluginVersion = plugin.get().version
if (checkUpdateRequired(pluginIdString, pluginVersion)) {
ApplicationManager.getApplication().executeOnPooledThread {
update(pluginIdString, pluginVersion)
}
}
}
override fun dispose() {
}
}
private class UpdateComponentEditorListener : EditorFactoryListener {
override fun editorCreated(event: EditorFactoryEvent) {
if (!ApplicationManager.getApplication().isUnitTestMode) {
service<UpdateComponentWatcher>().scheduleUpdate(event.editor)
}
}
}
private val lock = ObjectUtils.sentinel("updating_monitor")
private val LOG = logger<UpdateComponentWatcher>()
private fun update(pluginIdString: String, pluginVersion: String) {
val url = getUpdateUrl(pluginIdString, pluginVersion)
sendRequest(url)
}
private fun checkUpdateRequired(pluginIdString: String, pluginVersion: String): Boolean {
synchronized(lock) {
val lastVersionKey = "$pluginIdString.LAST_VERSION"
val lastUpdateKey = "$pluginIdString.LAST_UPDATE"
val properties = PropertiesComponent.getInstance()
val lastPluginVersion = properties.getValue(lastVersionKey)
val lastUpdate = properties.getLong(lastUpdateKey, 0L)
val shouldUpdate = lastUpdate == 0L
|| System.currentTimeMillis() - lastUpdate > TimeUnit.DAYS.toMillis(1)
|| lastPluginVersion == null
|| lastPluginVersion != pluginVersion
if (!shouldUpdate) return false
properties.setValue(lastUpdateKey, System.currentTimeMillis().toString())
properties.setValue(lastVersionKey, pluginVersion)
return true
}
}
private fun sendRequest(url: String) {
try {
HttpRequests.request(url).connect {
try {
JDOMUtil.load(it.reader)
}
catch (e: JDOMException) {
LOG.warn(e)
}
LOG.info("updated: $url")
}
}
catch (ignored: UnknownHostException) {
// No internet connections, no need to log anything
}
catch (e: IOException) {
LOG.warn(e)
}
}
private fun getUpdateUrl(pluginIdString: String, pluginVersion: String): String {
val applicationInfo = ApplicationInfoEx.getInstanceEx()
val buildNumber = applicationInfo.build.asString()
val os = URLEncoder.encode("${SystemInfo.OS_NAME} ${SystemInfo.OS_VERSION}", Charsets.UTF_8.name())
val uid = PermanentInstallationID.get()
val baseUrl = "https://plugins.jetbrains.com/plugins/list"
return "$baseUrl?pluginId=$pluginIdString&build=$buildNumber&pluginVersion=$pluginVersion&os=$os&uuid=$uid"
} | apache-2.0 | 93918c129ed4f87047515e3fdb6f9013 | 36.321678 | 140 | 0.753186 | 4.584192 | false | false | false | false |
deadpixelsociety/roto-ld34 | core/src/com/thedeadpixelsociety/ld34/scripts/WallScript.kt | 1 | 2162 | package com.thedeadpixelsociety.ld34.scripts
import com.badlogic.ashley.core.Engine
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.math.Vector2
import com.thedeadpixelsociety.ld34.Events
import com.thedeadpixelsociety.ld34.TimeKeeper
import com.thedeadpixelsociety.ld34.components.Box2DComponent
import com.thedeadpixelsociety.ld34.components.TransformComponent
import com.thedeadpixelsociety.ld34.systems.TagSystem
class WallScript() : Script {
companion object {
const val HIT_DELAY = .5f
}
private var hit = false
private var lastHit = 0f
private val proj = Vector2()
override fun act(engine: Engine, entity: Entity) {
val box2d = entity.getComponent(Box2DComponent::class.java)
if (box2d != null && box2d.collision) {
val player = engine.getSystem(TagSystem::class.java)["player"]
if (!hit && player != null && box2d.collided == player && (TimeKeeper.totalTime - lastHit) > HIT_DELAY) {
hit = true
lastHit = TimeKeeper.totalTime
Events.wall(entity, player)
}
}
// Box2d says we're longer colliding, but we don't want to end the 'hit' until we're at least a certain
// distance apart to eliminate repeat events
if (hit && box2d.collision == false) {
val player = engine.getSystem(TagSystem::class.java)["player"]
if (player != null) {
val transform = entity.getComponent(TransformComponent::class.java)
val playerTransform = player.getComponent(TransformComponent::class.java)
val a = playerTransform.position
val b = box2d.lastNormal
val dot = a.dot(b)
proj.set(dot * b.x, dot * b.y)
if (proj.x != 0f) {
proj.sub(transform.position.x, 0f)
} else if (proj.y != 0f) {
proj.sub(0f, transform.position.y)
}
val dist = proj.len()
if (dist > 17.5f) {
hit = false
}
}
}
}
}
| mit | ff639cb32bf5d43549108cd97f575388 | 34.442623 | 117 | 0.589269 | 4.149712 | false | false | false | false |
0xpr03/VocableTrainer-Android | app/src/main/java/vocabletrainer/heinecke/aron/vocabletrainer/editor/EditorActivity.kt | 1 | 17646 | package vocabletrainer.heinecke.aron.vocabletrainer.editor
import android.content.DialogInterface
import android.database.SQLException
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.AdapterView.OnItemLongClickListener
import android.widget.ListView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import org.acra.ACRA
import vocabletrainer.heinecke.aron.vocabletrainer.R
import vocabletrainer.heinecke.aron.vocabletrainer.activity.MainActivity
import vocabletrainer.heinecke.aron.vocabletrainer.dialog.ItemPickerDialog
import vocabletrainer.heinecke.aron.vocabletrainer.dialog.ItemPickerDialog.ItemPickerHandler
import vocabletrainer.heinecke.aron.vocabletrainer.editor.VEntryEditorDialog.EditorDialogDataProvider
import vocabletrainer.heinecke.aron.vocabletrainer.editor.VListEditorDialog.ListEditorDataProvider
import vocabletrainer.heinecke.aron.vocabletrainer.lib.Adapter.EntryListAdapter
import vocabletrainer.heinecke.aron.vocabletrainer.lib.Comparator.GenEntryComparator
import vocabletrainer.heinecke.aron.vocabletrainer.lib.Database
import vocabletrainer.heinecke.aron.vocabletrainer.lib.Storage.VEntry
import vocabletrainer.heinecke.aron.vocabletrainer.lib.Storage.VList
import vocabletrainer.heinecke.aron.vocabletrainer.lib.Storage.VList.Companion.isIDValid
import java.util.*
/**
* List editor activity
*/
class EditorActivity : AppCompatActivity(), EditorDialogDataProvider, ListEditorDataProvider,
ItemPickerHandler {
private var list: VList? = null
private var entries: ArrayList<VEntry>? = null
private var adapter: EntryListAdapter? = null
private var listView: ListView? = null
private lateinit var db: Database
private var sortSetting = 0
private var cComp: GenEntryComparator? = null
private var compA: GenEntryComparator? = null
private var compB: GenEntryComparator? = null
private var compTip: GenEntryComparator? = null
private var sortingDialog: ItemPickerDialog? = null
private var editorDialog: VEntryEditorDialog? = null
private var listEditorDialog: VListEditorDialog? = null
// current edit
private var editPosition: Int =
(Database.MIN_ID_TRESHOLD - 1).toInt() // store position for viewport change, shared object
private var editorEntry: VEntry? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate")
entries = ArrayList()
setContentView(R.layout.activity_editor)
db = Database(baseContext)
val ab = supportActionBar
ab?.setDisplayHomeAsUpEnabled(true)
clearEdit()
compA = GenEntryComparator(
arrayOf(
GenEntryComparator.retA, GenEntryComparator.retB,
GenEntryComparator.retTip
), Database.ID_RESERVED_SKIP
)
compB = GenEntryComparator(
arrayOf(
GenEntryComparator.retB, GenEntryComparator.retA,
GenEntryComparator.retTip
), Database.ID_RESERVED_SKIP
)
compTip = GenEntryComparator(
arrayOf(
GenEntryComparator.retTip, GenEntryComparator.retA,
GenEntryComparator.retB
), Database.ID_RESERVED_SKIP
)
val intent = intent
val bNewEntry = findViewById<FloatingActionButton>(R.id.bEditorNewEntry)
bNewEntry.setOnClickListener { v: View? -> addEntry() }
// setup listview
initListView()
val settings = getSharedPreferences(MainActivity.PREFS_NAME, 0)
sortSetting = settings.getInt(P_KEY_EA_SORT, 0)
updateComp()
// handle passed params
var newTable = intent.getBooleanExtra(PARAM_NEW_TABLE, false)
ACRA.errorReporter.putCustomData("hasSavedInstanceState","$savedInstanceState");
if (savedInstanceState != null) {
newTable = savedInstanceState.getBoolean(PARAM_NEW_TABLE, false)
listEditorDialog = supportFragmentManager.getFragment(
savedInstanceState,
VListEditorDialog.TAG
) as VListEditorDialog?
}
ACRA.errorReporter.putCustomData("newTable","$newTable")
if (newTable) {
list = if (savedInstanceState != null) // viewport changed during creation phase
savedInstanceState.getParcelable(PARAM_TABLE) else VList.blank(
getString(R.string.Editor_Hint_Column_A), getString(
R.string.Editor_Hint_Column_B
), getString(R.string.Editor_Hint_List_Name)
)
Log.d(TAG, "new list mode")
if (savedInstanceState == null) showTableInfoDialog()
} else {
val tbl: VList? = intent.getParcelableExtra(PARAM_TABLE)
ACRA.errorReporter.putCustomData("intentHasList","$tbl")
if (tbl != null) {
list = tbl
// do not call updateColumnNames as we've to wait for onCreateOptionsMenu, calling it
entries!!.addAll(db.getEntriesOfList(list!!))
adapter!!.updateSorting(cComp)
Log.d(TAG, "edit list mode")
}
}
if (list == null) {
ACRA.errorReporter.handleException(throw Throwable("List for editor is null"))
}
if (listEditorDialog != null) setListEditorActions()
if (savedInstanceState != null) {
editorDialog = supportFragmentManager.getFragment(
savedInstanceState,
VEntryEditorDialog.TAG
) as VEntryEditorDialog?
if (editorDialog != null) {
// DialogFragment re-adds itself
editPosition = savedInstanceState.getInt(KEY_EDITOR_POSITION)
editorEntry =
if (isIDValid(editPosition)) adapter!!.getItem(editPosition) as VEntry else savedInstanceState.getParcelable(
KEY_EDITOR_ENTRY
)
setEditorDialogActions()
}
sortingDialog = supportFragmentManager.getFragment(
savedInstanceState,
P_KEY_SORTING_DIALOG
) as ItemPickerDialog?
if (sortingDialog != null) {
setSortingDialogParams()
}
}
this.title = list!!.name
}
/**
* Set handlers & overrides for sortingDialog
*/
private fun setSortingDialogParams() {
sortingDialog!!.run {
setItemPickerHandler(this@EditorActivity)
overrideEntry(0, list!!.nameA)
overrideEntry(1, list!!.nameB)
}
}
/**
* Clear current edit state
*/
private fun clearEdit() {
editPosition = (Database.MIN_ID_TRESHOLD - 1).toInt() // clear
editorEntry = null
}
/**
* Handles list column name changes
*/
private fun updateColumnNames() {
adapter!!.setTableData(list)
}
/**
* Changes cComp to current selection
*/
private fun updateComp() {
when (sortSetting) {
0 -> cComp = compA
1 -> cComp = compB
2 -> cComp = compTip
else -> {
cComp = compA
sortSetting = 0
}
}
adapter!!.updateSorting(cComp)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.editor, menu)
updateColumnNames()
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
return true
}
R.id.tEditorListEdit -> {
showTableInfoDialog()
return true
}
R.id.eMenu_sort -> {
sortingDialog =
ItemPickerDialog.newInstance(R.array.sort_entries, R.string.GEN_Sort)
setSortingDialogParams()
sortingDialog!!.show(supportFragmentManager, P_KEY_SORTING_DIALOG)
return true
}
}
return super.onOptionsItemSelected(item)
}
/**
* Save editorEntry to DB & update listview
*/
private fun saveEdit() {
val lst = ArrayList<VEntry>(1)
editorEntry!!.let {
lst.add(it)
val isExisting = it.isExisting
if (!isExisting) {
adapter!!.addEntryUnrendered(it)
}
db.upsertEntries(lst)
adapter!!.notifyDataSetChanged()
if (!isExisting) {
addEntry()
}
}
}
/**
* Setup listview
*/
private fun initListView() {
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val ab = supportActionBar
ab?.setDisplayHomeAsUpEnabled(true)
listView = findViewById(R.id.listviewEditor)
entries = ArrayList()
[email protected] = EntryListAdapter(this@EditorActivity, entries)
listView!!.run {
isLongClickable = true
adapter = [email protected]
onItemClickListener =
OnItemClickListener { parent: AdapterView<*>?, view: View?, pos: Int, id: Long ->
showEntryEditDialog(
adapter!!.getItem(pos) as VEntry, pos, false
)
}
onItemLongClickListener =
OnItemLongClickListener { arg0: AdapterView<*>?, arg1: View?, pos: Int, id: Long ->
showEntryDeleteDialog(
adapter!!.getItem(pos) as VEntry, pos
)
true
}
}
}
/**
* Add new VEntry
*/
private fun addEntry() {
editorEntry = VEntry.blankFromList(list!!)
showEntryEditDialog(editorEntry!!)
}
/**
* Show entry delete dialog
*
* @param entry
* @param position
*/
private fun showEntryDeleteDialog(entry: VEntry, position: Int) {
if (entry.id == Database.ID_RESERVED_SKIP) return
val delDiag = AlertDialog.Builder(this, R.style.CustomDialog)
delDiag.setTitle(R.string.Editor_Diag_delete_Title)
delDiag.setMessage(
String.format(
"${getString(R.string.Editor_Diag_delete_MSG_part)}\n %s %s %s", entry.aString, entry.bString, entry.tip
)
)
delDiag.setPositiveButton(R.string.Editor_Diag_delete_btn_OK) { dialog: DialogInterface?, whichButton: Int ->
deleteEntry(
position,
entry
)
}
delDiag.setNegativeButton(R.string.Editor_Diag_delete_btn_CANCEL) { dialog: DialogInterface?, whichButton: Int ->
Log.d(
TAG, "canceled"
)
}
delDiag.show()
}
/**
* Perform entry deletion with undo possibility
* @param deletedPosition
* @param entry
*/
private fun deleteEntry(deletedPosition: Int, entry: VEntry) {
adapter!!.remove(entry)
val snackbar = Snackbar
.make(listView!!, R.string.Editor_Entry_Deleted_Message, Snackbar.LENGTH_LONG)
.setAction(R.string.GEN_Undo) { view: View? ->
adapter!!.addEntryRendered(
entry,
deletedPosition
)
}
.addCallback(object : Snackbar.Callback() {
override fun onDismissed(transientBottomBar: Snackbar, event: Int) {
when (event) {
DISMISS_EVENT_CONSECUTIVE, DISMISS_EVENT_TIMEOUT, DISMISS_EVENT_MANUAL, DISMISS_EVENT_SWIPE -> {
Log.d(TAG, "deleting entry")
entry.isDelete = true
val lst = ArrayList<VEntry>(1)
lst.add(entry)
val db = Database(applicationContext)
db.upsertEntries(lst) // TODO make a single function
}
}
}
})
snackbar.show()
}
/**
* Show entry edit dialog for new vocable
* @param entry
*/
private fun showEntryEditDialog(entry: VEntry) {
showEntryEditDialog(entry, (Database.MIN_ID_TRESHOLD - 1).toInt(), true)
}
/**
* Show entry edit dialog
*
* @param entry VEntry to edit/create
* @param position edit position in list, if existing
*/
@Synchronized
private fun showEntryEditDialog(entry: VEntry, position: Int, forceDialog: Boolean) {
if (entry.id == Database.ID_RESERVED_SKIP) {
showTableInfoDialog()
return
}
if (!forceDialog && editorDialog != null && editorDialog!!.isAdded) {
return
}
editPosition = position
editorEntry = entry
editorDialog = VEntryEditorDialog.newInstance()
setEditorDialogActions()
editorDialog!!.show(supportFragmentManager, VEntryEditorDialog.TAG)
}
/**
* Setup editor dialog actions
*/
private fun setEditorDialogActions() {
editorDialog!!.setOkAction { e: VEntry? ->
saveEdit()
null
}
editorDialog!!.setCancelAction { e: VEntry? ->
val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInput(0, 0)
null
}
}
/**
* Setup list editor actions
*/
private fun setListEditorActions() {
listEditorDialog!!.setCancelAction {
if (!list!!.isExisting) {
finish()
}
null
}
listEditorDialog!!.setOkAction {
try {
db.upsertVList(list!!)
intent.putExtra(PARAM_TABLE, list)
title = list!!.name
updateColumnNames()
} catch (e: SQLException) {
Toast.makeText(
this, "Unable to save list!",
Toast.LENGTH_LONG
).show()
ACRA.errorReporter.handleException(e)
finish() // TODO: is this the right place ?
}
null
}
}
/**
* Show list title editor dialog<br></br>
* Exit editor when newTbl is set and user cancels the dialog
*/
@Synchronized
private fun showTableInfoDialog() {
if (listEditorDialog != null && listEditorDialog!!.isAdded) {
return
}
listEditorDialog = VListEditorDialog.newInstance(!list!!.isExisting)
setListEditorActions()
listEditorDialog!!.show(supportFragmentManager, VListEditorDialog.TAG)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (editorDialog != null && editorDialog!!.isAdded) supportFragmentManager.putFragment(
outState,
VEntryEditorDialog.TAG,
editorDialog!!
)
if (listEditorDialog != null && listEditorDialog!!.isAdded) supportFragmentManager.putFragment(
outState,
VListEditorDialog.TAG,
listEditorDialog!!
)
outState.putInt(KEY_EDITOR_POSITION, editPosition)
if (editorEntry != null && !editorEntry!!.isExisting) // unsaved new entry (empty entry as filled by editor)
outState.putParcelable(KEY_EDITOR_ENTRY, editorEntry)
if (!list!!.isExisting) { // unsaved new table, still in creation dialog
outState.putBoolean(PARAM_NEW_TABLE, true)
outState.putParcelable(PARAM_TABLE, list)
}
if (sortingDialog != null && sortingDialog!!.isAdded) supportFragmentManager.putFragment(
outState,
P_KEY_SORTING_DIALOG,
sortingDialog!!
)
}
override fun onStop() {
super.onStop()
val settings = getSharedPreferences(MainActivity.PREFS_NAME, 0)
val editor = settings.edit()
editor.putInt(P_KEY_EA_SORT, sortSetting)
editor.apply()
}
override fun getEditVEntry(): VEntry {
return editorEntry!!
}
override fun getList(): VList {
return list!!
}
override fun onItemPickerSelected(position: Int) {
sortSetting = position
updateComp()
}
companion object {
/**
* Param key for new list, default is false
*/
const val PARAM_NEW_TABLE = "NEW_TABLE"
/**
* Param key for list to load upon new_table false
*/
const val PARAM_TABLE = "list"
const val TAG = "EditorActivity"
private const val P_KEY_EA_SORT = "EA_sorting"
private const val P_KEY_SORTING_DIALOG = "sorting_dialog_editor"
private const val KEY_EDITOR_POSITION = "editorPosition"
private const val KEY_EDITOR_ENTRY = "editorEntry"
}
} | apache-2.0 | 97bd5e10f2ca9ceb768cce1998336064 | 34.795132 | 129 | 0.597132 | 4.817363 | false | false | false | false |
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/settings/LocalSettings.kt | 1 | 2967 | /*
* (C) Copyright 2019 Lukas Morawietz (https://github.com/F43nd1r)
*
* 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.faendir.acra.settings
import com.faendir.acra.util.tryOrNull
import com.fasterxml.jackson.databind.ObjectMapper
import com.vaadin.flow.component.UI
import com.vaadin.flow.server.VaadinRequest
import com.vaadin.flow.server.VaadinResponse
import com.vaadin.flow.server.VaadinService
import com.vaadin.flow.spring.annotation.SpringComponent
import com.vaadin.flow.spring.annotation.VaadinSessionScope
import java.io.Serializable
import java.net.URLDecoder
import java.net.URLEncoder
import java.util.*
import javax.servlet.http.Cookie
import kotlin.reflect.KProperty
/**
* @author lukas
* @since 10.09.19
*/
@SpringComponent
@VaadinSessionScope
class LocalSettings(private val objectMapper: ObjectMapper) : Serializable {
private val cache = mutableMapOf<String, String>()
var darkTheme: Boolean by Cookie({ it?.toBoolean() ?: false }, { it.toString() })
var locale: Locale by Cookie({
it?.let { Locale(it) }
?: UI.getCurrent()?.locale
?: VaadinService.getCurrent().instantiator.i18NProvider.providedLocales?.firstOrNull()
?: Locale.getDefault()
}, { it.toString() })
var bugGridSettings: GridSettings? by jsonCookie()
var reportGridSettings: GridSettings? by jsonCookie()
private class Cookie<T>(
private val fromString: LocalSettings.(String?) -> T,
private val toString: LocalSettings.(T) -> String
) {
operator fun getValue(localSettings: LocalSettings, property: KProperty<*>): T {
val id = property.name
return localSettings.fromString(localSettings.cache[id]
?: VaadinRequest.getCurrent()?.cookies?.firstOrNull { it.name == id }?.value?.also { localSettings.cache[id] = it })
}
operator fun setValue(localSettings: LocalSettings, property: KProperty<*>, value: T) {
val id = property.name
val stringValue = localSettings.toString(value)
VaadinResponse.getCurrent()?.addCookie(Cookie(id, stringValue))
localSettings.cache[id] = stringValue
}
}
private inline fun <reified T> jsonCookie() = Cookie(
{ tryOrNull { objectMapper.readValue(URLDecoder.decode(it, Charsets.UTF_8), T::class.java) } },
{ URLEncoder.encode(objectMapper.writeValueAsString(it), Charsets.UTF_8) })
} | apache-2.0 | 045546faf2596fe0ed83e0a093128cd9 | 37.545455 | 132 | 0.7061 | 4.244635 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-core/src/main/kotlin/slatekit/core/common/Backoffs.kt | 1 | 881 | package slatekit.core.common
import slatekit.utils.paged.Pager
/**
* Used to cycle through exponential "backoff" time in seconds
* This can be used to back-off from processing a job/worker.
* e.g.
* 1, 2, 4, 8, 16, 32, 64
*/
class Backoffs(val times: Pager<Long> = times()){
private var isOn = false
fun next():Long {
return when(isOn){
true -> {
times.next()
}
false -> {
isOn = true
val currSec = times.current(moveNext = true)
currSec
}
}
}
fun reset() {
isOn = false
times.reset()
}
fun curr():Long {
return times.current()
}
companion object {
fun default() = Backoffs(times())
fun times() = Pager<Long>(listOf(2, 4, 8, 16, 32, 64, 128, 256), true, 0)
}
}
| apache-2.0 | 844fc98d1f2ec3bc0418279e3ac92ddc | 19.022727 | 81 | 0.503973 | 3.813853 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/rule/attribute/OnnxSizeThresholdIntArrayIntIndexRule.kt | 1 | 5282 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.rule.attribute
import onnx.Onnx
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.*
import org.nd4j.samediff.frameworkimport.ir.IRAttribute
import org.nd4j.samediff.frameworkimport.onnx.ir.OnnxIRAttr
import org.nd4j.samediff.frameworkimport.onnx.isOnnxAttributeName
import org.nd4j.samediff.frameworkimport.onnx.isOnnxTensorName
import org.nd4j.samediff.frameworkimport.onnx.onnxAttributeTypeFor
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder
import org.nd4j.samediff.frameworkimport.process.MappingProcess
import org.nd4j.samediff.frameworkimport.rule.MappingRule
import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType
import org.nd4j.samediff.frameworkimport.rule.attribute.SizeThresholdIntArrayIntIndexRule
@MappingRule("onnx","sizethresholdarrayint","attribute")
class OnnxSizeThresholdIntArrayIntIndexRule(mappingNamesToPerform: Map<String, String>,
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>) : SizeThresholdIntArrayIntIndexRule<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto, Onnx.TensorProto.DataType>(mappingNamesToPerform, transformerArgs) {
override fun createIRAttribute(name: String, attrDef: Onnx.AttributeProto, attributeValueType: Onnx.AttributeProto): IRAttribute<Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto, Onnx.TensorProto.DataType> {
return OnnxIRAttr(attrDef, attributeValueType)
}
override fun convertAttributesReverse(allInputArguments: List<OpNamespace.ArgDescriptor>, inputArgumentsToProcess: List<OpNamespace.ArgDescriptor>): List<IRAttribute<Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto, Onnx.TensorProto.DataType>> {
TODO("Not yet implemented")
}
override fun isInputFrameworkTensorName(name: String, mappingProcess: MappingProcess<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.TensorProto, Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto.DataType>): Boolean {
val onnxOp = OpDescriptorLoaderHolder.listForFramework<Onnx.NodeProto>("onnx")[mappingProcess.inputFrameworkOpName()]!!
return isOnnxTensorName(name, onnxOp)
}
override fun isNd4jTensorName(name: String, mappingProcess: MappingProcess<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.TensorProto, Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto.DataType>): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return isNd4jTensorName(name,nd4jOpDescriptor)
}
override fun isInputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.TensorProto, Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto.DataType>): Boolean {
val onnxOp = OpDescriptorLoaderHolder.listForFramework<Onnx.NodeProto>("onnx")[mappingProcess.inputFrameworkOpName()]!!
return isOnnxAttributeName(name, onnxOp)
}
override fun isOutputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.TensorProto, Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto.DataType>): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return isOutputFrameworkAttributeName(name,nd4jOpDescriptor) }
override fun argDescriptorType(name: String, mappingProcess: MappingProcess<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.TensorProto, Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto.DataType>): OpNamespace.ArgDescriptor.ArgType {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return argDescriptorType(name,nd4jOpDescriptor)
}
override fun attributeValueTypeFor(name: String, mappingProcess: MappingProcess<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.TensorProto, Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto.DataType>): AttributeValueType {
val onnxOp = OpDescriptorLoaderHolder.listForFramework<Onnx.NodeProto>("onnx")[mappingProcess.inputFrameworkOpName()]!!
return onnxAttributeTypeFor(name, onnxOp)
}
} | apache-2.0 | b0d7b5c0b384f4fa071568fe9801229f | 64.222222 | 320 | 0.769216 | 4.886216 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-api/src/com/intellij/util/animation/components/BezierPainter.kt | 4 | 5152 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.animation.components
import com.intellij.ui.JBColor
import com.intellij.util.animation.Easing
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.geom.CubicCurve2D
import java.awt.geom.Point2D
import javax.swing.JComponent
import kotlin.properties.Delegates
import kotlin.reflect.KProperty
class BezierPainter(x1: Double, y1: Double, x2: Double, y2: Double) : JComponent() {
private val controlSize = 10
private val gridColor = JBColor(Color(0xF0F0F0), Color(0x313335))
var firstControlPoint: Point2D by Delegates.observable(Point2D.Double(x1, y1), this::fireEvents)
var secondControlPoint: Point2D by Delegates.observable(Point2D.Double(x2, y2), this::fireEvents)
private fun fireEvents(prop: KProperty<*>, oldValue: Any?, newValue: Any?) {
if (oldValue != newValue) {
firePropertyChange(prop.name, oldValue, newValue)
repaint()
}
}
init {
val value = object : MouseAdapter() {
var i = 0
override fun mouseDragged(e: MouseEvent) {
val point = e.point
when (i) {
1 -> firstControlPoint = fromScreenXY(point)
2 -> secondControlPoint = fromScreenXY(point)
}
repaint()
}
override fun mouseMoved(e: MouseEvent) = with (e.point ) {
i = when {
this intersects firstControlPoint -> 1
this intersects secondControlPoint -> 2
else -> 0
}
if (i != 0) {
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
} else {
cursor = Cursor.getDefaultCursor()
}
}
private infix fun Point.intersects(point: Point2D) : Boolean {
val xy = toScreenXY(point)
return xy.x - controlSize / 2 <= x && x <= xy.x + controlSize / 2 &&
xy.y - controlSize / 2 <= y && y <= xy.y + controlSize / 2
}
}
addMouseMotionListener(value)
addMouseListener(value)
minimumSize = Dimension(300, 300)
}
fun getEasing() : Easing = Easing.bezier(firstControlPoint.x, firstControlPoint.y, secondControlPoint.x, secondControlPoint.y)
private fun toScreenXY(point: Point2D) : Point = visibleRect.let { b ->
val insets = insets
val width = b.width - (insets.left + insets.right)
val height = b.height - (insets.top + insets.bottom)
return Point((point.x * width + insets.left + b.x).toInt(), height - (point.y * height).toInt() + insets.top + b.y)
}
private fun fromScreenXY(point: Point) : Point2D.Double = visibleRect.let { b ->
val insets = insets
val left = insets.left + b.x
val top = insets.top + b.y
val width = b.width - (insets.left + insets.right)
val height = b.height - (insets.top + insets.bottom)
val x = (minOf(maxOf(-left, point.x - left), b.width - left).toDouble()) / width
val y = (minOf(maxOf(-top, point.y - top), b.height - top).toDouble()) / height
return Point2D.Double(x, 1.0 - y)
}
override fun paintComponent(g: Graphics) {
val bounds = visibleRect
val insets = insets
val x = bounds.x + insets.left
val y = bounds.y + insets.top
val width = bounds.width - (insets.left + insets.right)
val height = bounds.height - (insets.top + insets.bottom)
val g2d = g.create() as Graphics2D
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED)
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE)
g2d.color = JBColor.background()
g2d.fillRect(0, 0, bounds.width, bounds.height)
g2d.color = gridColor
for (i in 0..4) {
g2d.drawLine(x + width * i / 4, y, x + width * i / 4, y + height)
g2d.drawLine(x,y + height * i / 4, x + width, y + height * i / 4)
}
val (x0, y0) = toScreenXY(Point2D.Double(0.0, 0.0))
val (x1, y1) = toScreenXY(firstControlPoint)
val (x2, y2) = toScreenXY(secondControlPoint)
val (x3, y3) = toScreenXY(Point2D.Double(1.0, 1.0))
val bez = CubicCurve2D.Double(x0, y0, x1, y1, x2, y2, x3, y3)
g2d.color = JBColor.foreground()
g2d.stroke = BasicStroke(2f)
g2d.draw(bez)
g2d.stroke = BasicStroke(1f)
g2d.color = when {
isEnabled -> Color(151, 118, 169)
JBColor.isBright() -> JBColor.LIGHT_GRAY
else -> JBColor.GRAY
}
g2d.fillOval(x1.toInt() - controlSize / 2, y1.toInt() - controlSize / 2, controlSize, controlSize)
g2d.drawLine(x0.toInt(), y0.toInt(), x1.toInt(), y1.toInt())
g2d.color = when {
isEnabled -> Color(208, 167, 8)
JBColor.isBright() -> JBColor.LIGHT_GRAY
else -> JBColor.GRAY
}
g2d.fillOval(x2.toInt() - controlSize / 2, y2.toInt() - controlSize / 2, controlSize, controlSize)
g2d.drawLine(x2.toInt(), y2.toInt(), x3.toInt(), y3.toInt())
g2d.dispose()
}
private operator fun Point2D.component1() = x
private operator fun Point2D.component2() = y
} | apache-2.0 | 27a28acf53b226e17dce689c5d649193 | 36.34058 | 140 | 0.652368 | 3.393939 | false | false | false | false |
android/compose-samples | Jetsnack/app/src/main/java/com/example/jetsnack/ui/JetsnackApp.kt | 1 | 3534 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetsnack.ui
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.material.SnackbarHost
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import androidx.navigation.navigation
import com.example.jetsnack.ui.components.JetsnackScaffold
import com.example.jetsnack.ui.components.JetsnackSnackbar
import com.example.jetsnack.ui.home.HomeSections
import com.example.jetsnack.ui.home.JetsnackBottomBar
import com.example.jetsnack.ui.home.addHomeGraph
import com.example.jetsnack.ui.snackdetail.SnackDetail
import com.example.jetsnack.ui.theme.JetsnackTheme
@Composable
fun JetsnackApp() {
JetsnackTheme {
val appState = rememberJetsnackAppState()
JetsnackScaffold(
bottomBar = {
if (appState.shouldShowBottomBar) {
JetsnackBottomBar(
tabs = appState.bottomBarTabs,
currentRoute = appState.currentRoute!!,
navigateToRoute = appState::navigateToBottomBarRoute
)
}
},
snackbarHost = {
SnackbarHost(
hostState = it,
modifier = Modifier.systemBarsPadding(),
snackbar = { snackbarData -> JetsnackSnackbar(snackbarData) }
)
},
scaffoldState = appState.scaffoldState
) { innerPaddingModifier ->
NavHost(
navController = appState.navController,
startDestination = MainDestinations.HOME_ROUTE,
modifier = Modifier.padding(innerPaddingModifier)
) {
jetsnackNavGraph(
onSnackSelected = appState::navigateToSnackDetail,
upPress = appState::upPress
)
}
}
}
}
private fun NavGraphBuilder.jetsnackNavGraph(
onSnackSelected: (Long, NavBackStackEntry) -> Unit,
upPress: () -> Unit
) {
navigation(
route = MainDestinations.HOME_ROUTE,
startDestination = HomeSections.FEED.route
) {
addHomeGraph(onSnackSelected)
}
composable(
"${MainDestinations.SNACK_DETAIL_ROUTE}/{${MainDestinations.SNACK_ID_KEY}}",
arguments = listOf(navArgument(MainDestinations.SNACK_ID_KEY) { type = NavType.LongType })
) { backStackEntry ->
val arguments = requireNotNull(backStackEntry.arguments)
val snackId = arguments.getLong(MainDestinations.SNACK_ID_KEY)
SnackDetail(snackId, upPress)
}
}
| apache-2.0 | 8626414a8d6c079fe234bd1c975d50b8 | 36.595745 | 98 | 0.672609 | 4.92887 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/cli/test/org/jetbrains/kotlin/tools/projectWizard/cli/ProjectImportingTestParameters.kt | 6 | 682 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.cli
import java.nio.file.Path
data class DefaultTestParameters(
val runForMaven: Boolean = false,
val runForGradleGroovy: Boolean = true,
val keepKotlinVersion: Boolean = false
) : TestParameters {
companion object {
fun fromTestDataOrDefault(directory: Path): DefaultTestParameters =
TestParameters.fromTestDataOrDefault(directory, PARAMETERS_FILE_NAME)
private const val PARAMETERS_FILE_NAME = "importParameters.txt"
}
} | apache-2.0 | 3ff644e670c887ef2c84de47d7813719 | 36.944444 | 158 | 0.749267 | 4.343949 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspections/coroutines/asyncResultUnused/simple.kt | 10 | 1298 | package kotlinx.coroutines
import kotlin.test.assertNotNull
interface Deferred<T> {
suspend fun await(): T
}
interface CoroutineContext
object DefaultContext : CoroutineContext
enum class CoroutineStart {
DEFAULT,
LAZY,
ATOMIC,
UNDISPATCHED
}
interface Job
fun <T> async(
context: CoroutineContext = DefaultContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
parent: Job? = null,
f: suspend () -> T
): Deferred<T> {
TODO()
}
fun test() {
async { 42 }
}
fun useIt(d: Deferred<Int>) {}
fun falsePositives() {
async { 3 }.await()
val res = async { 13 }
useIt(async { 7 })
}
class User
interface DbHandler {
fun getUser(id: Long): Deferred<User>
fun doStuff(): Deferred<Unit>
}
fun DbHandler.test() {
getUser(42L)
val user = getUser(42L).await()
doStuff()
doStuff().await()
}
operator fun Deferred<Int>.unaryPlus() = this
operator fun Deferred<Int>.plus(arg: Int) = this
fun moreFalsePositives() {
+(async { 0 })
async { -1 } + 1
}
suspend fun kt33741() {
val d: Deferred<Int>? = async { 42 }
assertNotNull(d)
d.await()
val d2: Deferred<Int>? = async { 42 }
requireNotNull(d2)
d2.await()
val d3: Deferred<Int>? = async { 42 }
checkNotNull(d3)
d3.await()
} | apache-2.0 | a7141a5ae9b54b724b772f1813bdb455 | 15.87013 | 51 | 0.62943 | 3.362694 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/fragments/DiscoveryFragment.kt | 1 | 13148 | package com.kickstarter.ui.fragments
import android.animation.AnimatorSet
import android.app.ActivityOptions
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import com.jakewharton.rxbinding.view.RxView
import com.kickstarter.R
import com.kickstarter.databinding.FragmentDiscoveryBinding
import com.kickstarter.libs.ActivityRequestCodes
import com.kickstarter.libs.BaseFragment
import com.kickstarter.libs.RecyclerViewPaginator
import com.kickstarter.libs.RefTag
import com.kickstarter.libs.SwipeRefresher
import com.kickstarter.libs.qualifiers.RequiresFragmentViewModel
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.utils.AnimationUtils.crossFadeAndReverse
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.TransitionUtils
import com.kickstarter.libs.utils.ViewUtils
import com.kickstarter.libs.utils.extensions.getProjectIntent
import com.kickstarter.libs.utils.extensions.getSetPasswordActivity
import com.kickstarter.models.Activity
import com.kickstarter.models.Category
import com.kickstarter.models.Project
import com.kickstarter.services.DiscoveryParams
import com.kickstarter.ui.ArgumentsKey
import com.kickstarter.ui.IntentKey
import com.kickstarter.ui.activities.ActivityFeedActivity
import com.kickstarter.ui.activities.EditorialActivity
import com.kickstarter.ui.activities.LoginToutActivity
import com.kickstarter.ui.activities.UpdateActivity
import com.kickstarter.ui.adapters.DiscoveryActivitySampleAdapter
import com.kickstarter.ui.adapters.DiscoveryEditorialAdapter
import com.kickstarter.ui.adapters.DiscoveryOnboardingAdapter
import com.kickstarter.ui.adapters.DiscoveryProjectCardAdapter
import com.kickstarter.ui.data.Editorial
import com.kickstarter.ui.data.LoginReason
import com.kickstarter.ui.viewholders.EditorialViewHolder
import com.kickstarter.viewmodels.DiscoveryFragmentViewModel
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
@RequiresFragmentViewModel(DiscoveryFragmentViewModel.ViewModel::class)
class DiscoveryFragment : BaseFragment<DiscoveryFragmentViewModel.ViewModel>() {
private var heartsAnimation: AnimatorSet? = null
private var recyclerViewPaginator: RecyclerViewPaginator? = null
private var binding: FragmentDiscoveryBinding? = null
private var discoveryEditorialAdapter: DiscoveryEditorialAdapter? = null
private val projectStarConfirmationString = R.string.project_star_confirmation
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
binding = FragmentDiscoveryBinding.inflate(inflater, container, false)
return binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
this.lifecycle()
.compose(bindToLifecycle())
.compose(Transformers.observeForUI())
.filter { ObjectUtils.isNotNull(it) }
.subscribe {
this.viewModel.inputs.fragmentLifeCycle(it)
}
val discoveryActivitySampleAdapter = DiscoveryActivitySampleAdapter(this.viewModel.inputs)
val discoveryEditorialAdapter = DiscoveryEditorialAdapter(this.viewModel.inputs)
val discoveryOnboardingAdapter = DiscoveryOnboardingAdapter(this.viewModel.inputs)
val discoveryProjectCardAdapter = DiscoveryProjectCardAdapter(this.viewModel.inputs)
val discoveryAdapter = ConcatAdapter(discoveryOnboardingAdapter, discoveryEditorialAdapter, discoveryActivitySampleAdapter, discoveryProjectCardAdapter)
this.discoveryEditorialAdapter = discoveryEditorialAdapter
binding?.discoveryRecyclerView?.apply {
adapter = discoveryAdapter
layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
recyclerViewPaginator = RecyclerViewPaginator(
this,
{ [email protected]() },
[email protected]()
)
}
binding?.discoverySwipeRefreshLayout?.let {
SwipeRefresher(
this, it, { this.viewModel.inputs.refresh() }
) { this.viewModel.outputs.isFetchingProjects() }
}
this.viewModel.outputs.activity()
.compose(bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { discoveryActivitySampleAdapter.takeActivity(it) }
this.viewModel.outputs.startHeartAnimation()
.compose(bindToLifecycle())
.compose(Transformers.observeForUI())
.filter { !(lazyHeartCrossFadeAnimation()?.isRunning?:false) }
.subscribe { lazyHeartCrossFadeAnimation()?.start() }
this.viewModel.outputs.projectList()
.compose(bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { discoveryProjectCardAdapter.takeProjects(it) }
this.viewModel.outputs.shouldShowEditorial()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { discoveryEditorialAdapter.setShouldShowEditorial(it) }
this.viewModel.outputs.shouldShowEmptySavedView()
.compose(bindToLifecycle())
.compose(Transformers.observeForUI())
.subscribe {
binding?.discoveryEmptyView?.isGone = !it
}
this.viewModel.outputs.shouldShowOnboardingView()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { discoveryOnboardingAdapter.setShouldShowOnboardingView(it) }
this.viewModel.outputs.showActivityFeed()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { startActivityFeedActivity() }
this.viewModel.outputs.startSetPasswordActivity()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { startSetPasswordActivity(it) }
this.viewModel.outputs.startEditorialActivity()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { startEditorialActivity(it) }
this.viewModel.outputs.startUpdateActivity()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { startUpdateActivity(it) }
this.viewModel.outputs.startProjectActivity()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { startProjectActivity(it.first, it.second) }
this.viewModel.outputs.showLoginTout()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { startLoginToutActivity() }
binding?.discoveryHeartsContainer?.let {
RxView.clicks(it)
.compose(bindToLifecycle())
.subscribe { this.viewModel.inputs.heartContainerClicked() }
}
this.viewModel.outputs.startLoginToutActivityToSaveProject()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { this.startLoginToutActivity() }
this.viewModel.outputs.scrollToSavedProjectPosition()
.filter { it != -1 }
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
binding?.discoveryRecyclerView?.smoothScrollToPosition(it)
}
this.viewModel.outputs.showSavedPrompt()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { this.showStarToast() }
}
override fun onPause() {
super.onPause()
heartsAnimation = null
}
override fun onDetach() {
super.onDetach()
binding?.discoveryRecyclerView?.adapter = null
recyclerViewPaginator?.stop()
}
val isAttached: Boolean
get() = viewModel != null
val isInstantiated: Boolean
get() = binding?.discoveryRecyclerView != null
private val editorialImageView: ImageView?
get() {
val layoutManager = binding?.discoveryRecyclerView?.layoutManager as? LinearLayoutManager
if (layoutManager != null && discoveryEditorialAdapter != null) {
for (i in layoutManager.findFirstVisibleItemPosition()..layoutManager.findLastVisibleItemPosition()) {
val childView = layoutManager.getChildAt(i)
if (childView != null) {
val viewHolder = binding?.discoveryRecyclerView?.getChildViewHolder(childView)
if (viewHolder is EditorialViewHolder) {
return childView.findViewById(R.id.editorial_graphic)
}
}
}
}
return null
}
private fun lazyHeartCrossFadeAnimation(): AnimatorSet? {
if (heartsAnimation == null) {
binding?.discoveryEmptyHeartOutline?.let { discoveryEmptyHeartOutline ->
binding?.discoveryEmptyHeartFilled?.let {
heartsAnimation = crossFadeAndReverse(discoveryEmptyHeartOutline, it, 400L)
}
}
}
return heartsAnimation
}
private fun startActivityFeedActivity() {
startActivity(Intent(activity, ActivityFeedActivity::class.java))
}
private fun startSetPasswordActivity(email: String) {
val intent = Intent().getSetPasswordActivity(requireContext(), email)
startActivityForResult(intent, ActivityRequestCodes.LOGIN_FLOW)
TransitionUtils.transition(requireContext(), TransitionUtils.fadeIn())
}
private fun showStarToast() {
ViewUtils.showToastFromTop(requireContext(), getString(this.projectStarConfirmationString), 0, resources.getDimensionPixelSize(R.dimen.grid_8))
}
private fun startEditorialActivity(editorial: Editorial) {
val activity = activity
// The transition view must be an ImageView
val editorialImageView = editorialImageView
if (activity != null && editorialImageView != null) {
val intent = Intent(activity, EditorialActivity::class.java)
.putExtra(IntentKey.EDITORIAL, editorial)
val options = ActivityOptions.makeSceneTransitionAnimation(activity, editorialImageView, "editorial")
startActivity(intent, options.toBundle())
}
}
private fun startLoginToutActivity() {
val intent = Intent(activity, LoginToutActivity::class.java)
.putExtra(IntentKey.LOGIN_REASON, LoginReason.DEFAULT)
startActivityForResult(intent, ActivityRequestCodes.LOGIN_FLOW)
context?.let {
TransitionUtils.transition(it, TransitionUtils.fadeIn())
}
}
private fun startProjectActivity(project: Project, refTag: RefTag) {
context?.let {
val intent = Intent().getProjectIntent(it)
.putExtra(IntentKey.PROJECT, project)
.putExtra(IntentKey.REF_TAG, refTag)
startActivity(intent)
TransitionUtils.transition(it, TransitionUtils.slideInFromRight())
}
}
private fun startUpdateActivity(activity: Activity) {
val intent = Intent(getActivity(), UpdateActivity::class.java)
.putExtra(IntentKey.PROJECT, activity.project())
.putExtra(IntentKey.UPDATE, activity.update())
startActivity(intent)
context?.let {
TransitionUtils.transition(it, TransitionUtils.slideInFromRight())
}
}
fun refresh() {
this.viewModel.inputs.refresh()
}
fun takeCategories(categories: List<Category>) {
this.viewModel.inputs.rootCategories(categories)
}
fun updateParams(params: DiscoveryParams) {
this.viewModel.inputs.paramsFromActivity(params)
}
fun clearPage() {
this.viewModel.inputs.clearPage()
}
fun scrollToTop() {
binding?.discoveryRecyclerView?.smoothScrollToPosition(0)
}
companion object {
@JvmStatic
fun newInstance(position: Int): DiscoveryFragment {
val fragment = DiscoveryFragment()
val bundle = Bundle()
bundle.putInt(ArgumentsKey.DISCOVERY_SORT_POSITION, position)
fragment.arguments = bundle
return fragment
}
}
}
| apache-2.0 | fd2e95ac7ef5813237df9f53c4890a62 | 39.832298 | 160 | 0.690067 | 5.496656 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/NewKotlinFileAction.kt | 1 | 12490 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.actions
import com.intellij.ide.actions.*
import com.intellij.ide.fileTemplates.FileTemplate
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.ide.fileTemplates.actions.AttributesDefaults
import com.intellij.ide.fileTemplates.ui.CreateFromTemplateDialog
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.InputValidatorEx
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.util.IncorrectOperationException
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.base.projectStructure.NewKotlinFileHook
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.projectStructure.toModuleGroup
import org.jetbrains.kotlin.idea.configuration.ConfigureKotlinStatus
import org.jetbrains.kotlin.idea.configuration.KotlinProjectConfigurator
import org.jetbrains.kotlin.idea.statistics.KotlinCreateFileFUSCollector
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.parsing.KotlinParserDefinition.Companion.STD_SCRIPT_SUFFIX
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import java.util.*
class NewKotlinFileAction : CreateFileFromTemplateAction(
KotlinBundle.message("action.new.file.text"),
KotlinBundle.message("action.new.file.description"),
KotlinFileType.INSTANCE.icon
), DumbAware {
override fun postProcess(createdElement: PsiFile, templateName: String?, customProperties: Map<String, String>?) {
super.postProcess(createdElement, templateName, customProperties)
val module = ModuleUtilCore.findModuleForPsiElement(createdElement)
if (createdElement is KtFile) {
if (module != null) {
for (hook in NewKotlinFileHook.EP_NAME.extensions) {
hook.postProcess(createdElement, module)
}
}
val ktClass = createdElement.declarations.singleOrNull() as? KtNamedDeclaration
if (ktClass != null) {
if (ktClass is KtClass && ktClass.isData()) {
val primaryConstructor = ktClass.primaryConstructor
if (primaryConstructor != null) {
createdElement.editor()?.caretModel?.moveToOffset(primaryConstructor.startOffset + 1)
return
}
}
CreateFromTemplateAction.moveCaretAfterNameIdentifier(ktClass)
} else {
val editor = createdElement.editor() ?: return
val lineCount = editor.document.lineCount
if (lineCount > 0) {
editor.caretModel.moveToLogicalPosition(LogicalPosition(lineCount - 1, 0))
}
}
}
}
private fun KtFile.editor() =
FileEditorManager.getInstance(this.project).selectedTextEditor?.takeIf { it.document == this.viewProvider.document }
override fun buildDialog(project: Project, directory: PsiDirectory, builder: CreateFileFromTemplateDialog.Builder) {
builder.setTitle(KotlinBundle.message("action.new.file.dialog.title"))
.addKind(
KotlinBundle.message("action.new.file.dialog.class.title"),
KotlinIcons.CLASS,
"Kotlin Class"
)
.addKind(
KotlinBundle.message("action.new.file.dialog.file.title"),
KotlinFileType.INSTANCE.icon,
"Kotlin File"
)
.addKind(
KotlinBundle.message("action.new.file.dialog.interface.title"),
KotlinIcons.INTERFACE,
"Kotlin Interface"
)
if (project.languageVersionSettings.supportsFeature(LanguageFeature.SealedInterfaces)) {
builder.addKind(
KotlinBundle.message("action.new.file.dialog.sealed.interface.title"),
KotlinIcons.INTERFACE,
"Kotlin Sealed Interface"
)
}
builder.addKind(
KotlinBundle.message("action.new.file.dialog.data.class.title"),
KotlinIcons.CLASS,
"Kotlin Data Class"
)
.addKind(
KotlinBundle.message("action.new.file.dialog.enum.title"),
KotlinIcons.ENUM,
"Kotlin Enum"
)
.addKind(
KotlinBundle.message("action.new.file.dialog.sealed.class.title"),
KotlinIcons.CLASS,
"Kotlin Sealed Class"
)
.addKind(
KotlinBundle.message("action.new.file.dialog.annotation.title"),
KotlinIcons.ANNOTATION,
"Kotlin Annotation"
)
.addKind(
KotlinBundle.message("action.new.file.dialog.object.title"),
KotlinIcons.OBJECT,
"Kotlin Object"
)
builder.setValidator(NameValidator)
}
override fun getActionName(directory: PsiDirectory, newName: String, templateName: String): String =
KotlinBundle.message("action.new.file.text")
override fun isAvailable(dataContext: DataContext): Boolean {
if (super.isAvailable(dataContext)) {
val ideView = LangDataKeys.IDE_VIEW.getData(dataContext)!!
val project = PlatformDataKeys.PROJECT.getData(dataContext)!!
val projectFileIndex = ProjectRootManager.getInstance(project).fileIndex
return ideView.directories.any {
projectFileIndex.isInSourceContent(it.virtualFile) ||
CreateTemplateInPackageAction.isInContentRoot(it.virtualFile, projectFileIndex)
}
}
return false
}
override fun hashCode(): Int = 0
override fun equals(other: Any?): Boolean = other is NewKotlinFileAction
override fun startInWriteAction() = false
override fun createFileFromTemplate(name: String, template: FileTemplate, dir: PsiDirectory) =
createFileFromTemplateWithStat(name, template, dir)
companion object {
private object NameValidator : InputValidatorEx {
override fun getErrorText(inputString: String): String? {
if (inputString.trim().isEmpty()) {
return KotlinBundle.message("action.new.file.error.empty.name")
}
val parts: List<String> = inputString.split(*FQNAME_SEPARATORS)
if (parts.any { it.trim().isEmpty() }) {
return KotlinBundle.message("action.new.file.error.empty.name.part")
}
return null
}
override fun checkInput(inputString: String): Boolean = true
override fun canClose(inputString: String): Boolean = getErrorText(inputString) == null
}
@get:TestOnly
val nameValidator: InputValidatorEx
get() = NameValidator
private fun findOrCreateTarget(dir: PsiDirectory, name: String, directorySeparators: CharArray): Pair<String, PsiDirectory> {
var className = removeKotlinExtensionIfPresent(name)
var targetDir = dir
for (splitChar in directorySeparators) {
if (splitChar in className) {
val names = className.trim().split(splitChar)
for (dirName in names.dropLast(1)) {
targetDir = targetDir.findSubdirectory(dirName) ?: runWriteAction {
targetDir.createSubdirectory(dirName)
}
}
className = names.last()
break
}
}
return Pair(className, targetDir)
}
private fun removeKotlinExtensionIfPresent(name: String): String = when {
name.endsWith(".$KOTLIN_WORKSHEET_EXTENSION") -> name.removeSuffix(".$KOTLIN_WORKSHEET_EXTENSION")
name.endsWith(".$STD_SCRIPT_SUFFIX") -> name.removeSuffix(".$STD_SCRIPT_SUFFIX")
name.endsWith(".${KotlinFileType.EXTENSION}") -> name.removeSuffix(".${KotlinFileType.EXTENSION}")
else -> name
}
private fun createFromTemplate(dir: PsiDirectory, className: String, template: FileTemplate): PsiFile? {
val project = dir.project
val defaultProperties = FileTemplateManager.getInstance(project).defaultProperties
val properties = Properties(defaultProperties)
val element = try {
CreateFromTemplateDialog(
project, dir, template,
AttributesDefaults(className).withFixedName(true),
properties
).create()
} catch (e: IncorrectOperationException) {
throw e
} catch (e: Exception) {
LOG.error(e)
return null
}
return element?.containingFile
}
private val FILE_SEPARATORS = charArrayOf('/', '\\')
private val FQNAME_SEPARATORS = charArrayOf('/', '\\', '.')
fun createFileFromTemplateWithStat(name: String, template: FileTemplate, dir: PsiDirectory): PsiFile? {
KotlinCreateFileFUSCollector.logFileTemplate(template.name)
return createFileFromTemplate(name, template, dir)
}
fun createFileFromTemplate(name: String, template: FileTemplate, dir: PsiDirectory): PsiFile? {
val directorySeparators = when (template.name) {
"Kotlin File" -> FILE_SEPARATORS
else -> FQNAME_SEPARATORS
}
val (className, targetDir) = findOrCreateTarget(dir, name, directorySeparators)
val service = DumbService.getInstance(dir.project)
return service.computeWithAlternativeResolveEnabled<PsiFile?, Throwable> {
val adjustedDir = CreateTemplateInPackageAction.adjustDirectory(targetDir, JavaModuleSourceRootTypes.SOURCES)
val psiFile = createFromTemplate(adjustedDir, className, template)
if (psiFile is KtFile) {
val singleClass = psiFile.declarations.singleOrNull() as? KtClass
if (singleClass != null && !singleClass.isEnum() && !singleClass.isInterface() && name.contains("Abstract")) {
runWriteAction {
singleClass.addModifier(KtTokens.ABSTRACT_KEYWORD)
}
}
}
JavaCreateTemplateInPackageAction.setupJdk(adjustedDir, psiFile)
val module = ModuleUtil.findModuleForFile(psiFile)
val configurator = KotlinProjectConfigurator.EP_NAME.extensions.firstOrNull()
if (module != null && configurator != null) {
DumbService.getInstance(module.project).runWhenSmart {
if (configurator.getStatus(module.toModuleGroup()) == ConfigureKotlinStatus.CAN_BE_CONFIGURED) {
configurator.configure(module.project, emptyList())
}
}
}
return@computeWithAlternativeResolveEnabled psiFile
}
}
}
} | apache-2.0 | 777fdde54f3faa7190e09074683eb98f | 43.137809 | 158 | 0.63755 | 5.406926 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddForLoopIndicesIntention.kt | 1 | 4597 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.analysis.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class AddForLoopIndicesIntention : SelfTargetingRangeIntention<KtForExpression>(
KtForExpression::class.java,
KotlinBundle.lazyMessage("add.indices.to.for.loop"),
), LowPriorityAction {
private val WITH_INDEX_NAME = "withIndex"
private val WITH_INDEX_FQ_NAMES: Set<String> by lazy {
sequenceOf("collections", "sequences", "text", "ranges").map { "kotlin.$it.$WITH_INDEX_NAME" }.toSet()
}
override fun applicabilityRange(element: KtForExpression): TextRange? {
if (element.loopParameter == null) return null
if (element.loopParameter?.destructuringDeclaration != null) return null
val loopRange = element.loopRange ?: return null
val bindingContext = element.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val resolvedCall = loopRange.getResolvedCall(bindingContext)
if (resolvedCall?.resultingDescriptor?.fqNameUnsafe?.asString() in WITH_INDEX_FQ_NAMES) return null // already withIndex() call
val potentialExpression = createWithIndexExpression(loopRange, reformat = false)
val newBindingContext = potentialExpression.analyzeAsReplacement(loopRange, bindingContext)
val newResolvedCall = potentialExpression.getResolvedCall(newBindingContext) ?: return null
if (newResolvedCall.resultingDescriptor.fqNameUnsafe.asString() !in WITH_INDEX_FQ_NAMES) return null
return TextRange(element.startOffset, element.body?.startOffset ?: element.endOffset)
}
override fun applyTo(element: KtForExpression, editor: Editor?) {
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val loopRange = element.loopRange!!
val loopParameter = element.loopParameter!!
val psiFactory = KtPsiFactory(element)
loopRange.replace(createWithIndexExpression(loopRange, reformat = true))
var multiParameter = (psiFactory.createExpressionByPattern(
"for((index, $0) in x){}",
loopParameter.text
) as KtForExpression).destructuringDeclaration!!
multiParameter = loopParameter.replaced(multiParameter)
val indexVariable = multiParameter.entries[0]
editor.caretModel.moveToOffset(indexVariable.startOffset)
runTemplate(editor, element, indexVariable)
}
private fun runTemplate(editor: Editor, forExpression: KtForExpression, indexVariable: KtDestructuringDeclarationEntry) {
PsiDocumentManager.getInstance(forExpression.project).doPostponedOperationsAndUnblockDocument(editor.document)
val templateBuilder = TemplateBuilderImpl(forExpression)
templateBuilder.replaceElement(indexVariable, ChooseStringExpression(listOf("index", "i")))
when (val body = forExpression.body) {
is KtBlockExpression -> {
val statement = body.statements.firstOrNull()
if (statement != null) {
templateBuilder.setEndVariableBefore(statement)
} else {
templateBuilder.setEndVariableAfter(body.lBrace)
}
}
null -> forExpression.rightParenthesis.let { templateBuilder.setEndVariableAfter(it) }
else -> templateBuilder.setEndVariableBefore(body)
}
templateBuilder.run(editor, true)
}
private fun createWithIndexExpression(originalExpression: KtExpression, reformat: Boolean): KtExpression =
KtPsiFactory(originalExpression).createExpressionByPattern(
"$0.$WITH_INDEX_NAME()", originalExpression,
reformat = reformat
)
}
| apache-2.0 | f2a090772cd47c4fffb8a5d685221bdc | 45.434343 | 158 | 0.734827 | 5.206116 | false | false | false | false |
JetBrains/kotlin-native | Interop/Indexer/src/main/kotlin/org/jetbrains/kotlin/native/interop/indexer/HeaderToIdMapper.kt | 4 | 1242 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.native.interop.indexer
import java.io.File
class HeaderToIdMapper(sysRoot: String) {
private val headerPathToId = mutableMapOf<String, HeaderId>()
private val sysRoot = File(sysRoot).canonicalFile.toPath()
internal fun getHeaderId(filePath: String) = headerPathToId.getOrPut(filePath) {
val path = File(filePath).canonicalFile.toPath()
val headerIdValue = if (path.startsWith(sysRoot)) {
val relative = sysRoot.relativize(path)
relative.toString()
} else {
headerContentsHash(filePath)
}
HeaderId(headerIdValue)
}
}
| apache-2.0 | bb13947527879c90d3c0ac7724cd2d26 | 34.485714 | 84 | 0.707729 | 4.195946 | false | false | false | false |
androidx/androidx | compose/foundation/foundation-layout/src/commonMain/kotlin/androidx/compose/foundation/layout/Intrinsic.kt | 3 | 10618 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.layout
import androidx.compose.runtime.Stable
import androidx.compose.ui.layout.LayoutModifier
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.IntrinsicMeasurable
import androidx.compose.ui.layout.IntrinsicMeasureScope
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.constrain
/**
* Declare the preferred width of the content to be the same as the min or max intrinsic width of
* the content. The incoming measurement [Constraints] may override this value, forcing the content
* to be either smaller or larger.
*
* See [height] for options of sizing to intrinsic height.
* Also see [width] and [widthIn] for other options to set the preferred width.
*
* Example usage for min intrinsic:
* @sample androidx.compose.foundation.layout.samples.SameWidthBoxes
*
* Example usage for max intrinsic:
* @sample androidx.compose.foundation.layout.samples.SameWidthTextBoxes
*/
@Stable
fun Modifier.width(intrinsicSize: IntrinsicSize) = when (intrinsicSize) {
IntrinsicSize.Min -> this.then(MinIntrinsicWidthModifier)
IntrinsicSize.Max -> this.then(MaxIntrinsicWidthModifier)
}
/**
* Declare the preferred height of the content to be the same as the min or max intrinsic height of
* the content. The incoming measurement [Constraints] may override this value, forcing the content
* to be either smaller or larger.
*
* See [width] for other options of sizing to intrinsic width.
* Also see [height] and [heightIn] for other options to set the preferred height.
*
* Example usage for min intrinsic:
* @sample androidx.compose.foundation.layout.samples.MatchParentDividerForText
*
* Example usage for max intrinsic:
* @sample androidx.compose.foundation.layout.samples.MatchParentDividerForAspectRatio
*/
@Stable
fun Modifier.height(intrinsicSize: IntrinsicSize) = when (intrinsicSize) {
IntrinsicSize.Min -> this.then(MinIntrinsicHeightModifier)
IntrinsicSize.Max -> this.then(MaxIntrinsicHeightModifier)
}
/**
* Declare the width of the content to be exactly the same as the min or max intrinsic width of
* the content. The incoming measurement [Constraints] will not override this value. If the content
* intrinsic width does not satisfy the incoming [Constraints], the parent layout will be
* reported a size coerced in the [Constraints], and the position of the content will be
* automatically offset to be centered on the space assigned to the child by the parent layout under
* the assumption that [Constraints] were respected.
*
* See [height] for options of sizing to intrinsic height.
* See [width] and [widthIn] for options to set the preferred width.
* See [requiredWidth] and [requiredWidthIn] for other options to set the required width.
*/
@Stable
fun Modifier.requiredWidth(intrinsicSize: IntrinsicSize) = when (intrinsicSize) {
IntrinsicSize.Min -> this.then(RequiredMinIntrinsicWidthModifier)
IntrinsicSize.Max -> this.then(RequiredMaxIntrinsicWidthModifier)
}
/**
* Declare the height of the content to be exactly the same as the min or max intrinsic height of
* the content. The incoming measurement [Constraints] will not override this value. If the content
* intrinsic height does not satisfy the incoming [Constraints], the parent layout will be
* reported a size coerced in the [Constraints], and the position of the content will be
* automatically offset to be centered on the space assigned to the child by the parent layout under
* the assumption that [Constraints] were respected.
*
* See [width] for options of sizing to intrinsic width.
* See [height] and [heightIn] for options to set the preferred height.
* See [requiredHeight] and [requiredHeightIn] for other options to set the required height.
*/
@Stable
fun Modifier.requiredHeight(intrinsicSize: IntrinsicSize) = when (intrinsicSize) {
IntrinsicSize.Min -> this.then(RequiredMinIntrinsicHeightModifier)
IntrinsicSize.Max -> this.then(RequiredMaxIntrinsicHeightModifier)
}
/**
* Intrinsic size used in [width] or [height] which can refer to width or height.
*/
enum class IntrinsicSize { Min, Max }
private object MinIntrinsicWidthModifier : IntrinsicSizeModifier {
override fun MeasureScope.calculateContentConstraints(
measurable: Measurable,
constraints: Constraints
): Constraints {
val width = measurable.minIntrinsicWidth(constraints.maxHeight)
return Constraints.fixedWidth(width)
}
override fun IntrinsicMeasureScope.maxIntrinsicWidth(
measurable: IntrinsicMeasurable,
height: Int
) = measurable.minIntrinsicWidth(height)
}
private object MinIntrinsicHeightModifier : IntrinsicSizeModifier {
override fun MeasureScope.calculateContentConstraints(
measurable: Measurable,
constraints: Constraints
): Constraints {
val height = measurable.minIntrinsicHeight(constraints.maxWidth)
return Constraints.fixedHeight(height)
}
override fun IntrinsicMeasureScope.maxIntrinsicHeight(
measurable: IntrinsicMeasurable,
width: Int
) = measurable.minIntrinsicHeight(width)
}
private object MaxIntrinsicWidthModifier : IntrinsicSizeModifier {
override fun MeasureScope.calculateContentConstraints(
measurable: Measurable,
constraints: Constraints
): Constraints {
val width = measurable.maxIntrinsicWidth(constraints.maxHeight)
return Constraints.fixedWidth(width)
}
override fun IntrinsicMeasureScope.minIntrinsicWidth(
measurable: IntrinsicMeasurable,
height: Int
) = measurable.maxIntrinsicWidth(height)
}
private object MaxIntrinsicHeightModifier : IntrinsicSizeModifier {
override fun MeasureScope.calculateContentConstraints(
measurable: Measurable,
constraints: Constraints
): Constraints {
val height = measurable.maxIntrinsicHeight(constraints.maxWidth)
return Constraints.fixedHeight(height)
}
override fun IntrinsicMeasureScope.minIntrinsicHeight(
measurable: IntrinsicMeasurable,
width: Int
) = measurable.maxIntrinsicHeight(width)
}
private object RequiredMinIntrinsicWidthModifier : IntrinsicSizeModifier {
override val enforceIncoming: Boolean = false
override fun MeasureScope.calculateContentConstraints(
measurable: Measurable,
constraints: Constraints
): Constraints {
val width = measurable.minIntrinsicWidth(constraints.maxHeight)
return Constraints.fixedWidth(width)
}
override fun IntrinsicMeasureScope.maxIntrinsicWidth(
measurable: IntrinsicMeasurable,
height: Int
) = measurable.minIntrinsicWidth(height)
}
private object RequiredMinIntrinsicHeightModifier : IntrinsicSizeModifier {
override val enforceIncoming: Boolean = false
override fun MeasureScope.calculateContentConstraints(
measurable: Measurable,
constraints: Constraints
): Constraints {
val height = measurable.minIntrinsicHeight(constraints.maxWidth)
return Constraints.fixedHeight(height)
}
override fun IntrinsicMeasureScope.maxIntrinsicHeight(
measurable: IntrinsicMeasurable,
width: Int
) = measurable.minIntrinsicHeight(width)
}
private object RequiredMaxIntrinsicWidthModifier : IntrinsicSizeModifier {
override val enforceIncoming: Boolean = false
override fun MeasureScope.calculateContentConstraints(
measurable: Measurable,
constraints: Constraints
): Constraints {
val width = measurable.maxIntrinsicWidth(constraints.maxHeight)
return Constraints.fixedWidth(width)
}
override fun IntrinsicMeasureScope.minIntrinsicWidth(
measurable: IntrinsicMeasurable,
height: Int
) = measurable.maxIntrinsicWidth(height)
}
private object RequiredMaxIntrinsicHeightModifier : IntrinsicSizeModifier {
override val enforceIncoming: Boolean = false
override fun MeasureScope.calculateContentConstraints(
measurable: Measurable,
constraints: Constraints
): Constraints {
val height = measurable.maxIntrinsicHeight(constraints.maxWidth)
return Constraints.fixedHeight(height)
}
override fun IntrinsicMeasureScope.minIntrinsicHeight(
measurable: IntrinsicMeasurable,
width: Int
) = measurable.maxIntrinsicHeight(width)
}
private interface IntrinsicSizeModifier : LayoutModifier {
val enforceIncoming: Boolean get() = true
fun MeasureScope.calculateContentConstraints(
measurable: Measurable,
constraints: Constraints
): Constraints
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val contentConstraints = calculateContentConstraints(measurable, constraints)
val placeable = measurable.measure(
if (enforceIncoming) constraints.constrain(contentConstraints) else contentConstraints
)
return layout(placeable.width, placeable.height) {
placeable.placeRelative(IntOffset.Zero)
}
}
override fun IntrinsicMeasureScope.minIntrinsicWidth(
measurable: IntrinsicMeasurable,
height: Int
) = measurable.minIntrinsicWidth(height)
override fun IntrinsicMeasureScope.minIntrinsicHeight(
measurable: IntrinsicMeasurable,
width: Int
) = measurable.minIntrinsicHeight(width)
override fun IntrinsicMeasureScope.maxIntrinsicWidth(
measurable: IntrinsicMeasurable,
height: Int
) = measurable.maxIntrinsicWidth(height)
override fun IntrinsicMeasureScope.maxIntrinsicHeight(
measurable: IntrinsicMeasurable,
width: Int
) = measurable.maxIntrinsicHeight(width)
}
| apache-2.0 | 873e0e63a8210bde4c6a55328db54b08 | 36.921429 | 100 | 0.751931 | 4.989662 | false | false | false | false |
androidx/androidx | glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/RemoteViewsRoot.kt | 3 | 1372 | /*
* 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.glance.appwidget
import androidx.glance.Emittable
import androidx.glance.EmittableWithChildren
import androidx.glance.GlanceModifier
/**
* Root view, with a maximum depth. No default value is specified, as the exact value depends on
* specific circumstances.
*/
internal class RemoteViewsRoot(private val maxDepth: Int) : EmittableWithChildren(maxDepth) {
override var modifier: GlanceModifier = GlanceModifier
override fun copy(): Emittable = RemoteViewsRoot(maxDepth).also {
it.modifier = modifier
it.children.addAll(children.map { it.copy() })
}
override fun toString(): String = "RemoteViewsRoot(" +
"modifier=$modifier, " +
"children=[\n${childrenToString()}\n]" +
")"
}
| apache-2.0 | 09d797ac4742d224ad33cb5cd5bf6026 | 35.105263 | 96 | 0.72449 | 4.341772 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/DynamicPluginVfsListener.kt | 4 | 4998 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.plugins
import com.intellij.ide.IdeBundle
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationActivationListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.PreloadingActivity
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.vfs.AsyncFileListener
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.RefreshQueue
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.wm.IdeFrame
import java.nio.file.Path
private const val AUTO_RELOAD_PLUGINS_SYSTEM_PROPERTY = "idea.auto.reload.plugins"
private var initialRefreshDone = false
internal class DynamicPluginVfsListenerInitializer : PreloadingActivity() {
override suspend fun execute() {
if (java.lang.Boolean.getBoolean(AUTO_RELOAD_PLUGINS_SYSTEM_PROPERTY)) {
val pluginsPath = PathManager.getPluginsPath()
LocalFileSystem.getInstance().addRootToWatch(pluginsPath, true)
val pluginsRoot = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(Path.of(pluginsPath))
if (pluginsRoot != null) {
// ensure all plugins are in VFS
VfsUtilCore.processFilesRecursively(pluginsRoot) { true }
RefreshQueue.getInstance().refresh(true, true, Runnable { initialRefreshDone = true }, pluginsRoot)
}
else {
DynamicPluginVfsListener.LOG.info("Dynamic plugin VFS listener not active, couldn't find plugins root in VFS")
}
}
}
}
internal class DynamicPluginVfsListener : AsyncFileListener {
override fun prepareChange(events: List<VFileEvent>): AsyncFileListener.ChangeApplier? {
if (!java.lang.Boolean.getBoolean(AUTO_RELOAD_PLUGINS_SYSTEM_PROPERTY)) return null
if (!initialRefreshDone) return null
val pluginsToReload = hashSetOf<IdeaPluginDescriptorImpl>()
for (event in events) {
if (!event.isFromRefresh) continue
if (event is VFileContentChangeEvent) {
findPluginByPath(event.file)?.let {
LOG.info("Detected plugin .jar file change ${event.path}, reloading plugin")
pluginsToReload.add(it)
}
}
}
val descriptorsToReload = pluginsToReload.filter { it.isEnabled && DynamicPlugins.allowLoadUnloadWithoutRestart(it) }
if (descriptorsToReload.isEmpty()) {
return null
}
return object : AsyncFileListener.ChangeApplier {
override fun afterVfsChange() {
ApplicationManager.getApplication().invokeLater {
val reloaded = mutableListOf<String>()
val unloadFailed = mutableListOf<String>()
for (pluginDescriptor in descriptorsToReload) {
if (!DynamicPlugins.unloadPlugin(pluginDescriptor, DynamicPlugins.UnloadPluginOptions(isUpdate = true, waitForClassloaderUnload = true))) {
unloadFailed.add(pluginDescriptor.name)
continue
}
reloaded.add(pluginDescriptor.name)
DynamicPlugins.loadPlugin(pluginDescriptor)
}
if (unloadFailed.isNotEmpty()) {
DynamicPlugins.notify(IdeBundle.message("failed.to.unload.modified.plugins", unloadFailed.joinToString()), NotificationType.INFORMATION,
object : AnAction(IdeBundle.message("ide.restart.action")) {
override fun actionPerformed(e: AnActionEvent) {
ApplicationManager.getApplication().restart()
}
})
}
else if (reloaded.isNotEmpty()) {
DynamicPlugins.notify(IdeBundle.message("plugins.reloaded.successfully", reloaded.joinToString()), NotificationType.INFORMATION)
}
}
}
}
}
private fun findPluginByPath(file: VirtualFile): IdeaPluginDescriptorImpl? {
if (!VfsUtilCore.isAncestorOrSelf(PathManager.getPluginsPath(), file)) {
return null
}
return PluginManager.getPlugins().firstOrNull {
VfsUtilCore.isAncestorOrSelf(it.pluginPath.toAbsolutePath().toString(), file)
} as IdeaPluginDescriptorImpl?
}
companion object {
val LOG = Logger.getInstance(DynamicPluginVfsListener::class.java)
}
}
class DynamicPluginsFrameStateListener : ApplicationActivationListener {
override fun applicationActivated(ideFrame: IdeFrame) {
if (!java.lang.Boolean.getBoolean(AUTO_RELOAD_PLUGINS_SYSTEM_PROPERTY)) return
val pluginsRoot = LocalFileSystem.getInstance().findFileByPath(PathManager.getPluginsPath())
pluginsRoot?.refresh(true, true)
}
}
| apache-2.0 | 629637d4e8699acdb2955d57fbd8602d | 42.086207 | 151 | 0.733293 | 4.914454 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinClassifierProcessor.kt | 1 | 5928 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.SearchScope
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings
import org.jetbrains.kotlin.idea.refactoring.withExpectedActuals
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.SmartList
class RenameKotlinClassifierProcessor : RenameKotlinPsiProcessor() {
override fun canProcessElement(element: PsiElement): Boolean {
return element is KtClassOrObject || element is KtLightClass || element is KtConstructor<*> || element is KtTypeAlias
}
override fun isToSearchInComments(psiElement: PsiElement) = KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_CLASS
override fun setToSearchInComments(element: PsiElement, enabled: Boolean) {
KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_CLASS = enabled
}
override fun isToSearchForTextOccurrences(element: PsiElement) = KotlinRefactoringSettings.instance.RENAME_SEARCH_FOR_TEXT_FOR_CLASS
override fun setToSearchForTextOccurrences(element: PsiElement, enabled: Boolean) {
KotlinRefactoringSettings.instance.RENAME_SEARCH_FOR_TEXT_FOR_CLASS = enabled
}
override fun substituteElementToRename(element: PsiElement, editor: Editor?) = getClassOrObject(element)
override fun prepareRenaming(element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>) {
super.prepareRenaming(element, newName, allRenames)
val classOrObject = getClassOrObject(element) as? KtClassOrObject ?: return
classOrObject.withExpectedActuals().forEach {
val file = it.containingKtFile
val virtualFile = file.virtualFile
if (virtualFile != null) {
val nameWithoutExtensions = virtualFile.nameWithoutExtension
if (nameWithoutExtensions == it.name) {
val newFileName = newName + "." + virtualFile.extension
allRenames.put(file, newFileName)
forElement(file).prepareRenaming(file, newFileName, allRenames)
}
}
}
}
protected fun processFoundReferences(
element: PsiElement,
references: Collection<PsiReference>
): Collection<PsiReference> {
if (element is KtObjectDeclaration && element.isCompanion()) {
return references.filter { !it.isCompanionObjectClassReference() }
}
return references
}
private fun PsiReference.isCompanionObjectClassReference(): Boolean {
if (this !is KtSimpleNameReference) {
return false
}
val bindingContext = element.analyze(BodyResolveMode.PARTIAL)
return bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, element] != null
}
override fun findCollisions(
element: PsiElement,
newName: String,
allRenames: MutableMap<out PsiElement, String>,
result: MutableList<UsageInfo>
) {
val declaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return
val collisions = SmartList<UsageInfo>()
checkRedeclarations(declaration, newName, collisions)
checkOriginalUsagesRetargeting(declaration, newName, result, collisions)
checkNewNameUsagesRetargeting(declaration, newName, collisions)
result += collisions
}
private fun getClassOrObject(element: PsiElement?): PsiElement? = when (element) {
is KtLightClass ->
when (element) {
is KtLightClassForSourceDeclaration -> element.kotlinOrigin
is KtLightClassForFacade -> element
else -> throw AssertionError("Should not be suggested to rename element of type " + element::class.java + " " + element)
}
is KtConstructor<*> ->
element.getContainingClassOrObject()
is KtClassOrObject, is KtTypeAlias -> element
else -> null
}
override fun renameElement(element: PsiElement, newName: String, usages: Array<UsageInfo>, listener: RefactoringElementListener?) {
val simpleUsages = ArrayList<UsageInfo>(usages.size)
val ambiguousImportUsages = com.intellij.util.SmartList<UsageInfo>()
for (usage in usages) {
if (usage.isAmbiguousImportUsage()) {
ambiguousImportUsages += usage
} else {
simpleUsages += usage
}
}
element.ambiguousImportUsages = ambiguousImportUsages
super.renameElement(element, newName, simpleUsages.toTypedArray(), listener)
usages.forEach { (it as? KtResolvableCollisionUsageInfo)?.apply() }
}
override fun findReferences(
element: PsiElement,
searchScope: SearchScope,
searchInCommentsAndStrings: Boolean
): Collection<PsiReference> {
val references = super.findReferences(element, searchScope, searchInCommentsAndStrings)
return processFoundReferences(element, references)
}
}
| apache-2.0 | c20c57cc30ee5da6d827a64ca96f1bb5 | 41.956522 | 158 | 0.71525 | 5.37931 | false | false | false | false |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/fragments/WeekFragment.kt | 1 | 39162 | package com.simplemobiletools.calendar.pro.fragments
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipDescription
import android.content.Intent
import android.content.res.Resources
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Handler
import android.util.Range
import android.view.*
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.collection.LongSparseArray
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import com.simplemobiletools.calendar.pro.R
import com.simplemobiletools.calendar.pro.extensions.*
import com.simplemobiletools.calendar.pro.helpers.*
import com.simplemobiletools.calendar.pro.helpers.Formatter
import com.simplemobiletools.calendar.pro.interfaces.WeekFragmentListener
import com.simplemobiletools.calendar.pro.interfaces.WeeklyCalendar
import com.simplemobiletools.calendar.pro.models.Event
import com.simplemobiletools.calendar.pro.models.EventWeeklyView
import com.simplemobiletools.calendar.pro.views.MyScrollView
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.commons.views.MyTextView
import kotlinx.android.synthetic.main.fragment_week.*
import kotlinx.android.synthetic.main.fragment_week.view.*
import kotlinx.android.synthetic.main.week_event_marker.view.*
import org.joda.time.DateTime
import org.joda.time.Days
import java.util.*
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
class WeekFragment : Fragment(), WeeklyCalendar {
private val WEEKLY_EVENT_ID_LABEL = "event_id_label"
private val PLUS_FADEOUT_DELAY = 5000L
private val MIN_SCALE_FACTOR = 0.3f
private val MAX_SCALE_FACTOR = 5f
private val MIN_SCALE_DIFFERENCE = 0.02f
private val SCALE_RANGE = MAX_SCALE_FACTOR - MIN_SCALE_FACTOR
var listener: WeekFragmentListener? = null
private var weekTimestamp = 0L
private var rowHeight = 0f
private var todayColumnIndex = -1
private var primaryColor = 0
private var lastHash = 0
private var prevScaleSpanY = 0f
private var scaleCenterPercent = 0f
private var defaultRowHeight = 0f
private var screenHeight = 0
private var rowHeightsAtScale = 0f
private var prevScaleFactor = 0f
private var mWasDestroyed = false
private var isFragmentVisible = false
private var wasFragmentInit = false
private var wasExtraHeightAdded = false
private var dimPastEvents = true
private var dimCompletedTasks = true
private var highlightWeekends = false
private var wasScaled = false
private var isPrintVersion = false
private var selectedGrid: View? = null
private var currentTimeView: ImageView? = null
private var fadeOutHandler = Handler()
private var allDayHolders = ArrayList<RelativeLayout>()
private var allDayRows = ArrayList<HashSet<Int>>()
private var allDayEventToRow = LinkedHashMap<Event, Int>()
private var currEvents = ArrayList<Event>()
private var dayColumns = ArrayList<RelativeLayout>()
private var eventTypeColors = LongSparseArray<Int>()
private var eventTimeRanges = LinkedHashMap<String, LinkedHashMap<Long, EventWeeklyView>>()
private var currentlyDraggedView: View? = null
private lateinit var inflater: LayoutInflater
private lateinit var mView: View
private lateinit var scrollView: MyScrollView
private lateinit var res: Resources
private lateinit var config: Config
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
res = requireContext().resources
config = requireContext().config
rowHeight = requireContext().getWeeklyViewItemHeight()
defaultRowHeight = res.getDimension(R.dimen.weekly_view_row_height)
weekTimestamp = requireArguments().getLong(WEEK_START_TIMESTAMP)
dimPastEvents = config.dimPastEvents
dimCompletedTasks = config.dimCompletedTasks
highlightWeekends = config.highlightWeekends
primaryColor = requireContext().getProperPrimaryColor()
allDayRows.add(HashSet())
}
@SuppressLint("ClickableViewAccessibility")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
this.inflater = inflater
val fullHeight = requireContext().getWeeklyViewItemHeight().toInt() * 24
mView = inflater.inflate(R.layout.fragment_week, container, false).apply {
scrollView = week_events_scrollview
week_horizontal_grid_holder.layoutParams.height = fullHeight
week_events_columns_holder.layoutParams.height = fullHeight
val scaleDetector = getViewScaleDetector()
scrollView.setOnTouchListener { view, motionEvent ->
scaleDetector.onTouchEvent(motionEvent)
if (motionEvent.action == MotionEvent.ACTION_UP && wasScaled) {
scrollView.isScrollable = true
wasScaled = false
true
} else {
false
}
}
}
addDayColumns()
scrollView.setOnScrollviewListener(object : MyScrollView.ScrollViewListener {
override fun onScrollChanged(scrollView: MyScrollView, x: Int, y: Int, oldx: Int, oldy: Int) {
checkScrollLimits(y)
}
})
scrollView.onGlobalLayout {
if (fullHeight < scrollView.height) {
scrollView.layoutParams.height = fullHeight - res.getDimension(R.dimen.one_dp).toInt()
}
val initialScrollY = (rowHeight * config.startWeeklyAt).toInt()
updateScrollY(max(listener?.getCurrScrollY() ?: 0, initialScrollY))
}
wasFragmentInit = true
return mView
}
override fun onResume() {
super.onResume()
requireContext().eventsHelper.getEventTypes(requireActivity(), false) {
it.map { eventType ->
eventTypeColors.put(eventType.id!!, eventType.color)
}
}
setupDayLabels()
updateCalendar()
if (rowHeight != 0f && mView.width != 0) {
addCurrentTimeIndicator()
}
}
override fun onPause() {
super.onPause()
wasExtraHeightAdded = true
}
override fun onDestroyView() {
super.onDestroyView()
mWasDestroyed = true
}
override fun setMenuVisibility(menuVisible: Boolean) {
super.setMenuVisibility(menuVisible)
isFragmentVisible = menuVisible
if (isFragmentVisible && wasFragmentInit) {
listener?.updateHoursTopMargin(mView.week_top_holder.height)
checkScrollLimits(scrollView.scrollY)
// fix some glitches like at swiping from a fully scaled out fragment with all-day events to an empty one
val fullFragmentHeight = (listener?.getFullFragmentHeight() ?: 0) - mView.week_top_holder.height
if (scrollView.height < fullFragmentHeight) {
config.weeklyViewItemHeightMultiplier = fullFragmentHeight / 24 / defaultRowHeight
updateViewScale()
listener?.updateRowHeight(rowHeight.toInt())
}
}
}
fun updateCalendar() {
if (context != null) {
WeeklyCalendarImpl(this, requireContext()).updateWeeklyCalendar(weekTimestamp)
}
}
private fun addDayColumns() {
mView.week_events_columns_holder.removeAllViews()
(0 until config.weeklyViewDays).forEach {
val column = inflater.inflate(R.layout.weekly_view_day_column, mView.week_events_columns_holder, false) as RelativeLayout
column.tag = Formatter.getUTCDayCodeFromTS(weekTimestamp + it * DAY_SECONDS)
mView.week_events_columns_holder.addView(column)
dayColumns.add(column)
}
}
private fun setupDayLabels() {
var curDay = Formatter.getUTCDateTimeFromTS(weekTimestamp)
val todayCode = Formatter.getDayCodeFromDateTime(DateTime())
val screenWidth = context?.usableScreenSize?.x ?: return
val dayWidth = screenWidth / config.weeklyViewDays
val useLongerDayLabels = dayWidth > res.getDimension(R.dimen.weekly_view_min_day_label)
mView.week_letters_holder.removeAllViews()
for (i in 0 until config.weeklyViewDays) {
val dayCode = Formatter.getDayCodeFromDateTime(curDay)
val labelIDs = if (useLongerDayLabels) {
R.array.week_days_short
} else {
R.array.week_day_letters
}
val dayLetters = res.getStringArray(labelIDs).toMutableList() as ArrayList<String>
val dayLetter = dayLetters[curDay.dayOfWeek - 1]
val textColor = if (isPrintVersion) {
resources.getColor(R.color.theme_light_text_color)
} else if (todayCode == dayCode) {
primaryColor
} else if (highlightWeekends && isWeekend(curDay.dayOfWeek, true)) {
config.highlightWeekendsColor
} else {
requireContext().getProperTextColor()
}
val label = inflater.inflate(R.layout.weekly_view_day_letter, mView.week_letters_holder, false) as MyTextView
label.text = "$dayLetter\n${curDay.dayOfMonth}"
label.setTextColor(textColor)
if (todayCode == dayCode) {
todayColumnIndex = i
}
mView.week_letters_holder.addView(label)
curDay = curDay.plusDays(1)
}
}
private fun checkScrollLimits(y: Int) {
if (isFragmentVisible) {
listener?.scrollTo(y)
}
}
private fun initGrid() {
(0 until config.weeklyViewDays).mapNotNull { dayColumns.getOrNull(it) }
.forEachIndexed { index, layout ->
layout.removeAllViews()
val gestureDetector = getViewGestureDetector(layout, index)
layout.setOnTouchListener { view, motionEvent ->
gestureDetector.onTouchEvent(motionEvent)
true
}
layout.setOnDragListener { view, dragEvent ->
when (dragEvent.action) {
DragEvent.ACTION_DRAG_STARTED -> dragEvent.clipDescription.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)
DragEvent.ACTION_DRAG_ENTERED,
DragEvent.ACTION_DRAG_EXITED,
DragEvent.ACTION_DRAG_LOCATION,
DragEvent.ACTION_DRAG_ENDED -> true
DragEvent.ACTION_DROP -> {
try {
val eventId = dragEvent.clipData.getItemAt(0).text.toString().toLong()
val startHour = (dragEvent.y / rowHeight).toInt()
ensureBackgroundThread {
val event = context?.eventsDB?.getEventOrTaskWithId(eventId)
event?.let {
val currentStartTime = Formatter.getDateTimeFromTS(it.startTS)
val startTime = Formatter.getDateTimeFromTS(weekTimestamp + index * DAY_SECONDS)
.withTime(
startHour,
currentStartTime.minuteOfHour,
currentStartTime.secondOfMinute,
currentStartTime.millisOfSecond
).seconds()
val currentEventDuration = event.endTS - event.startTS
val endTime = startTime + currentEventDuration
context?.eventsHelper?.updateEvent(
it.copy(
startTS = startTime,
endTS = endTime,
flags = it.flags.removeBit(FLAG_ALL_DAY)
), updateAtCalDAV = true, showToasts = false
) {
updateCalendar()
}
}
}
true
} catch (ignored: Exception) {
false
}
}
else -> false
}
}
}
}
private fun getViewGestureDetector(view: ViewGroup, index: Int): GestureDetector {
return GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(event: MotionEvent): Boolean {
selectedGrid?.animation?.cancel()
selectedGrid?.beGone()
val hour = (event.y / rowHeight).toInt()
selectedGrid = (inflater.inflate(R.layout.week_grid_item, null, false) as ImageView).apply {
view.addView(this)
background = ColorDrawable(primaryColor)
layoutParams.width = view.width
layoutParams.height = rowHeight.toInt()
y = hour * rowHeight
applyColorFilter(primaryColor.getContrastColor())
setOnClickListener {
val timestamp = Formatter.getDateTimeFromTS(weekTimestamp + index * DAY_SECONDS).withTime(hour, 0, 0, 0).seconds()
if (config.allowCreatingTasks) {
val items = arrayListOf(
RadioItem(TYPE_EVENT, getString(R.string.event)),
RadioItem(TYPE_TASK, getString(R.string.task))
)
RadioGroupDialog(activity!!, items) {
launchNewEventIntent(timestamp, it as Int == TYPE_TASK)
}
} else {
launchNewEventIntent(timestamp, false)
}
}
// do not use setStartDelay, it will trigger instantly if the device has disabled animations
fadeOutHandler.removeCallbacksAndMessages(null)
fadeOutHandler.postDelayed({
animate().alpha(0f).withEndAction {
beGone()
}
}, PLUS_FADEOUT_DELAY)
}
return super.onSingleTapUp(event)
}
})
}
private fun launchNewEventIntent(timestamp: Long, isTask: Boolean) {
Intent(context, getActivityToOpen(isTask)).apply {
putExtra(NEW_EVENT_START_TS, timestamp)
putExtra(NEW_EVENT_SET_HOUR_DURATION, true)
startActivity(this)
}
}
private fun getViewScaleDetector(): ScaleGestureDetector {
return ScaleGestureDetector(requireContext(), object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
val percent = (prevScaleSpanY - detector.currentSpanY) / screenHeight
prevScaleSpanY = detector.currentSpanY
val wantedFactor = config.weeklyViewItemHeightMultiplier - (SCALE_RANGE * percent)
var newFactor = max(min(wantedFactor, MAX_SCALE_FACTOR), MIN_SCALE_FACTOR)
if (scrollView.height > defaultRowHeight * newFactor * 24) {
newFactor = scrollView.height / 24f / defaultRowHeight
}
if (Math.abs(newFactor - prevScaleFactor) > MIN_SCALE_DIFFERENCE) {
prevScaleFactor = newFactor
config.weeklyViewItemHeightMultiplier = newFactor
updateViewScale()
listener?.updateRowHeight(rowHeight.toInt())
val targetY = rowHeightsAtScale * rowHeight - scaleCenterPercent * getVisibleHeight()
scrollView.scrollTo(0, targetY.toInt())
}
return super.onScale(detector)
}
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
scaleCenterPercent = detector.focusY / scrollView.height
rowHeightsAtScale = (scrollView.scrollY + scaleCenterPercent * getVisibleHeight()) / rowHeight
scrollView.isScrollable = false
prevScaleSpanY = detector.currentSpanY
prevScaleFactor = config.weeklyViewItemHeightMultiplier
wasScaled = true
screenHeight = context!!.realScreenSize.y
return super.onScaleBegin(detector)
}
})
}
private fun getVisibleHeight(): Float {
val fullContentHeight = rowHeight * 24
val visibleRatio = scrollView.height / fullContentHeight
return fullContentHeight * visibleRatio
}
override fun updateWeeklyCalendar(events: ArrayList<Event>) {
val newHash = events.hashCode()
if (newHash == lastHash || mWasDestroyed || context == null) {
return
}
lastHash = newHash
requireActivity().runOnUiThread {
if (context != null && activity != null && isAdded) {
val replaceDescription = config.replaceDescription
val sorted = events.sortedWith(
compareBy<Event> { it.startTS }.thenBy { it.endTS }.thenBy { it.title }.thenBy { if (replaceDescription) it.location else it.description }
).toMutableList() as ArrayList<Event>
currEvents = sorted
addEvents(sorted)
}
}
}
private fun updateViewScale() {
rowHeight = context?.getWeeklyViewItemHeight() ?: return
val oneDp = res.getDimension(R.dimen.one_dp).toInt()
val fullHeight = max(rowHeight.toInt() * 24, scrollView.height + oneDp)
scrollView.layoutParams.height = fullHeight - oneDp
mView.week_horizontal_grid_holder.layoutParams.height = fullHeight
mView.week_events_columns_holder.layoutParams.height = fullHeight
addEvents(currEvents)
}
private fun addEvents(events: ArrayList<Event>) {
initGrid()
allDayHolders.clear()
allDayRows.clear()
eventTimeRanges.clear()
allDayRows.add(HashSet())
week_all_day_holder?.removeAllViews()
addNewLine()
allDayEventToRow.clear()
val minuteHeight = rowHeight / 60
val minimalHeight = res.getDimension(R.dimen.weekly_view_minimal_event_height).toInt()
val density = res.displayMetrics.density.roundToInt()
for (event in events) {
val startDateTime = Formatter.getDateTimeFromTS(event.startTS)
val startDayCode = Formatter.getDayCodeFromDateTime(startDateTime)
val endDateTime = Formatter.getDateTimeFromTS(event.endTS)
val endDayCode = Formatter.getDayCodeFromDateTime(endDateTime)
val isAllDay = event.getIsAllDay()
if ((isAllDay || (startDayCode != endDayCode)) && config.showMidnightSpanningEventsAtTop) {
continue
}
var currentDateTime = startDateTime
var currentDayCode = Formatter.getDayCodeFromDateTime(currentDateTime)
do {
// all-day events always start at the 0 minutes and end at the end of the day (1440 minutes)
val startMinutes = when {
currentDayCode == startDayCode && !isAllDay -> (startDateTime.minuteOfDay)
else -> 0
}
val duration = when {
currentDayCode == endDayCode && !isAllDay -> (endDateTime.minuteOfDay - startMinutes)
else -> 1440
}
var endMinutes = startMinutes + duration
if ((endMinutes - startMinutes) * minuteHeight < minimalHeight) {
endMinutes = startMinutes + (minimalHeight / minuteHeight).toInt()
}
val range = Range(startMinutes, endMinutes)
val eventWeekly = EventWeeklyView(range)
if (!eventTimeRanges.containsKey(currentDayCode)) {
eventTimeRanges[currentDayCode] = LinkedHashMap()
}
eventTimeRanges[currentDayCode]?.put(event.id!!, eventWeekly)
currentDateTime = currentDateTime.plusDays(1)
currentDayCode = Formatter.getDayCodeFromDateTime(currentDateTime)
} while (currentDayCode.toInt() <= endDayCode.toInt())
}
for ((_, eventDayList) in eventTimeRanges) {
val eventsCollisionChecked = ArrayList<Long>()
for ((eventId, eventWeeklyView) in eventDayList) {
if (eventWeeklyView.slot == 0) {
eventWeeklyView.slot = 1
eventWeeklyView.slot_max = 1
}
eventsCollisionChecked.add(eventId)
val eventWeeklyViewsToCheck = eventDayList.filterNot { eventsCollisionChecked.contains(it.key) }
for ((toCheckId, eventWeeklyViewToCheck) in eventWeeklyViewsToCheck) {
val areTouching = eventWeeklyView.range.intersects(eventWeeklyViewToCheck.range)
val doHaveCommonMinutes = if (areTouching) {
eventWeeklyView.range.upper > eventWeeklyViewToCheck.range.lower || (eventWeeklyView.range.lower == eventWeeklyView.range.upper &&
eventWeeklyView.range.upper == eventWeeklyViewToCheck.range.lower)
} else {
false
}
if (areTouching && doHaveCommonMinutes) {
if (eventWeeklyViewToCheck.slot == 0) {
val nextSlot = eventWeeklyView.slot_max + 1
val slotRange = Array(eventWeeklyView.slot_max) { it + 1 }
val collisionEventWeeklyViews = eventDayList.filter { eventWeeklyView.collisions.contains(it.key) }
for ((_, collisionEventWeeklyView) in collisionEventWeeklyViews) {
if (collisionEventWeeklyView.range.intersects(eventWeeklyViewToCheck.range)) {
slotRange[collisionEventWeeklyView.slot - 1] = nextSlot
}
}
slotRange[eventWeeklyView.slot - 1] = nextSlot
val slot = slotRange.minOrNull()
eventWeeklyViewToCheck.slot = slot!!
if (slot == nextSlot) {
eventWeeklyViewToCheck.slot_max = nextSlot
eventWeeklyView.slot_max = nextSlot
for ((_, collisionEventWeeklyView) in collisionEventWeeklyViews) {
collisionEventWeeklyView.slot_max++
}
} else {
eventWeeklyViewToCheck.slot_max = eventWeeklyView.slot_max
}
}
eventWeeklyView.collisions.add(toCheckId)
eventWeeklyViewToCheck.collisions.add(eventId)
}
}
}
}
dayevents@ for (event in events) {
val startDateTime = Formatter.getDateTimeFromTS(event.startTS)
val startDayCode = Formatter.getDayCodeFromDateTime(startDateTime)
val endDateTime = Formatter.getDateTimeFromTS(event.endTS)
val endDayCode = Formatter.getDayCodeFromDateTime(endDateTime)
if ((event.getIsAllDay() || (startDayCode != endDayCode)) && config.showMidnightSpanningEventsAtTop) {
addAllDayEvent(event)
} else {
var currentDateTime = startDateTime
var currentDayCode = Formatter.getDayCodeFromDateTime(currentDateTime)
do {
val dayOfWeek = dayColumns.indexOfFirst { it.tag == currentDayCode }
if (dayOfWeek == -1 || dayOfWeek >= config.weeklyViewDays) {
continue@dayevents
}
val dayColumn = dayColumns[dayOfWeek]
(inflater.inflate(R.layout.week_event_marker, null, false) as ConstraintLayout).apply {
var backgroundColor = eventTypeColors.get(event.eventType, primaryColor)
var textColor = backgroundColor.getContrastColor()
val currentEventWeeklyView = eventTimeRanges[currentDayCode]!!.get(event.id)
val adjustAlpha = if (event.isTask()) {
dimCompletedTasks && event.isTaskCompleted()
} else {
dimPastEvents && event.isPastEvent && !isPrintVersion
}
if (adjustAlpha) {
backgroundColor = backgroundColor.adjustAlpha(MEDIUM_ALPHA)
textColor = textColor.adjustAlpha(HIGHER_ALPHA)
}
background = ColorDrawable(backgroundColor)
dayColumn.addView(this)
y = currentEventWeeklyView!!.range.lower * minuteHeight
week_event_task_image.beVisibleIf(event.isTask())
if (event.isTask()) {
week_event_task_image.applyColorFilter(textColor)
}
week_event_label.apply {
setTextColor(textColor)
maxLines = if (event.isTask() || event.startTS == event.endTS) {
1
} else {
3
}
text = event.title
checkViewStrikeThrough(event.isTaskCompleted())
contentDescription = text
minHeight = if (event.startTS == event.endTS) {
minimalHeight
} else {
((currentEventWeeklyView.range.upper - currentEventWeeklyView.range.lower) * minuteHeight).toInt() - 1
}
}
(layoutParams as RelativeLayout.LayoutParams).apply {
width = (dayColumn.width - 1) / currentEventWeeklyView.slot_max
x = (width * (currentEventWeeklyView.slot - 1)).toFloat()
if (currentEventWeeklyView.slot > 1) {
x += density
width -= density
}
}
setOnClickListener {
Intent(context, getActivityToOpen(event.isTask())).apply {
putExtra(EVENT_ID, event.id!!)
putExtra(EVENT_OCCURRENCE_TS, event.startTS)
putExtra(IS_TASK_COMPLETED, event.isTaskCompleted())
startActivity(this)
}
}
setOnLongClickListener { view ->
currentlyDraggedView = view
val shadowBuilder = View.DragShadowBuilder(view)
val clipData = ClipData.newPlainText(WEEKLY_EVENT_ID_LABEL, event.id.toString())
if (isNougatPlus()) {
view.startDragAndDrop(clipData, shadowBuilder, null, 0)
} else {
view.startDrag(clipData, shadowBuilder, null, 0)
}
true
}
setOnDragListener(DragListener())
}
currentDateTime = currentDateTime.plusDays(1)
currentDayCode = Formatter.getDayCodeFromDateTime(currentDateTime)
} while (currentDayCode.toInt() <= endDayCode.toInt())
}
}
checkTopHolderHeight()
addCurrentTimeIndicator()
}
private fun addNewLine() {
val allDaysLine = inflater.inflate(R.layout.all_day_events_holder_line, null, false) as RelativeLayout
week_all_day_holder?.addView(allDaysLine)
allDayHolders.add(allDaysLine)
}
private fun addCurrentTimeIndicator() {
if (todayColumnIndex != -1) {
val calendar = Calendar.getInstance()
val minutes = calendar.get(Calendar.HOUR_OF_DAY) * 60 + calendar.get(Calendar.MINUTE)
if (todayColumnIndex >= dayColumns.size) {
currentTimeView?.alpha = 0f
return
}
if (currentTimeView != null) {
mView.week_events_holder.removeView(currentTimeView)
}
if (isPrintVersion) {
return
}
val weeklyViewDays = config.weeklyViewDays
currentTimeView = (inflater.inflate(R.layout.week_now_marker, null, false) as ImageView).apply {
applyColorFilter(primaryColor)
mView.week_events_holder.addView(this, 0)
val extraWidth = res.getDimension(R.dimen.activity_margin).toInt()
val markerHeight = res.getDimension(R.dimen.weekly_view_now_height).toInt()
val minuteHeight = rowHeight / 60
(layoutParams as RelativeLayout.LayoutParams).apply {
width = (mView.width / weeklyViewDays) + extraWidth
height = markerHeight
}
x = if (weeklyViewDays == 1) {
0f
} else {
(mView.width / weeklyViewDays * todayColumnIndex).toFloat() - extraWidth / 2f
}
y = minutes * minuteHeight - markerHeight / 2
}
}
}
private fun checkTopHolderHeight() {
mView.week_top_holder.onGlobalLayout {
if (isFragmentVisible && activity != null && !mWasDestroyed) {
listener?.updateHoursTopMargin(mView.week_top_holder.height)
}
}
}
@SuppressLint("NewApi")
private fun addAllDayEvent(event: Event) {
(inflater.inflate(R.layout.week_all_day_event_marker, null, false) as ConstraintLayout).apply {
var backgroundColor = eventTypeColors.get(event.eventType, primaryColor)
var textColor = backgroundColor.getContrastColor()
val adjustAlpha = if (event.isTask()) {
dimCompletedTasks && event.isTaskCompleted()
} else {
dimPastEvents && event.isPastEvent && !isPrintVersion
}
if (adjustAlpha) {
backgroundColor = backgroundColor.adjustAlpha(LOWER_ALPHA)
textColor = textColor.adjustAlpha(HIGHER_ALPHA)
}
background = ColorDrawable(backgroundColor)
week_event_label.apply {
setTextColor(textColor)
maxLines = if (event.isTask()) 1 else 2
text = event.title
checkViewStrikeThrough(event.isTaskCompleted())
contentDescription = text
}
week_event_task_image.beVisibleIf(event.isTask())
if (event.isTask()) {
week_event_task_image.applyColorFilter(textColor)
}
val startDateTime = Formatter.getDateTimeFromTS(event.startTS)
val endDateTime = Formatter.getDateTimeFromTS(event.endTS)
val eventStartDayStartTime = startDateTime.withTimeAtStartOfDay().seconds()
val eventEndDayStartTime = endDateTime.withTimeAtStartOfDay().seconds()
val minTS = max(startDateTime.seconds(), weekTimestamp)
val maxTS = min(endDateTime.seconds(), weekTimestamp + 2 * WEEK_SECONDS)
// fix a visual glitch with all-day events or events lasting multiple days starting at midnight on monday, being shown the previous week too
if (minTS == maxTS && (minTS - weekTimestamp == WEEK_SECONDS.toLong())) {
return
}
val isStartTimeDay = Formatter.getDateTimeFromTS(maxTS) == Formatter.getDateTimeFromTS(maxTS).withTimeAtStartOfDay()
val numDays = Days.daysBetween(Formatter.getDateTimeFromTS(minTS).toLocalDate(), Formatter.getDateTimeFromTS(maxTS).toLocalDate()).days
val daysCnt = if (numDays == 1 && isStartTimeDay) 0 else numDays
val startDateTimeInWeek = Formatter.getDateTimeFromTS(minTS)
val firstDayIndex = startDateTimeInWeek.dayOfMonth // indices must be unique for the visible range (2 weeks)
val lastDayIndex = firstDayIndex + daysCnt
val dayIndices = firstDayIndex..lastDayIndex
val isAllDayEvent = firstDayIndex == lastDayIndex
val isRepeatingOverlappingEvent = eventEndDayStartTime - eventStartDayStartTime >= event.repeatInterval
var doesEventFit: Boolean
var wasEventHandled = false
var drawAtLine = 0
for (index in allDayRows.indices) {
drawAtLine = index
val row = allDayRows[index]
doesEventFit = dayIndices.all { !row.contains(it) }
val firstEvent = allDayEventToRow.keys.firstOrNull { it.id == event.id }
val lastEvent = allDayEventToRow.keys.lastOrNull { it.id == event.id }
val firstEventRowIdx = allDayEventToRow[firstEvent]
val lastEventRowIdx = allDayEventToRow[lastEvent]
val adjacentEvents = currEvents.filter { event.id == it.id }
val repeatingEventIndex = adjacentEvents.indexOf(event)
val isRowValidForEvent = lastEvent == null || firstEventRowIdx!! + repeatingEventIndex == index && lastEventRowIdx!! < index
if (doesEventFit && (!isRepeatingOverlappingEvent || isAllDayEvent || isRowValidForEvent)) {
dayIndices.forEach {
row.add(it)
}
allDayEventToRow[event] = index
wasEventHandled = true
} else {
// create new row
if (index == allDayRows.lastIndex) {
allDayRows.add(HashSet())
addNewLine()
drawAtLine++
val lastRow = allDayRows.last()
dayIndices.forEach {
lastRow.add(it)
}
allDayEventToRow[event] = allDayRows.lastIndex
wasEventHandled = true
}
}
if (wasEventHandled) {
break
}
}
val dayCodeStart = Formatter.getDayCodeFromDateTime(startDateTime).toInt()
val dayCodeEnd = Formatter.getDayCodeFromDateTime(endDateTime).toInt()
val dayOfWeek = dayColumns.indexOfFirst { it.tag.toInt() == dayCodeStart || it.tag.toInt() in (dayCodeStart + 1)..dayCodeEnd }
if (dayOfWeek == -1) {
return
}
allDayHolders[drawAtLine].addView(this)
val dayWidth = mView.width / config.weeklyViewDays
(layoutParams as RelativeLayout.LayoutParams).apply {
leftMargin = dayOfWeek * dayWidth
bottomMargin = 1
width = (dayWidth) * (daysCnt + 1)
}
calculateExtraHeight()
setOnClickListener {
Intent(context, getActivityToOpen(event.isTask())).apply {
putExtra(EVENT_ID, event.id)
putExtra(EVENT_OCCURRENCE_TS, event.startTS)
putExtra(IS_TASK_COMPLETED, event.isTaskCompleted())
startActivity(this)
}
}
}
}
private fun calculateExtraHeight() {
mView.week_top_holder.onGlobalLayout {
if (activity != null && !mWasDestroyed) {
if (isFragmentVisible) {
listener?.updateHoursTopMargin(mView.week_top_holder.height)
}
if (!wasExtraHeightAdded) {
wasExtraHeightAdded = true
}
}
}
}
fun updateScrollY(y: Int) {
if (wasFragmentInit) {
scrollView.scrollY = y
}
}
fun updateNotVisibleViewScaleLevel() {
if (!isFragmentVisible) {
updateViewScale()
}
}
fun togglePrintMode() {
isPrintVersion = !isPrintVersion
updateCalendar()
setupDayLabels()
addEvents(currEvents)
}
inner class DragListener : View.OnDragListener {
override fun onDrag(view: View, dragEvent: DragEvent): Boolean {
return when (dragEvent.action) {
DragEvent.ACTION_DRAG_STARTED -> currentlyDraggedView == view
DragEvent.ACTION_DRAG_ENTERED -> {
view.beGone()
false
}
// handle ACTION_DRAG_LOCATION due to https://stackoverflow.com/a/19460338
DragEvent.ACTION_DRAG_LOCATION -> true
DragEvent.ACTION_DROP -> {
view.beVisible()
true
}
DragEvent.ACTION_DRAG_ENDED -> {
if (!dragEvent.result) {
view.beVisible()
}
currentlyDraggedView = null
true
}
else -> false
}
}
}
}
| gpl-3.0 | 63b056e64c6043f786e95e79bf7e583c | 43.300905 | 158 | 0.56016 | 5.418096 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/objcexport/functionalTypes.kt | 4 | 4144 | /*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package functionalTypes
import kotlin.test.*
typealias AN = Any?
typealias F2 = (AN, AN) -> AN
typealias F5 = (AN, AN, AN, AN, AN) -> AN
typealias F6 = (AN, AN, AN, AN, AN, AN,) -> AN
typealias F32 = (AN, AN, AN, AN, AN, AN, AN, AN, AN, AN, AN, AN,
AN, AN, AN, AN, AN, AN, AN, AN, AN, AN, AN, AN,
AN, AN, AN, AN, AN, AN, AN, AN) -> AN
typealias F33 = (AN, AN, AN, AN, AN, AN, AN, AN, AN, AN, AN, AN,
AN, AN, AN, AN, AN, AN, AN, AN, AN, AN, AN, AN,
AN, AN, AN, AN, AN, AN, AN, AN, AN) -> AN
fun callDynType2(list: List<F2>, param: AN) {
val fct = list.first()
val ret = fct(param, null)
assertEquals(param, ret)
}
fun callStaticType2(fct: F2, param: AN) {
val ret = fct(param, null)
assertEquals(param, ret)
}
fun callDynType32(list: List<F32>, param: AN) {
val fct = list.first()
val ret = fct(param
, null, null, null, null, null, null, null
, null, null, null, null, null, null, null, null
, null, null, null, null, null, null, null, null
, null, null, null, null, null, null, null, null
)
assertEquals(param, ret)
}
fun callStaticType32(fct: F32, param: AN) {
val ret = fct(param
, null, null, null, null, null, null, null
, null, null, null, null, null, null, null, null
, null, null, null, null, null, null, null, null
, null, null, null, null, null, null, null, null
)
assertEquals(param, ret)
}
fun callDynType33(list: List<F33>, param: AN) {
val fct = list.first()
val ret = fct(param
, null, null, null, null, null, null, null
, null, null, null, null, null, null, null, null
, null, null, null, null, null, null, null, null
, null, null, null, null, null, null, null, null, null
)
assertEquals(param, ret)
}
fun callStaticType33(fct: F33, param: AN) {
val ret = fct(param
, null, null, null, null, null, null, null
, null, null, null, null, null, null, null, null
, null, null, null, null, null, null, null, null
, null, null, null, null, null, null, null, null, null
)
assertEquals(param, ret)
}
abstract class FHolder {
abstract val value: Any?
}
// Note: can't provoke dynamic function type conversion using list (as above) or generics
// due to Swift <-> Obj-C interop bugs/limitations.
// Use covariant return type instead:
class F2Holder(override val value: F2) : FHolder()
fun getDynTypeLambda2(): F2Holder = F2Holder({ p1, _ -> p1 })
fun getStaticLambda2(): F2 = { p1, _ -> p1 }
private fun f2(p1: AN, p2: AN): AN = p1
fun getDynTypeRef2(): F2Holder = F2Holder(::f2)
fun getStaticRef2(): F2 = ::f2
private fun f32(
p1: AN, p2: AN, p3: AN, p4: AN, p5: AN, p6: AN, p7: AN, p8: AN,
p9: AN, p10: AN, p11: AN, p12: AN, p13: AN, p14: AN, p15: AN, p16: AN,
p17: AN, p18: AN, p19: AN, p20: AN, p21: AN, p22: AN, p23: AN, p24: AN,
p25: AN, p26: AN, p27: AN, p28: AN, p29: AN, p30: AN, p31: AN, p32: AN
): AN = p1
private fun f33(
p1: AN, p2: AN, p3: AN, p4: AN, p5: AN, p6: AN, p7: AN, p8: AN,
p9: AN, p10: AN, p11: AN, p12: AN, p13: AN, p14: AN, p15: AN, p16: AN,
p17: AN, p18: AN, p19: AN, p20: AN, p21: AN, p22: AN, p23: AN, p24: AN,
p25: AN, p26: AN, p27: AN, p28: AN, p29: AN, p30: AN, p31: AN, p32: AN,
p33: AN
): AN = p1
class F32Holder(override val value: F32) : FHolder()
fun getDynType32(): F32Holder = F32Holder(::f32)
fun getStaticType32(): F32 = ::f32
class F33Holder(override val value: F33) : FHolder()
fun getDynTypeRef33(): F33Holder = F33Holder(::f33)
fun getStaticTypeRef33(): F33 = ::f33
fun getDynTypeLambda33(): F33Holder = F33Holder(getStaticTypeLambda33())
fun getStaticTypeLambda33(): F33 = {
p,
_, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _
->
p
}
| apache-2.0 | 4f03efc23e9c3481eaf34c290f990cc4 | 32.152 | 101 | 0.562259 | 2.771906 | false | false | false | false |
80998062/Fank | domain/src/main/java/com/sinyuk/fanfou/domain/api/ApiResponse.kt | 1 | 2011 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.domain.api
import android.util.Log
import retrofit2.Response
import java.io.IOException
/**
* Common class used by API responses.
*
* @param <T>
*
* https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/api/ApiResponse.java
</T> */
class ApiResponse<T> {
val code: Int
val body: T?
val errorMessage: String?
fun isSuccessful() = code in 200..299
constructor(error: Throwable) {
code = 500
body = null
errorMessage = error.message
}
constructor(response: Response<T>) {
code = response.code()
if (response.isSuccessful) {
body = response.body()
errorMessage = null
} else {
var message: String? = null
if (response.errorBody() != null) {
try {
message = response.errorBody()!!.string()
} catch (ignored: IOException) {
Log.e("ApiResponse", "error while parsing response", ignored)
}
}
if (message == null || message.trim { it <= ' ' }.isEmpty()) {
message = response.message()
}
errorMessage = message
body = null
}
}
} | mit | 3d7f27e4d964f292a206b86120fc0c82 | 26.944444 | 165 | 0.595724 | 4.112474 | false | false | false | false |
7449/Album | core/src/main/java/com/gallery/core/widget/GalleryDivider.kt | 1 | 1364 | package com.gallery.core.widget
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
/**
* @author y
* @create 2019/2/27
*/
class GalleryDivider(private val divider: Int) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
super.getItemOffsets(outRect, view, parent, state)
val position: Int = parent.getChildAdapterPosition(view)
val layoutManager = parent.layoutManager
if (layoutManager is GridLayoutManager) {
val spanCount: Int = layoutManager.spanCount
val i: Int = position % spanCount
val first: Boolean = position / spanCount + 1 == 1
val top: Int = if (first) divider / 2 else 0
val left: Int = if (i + 1 == 1) divider else divider / 2
val right: Int = if (i + 1 == spanCount) divider else divider / 2
outRect.set(left, top, right, divider)
} else if (layoutManager is LinearLayoutManager) {
outRect.set(divider / 2, divider / 2, divider / 2, divider / 2)
}
}
} | mpl-2.0 | 3db5cd599638a02dfca2139160d11547 | 37.028571 | 80 | 0.626833 | 4.623729 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.