repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
NephyProject/Penicillin | src/main/kotlin/jp/nephy/penicillin/extensions/models/builder/CustomDirectMessageBuilder.kt | 1 | 3690 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* 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.
*/
@file:Suppress("UNUSED")
package jp.nephy.penicillin.extensions.models.builder
import jp.nephy.jsonkt.*
import jp.nephy.penicillin.core.experimental.PenicillinExperimentalApi
import jp.nephy.penicillin.extensions.parseModel
import jp.nephy.penicillin.models.DirectMessage
import java.time.temporal.TemporalAccessor
import kotlin.collections.set
/**
* Custom payload builder for [DirectMessage].
*/
class CustomDirectMessageBuilder: JsonBuilder<DirectMessage>, JsonMap by jsonMapOf(
"created_at" to null,
"entities" to jsonObjectOf(),
"id" to null,
"id_str" to null,
"read" to false,
"recipient" to null,
"recipient_id" to null,
"recipient_id_str" to null,
"sender" to null,
"sender_id" to null,
"sender_id_str" to null,
"sender_screen_name" to null,
"text" to null
) {
/**
* "created_at".
*/
var createdAt: TemporalAccessor? = null
private var read = false
/**
* Sets read.
*/
fun read() {
read = true
}
private val recipientBuilder = CustomUserBuilder()
/**
* Sets recipient.
*/
fun recipient(builder: CustomUserBuilder.() -> Unit) {
recipientBuilder.apply(builder)
}
private val senderBuilder = CustomUserBuilder()
/**
* Sets sender.
*/
fun sender(builder: CustomUserBuilder.() -> Unit) {
senderBuilder.apply(builder)
}
private lateinit var message: String
/**
* Sets text.
*/
fun text(text: () -> Any?) {
message = text()?.toString().orEmpty()
}
private var entities = jsonObjectOf()
/**
* Sets entities.
*/
fun entities(json: JsonObject) {
entities = json
}
@UseExperimental(PenicillinExperimentalApi::class)
override fun build(): DirectMessage {
val id = generateId()
val recipient = recipientBuilder.build()
val sender = senderBuilder.build()
this["text"] = message
this["read"] = read
this["created_at"] = createdAt.toCreatedAt()
this["id"] = id
this["id_str"] = id.toString()
this["recipient"] = recipient.json
this["recipient_id"] = recipient.id
this["recipient_id_str"] = recipient.idStr
this["sender"] = sender.json
this["sender_id"] = sender.id
this["sender_id_str"] = sender.idStr
this["sender_screen_name"] = sender.screenName
this["entities"] = entities
return toJsonObject().parseModel()
}
}
| mit | 741d2d3d81863d72c4d978f7321b76ca | 28.52 | 83 | 0.65664 | 4.217143 | false | false | false | false |
chaseberry/KJson | src/main/kotlin/edu/csh/chase/kjson/JsonBase.kt | 1 | 8818 | package edu.csh.chase.kjson
abstract class JsonBase : JsonSerializable {
/**
* A value that equals how large this JsonBase is
*/
abstract val size: Int
var delim = ":"
abstract fun toString(shouldIndent: Boolean, depth: Int = 1): String
/**
* Attempts to walk down a chain of Objects and Arrays based on a compoundKey
* Compound keys will be split by the delim(base of ":")
* If it encounters a dead route it will return what it last found, including the array or object it's checking
* An int will be parses as an array index, all else will be object keys
*
* @param compoundKey A compound key in the form of key:key2:key3 to dig down into
* @return The value that was found by the provided key, or null if nothing was found
*/
fun traverse(compoundKey: String): Any? {
val key = compoundKey.split(delim).iterator()
return when (this) {
is JsonArray -> traverseArray(key, this)
is JsonObject -> traverseObject(key, this)
else -> null
}
}
/**
* Attempts to walk down a chain of Objects and Arrays based on a compoundKey
* Compound keys will be split by the delim(base of ":")
* If it encounters a dead route it will return what it last found, including the array or object it's checking
* An int will be parses as an array index, all else will be object keys
*
* @param compoundKey A compound key in the form of key:key2:key3 to dig down into
* @param default A default value to return if null was encountered
* @return The value that was found by the provided key, or null if nothing was found
*/
fun traverse(compoundKey: String, default: Any): Any {
return traverse(compoundKey = compoundKey) ?: default
}
/**
* Traverses a JsonBase for a Boolean?
*
* @param compoundKey The compound key to search for
* @return A boolean if the key resolved or null if the value was not found or not a boolean
*/
fun traverseBoolean(compoundKey: String): Boolean? = traverse(compoundKey) as? Boolean
/**
* Traverses a JsonBase for a Boolean
*
* @param compoundKey The compound key to search for
* @param default A default value
* @return A boolean if the key resolved or default if the value was not found or not a boolean
*/
fun traverseBoolean(compoundKey: String, default: Boolean): Boolean = traverseBoolean(compoundKey) ?: default
/**
* Traverses a JsonBase for an Int?
*
* @param compoundKey The compound key to search for
* @return An Int if the key resolved or null
*/
fun traverseInt(compoundKey: String): Int? = traverse(compoundKey) as? Int
/**
* Traverses a JsonBase for an Int
*
* @param compoundKey The compound key to search for
* @param default A default value
* @return An Int if the key resolved or default if the value was not found or not an Int
*/
fun traverseInt(compoundKey: String, default: Int): Int = traverseInt(compoundKey) ?: default
/**
* Traverses a JsonBase for a Double?
*
* @param compoundKey The compound key to search for
* @return A Double if the key resolved or null
*/
fun traverseDouble(compoundKey: String): Double? = traverse(compoundKey) as? Double
/**
* Traverses a JsonBase for a Double
*
* @param compoundKey The compound key to search for
* @param default A default value
* @return A Double if the key resolved or default if the value was not found or not a Double
*/
fun traverseDouble(compoundKey: String, default: Double): Double = traverseDouble(compoundKey) ?: default
/**
* Traverses a JsonBase for a String?
*
* @param compoundKey The compound key to search for
* @return A String if the key resolved or null
*/
fun traverseString(compoundKey: String): String? = traverse(compoundKey) as? String
/**
* Traverses a JsonBase for a String
*
* @param compoundKey The compound key to search for
* @param default A default value
* @return A String if the key resolved or default if the value was not found or not a String
*/
fun traverseString(compoundKey: String, default: String): String = traverseString(compoundKey) ?: default
/**
* Traverses a JsonBase for a JsonObject?
*
* @param compoundKey The compound key to search for
* @return A JsonObject if the key resolved or null
*/
fun traverseJsonObject(compoundKey: String): JsonObject? = traverse(compoundKey) as? JsonObject
/**
* Traverses a JsonBase for a JsonObject
*
* @param compoundKey The compound key to search for
* @param default A default value
* @return A JsonObject if the key resolved or default if the value was not found or not a JsonObject
*/
fun traverseJsonObject(compoundKey: String, default: JsonObject): JsonObject = traverseJsonObject(compoundKey) ?: default
/**
* Traverses a JsonBase for a JsonArray?
*
* @param compoundKey The compound key to search for
* @return A JsonArray if the key resolved or null
*/
fun traverseJsonArray(compoundKey: String): JsonArray? = traverse(compoundKey) as? JsonArray
/**
* Traverses a JsonBase for a JsonArray
*
* @param compoundKey The compound key to search for
* @param default A default value
* @return A JsonArray if the key resolved or default if the value was not found or not a JsonArray
*/
fun traverseJsonArray(compoundKey: String, default: JsonArray): JsonArray = traverseJsonArray(compoundKey) ?: default
/**
* Traverses a JsonBase for a Float?
*
* @param compoundKey The compound key to search for
* @return A Float if the key resolved or null
*/
fun traverseFloat(compoundKey: String): Float? {
val num = traverse(compoundKey)
if (num is Number) {
return num.toFloat()
}
return null
}
/**
* Traverses a JsonBase for a Float
*
* @param compoundKey The compound key to search for
* @param default A default value
* @return A Float if the key resolved or default if the value was not found or not a Float
*/
fun traverseFloat(compoundKey: String, default: Float): Float {
return traverseFloat(compoundKey) ?: default
}
/**
* Traverses a JsonBase for a Long?
*
* @param compoundKey The compound key to search for
* @return A Long if the key resolved or null
*/
fun traverseLong(compoundKey: String): Long? = traverse(compoundKey) as? Long
/**
* Traverses a JsonBase for a Long
*
* @param compoundKey The compound key to search for
* @param default A default value
* @return A Long if the key resolved or default if the value was not found or not a Long
*/
fun traverseLong(compoundKey: String, default: Long): Long = traverseLong(compoundKey) ?: default
/**
* Traverses this JsonBase with multiple keys
*
* @param keys A list of keys to check
* @return The first found value or null if no key matched
*/
@Deprecated("Might be removed in the future. To be determined")
fun traverseMulti(vararg keys: String): Any? {
for (key in keys) {
return traverse(compoundKey = key) ?: continue
}
return null
}
/**
* Traverses this JsonBase with a default value if a null was found
*
* @param default A default if null was found
* @param keys A list of keys to check
* @return The first found value or default if none worked
*/
@Deprecated("Might be removed in the future. To be determined")
fun traverseMultiWithDefault(default: Any, vararg keys: String): Any {
return traverseMulti(keys = *keys) ?: default
}
private fun traverseArray(key: Iterator<String>, array: JsonArray): Any? {
if (!key.hasNext()) {
return array
}
val index = try {
key.next().toInt()
} catch(e: NumberFormatException) {
return null
}
val value = array[index]
return when (value) {
is JsonArray -> traverseArray(key, value)
is JsonObject -> traverseObject(key, value)
else -> value
}
}
private fun traverseObject(key: Iterator<String>, `object`: JsonObject): Any? {
if (!key.hasNext()) {
return `object`
}
val value = `object`[key.next()]
return when (value) {
is JsonObject -> traverseObject(key, value)
is JsonArray -> traverseArray(key, value)
else -> value
}
}
} | apache-2.0 | 09b32c184d93d2b3a135ab14e1d6e3ac | 34.704453 | 125 | 0.643003 | 4.424486 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/glNext/tut02/fragPosition.kt | 2 | 2739 | package glNext.tut02
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL2ES2
import com.jogamp.opengl.GL3
import com.jogamp.opengl.util.glsl.ShaderProgram
import glNext.*
import main.framework.Framework
import uno.buffer.destroyBuffers
import uno.buffer.floatBufferOf
import uno.buffer.intBufferBig
import uno.glsl.shaderCodeOf
/**
* Created by GBarbieri on 21.02.2017.
*/
fun main(args: Array<String>) {
FragPosition_Next().setup("Tutorial 02 - Fragment Position")
}
class FragPosition_Next : Framework() {
var theProgram = 0
val vertexBufferObject = intBufferBig(1)
var vao = intBufferBig(1)
val vertexData = floatBufferOf(
+0.75f, +0.75f, 0.0f, 1.0f,
+0.75f, -0.75f, 0.0f, 1.0f,
-0.75f, -0.75f, 0.0f, 1.0f)
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeVertexBuffer(gl)
glGenVertexArray(vao)
glBindVertexArray(vao)
}
fun initializeProgram(gl: GL3) {
theProgram = shaderProgramOf(gl, javaClass, "tut02", "frag-position.vert", "frag-position.frag")
}
fun shaderProgramOf(gl: GL2ES2, context: Class<*>, vararg strings: String): Int = with(gl) {
val shaders =
if (strings[0].contains('.'))
strings.toList()
else {
val root = if (strings[0].endsWith('/')) strings[0] else strings[0] + '/'
strings.drop(1).map { root + it }
}
val shaderProgram = ShaderProgram()
val shaderCodes = shaders.map { shaderCodeOf(gl, context, it) }
shaderCodes.forEach { shaderProgram.add(gl, it, System.err) }
shaderProgram.link(gl, System.err)
shaderCodes.forEach {
glDetachShader(shaderProgram.program(), it.id())
glDeleteShader(it.id())
}
return shaderProgram.program()
}
fun initializeVertexBuffer(gl: GL3) = gl.initArrayBuffer(vertexBufferObject) { data(vertexData, GL_STATIC_DRAW) }
override fun display(gl: GL3) = with(gl) {
clear { color() }
usingProgram(theProgram) {
withVertexLayout(vertexBufferObject, glf.pos4) { glDrawArrays(3) }
}
}
public override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffer(vertexBufferObject)
glDeleteVertexArray(vao)
destroyBuffers(vertexBufferObject, vao)
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
}
}
}
| mit | 74fb0fb23cad93fcdad2114255f97e80 | 25.852941 | 117 | 0.615918 | 3.874116 | false | false | false | false |
alexmonthy/lttng-scope | lttng-scope/src/main/kotlin/org/lttng/scope/views/timeline/widgets/xychart/layer/XYChartSelectionLayer.kt | 2 | 8530 | /*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.views.timeline.widgets.xychart.layer
import com.efficios.jabberwocky.common.TimeRange
import javafx.event.EventHandler
import javafx.scene.input.MouseButton
import javafx.scene.input.MouseEvent
import javafx.scene.layout.Pane
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import javafx.scene.shape.StrokeLineCap
import org.lttng.scope.views.timeline.widgets.xychart.XYChartFullRangeWidget
import org.lttng.scope.views.timeline.widgets.xychart.XYChartVisibleRangeWidget
import org.lttng.scope.views.timeline.widgets.xychart.XYChartWidget
abstract class XYChartSelectionLayer(protected val widget: XYChartWidget, protected val chartBackgroundAdjustment: Double) : Pane() {
companion object {
/* Style settings. TODO Move to debug options? */
private const val SELECTION_STROKE_WIDTH = 1.0
private val SELECTION_STROKE_COLOR = Color.BLUE
private val SELECTION_FILL_COLOR = Color.LIGHTBLUE.deriveColor(0.0, 1.2, 1.0, 0.4)
/**
* Factory method
*/
fun build(widget: XYChartWidget, chartBackgroundAdjustment: Double): XYChartSelectionLayer {
return when (widget) {
is XYChartVisibleRangeWidget -> XYChartVisibleRangeSelectionLayer(widget, chartBackgroundAdjustment)
is XYChartFullRangeWidget -> XYChartFullRangeSelectionLayer(widget, chartBackgroundAdjustment)
else -> throw UnsupportedOperationException("Unknown XY Chart class")
}
}
}
protected val selectionRectangle = Rectangle().apply {
stroke = SELECTION_STROKE_COLOR
strokeWidth = SELECTION_STROKE_WIDTH
strokeLineCap = StrokeLineCap.ROUND
}
protected val ongoingSelectionRectangle = Rectangle()
private val selectionCtx = SelectionContext()
init {
isMouseTransparent = true
listOf(selectionRectangle, ongoingSelectionRectangle).forEach {
// deal
with(it) {
isMouseTransparent = true
fill = SELECTION_FILL_COLOR
x = 0.0
width = 0.0
yProperty().bind(widget.chartPlotArea.layoutYProperty().add(chartBackgroundAdjustment))
heightProperty().bind(widget.chartPlotArea.heightProperty())
isVisible = false
}
}
children.addAll(selectionRectangle, ongoingSelectionRectangle)
/*
* Add mouse listeners to handle the ongoing selection.
*/
with(widget.chart) {
addEventHandler(MouseEvent.MOUSE_PRESSED, selectionCtx.mousePressedEventHandler)
addEventHandler(MouseEvent.MOUSE_DRAGGED, selectionCtx.mouseDraggedEventHandler)
addEventHandler(MouseEvent.MOUSE_RELEASED, selectionCtx.mouseReleasedEventHandler)
}
}
abstract fun drawSelection(sr: TimeRange)
/**
* Class encapsulating the time range selection, related drawing and
* listeners.
*/
private inner class SelectionContext {
/**
* Do not handle the mouse event if it matches these condition. It should be handled
* at another level (for moving the visible range, etc.)
*/
private fun MouseEvent.isToBeIgnored(): Boolean =
this.button == MouseButton.SECONDARY
|| this.button == MouseButton.MIDDLE
|| this.isControlDown
private var ongoingSelection: Boolean = false
private var mouseOriginX: Double = 0.0
val mousePressedEventHandler = EventHandler<MouseEvent> { e ->
if (e.isToBeIgnored()) return@EventHandler
e.consume()
if (ongoingSelection) return@EventHandler
/* Remove the current selection, if there is one */
selectionRectangle.isVisible = false
mouseOriginX = e.x
with(ongoingSelectionRectangle) {
layoutX = mouseOriginX
width = 0.0
isVisible = true
}
ongoingSelection = true
}
val mouseDraggedEventHandler = EventHandler<MouseEvent> { e ->
if (e.isToBeIgnored()) return@EventHandler
e.consume()
val newX = e.x
val offsetX = newX - mouseOriginX
with(ongoingSelectionRectangle) {
if (offsetX > 0) {
layoutX = mouseOriginX
width = offsetX
} else {
layoutX = newX
width = -offsetX
}
}
}
val mouseReleasedEventHandler = EventHandler<MouseEvent> { e ->
if (e.isToBeIgnored()) return@EventHandler
e.consume()
ongoingSelectionRectangle.isVisible = false
/* Send a time range selection signal for the currently highlighted time range */
val startX = ongoingSelectionRectangle.layoutX
// FIXME Possible glitch when selecting backwards outside of the window?
val endX = startX + ongoingSelectionRectangle.width
val localStartX = widget.chartPlotArea.parentToLocal(startX, 0.0).x - chartBackgroundAdjustment
val localEndX = widget.chartPlotArea.parentToLocal(endX, 0.0).x - chartBackgroundAdjustment
val tsStart = widget.mapXPositionToTimestamp(localStartX)
val tsEnd = widget.mapXPositionToTimestamp(localEndX)
widget.control.updateTimeRangeSelection(TimeRange.of(tsStart, tsEnd))
ongoingSelection = false
}
}
}
private class XYChartFullRangeSelectionLayer(widget: XYChartFullRangeWidget,
chartBackgroundAdjustment: Double) : XYChartSelectionLayer(widget, chartBackgroundAdjustment) {
override fun drawSelection(sr: TimeRange) {
val viewWidth = widget.chartPlotArea.width
if (viewWidth < 1.0) return
val project = widget.viewContext.traceProject ?: return
val projectRange = project.fullRange
val startRatio = (sr.startTime - projectRange.startTime) / projectRange.duration.toDouble()
val startPos = startRatio * viewWidth + widget.chartPlotArea.layoutX + chartBackgroundAdjustment
val endRatio = (sr.endTime - projectRange.startTime) / projectRange.duration.toDouble()
val endPos = endRatio * viewWidth + widget.chartPlotArea.layoutX + chartBackgroundAdjustment
with(selectionRectangle) {
x = startPos
width = endPos - startPos
isVisible = true
}
}
}
private class XYChartVisibleRangeSelectionLayer(widget: XYChartVisibleRangeWidget,
chartBackgroundAdjustment: Double) : XYChartSelectionLayer(widget, chartBackgroundAdjustment) {
override fun drawSelection(sr: TimeRange) {
val vr = widget.viewContext.visibleTimeRange
if (sr.startTime <= vr.startTime && sr.endTime <= vr.startTime) {
/* Selection is completely before the visible range, no range to display. */
selectionRectangle.isVisible = false
return
}
if (sr.startTime >= vr.endTime && sr.endTime >= vr.endTime) {
/* Selection is completely after the visible range, no range to display. */
selectionRectangle.isVisible = false
return
}
val viewWidth = widget.chartPlotArea.width
if (viewWidth < 1.0) return
val startTime = (Math.max(sr.startTime, vr.startTime))
val startRatio = (startTime - vr.startTime) / vr.duration.toDouble()
val startPos = startRatio * viewWidth + widget.chartPlotArea.layoutX + chartBackgroundAdjustment
val endTime = (Math.min(sr.endTime, vr.endTime))
val endRatio = (endTime - vr.startTime) / vr.duration.toDouble()
val endPos = endRatio * viewWidth + widget.chartPlotArea.layoutX + chartBackgroundAdjustment
with(selectionRectangle) {
x = startPos
width = endPos - startPos
isVisible = true
}
}
}
| epl-1.0 | 4db9255d5736e9d54fd7ee7891dd451a | 37.080357 | 143 | 0.644783 | 5 | false | false | false | false |
jabbink/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/tasks/LootOneNearbyPokestop.kt | 2 | 5407 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.tasks
import POGOProtos.Networking.Responses.FortSearchResponseOuterClass
import POGOProtos.Networking.Responses.FortSearchResponseOuterClass.FortSearchResponse.Result
import ink.abb.pogo.api.cache.Pokestop
import ink.abb.pogo.scraper.Bot
import ink.abb.pogo.scraper.Context
import ink.abb.pogo.scraper.Settings
import ink.abb.pogo.scraper.Task
import ink.abb.pogo.scraper.util.Log
import ink.abb.pogo.scraper.util.directions.getAltitude
import ink.abb.pogo.scraper.util.map.canLoot
import ink.abb.pogo.scraper.util.map.distance
import ink.abb.pogo.scraper.util.map.loot
import java.text.DecimalFormat
import java.util.*
class LootOneNearbyPokestop(val sortedPokestops: List<Pokestop>, val lootTimeouts: HashMap<String, Long>) : Task {
private var cooldownPeriod = 5
override fun run(bot: Bot, ctx: Context, settings: Settings) {
// STOP WALKING! until loot is done
ctx.pauseWalking.set(true)
ctx.api.setLocation(ctx.lat.get(), ctx.lng.get(), getAltitude(ctx.lat.get(), ctx.lng.get(), ctx))
val nearbyPokestops = sortedPokestops.filter {
it.canLoot(lootTimeouts = lootTimeouts)
}
if (nearbyPokestops.isNotEmpty()) {
val closest = nearbyPokestops.first()
var pokestopID = closest.id
if (settings.displayPokestopName) {
pokestopID = "\"${closest.name}\""
}
Log.normal("Looting nearby pokestop $pokestopID")
val result = closest.loot().toBlocking().first().response
if (result.itemsAwardedCount != 0) {
ctx.itemStats.first.getAndAdd(result.itemsAwardedCount)
}
if (result.experienceAwarded > 0) {
ctx.server.sendProfile()
}
when (result.result) {
Result.SUCCESS -> {
ctx.server.sendPokestop(closest)
ctx.server.sendProfile()
var message = "Looted pokestop $pokestopID; +${result.experienceAwarded} XP"
if (settings.displayPokestopRewards)
message += ": ${result.itemsAwardedList.groupBy { it.itemId.name }.map { "${it.value.size}x${it.key}" }}"
Log.green(message)
lootTimeouts.put(closest.id, closest.cooldownCompleteTimestampMs)
checkForBan(result, closest, bot, settings)
}
Result.INVENTORY_FULL -> {
ctx.server.sendPokestop(closest)
ctx.server.sendProfile()
var message = "Looted pokestop $pokestopID; +${result.experienceAwarded} XP, but inventory is full"
if (settings.displayPokestopRewards)
message += ": ${result.itemsAwardedList.groupBy { it.itemId.name }.map { "${it.value.size}x${it.key}" }}"
Log.red(message)
lootTimeouts.put(closest.id, closest.cooldownCompleteTimestampMs)
}
Result.OUT_OF_RANGE -> {
Log.red("Pokestop out of range; our calculated distance: ${DecimalFormat("#0.00").format(closest.distance)}m")
if (closest.distance < ctx.api.fortSettings.interactionRangeMeters) {
Log.red("Server is lying to us (${Math.round(closest.distance)}m < ${Math.round(ctx.api.fortSettings.interactionRangeMeters)}m!); blacklisting for $cooldownPeriod minutes")
lootTimeouts.put(closest.id, ctx.api.currentTimeMillis() + cooldownPeriod * 60 * 1000)
}
}
Result.IN_COOLDOWN_PERIOD -> {
lootTimeouts.put(closest.id, ctx.api.currentTimeMillis() + cooldownPeriod * 60 * 1000)
Log.red("Pokestop still in cooldown mode; blacklisting for $cooldownPeriod minutes")
}
Result.NO_RESULT_SET -> {
lootTimeouts.put(closest.id, ctx.api.currentTimeMillis() + cooldownPeriod * 60 * 1000)
Log.red("Server refuses to loot this Pokestop (usually temporary issue); blacklisting for $cooldownPeriod minutes")
}
else -> Log.yellow(result.result.toString())
}
}
// unlock walk block
ctx.pauseWalking.set(false)
}
private fun checkForBan(result: FortSearchResponseOuterClass.FortSearchResponse, pokestop: Pokestop, bot: Bot, settings: Settings) {
if (settings.banSpinCount > 0 && result.experienceAwarded == 0 && result.itemsAwardedCount == 0) {
Log.red("Looks like a ban. Trying to bypass softban by repeatedly spinning the pokestop.")
bot.task(BypassSoftban(pokestop))
Log.yellow("Finished softban bypass attempt. Continuing.")
// Add pokestop to cooldown list to prevent immediate retry in the next loop
lootTimeouts.put(pokestop.id, bot.ctx.api.currentTimeMillis() + cooldownPeriod * 60 * 1000)
}
}
}
| gpl-3.0 | 41f3f049074981358982bfcbc3565793 | 48.605505 | 196 | 0.624376 | 4.385239 | false | false | false | false |
signed/intellij-community | python/python-terminal/src/com/jetbrains/python/sdk/PyVirtualEnvTerminalCustomizer.kt | 1 | 5053 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.sdk
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.SystemInfo
import com.jetbrains.python.run.PyVirtualEnvReader
import com.jetbrains.python.run.findActivateScript
import org.jetbrains.plugins.terminal.LocalTerminalCustomizer
import java.io.File
import javax.swing.JCheckBox
/**
* @author traff
*/
class PyVirtualEnvTerminalCustomizer : LocalTerminalCustomizer() {
override fun customizeCommandAndEnvironment(project: Project,
command: Array<out String>,
envs: MutableMap<String, String>): Array<out String> {
val sdk: Sdk? = findSdk(project)
if (sdk != null && (PythonSdkType.isVirtualEnv(sdk) || PythonSdkType.isCondaVirtualEnv(
sdk)) && PyVirtualEnvTerminalSettings.getInstance(project).virtualEnvActivate) {
// in case of virtualenv sdk on unix we activate virtualenv
val path = sdk.homePath
if (path != null) {
val shellPath = command[0]
val shellName = File(shellPath).name
if (shellName == "bash" || (SystemInfo.isMac && shellName == "sh") || (shellName == "zsh") ||
((shellName == "fish") && PythonSdkType.isVirtualEnv(sdk))) { //fish shell works only for virtualenv and not for conda
//for bash we pass activate script to jediterm shell integration (see jediterm-bash.in) to source it there
findActivateScript(path, shellPath)?.let { activate ->
envs.put("JEDITERM_SOURCE", if (activate.second != null) "${activate.first} ${activate.second}" else activate.first)
}
}
else {
//for other shells we read envs from activate script by the default shell and pass them to the process
val reader = PyVirtualEnvReader(path)
reader.activate?.let {
// we add only envs that are setup by the activate script, because adding other variables from the different shell
// can break the actual shell
envs.putAll(reader.readShellEnv().mapKeys { k -> k.key.toUpperCase() }.filterKeys { k ->
k in PyVirtualEnvReader.virtualEnvVars
})
}
}
}
}
// for some reason virtualenv isn't activated in the rcfile for the login shell, so we make it non-login
return command.filter { arg -> arg != "--login" && arg != "-l" }.toTypedArray()
}
private fun findSdk(project: Project): Sdk? {
for (m in ModuleManager.getInstance(project).modules) {
val sdk: Sdk? = PythonSdkType.findPythonSdk(m)
if (sdk != null && !PythonSdkType.isRemote(sdk)) {
return sdk
}
}
return null
}
override fun getDefaultFolder(project: Project): String? {
return null
}
override fun getConfigurable(project: Project) = object : UnnamedConfigurable {
val settings = PyVirtualEnvTerminalSettings.getInstance(project)
var myCheckbox: JCheckBox = JCheckBox("Activate virtualenv")
override fun createComponent() = myCheckbox
override fun isModified() = myCheckbox.isSelected != settings.virtualEnvActivate
override fun apply() {
settings.virtualEnvActivate = myCheckbox.isSelected
}
override fun reset() {
myCheckbox.isSelected = settings.virtualEnvActivate
}
}
}
class SettingsState {
var virtualEnvActivate = true
}
@State(name = "PyVirtualEnvTerminalCustomizer", storages = arrayOf(Storage("python-terminal.xml")))
class PyVirtualEnvTerminalSettings : PersistentStateComponent<SettingsState> {
var myState = SettingsState()
var virtualEnvActivate: Boolean
get() = myState.virtualEnvActivate
set(value) {
myState.virtualEnvActivate = value
}
override fun getState() = myState
override fun loadState(state: SettingsState) {
myState.virtualEnvActivate = state.virtualEnvActivate
}
companion object {
fun getInstance(project: Project): PyVirtualEnvTerminalSettings {
return ServiceManager.getService(project, PyVirtualEnvTerminalSettings::class.java)
}
}
}
| apache-2.0 | 65b87317613787bf808deb8cb0eadf4b | 34.090278 | 130 | 0.698397 | 4.72243 | false | false | false | false |
cbeyls/fosdem-companion-android | app/src/main/java/be/digitalia/fosdem/db/ScheduleDao.kt | 1 | 17207 | package be.digitalia.fosdem.db
import androidx.annotation.WorkerThread
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.TypeConverters
import be.digitalia.fosdem.db.converters.NonNullInstantTypeConverters
import be.digitalia.fosdem.db.entities.EventEntity
import be.digitalia.fosdem.db.entities.EventTitles
import be.digitalia.fosdem.db.entities.EventToPerson
import be.digitalia.fosdem.model.Day
import be.digitalia.fosdem.model.DetailedEvent
import be.digitalia.fosdem.model.Event
import be.digitalia.fosdem.model.EventDetails
import be.digitalia.fosdem.model.Link
import be.digitalia.fosdem.model.Person
import be.digitalia.fosdem.model.StatusEvent
import be.digitalia.fosdem.model.Track
import be.digitalia.fosdem.utils.BackgroundWorkScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.runBlocking
import java.time.Instant
import java.time.LocalDate
@Dao
abstract class ScheduleDao(private val appDatabase: AppDatabase) {
val version: StateFlow<Int> =
appDatabase.createVersionFlow(EventEntity.TABLE_NAME)
val bookmarksVersion: StateFlow<Int>
get() = appDatabase.bookmarksDao.version
/**
* @return The latest update time, or null if not available.
*/
val latestUpdateTime: Flow<Instant?> = appDatabase.dataStore.data.map { prefs ->
prefs[LATEST_UPDATE_TIME_PREF_KEY]?.let { Instant.ofEpochMilli(it) }
}
/**
* @return The time identifier of the current version of the database.
*/
val lastModifiedTag: Flow<String?> = appDatabase.dataStore.data.map { prefs ->
prefs[LAST_MODIFIED_TAG_PREF]
}
private class EmptyScheduleException : Exception()
/**
* Stores the schedule in the database.
*
* @param events The events stream.
* @return The number of events processed.
*/
@WorkerThread
fun storeSchedule(events: Sequence<DetailedEvent>, lastModifiedTag: String?): Int {
val totalEvents = try {
storeScheduleInternal(events, lastModifiedTag)
} catch (ese: EmptyScheduleException) {
0
}
if (totalEvents > 0) { // Set last update time and server's last modified tag
val now = Instant.now()
runBlocking {
appDatabase.dataStore.edit { prefs ->
prefs.clear()
prefs[LATEST_UPDATE_TIME_PREF_KEY] = now.toEpochMilli()
if (lastModifiedTag != null) {
prefs[LAST_MODIFIED_TAG_PREF] = lastModifiedTag
}
}
}
}
return totalEvents
}
@Transaction
protected open fun storeScheduleInternal(events: Sequence<DetailedEvent>, lastModifiedTag: String?): Int {
// 1: Delete the previous schedule
clearSchedule()
// 2: Insert the events
var totalEvents = 0
val tracks = mutableMapOf<Track, Long>()
var nextTrackId = 0L
var minEventId = Long.MAX_VALUE
val days: MutableSet<Day> = HashSet(2)
for ((event, details) in events) {
// Retrieve or insert Track
val track = event.track
var trackId = tracks[track]
if (trackId == null) {
// New track
trackId = ++nextTrackId
val newTrack = Track(trackId, track.name, track.type)
insertTrack(newTrack)
tracks[newTrack] = trackId
}
val eventId = event.id
try {
// Insert main event and fulltext fields
val eventEntity = EventEntity(
eventId,
event.day.index,
event.startTime,
event.endTime,
event.roomName,
event.slug,
trackId,
event.abstractText,
event.description
)
val eventTitles = EventTitles(
eventId,
event.title,
event.subTitle
)
insertEvent(eventEntity, eventTitles)
} catch (e: Exception) {
// Duplicate event: skip
continue
}
days += event.day
if (eventId < minEventId) {
minEventId = eventId
}
val persons = details.persons
insertPersons(persons)
val eventsToPersons = persons.map { EventToPerson(eventId, it.id) }
insertEventsToPersons(eventsToPersons)
insertLinks(details.links)
totalEvents++
}
if (totalEvents == 0) {
// Rollback the transaction
throw EmptyScheduleException()
}
// 3: Insert collected days
insertDays(days)
// 4: Purge outdated bookmarks
purgeOutdatedBookmarks(minEventId)
return totalEvents
}
@Insert
protected abstract fun insertTrack(track: Track)
@Insert
protected abstract fun insertEvent(eventEntity: EventEntity, eventTitles: EventTitles)
@Insert(onConflict = OnConflictStrategy.IGNORE)
protected abstract fun insertPersons(persons: List<Person>)
@Insert(onConflict = OnConflictStrategy.IGNORE)
protected abstract fun insertEventsToPersons(eventsToPersons: List<EventToPerson>)
@Insert
protected abstract fun insertLinks(links: List<Link>)
@Insert
protected abstract fun insertDays(days: Set<Day>)
@Query("DELETE FROM bookmarks WHERE event_id < :minEventId")
protected abstract fun purgeOutdatedBookmarks(minEventId: Long)
@WorkerThread
@Transaction
open fun clearSchedule() {
clearEvents()
clearEventTitles()
clearPersons()
clearEventToPersons()
clearLinks()
clearTracks()
clearDays()
}
@Query("DELETE FROM events")
protected abstract fun clearEvents()
@Query("DELETE FROM events_titles")
protected abstract fun clearEventTitles()
@Query("DELETE FROM persons")
protected abstract fun clearPersons()
@Query("DELETE FROM events_persons")
protected abstract fun clearEventToPersons()
@Query("DELETE FROM links")
protected abstract fun clearLinks()
@Query("DELETE FROM tracks")
protected abstract fun clearTracks()
@Query("DELETE FROM days")
protected abstract fun clearDays()
// Cache days
@OptIn(ExperimentalCoroutinesApi::class)
val days: Flow<List<Day>> = appDatabase.createVersionFlow(Day.TABLE_NAME)
.mapLatest { getDaysInternal() }
.stateIn(
scope = BackgroundWorkScope,
started = SharingStarted.Lazily,
initialValue = null
).filterNotNull()
@Query("SELECT `index`, date FROM days ORDER BY `index` ASC")
protected abstract suspend fun getDaysInternal(): List<Day>
suspend fun getYear(): Int {
// Compute from days if available, fall back to current year
val date = days.first().firstOrNull()?.date ?: LocalDate.now()
return date.year
}
@Query("""SELECT t.id, t.name, t.type FROM tracks t
JOIN events e ON t.id = e.track_id
WHERE e.day_index = :day
GROUP BY t.id
ORDER BY t.name ASC""")
abstract suspend fun getTracks(day: Day): List<Track>
/**
* Returns the event with the specified id, or null if not found.
*/
@Query("""SELECT e.id, e.start_time, e.end_time, e.room_name, e.slug, et.title, et.subtitle, e.abstract, e.description,
GROUP_CONCAT(p.name, ', ') AS persons, e.day_index, d.date AS day_date, e.track_id, t.name AS track_name, t.type AS track_type
FROM events e
JOIN events_titles et ON e.id = et.`rowid`
JOIN days d ON e.day_index = d.`index`
JOIN tracks t ON e.track_id = t.id
LEFT JOIN events_persons ep ON e.id = ep.event_id
LEFT JOIN persons p ON ep.person_id = p.`rowid`
WHERE e.id = :id
GROUP BY e.id""")
abstract suspend fun getEvent(id: Long): Event?
/**
* Returns all found events whose id is part of the given list.
*/
@Query("""SELECT e.id, e.start_time, e.end_time, e.room_name, e.slug, et.title, et.subtitle, e.abstract, e.description,
GROUP_CONCAT(p.name, ', ') AS persons, e.day_index, d.date AS day_date, e.track_id, t.name AS track_name, t.type AS track_type,
b.event_id IS NOT NULL AS is_bookmarked
FROM events e
JOIN events_titles et ON e.id = et.`rowid`
JOIN days d ON e.day_index = d.`index`
JOIN tracks t ON e.track_id = t.id
LEFT JOIN events_persons ep ON e.id = ep.event_id
LEFT JOIN persons p ON ep.person_id = p.`rowid`
LEFT JOIN bookmarks b ON e.id = b.event_id
WHERE e.id IN (:ids)
GROUP BY e.id
ORDER BY e.start_time ASC""")
abstract fun getEvents(ids: LongArray): PagingSource<Int, StatusEvent>
/**
* Returns the events for a specified track, including their bookmark status.
*/
@Query("""SELECT e.id, e.start_time, e.end_time, e.room_name, e.slug, et.title, et.subtitle, e.abstract, e.description,
GROUP_CONCAT(p.name, ', ') AS persons, e.day_index, d.date AS day_date, e.track_id, t.name AS track_name, t.type AS track_type,
b.event_id IS NOT NULL AS is_bookmarked
FROM events e
JOIN events_titles et ON e.id = et.`rowid`
JOIN days d ON e.day_index = d.`index`
JOIN tracks t ON e.track_id = t.id
LEFT JOIN events_persons ep ON e.id = ep.event_id
LEFT JOIN persons p ON ep.person_id = p.`rowid`
LEFT JOIN bookmarks b ON e.id = b.event_id
WHERE e.day_index = :day AND e.track_id = :track
GROUP BY e.id
ORDER BY e.start_time ASC""")
abstract suspend fun getEvents(day: Day, track: Track): List<StatusEvent>
/**
* Returns the events for a specified track, without their bookmark status.
*/
@Query("""SELECT e.id, e.start_time, e.end_time, e.room_name, e.slug, et.title, et.subtitle, e.abstract, e.description,
GROUP_CONCAT(p.name, ', ') AS persons, e.day_index, d.date AS day_date, e.track_id, t.name AS track_name, t.type AS track_type
FROM events e
JOIN events_titles et ON e.id = et.`rowid`
JOIN days d ON e.day_index = d.`index`
JOIN tracks t ON e.track_id = t.id
LEFT JOIN events_persons ep ON e.id = ep.event_id
LEFT JOIN persons p ON ep.person_id = p.`rowid`
WHERE e.day_index = :day AND e.track_id = :track
GROUP BY e.id
ORDER BY e.start_time ASC""")
abstract suspend fun getEventsWithoutBookmarkStatus(day: Day, track: Track): List<Event>
/**
* Returns events starting in the specified interval, ordered by ascending start time.
*/
@Query("""SELECT e.id, e.start_time, e.end_time, e.room_name, e.slug, et.title, et.subtitle, e.abstract, e.description,
GROUP_CONCAT(p.name, ', ') AS persons, e.day_index, d.date AS day_date, e.track_id, t.name AS track_name, t.type AS track_type,
b.event_id IS NOT NULL AS is_bookmarked
FROM events e
JOIN events_titles et ON e.id = et.`rowid`
JOIN days d ON e.day_index = d.`index`
JOIN tracks t ON e.track_id = t.id
LEFT JOIN events_persons ep ON e.id = ep.event_id
LEFT JOIN persons p ON ep.person_id = p.`rowid`
LEFT JOIN bookmarks b ON e.id = b.event_id
WHERE e.start_time BETWEEN :minStartTime AND :maxStartTime
GROUP BY e.id
ORDER BY e.start_time ASC""")
@TypeConverters(NonNullInstantTypeConverters::class)
abstract fun getEventsWithStartTime(minStartTime: Instant, maxStartTime: Instant): PagingSource<Int, StatusEvent>
/**
* Returns events in progress at the specified time, ordered by descending start time.
*/
@Query("""SELECT e.id, e.start_time, e.end_time, e.room_name, e.slug, et.title, et.subtitle, e.abstract, e.description,
GROUP_CONCAT(p.name, ', ') AS persons, e.day_index, d.date AS day_date, e.track_id, t.name AS track_name, t.type AS track_type,
b.event_id IS NOT NULL AS is_bookmarked
FROM events e
JOIN events_titles et ON e.id = et.`rowid`
JOIN days d ON e.day_index = d.`index`
JOIN tracks t ON e.track_id = t.id
LEFT JOIN events_persons ep ON e.id = ep.event_id
LEFT JOIN persons p ON ep.person_id = p.`rowid`
LEFT JOIN bookmarks b ON e.id = b.event_id
WHERE e.start_time <= :time AND :time < e.end_time
GROUP BY e.id
ORDER BY e.start_time DESC""")
@TypeConverters(NonNullInstantTypeConverters::class)
abstract fun getEventsInProgress(time: Instant): PagingSource<Int, StatusEvent>
/**
* Returns the events presented by the specified person.
*/
@Query("""SELECT e.id , e.start_time, e.end_time, e.room_name, e.slug, et.title, et.subtitle, e.abstract, e.description,
GROUP_CONCAT(p.name, ', ') AS persons, e.day_index, d.date AS day_date, e.track_id, t.name AS track_name, t.type AS track_type,
b.event_id IS NOT NULL AS is_bookmarked
FROM events e JOIN events_titles et ON e.id = et.`rowid`
JOIN days d ON e.day_index = d.`index`
JOIN tracks t ON e.track_id = t.id
LEFT JOIN events_persons ep ON e.id = ep.event_id
LEFT JOIN persons p ON ep.person_id = p.`rowid`
LEFT JOIN bookmarks b ON e.id = b.event_id
JOIN events_persons ep2 ON e.id = ep2.event_id
WHERE ep2.person_id = :person
GROUP BY e.id
ORDER BY e.start_time ASC""")
abstract fun getEvents(person: Person): PagingSource<Int, StatusEvent>
/**
* Search through matching titles, subtitles, track names, person names.
* We need to use an union of 3 sub-queries because a "match" condition can not be
* accompanied by other conditions in a "where" statement.
*/
@Query("""SELECT e.id, e.start_time, e.end_time, e.room_name, e.slug, et.title, et.subtitle, e.abstract, e.description,
GROUP_CONCAT(p.name, ', ') AS persons, e.day_index, d.date AS day_date, e.track_id, t.name AS track_name, t.type AS track_type,
b.event_id IS NOT NULL AS is_bookmarked
FROM events e
JOIN events_titles et ON e.id = et.`rowid`
JOIN days d ON e.day_index = d.`index`
JOIN tracks t ON e.track_id = t.id
LEFT JOIN events_persons ep ON e.id = ep.event_id
LEFT JOIN persons p ON ep.person_id = p.`rowid`
LEFT JOIN bookmarks b ON e.id = b.event_id
WHERE e.id IN (
SELECT `rowid`
FROM events_titles
WHERE events_titles MATCH :query || '*'
UNION
SELECT e.id
FROM events e
JOIN tracks t ON e.track_id = t.id
WHERE t.name LIKE '%' || :query || '%'
UNION
SELECT ep.event_id
FROM events_persons ep
JOIN persons p ON ep.person_id = p.`rowid`
WHERE p.name MATCH :query || '*'
)
GROUP BY e.id
ORDER BY e.start_time ASC""")
abstract fun getSearchResults(query: String): PagingSource<Int, StatusEvent>
/**
* Returns all persons in alphabetical order.
*/
@Query("""SELECT `rowid`, name
FROM persons
ORDER BY name COLLATE NOCASE""")
abstract fun getPersons(): PagingSource<Int, Person>
suspend fun getEventDetails(event: Event): EventDetails {
// Load persons and links in parallel
return coroutineScope {
val persons = async { getPersons(event) }
val links = async { getLinks(event) }
EventDetails(persons.await(), links.await())
}
}
@Query("""SELECT p.`rowid`, p.name
FROM persons p
JOIN events_persons ep ON p.`rowid` = ep.person_id
WHERE ep.event_id = :event""")
protected abstract suspend fun getPersons(event: Event): List<Person>
@Query("SELECT * FROM links WHERE event_id = :event ORDER BY id ASC")
protected abstract suspend fun getLinks(event: Event?): List<Link>
companion object {
private val LATEST_UPDATE_TIME_PREF_KEY = longPreferencesKey("latest_update_time")
private val LAST_MODIFIED_TAG_PREF = stringPreferencesKey("last_modified_tag")
}
} | apache-2.0 | 933d3f3ecca58bcadf15150228a8ef96 | 38.287671 | 135 | 0.629569 | 4.063046 | false | false | false | false |
ruuvi/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/bluetooth/DefaultOnTagFoundListener.kt | 1 | 4306 | package com.ruuvi.station.bluetooth
import com.ruuvi.station.alarm.domain.AlarmCheckInteractor
import com.ruuvi.station.app.preferences.GlobalSettings
import com.ruuvi.station.app.preferences.Preferences
import com.ruuvi.station.bluetooth.domain.LocationInteractor
import com.ruuvi.station.database.TagRepository
import com.ruuvi.station.database.tables.RuuviTagEntity
import com.ruuvi.station.database.tables.TagSensorReading
import com.ruuvi.station.gateway.GatewaySender
import com.ruuvi.station.tagsettings.domain.HumidityCalibrationInteractor
import com.ruuvi.station.util.extensions.logData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber
import java.util.Calendar
import java.util.Date
import java.util.HashMap
@Suppress("NAME_SHADOWING")
class DefaultOnTagFoundListener(
private val preferences: Preferences,
private val gatewaySender: GatewaySender,
private val repository: TagRepository,
private val alarmCheckInteractor: AlarmCheckInteractor,
private val humidityCalibrationInteractor: HumidityCalibrationInteractor,
private val locationInteractor: LocationInteractor
) : IRuuviTagScanner.OnTagFoundListener {
var isForeground = false
private var lastLogged: MutableMap<String, Long> = HashMap()
private var lastCleanedDate: Long = Date().time
private var locationUpdateDate: Long = Long.MIN_VALUE
private val ioScope = CoroutineScope(Dispatchers.IO)
override fun onTagFound(tag: FoundRuuviTag) {
Timber.d("onTagFound: ${tag.logData()}")
UpdateLocation()
saveReading(RuuviTagEntity(tag))
cleanUpOldData()
}
private fun saveReading(ruuviTag: RuuviTagEntity) {
Timber.d("saveReading for tag(${ruuviTag.id})")
ioScope.launch {
val dbTag = ruuviTag.id?.let { repository.getTagById(it) }
if (dbTag != null) {
val ruuviTag = dbTag.preserveData(ruuviTag)
humidityCalibrationInteractor.apply(ruuviTag)
repository.updateTag(ruuviTag)
if (dbTag.favorite == true) saveFavouriteReading(ruuviTag)
} else {
ruuviTag.updateAt = Date()
repository.saveTag(ruuviTag)
}
}
}
private fun saveFavouriteReading(ruuviTag: RuuviTagEntity) {
val interval = if (isForeground) {
DATA_LOG_INTERVAL
} else {
preferences.backgroundScanInterval
}
Timber.d("saveFavouriteReading (interval = $interval)")
val calendar = Calendar.getInstance()
calendar.add(Calendar.SECOND, -interval)
val loggingThreshold = calendar.time.time
val lastLoggedDate = lastLogged[ruuviTag.id]
if (lastLoggedDate == null || lastLoggedDate <= loggingThreshold) {
ruuviTag.id?.let {
Timber.d("saveFavouriteReading actual SAVING for [${ruuviTag.name}] (${ruuviTag.id})")
lastLogged[it] = Date().time
val reading = TagSensorReading(ruuviTag)
reading.save()
gatewaySender.sendData(ruuviTag, locationInteractor.lastLocation)
}
} else {
Timber.d("saveFavouriteReading SKIPPED [${ruuviTag.name}] (${ruuviTag.id}) lastLogged = ${Date(lastLoggedDate)}")
}
alarmCheckInteractor.check(ruuviTag)
}
private fun cleanUpOldData() {
val calendar = Calendar.getInstance()
calendar.add(Calendar.MINUTE, -10)
val cleaningThreshold = calendar.time.time
if (lastCleanedDate == null || lastCleanedDate < cleaningThreshold) {
Timber.d("Cleaning DB from old tag readings")
TagSensorReading.removeOlderThan(GlobalSettings.historyLengthHours)
lastCleanedDate = Date().time
}
}
private fun UpdateLocation() {
val calendar = Calendar.getInstance()
calendar.add(Calendar.MINUTE, -1)
val cleaningThreshold = calendar.time.time
if (locationUpdateDate < cleaningThreshold) {
locationInteractor.updateLocation()
locationUpdateDate = Date().time
}
}
companion object {
private const val DATA_LOG_INTERVAL = 0
}
} | mit | 800d78df9a32cd1bf43cc987b10bb96c | 38.154545 | 125 | 0.682768 | 4.499478 | false | false | false | false |
JayNewstrom/ScreenSwitcher | tab-bar/src/main/java/com/jaynewstrom/screenswitcher/tabbar/BottomNavItemLayout.kt | 1 | 1957 | package com.jaynewstrom.screenswitcher.tabbar
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.core.widget.ImageViewCompat
class BottomNavItemLayout(
context: Context,
@DrawableRes icon: Int,
title: String
) : LinearLayout(context) {
private val titleTextView: TextView
private val iconImageView: ImageView
private val badgeTextView: TextView
init {
LayoutInflater.from(context).inflate(R.layout.bottom_nav_item, this, true)
titleTextView = findViewById(R.id.bottom_bar_title_text_view)
titleTextView.text = title
iconImageView = findViewById(R.id.bottom_bar_icon_image_view)
iconImageView.setImageResource(icon)
badgeTextView = findViewById(R.id.bottom_bar_badge_text_view)
style()
}
private fun style() {
val states = arrayOf(
intArrayOf(android.R.attr.state_selected),
intArrayOf(-android.R.attr.state_selected)
)
val colors = intArrayOf(
Color.WHITE,
Color.parseColor("#99FFFFFF")
)
val colorStateList = ColorStateList(states, colors)
titleTextView.setTextColor(colorStateList)
ImageViewCompat.setImageTintList(iconImageView, colorStateList)
}
override fun setSelected(selected: Boolean) {
super.setSelected(selected)
titleTextView.isSelected = selected
iconImageView.isSelected = selected
}
fun setBadgeText(badgeValue: Int) {
badgeTextView.visibility = if (badgeValue == 0) View.GONE else View.VISIBLE
val badgeText = if (badgeValue > 99) "99+" else badgeValue.toString()
badgeTextView.text = badgeText
}
}
| apache-2.0 | 9e660cb641e24500687717e39b3c4706 | 29.107692 | 83 | 0.703117 | 4.551163 | false | false | false | false |
anthologist/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/adapters/MyPagerAdapter.kt | 1 | 2332 | package com.simplemobiletools.gallery.adapters
import android.os.Bundle
import android.os.Parcelable
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.view.PagerAdapter
import android.view.ViewGroup
import com.simplemobiletools.gallery.activities.ViewPagerActivity
import com.simplemobiletools.gallery.fragments.PhotoFragment
import com.simplemobiletools.gallery.fragments.VideoFragment
import com.simplemobiletools.gallery.fragments.ViewPagerFragment
import com.simplemobiletools.gallery.helpers.MEDIUM
import com.simplemobiletools.gallery.models.Medium
class MyPagerAdapter(val activity: ViewPagerActivity, fm: FragmentManager, val media: MutableList<Medium>) : FragmentStatePagerAdapter(fm) {
private val fragments = HashMap<Int, ViewPagerFragment>()
override fun getCount() = media.size
override fun getItem(position: Int): Fragment {
val medium = media[position]
val bundle = Bundle()
bundle.putSerializable(MEDIUM, medium)
val fragment = if (medium.isVideo()) {
VideoFragment()
} else {
PhotoFragment()
}
fragment.arguments = bundle
fragment.listener = activity
return fragment
}
override fun getItemPosition(item: Any) = PagerAdapter.POSITION_NONE
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val fragment = super.instantiateItem(container, position) as ViewPagerFragment
fragments[position] = fragment
return fragment
}
override fun destroyItem(container: ViewGroup, position: Int, any: Any) {
fragments.remove(position)
super.destroyItem(container, position, any)
}
fun getCurrentFragment(position: Int) = fragments[position]
fun toggleFullscreen(isFullscreen: Boolean) {
for ((pos, fragment) in fragments) {
fragment.fullscreenToggled(isFullscreen)
}
}
// try fixing TransactionTooLargeException crash on Android Nougat, tip from https://stackoverflow.com/a/43193425/1967672
override fun saveState(): Parcelable? {
val bundle = super.saveState() as Bundle?
bundle!!.putParcelableArray("states", null)
return bundle
}
}
| apache-2.0 | 537cd8428637d191736e625206341f57 | 36.015873 | 140 | 0.730274 | 4.848233 | false | false | false | false |
fnouama/intellij-community | platform/configuration-store-impl/src/StateMap.kt | 4 | 7213 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.util.ArrayUtil
import com.intellij.util.SystemProperties
import gnu.trove.THashMap
import org.iq80.snappy.SnappyInputStream
import org.iq80.snappy.SnappyOutputStream
import org.jdom.Element
import org.jdom.output.Format
import java.io.ByteArrayInputStream
import java.io.OutputStreamWriter
import java.util.*
import java.util.concurrent.atomic.AtomicReferenceArray
class StateMap private constructor(private val names: Array<String>, private val states: AtomicReferenceArray<Any?>) {
companion object {
private val XML_FORMAT = Format.getRawFormat().setTextMode(Format.TextMode.TRIM).setOmitEncoding(true).setOmitDeclaration(true)
val EMPTY = StateMap(emptyArray(), AtomicReferenceArray(0))
public fun fromMap(map: Map<String, Any>): StateMap {
if (map.isEmpty()) {
return EMPTY
}
val names = map.keySet().toTypedArray()
if (map !is TreeMap) {
Arrays.sort(names)
}
val states = AtomicReferenceArray<Any?>(names.size())
for (i in names.indices) {
states.set(i, map.get(names[i]))
}
return StateMap(names, states)
}
public fun stateToElement(key: String, state: Any?, newLiveStates: Map<String, Element>? = null): Element {
if (state is Element) {
return state.clone()
}
else {
return newLiveStates?.get(key) ?: unarchiveState(state as ByteArray)
}
}
public fun getNewByteIfDiffers(key: String, newState: Any, oldState: ByteArray): ByteArray? {
val newBytes = if (newState is Element) archiveState(newState) else newState as ByteArray
if (Arrays.equals(newBytes, oldState)) {
return null
}
else if (SystemProperties.getBooleanProperty("idea.log.changed.components", false)) {
fun stateToString(state: Any) = JDOMUtil.writeParent(state as? Element ?: unarchiveState(state as ByteArray), "\n")
val before = stateToString(oldState)
val after = stateToString(newState)
if (before == after) {
LOG.info("Serialization error: serialized are different, but unserialized are equal")
}
else {
LOG.info("$key ${StringUtil.repeat("=", 80 - key.length())}\nBefore:\n$before\nAfter:\n$after")
}
}
return newBytes
}
private fun archiveState(state: Element): ByteArray {
val byteOut = BufferExposingByteArrayOutputStream()
OutputStreamWriter(SnappyOutputStream(byteOut), CharsetToolkit.UTF8_CHARSET).use {
val xmlOutputter = JDOMUtil.MyXMLOutputter()
xmlOutputter.format = XML_FORMAT
xmlOutputter.output(state, it)
}
return ArrayUtil.realloc(byteOut.internalBuffer, byteOut.size())
}
private fun unarchiveState(state: ByteArray) = JDOMUtil.load(SnappyInputStream(ByteArrayInputStream(state)))
}
public fun toMutableMap(): MutableMap<String, Any> {
val map = THashMap<String, Any>(names.size())
for (i in names.indices) {
map.put(names[i], states.get(i))
}
return map
}
/**
* Sorted by name.
*/
fun keys() = names
public fun get(key: String): Any? {
val index = Arrays.binarySearch(names, key)
return if (index < 0) null else states.get(index)
}
fun getElement(key: String, newLiveStates: Map<String, Element>? = null) = stateToElement(key, get(key), newLiveStates)
fun isEmpty() = names.isEmpty()
fun hasState(key: String) = get(key) is Element
public fun hasStates(): Boolean {
if (isEmpty()) {
return false
}
for (i in names.indices) {
if (states.get(i) is Element) {
return true
}
}
return false
}
public fun compare(key: String, newStates: StateMap, diffs: MutableSet<String>) {
val oldState = get(key)
val newState = newStates.get(key)
if (oldState is Element) {
if (!JDOMUtil.areElementsEqual(oldState as Element?, newState as Element?)) {
diffs.add(key)
}
}
else if (getNewByteIfDiffers(key, newState!!, oldState as ByteArray) != null) {
diffs.add(key)
}
}
fun getState(key: String, archive: Boolean = false): Element? {
val index = Arrays.binarySearch(names, key)
if (index < 0) {
return null
}
val state = states.get(index) as? Element ?: return null
if (!archive) {
return state
}
return if (states.compareAndSet(index, state, archiveState(state))) state else getState(key, true)
}
public fun archive(key: String, state: Element?) {
val index = Arrays.binarySearch(names, key)
if (index < 0) {
return
}
val currentState = states.get(index)
LOG.assertTrue(currentState is Element)
states.set(index, if (state == null) null else archiveState(state))
}
}
fun setStateAndCloneIfNeed(key: String, newState: Element?, oldStates: StateMap, newLiveStates: MutableMap<String, Element>? = null): MutableMap<String, Any>? {
val oldState = oldStates.get(key)
if (newState == null || JDOMUtil.isEmpty(newState)) {
if (oldState == null) {
return null
}
val newStates = oldStates.toMutableMap()
newStates.remove(key)
return newStates
}
newLiveStates?.put(key, newState)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return null
}
}
else if (oldState != null) {
newBytes = StateMap.getNewByteIfDiffers(key, newState, oldState as ByteArray)
if (newBytes == null) {
return null
}
}
val newStates = oldStates.toMutableMap()
newStates.put(key, newBytes ?: newState)
return newStates
}
// true if updated (not equals to previous state)
internal fun updateState(states: MutableMap<String, Any>, key: String, newState: Element?, newLiveStates: MutableMap<String, Element>? = null): Boolean {
if (newState == null || JDOMUtil.isEmpty(newState)) {
states.remove(key)
return true
}
newLiveStates?.put(key, newState)
val oldState = states.get(key)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return false
}
}
else if (oldState != null) {
newBytes = StateMap.getNewByteIfDiffers(key, newState, oldState as ByteArray) ?: return false
}
states.put(key, newBytes ?: newState)
return true
} | apache-2.0 | d61d5c8fddc8260e44f3b6d89b5f03b9 | 30.502183 | 160 | 0.681131 | 4.065953 | false | false | false | false |
cuebyte/rendition | src/main/kotlin/moe/cuebyte/rendition/Column.kt | 1 | 1853 | package moe.cuebyte.rendition
class Column
internal constructor(val name: String,val meta: Meta, val automated: Boolean, type: Class<*>, default: Any)
: IncompleteColumn(type, default) {
enum class Meta {
NONE,
STRING_PK, NUMBER_PK,
STRING_INDEX, NUMBER_INDEX
}
fun checkType(value: Any): Boolean {
return when (value) {
is String -> type == String::class.java
is Double -> type == Double::class.java
is Int -> type == Int::class.java
is Long -> type == Long::class.java
is Float -> type == Float::class.java
else -> false
}
}
}
open class IncompleteColumn(val type: Class<*>, val default: Any) {
private var automated = false
private var meta: Column.Meta = Column.Meta.NONE
fun primaryKey(): IncompleteColumn {
if (meta != Column.Meta.NONE) {
throw Exception("a column should only be set as primaryKey or with an index")
}
if (type == Boolean::class.java) {
throw Exception("Primary key could not be bool.")
}
meta = if (type == String::class.java) {
Column.Meta.STRING_PK
} else {
Column.Meta.NUMBER_PK
}
return this
}
fun auto(): IncompleteColumn {
if (meta != Column.Meta.STRING_PK) {
throw Exception("Only String Id could be generate automatically.")
}
automated = true
return this
}
fun index(): IncompleteColumn {
if (meta != Column.Meta.NONE) {
throw Exception("a column should only be set as an primaryKey or with an index")
}
if (type == Boolean::class.java) {
throw Exception("Index could not be bool.")
}
meta = if (type == String::class.java) {
Column.Meta.STRING_INDEX
} else {
Column.Meta.NUMBER_INDEX
}
return this
}
fun complete(name: String): Column = Column(name, meta, automated, this.type, this.default)
} | lgpl-3.0 | 38ba27df86206f4fcb81e87a1999fbc3 | 26.264706 | 107 | 0.62979 | 3.909283 | false | false | false | false |
JayNewstrom/ScreenSwitcher | screen-switcher-sample/src/main/java/screenswitchersample/activity/SampleInitialScreenFactory.kt | 1 | 1800 | package screenswitchersample.activity
import android.content.Intent
import com.jakewharton.rxrelay2.BehaviorRelay
import com.jaynewstrom.screenswitcher.Screen
import com.jaynewstrom.screenswitcher.dialogmanager.dialogDisplayer
import com.jaynewstrom.screenswitcher.tabbar.TabBarItem
import com.jaynewstrom.screenswitcher.tabbar.TabBarScreenFactory
import screenswitchersample.R
import screenswitchersample.badge.BadgeScreenFactory
import screenswitchersample.color.ColorScreenFactory
import screenswitchersample.core.activity.InitialScreenFactory
import screenswitchersample.first.FirstScreenFactory
import timber.log.Timber
import javax.inject.Inject
internal class SampleInitialScreenFactory @Inject constructor(
private val navigator: Navigator
) : InitialScreenFactory {
override fun create(intent: Intent?): List<Screen> {
val tabBarItems = mutableListOf<TabBarItem>()
tabBarItems += TabBarItem({ FirstScreenFactory.create(navigator) }, "Demo", R.drawable.ic_nav_demo)
tabBarItems += TabBarItem({ ColorScreenFactory.create(navigator, "#FF0000") }, "Color", R.drawable.ic_nav_color)
val badgeCountRelay = BehaviorRelay.createDefault(5)
tabBarItems += TabBarItem(
initialScreenFactory = { BadgeScreenFactory.create(badgeCountRelay) },
title = "Badge",
icon = R.drawable.ic_nav_badge,
badgeCountObservable = badgeCountRelay
)
val tabBarScreen = TabBarScreenFactory.create(
tabBarItems,
{
Timber.d("Dashboard Initialized")
},
{ popListenerView ->
popListenerView.dialogDisplayer()?.show(ConfirmExitDialogFactory())
true
}
)
return listOf(tabBarScreen)
}
}
| apache-2.0 | 71b0ff717e84e817789f47bdbe78223d | 39.909091 | 120 | 0.722778 | 4.83871 | false | false | false | false |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/event/EventCallbacks.kt | 1 | 3451 | package info.papdt.express.helper.event
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Parcelable
import android.util.Log
import androidx.recyclerview.widget.RecyclerView
import info.papdt.express.helper.EXTRA_DATA
import info.papdt.express.helper.EXTRA_OLD_DATA
import info.papdt.express.helper.model.Category
import info.papdt.express.helper.model.Kuaidi100Package
import info.papdt.express.helper.receiver.ActionBroadcastReceiver
import info.papdt.express.helper.receiver.ActionBroadcastReceiver.Companion.create
import me.drakeet.multitype.ItemViewBinder
import moe.feng.kotlinyan.common.get
import kotlin.reflect.KClass
object EventCallbacks {
private const val TAG = "EventCallbacks"
fun deletePackage(callback: (data: Kuaidi100Package) -> Unit): BroadcastReceiver {
return object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent == null || !intent.hasExtra(EXTRA_DATA)) {
Log.e(TAG, "deletePackage: receive empty data. It is invalid.")
return
}
callback(intent[EXTRA_DATA]!!.asParcelable())
}
}
}
fun onDeleteCategory(callback: (data: Category) -> Unit): BroadcastReceiver {
return object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent == null || !intent.hasExtra(EXTRA_DATA)) {
Log.e(TAG, "onDeleteCategory: receive empty data")
return
}
callback(intent[EXTRA_DATA]!!.asParcelable())
}
}
}
fun onSaveNewCategory(callback: (data: Category) -> Unit): BroadcastReceiver {
return object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent == null || !intent.hasExtra(EXTRA_DATA)) {
Log.e(TAG, "onSaveNewCategory: receive empty data")
return
}
callback(intent[EXTRA_DATA]!!.asParcelable())
}
}
}
fun onSaveEditCategory(
callback: (oldData: Category, data: Category) -> Unit): BroadcastReceiver {
return object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent == null
|| !intent.hasExtra(EXTRA_DATA)
|| !intent.hasExtra(EXTRA_OLD_DATA)) {
Log.e(TAG, "onSaveEditCategory: receive empty data")
return
}
callback(
intent[EXTRA_OLD_DATA]!!.asParcelable(),
intent[EXTRA_DATA]!!.asParcelable()
)
}
}
}
fun <T : Parcelable, VH : RecyclerView.ViewHolder, B: ItemViewBinder<T, VH>> onItemClick(
clazz: KClass<B>,
callback: (data: T?) -> Unit): BroadcastReceiver {
return create(EventIntents.getItemOnClickActionName(clazz)) { _, intent ->
if (intent == null || !intent.hasExtra(EXTRA_DATA)) {
Log.e(TAG, "onItemClick: receive empty data")
return@create
}
callback(intent[EXTRA_DATA]?.asParcelable())
}
}
} | gpl-3.0 | ce047c427c9fd423863ace7047c49861 | 37.786517 | 93 | 0.590264 | 4.826573 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/network/rest/wpcom/wc/GatewayRestClientTest.kt | 1 | 5388 | package org.wordpress.android.fluxc.network.rest.wpcom.wc
import com.android.volley.RequestQueue
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest.WPComGsonNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.wc.gateways.GatewayRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.wc.gateways.GatewayRestClient.GatewayId.CASH_ON_DELIVERY
class GatewayRestClientTest {
private lateinit var jetpackTunnelGsonRequestBuilder: JetpackTunnelGsonRequestBuilder
private lateinit var requestQueue: RequestQueue
private lateinit var accessToken: AccessToken
private lateinit var userAgent: UserAgent
private lateinit var gatewayRestClient: GatewayRestClient
@Before
fun setup() {
jetpackTunnelGsonRequestBuilder = mock()
requestQueue = mock()
accessToken = mock()
userAgent = mock()
gatewayRestClient = GatewayRestClient(
mock(),
jetpackTunnelGsonRequestBuilder,
mock(),
requestQueue,
accessToken,
userAgent
)
}
@Test
fun `given success response, when fetch gateway, return success`() {
runBlocking {
whenever(
jetpackTunnelGsonRequestBuilder.syncGetRequest(
any(),
any(),
any(),
any(),
any<Class<GatewayRestClient.GatewayResponse>>(),
any(),
any(),
any(),
anyOrNull()
)
).thenReturn(
JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess(mock())
)
val actualResponse = gatewayRestClient.fetchGateway(
SiteModel(),
""
)
Assertions.assertThat(actualResponse.isError).isFalse
Assertions.assertThat(actualResponse.result).isNotNull
}
}
@Test
fun `given error response, when fetch gateway, return error`() {
runBlocking {
val expectedError = mock<WPComGsonNetworkError>().apply {
type = mock()
}
whenever(
jetpackTunnelGsonRequestBuilder.syncGetRequest(
any(),
any(),
any(),
any(),
any<Class<GatewayRestClient.GatewayResponse>>(),
any(),
any(),
any(),
anyOrNull()
)
).thenReturn(
JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError(expectedError)
)
val actualResponse = gatewayRestClient.fetchGateway(SiteModel(), "")
Assertions.assertThat(actualResponse.isError).isTrue
Assertions.assertThat(actualResponse.error).isNotNull
}
}
@Test
fun `given success response, when update gateway, return success`() {
runBlocking {
whenever(
jetpackTunnelGsonRequestBuilder.syncPostRequest(
any(),
any(),
any(),
any(),
any<Class<GatewayRestClient.GatewayResponse>>()
)
).thenReturn(
JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess(mock())
)
val actualResponse = gatewayRestClient.updatePaymentGateway(
SiteModel(),
CASH_ON_DELIVERY,
enabled = false,
title = "title"
)
Assertions.assertThat(actualResponse.isError).isFalse
Assertions.assertThat(actualResponse.result).isNotNull
}
}
@Test
fun `given error response, when update gateway, return error`() {
runBlocking {
val expectedError = mock<WPComGsonNetworkError>().apply {
type = mock()
}
whenever(
jetpackTunnelGsonRequestBuilder.syncPostRequest(
any(),
any(),
any(),
any(),
any<Class<GatewayRestClient.GatewayResponse>>(),
)
).thenReturn(
JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError(expectedError)
)
val actualResponse = gatewayRestClient.updatePaymentGateway(
SiteModel(),
CASH_ON_DELIVERY,
enabled = true,
title = "title"
)
Assertions.assertThat(actualResponse.isError).isTrue
Assertions.assertThat(actualResponse.error).isNotNull
}
}
}
| gpl-2.0 | 9e16c15b231a7c5ed37075f6ca00f454 | 33.318471 | 110 | 0.57461 | 6.060742 | false | false | false | false |
cubex2/ObsidianAnimator | API/src/main/java/obsidianAPI/io/ModelImporter.kt | 1 | 2810 | package obsidianAPI.io
import obsidianAPI.data.ModelDefinition
import obsidianAPI.data.PartRotationDefinition
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.io.InputStreamReader
/**
* Imports models exported from blender
*/
object ModelImporter
{
fun importModel(file: File): ModelDefinition
{
return importModel(file.name.replace(".obm", ""), file)
}
fun importModel(modelName: String, file: File): ModelDefinition
{
return importModel(modelName, FileInputStream(file))
}
fun importModel(modelName: String, stream: InputStream): ModelDefinition
{
val lines = readAllLines(stream)
val objModelBytes = readModelBytes(lines)
val rotations = createRotationDefinitions(lines)
return ModelDefinition(modelName, objModelBytes, rotations, mutableListOf(), listOf(), listOf(), false)
}
private fun readAllLines(stream: InputStream): MutableList<String>
{
val reader = InputStreamReader(stream)
val lines = reader.readLines().toMutableList()
reader.close()
return lines
}
private fun readModelBytes(lines: MutableList<String>): ByteArray
{
val modelLines = mutableListOf<String>()
while (true)
{
val line = lines.removeAt(0)
if (line.trim() == "# Part #")
break
modelLines.add(line)
}
val modelString = modelLines.reduce { acc, s -> acc + "\n" + s }
return modelString.toByteArray(Charsets.UTF_8)
}
private fun createRotationDefinitions(lines: List<String>): List<PartRotationDefinition>
{
val definitions = mutableListOf<PartRotationDefinition>()
var partName = ""
var rotationPoint = floatArrayOf()
var defaultValues: FloatArray
lines.filter { it.isNotBlank() }
.map { it.trim() }
.forEach { line ->
when
{
partName.isEmpty() -> partName = line
rotationPoint.isEmpty() -> rotationPoint = lineToFloatArray(line)
else ->
{
defaultValues = lineToFloatArray(line)
definitions.add(PartRotationDefinition(partName, rotationPoint, defaultValues))
partName = ""
rotationPoint = floatArrayOf()
defaultValues = floatArrayOf()
}
}
}
return definitions
}
private fun lineToFloatArray(line: String): FloatArray
{
return line.split(",", limit = 3)
.map(String::trim)
.map(String::toFloat)
.toFloatArray()
}
} | gpl-3.0 | 0ef191ecec499caf8ba3f0cc34a939b0 | 27.683673 | 111 | 0.586833 | 5.081374 | false | false | false | false |
beyama/winter | winter/src/main/kotlin/io/jentz/winter/UnboundService.kt | 1 | 5068 | package io.jentz.winter
/**
* Interface for service entries registered in a [Component].
*
* Custom implementations can be added to a [Component] by using [ComponentBuilder.register].
*/
interface UnboundService<R : Any> {
/**
* The [TypeKey] of the type this service is providing.
*/
val key: TypeKey<R>
/**
* Return true if the bound service requires lifecycle calls to [BoundService.onPostConstruct]
* or [BoundService.onClose] otherwise false.
*/
val requiresLifecycleCallbacks: Boolean
/**
* Binds this unbound service a given [graph] and returns a [BoundService].
*/
fun bind(graph: Graph): BoundService<R>
}
@PublishedApi
internal class UnboundPrototypeService<R : Any>(
override val key: TypeKey<R>,
val factory: GFactory<R>,
val onPostConstruct: GFactoryCallback<R>?
) : UnboundService<R> {
override val requiresLifecycleCallbacks: Boolean
get() = onPostConstruct != null
override fun bind(graph: Graph): BoundService<R> {
return BoundPrototypeService(graph, this)
}
}
@PublishedApi
internal class UnboundSingletonService<R : Any>(
override val key: TypeKey<R>,
val factory: GFactory<R>,
val onPostConstruct: GFactoryCallback<R>?,
val onClose: GFactoryCallback<R>?
) : UnboundService<R> {
override val requiresLifecycleCallbacks: Boolean
get() = onPostConstruct != null || onClose != null
override fun bind(graph: Graph): BoundService<R> {
return BoundSingletonService(graph, this)
}
}
@PublishedApi
internal class UnboundWeakSingletonService<R : Any>(
override val key: TypeKey<R>,
val factory: GFactory<R>,
val onPostConstruct: GFactoryCallback<R>?
) : UnboundService<R> {
override val requiresLifecycleCallbacks: Boolean
get() = onPostConstruct != null
override fun bind(graph: Graph): BoundService<R> {
return BoundWeakSingletonService(graph, this)
}
}
@PublishedApi
internal class UnboundSoftSingletonService<R : Any>(
override val key: TypeKey<R>,
val factory: GFactory<R>,
val onPostConstruct: GFactoryCallback<R>?
) : UnboundService<R> {
override val requiresLifecycleCallbacks: Boolean
get() = onPostConstruct != null
override fun bind(graph: Graph): BoundService<R> {
return BoundSoftSingletonService(graph, this)
}
}
@PublishedApi
internal class ConstantService<R : Any>(
override val key: TypeKey<R>,
val value: R
) : UnboundService<R>, BoundService<R> {
override val requiresLifecycleCallbacks: Boolean
get() = false
override val scope: Scope get() = Scope.Prototype
override fun bind(graph: Graph): BoundService<R> = this
override fun instance(): R = value
override fun newInstance(): R {
throw AssertionError("BUG: This method should not be called.")
}
override fun onPostConstruct(instance: R) {
throw AssertionError("BUG: This method should not be called.")
}
override fun onClose() {
}
}
internal class AliasService<R: Any>(
private val targetKey: TypeKey<*>,
private val newKey: TypeKey<R>
) : UnboundService<R> {
override val requiresLifecycleCallbacks: Boolean get() = false
override val key: TypeKey<R> get() = newKey
override fun bind(graph: Graph): BoundService<R> {
try {
@Suppress("UNCHECKED_CAST")
return graph.service(targetKey as TypeKey<R>)
} catch (t: Throwable) {
throw WinterException("Error resolving alias `$newKey` pointing to `$targetKey`.", t)
}
}
}
internal abstract class OfTypeService<T: Any, R: Any>(
override val key: TypeKey<R>,
val typeOfKey: TypeKey<T>
) : UnboundService<R> {
override val requiresLifecycleCallbacks: Boolean
get() = false
}
@PublishedApi
internal class SetOfTypeService<T: Any>(
key: TypeKey<Set<T>>,
typeOfKey: TypeKey<T>
) : OfTypeService<T, Set<T>>(key, typeOfKey) {
override fun bind(graph: Graph): BoundService<Set<T>> =
BoundSetOfTypeService(graph, this)
}
@PublishedApi
internal class SetOfProvidersForTypeService<T: Any>(
key: TypeKey<Set<Provider<T>>>,
typeOfKey: TypeKey<T>
) : OfTypeService<T, Set<Provider<T>>>(key, typeOfKey) {
override fun bind(graph: Graph): BoundService<Set<Provider<T>>> =
BoundSetOfProvidersForTypeService(graph, this)
}
@PublishedApi
internal class MapOfTypeService<T: Any>(
key: TypeKey<Map<Any, T>>,
typeOfKey: TypeKey<T>,
val defaultKey: Any
) : OfTypeService<T, Map<Any, T>>(key, typeOfKey) {
override fun bind(graph: Graph): BoundService<Map<Any, T>> =
BoundMapOfTypeService(graph, this)
}
@PublishedApi
internal class MapOfProvidersForTypeService<T: Any>(
key: TypeKey<Map<Any, Provider<T>>>,
typeOfKey: TypeKey<T>,
val defaultKey: Any
) : OfTypeService<T, Map<Any, Provider<T>>>(key, typeOfKey) {
override fun bind(graph: Graph): BoundService<Map<Any, Provider<T>>> =
BoundMapOfProvidersForTypeService(graph, this)
}
| apache-2.0 | 820dbe665b6d8e8c5f4c176b1c27825a | 25.814815 | 98 | 0.678966 | 4.143908 | false | false | false | false |
jtlalka/fiszki | app/src/main/kotlin/net/tlalka/fiszki/model/entities/Cluster.kt | 1 | 810 | package net.tlalka.fiszki.model.entities
import com.j256.ormlite.dao.ForeignCollection
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.field.ForeignCollectionField
import com.j256.ormlite.table.DatabaseTable
import net.tlalka.fiszki.model.dao.ClusterDao
import net.tlalka.fiszki.model.types.OwnerType
@DatabaseTable(tableName = "clusters", daoClass = ClusterDao::class)
class Cluster {
@DatabaseField(generatedId = true)
var id: Long = 0
@DatabaseField(canBeNull = false)
var ownerType: OwnerType = OwnerType.SYSTEM
@ForeignCollectionField(eager = true)
var words: ForeignCollection<Word>? = null
constructor() {
// Constructor required for ORMLite library.
}
constructor(ownerType: OwnerType) {
this.ownerType = ownerType
}
}
| mit | 5fdc6dad18ae50c96dee2bc478b17c22 | 26.931034 | 68 | 0.746914 | 3.894231 | false | false | false | false |
ntemplon/legends-of-omterra | core/src/com/jupiter/europa/entity/component/NameComponent.kt | 1 | 1970 | /*
* The MIT License
*
* Copyright 2015 Nathan Templon.
*
* 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.jupiter.europa.entity.component
import com.badlogic.ashley.core.Component
import com.badlogic.gdx.utils.Json
import com.badlogic.gdx.utils.Json.Serializable
import com.badlogic.gdx.utils.JsonValue
/**
* @author Nathan Templon
*/
public class NameComponent(name: String = "default") : Component(), Serializable {
// Fields
public var name: String = ""
private set
// Initialization
init {
this.name = name
}
// Serializable (Json) implementation
override fun write(json: Json) {
json.writeValue(NAME_KEY, this.name)
}
override fun read(json: Json, jsonData: JsonValue) {
if (jsonData.has(NAME_KEY)) {
this.name = jsonData.getString(NAME_KEY)
}
}
companion object {
private val NAME_KEY = "name"
}
}
| mit | dc7e0ff3238e265c9707fda81199fec5 | 29.78125 | 82 | 0.71066 | 4.310722 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/RsLiteralKind.kt | 2 | 7147 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiErrorElement
import org.rust.lang.core.lexer.RustEscapesLexer
import org.rust.lang.core.psi.RsElementTypes.*
import org.rust.lang.utils.unescapeRust
interface RsComplexLiteral {
val node: ASTNode
val offsets: LiteralOffsets
}
interface RsLiteralWithSuffix : RsComplexLiteral {
val suffix: String? get() = offsets.suffix?.substring(node.text)
val validSuffixes: List<String>
}
interface RsTextLiteral {
val value: String?
val hasUnpairedQuotes: Boolean
}
sealed class RsLiteralKind(val node: ASTNode) {
class Boolean(node: ASTNode) : RsLiteralKind(node) {
val value: kotlin.Boolean = node.chars == "true"
}
class Integer(node: ASTNode) : RsLiteralKind(node), RsLiteralWithSuffix {
override val validSuffixes: List<kotlin.String>
get() = listOf("u8", "i8", "u16", "i16", "u32", "i32", "u64", "i64", "u128", "i128", "isize", "usize")
override val offsets: LiteralOffsets by lazy { offsetsForNumber(node) }
}
class Float(node: ASTNode) : RsLiteralKind(node), RsLiteralWithSuffix {
override val validSuffixes: List<kotlin.String>
get() = listOf("f32", "f64")
val value: Double? get() = offsets.value?.substring(node.text)
?.filter { it != '_' }
?.let {
try {
it.toDouble()
} catch(e: NumberFormatException) {
null
}
}
override val offsets: LiteralOffsets by lazy { offsetsForNumber(node) }
}
class String(node: ASTNode) : RsLiteralKind(node), RsLiteralWithSuffix, RsTextLiteral {
override val offsets: LiteralOffsets by lazy { offsetsForText(node) }
override val validSuffixes: List<kotlin.String> get() = emptyList()
override val hasUnpairedQuotes: kotlin.Boolean
get() = offsets.openDelim == null || offsets.closeDelim == null
override val value: kotlin.String? get() {
val rawValue = offsets.value?.substring(node.text)
return if (node.elementType in RS_RAW_LITERALS)
rawValue
else
rawValue?.unescapeRust(RustEscapesLexer.of(node.elementType))
}
}
class Char(node: ASTNode) : RsLiteralKind(node), RsLiteralWithSuffix, RsTextLiteral {
override val offsets: LiteralOffsets by lazy { offsetsForText(node) }
override val validSuffixes: List<kotlin.String> get() = emptyList()
override val hasUnpairedQuotes: kotlin.Boolean
get() = offsets.openDelim == null || offsets.closeDelim == null
override val value: kotlin.String?
get() = offsets.value?.substring(node.text)
?.unescapeRust(RustEscapesLexer.of(node.elementType))
}
companion object {
fun fromAstNode(node: ASTNode): RsLiteralKind? = when (node.elementType) {
BOOL_LITERAL -> Boolean(node)
INTEGER_LITERAL -> Integer(node)
FLOAT_LITERAL -> Float(node)
STRING_LITERAL, RAW_STRING_LITERAL,
BYTE_STRING_LITERAL, RAW_BYTE_STRING_LITERAL -> String(node)
CHAR_LITERAL, BYTE_LITERAL -> Char(node)
else -> null
}
}
}
val RsLitExpr.kind: RsLiteralKind? get() {
val literal = firstChild
if (literal is PsiErrorElement) return null
return RsLiteralKind.fromAstNode(literal.node)
?: error("Unknown literal: $firstChild (`$text`)")
}
fun offsetsForNumber(node: ASTNode): LiteralOffsets {
val (start, digits) = when (node.text.take(2)) {
"0b" -> 2 to "01"
"0o" -> 2 to "012345678"
"0x" -> 2 to "0123456789abcdefABCDEF"
else -> 0 to "0123456789"
}
var hasExponent = false
node.text.substring(start).forEachIndexed { i, ch ->
if (!hasExponent && ch in "eE") {
hasExponent = true
} else if (ch !in digits && ch !in "+-_.") {
return LiteralOffsets(
value = TextRange.create(0, i + start),
suffix = TextRange(i + start, node.textLength))
}
}
return LiteralOffsets(value = TextRange.allOf(node.text))
}
fun offsetsForText(node: ASTNode): LiteralOffsets {
when (node.elementType) {
RAW_STRING_LITERAL, RAW_BYTE_STRING_LITERAL ->
return offsetsForRawText(node)
}
val text = node.text
val quote = when (node.elementType) {
BYTE_LITERAL, CHAR_LITERAL -> '\''
else -> '"'
}
val prefixEnd = locatePrefix(node)
val openDelimEnd = doLocate(node, prefixEnd) {
assert(text[it] == quote) { "expected open delimiter `$quote` but found `${text[it]}`" }
it + 1
}
val valueEnd = doLocate(node, openDelimEnd, fun(start: Int): Int {
var escape = false
text.substring(start).forEachIndexed { i, ch ->
if (escape) {
escape = false
} else when (ch) {
'\\' -> escape = true
quote -> return i + start
}
}
return node.textLength
})
val closeDelimEnd = doLocate(node, valueEnd) {
assert(text[it] == quote) { "expected close delimiter `$quote` but found `${text[it]}`" }
it + 1
}
return LiteralOffsets.fromEndOffsets(prefixEnd, openDelimEnd, valueEnd, closeDelimEnd, node.textLength)
}
private fun offsetsForRawText(node: ASTNode): LiteralOffsets {
val text = node.text
val textLength = node.textLength
val prefixEnd = locatePrefix(node)
val hashes = run {
var pos = prefixEnd
while (pos < textLength && text[pos] == '#') {
pos++
}
pos - prefixEnd
}
val openDelimEnd = doLocate(node, prefixEnd) {
assert(textLength - it >= 1 + hashes && text[it] == '#' || text[it] == '"') { "expected open delim" }
it + 1 + hashes
}
val valueEnd = doLocate(node, openDelimEnd, fun(start: Int): Int {
text.substring(start).forEachIndexed { i, ch ->
if (start + i + hashes < textLength &&
ch == '"' &&
text.subSequence(start + i + 1, start + i + 1 + hashes).all { it == '#' }) {
return i + start
}
}
return textLength
})
val closeDelimEnd = doLocate(node, valueEnd) {
assert(textLength - it >= 1 + hashes && text[it] == '"') { "expected close delim" }
it + 1 + hashes
}
return LiteralOffsets.fromEndOffsets(prefixEnd, openDelimEnd, valueEnd, closeDelimEnd, textLength)
}
private fun locatePrefix(node: ASTNode): Int {
node.text.forEachIndexed { i, ch ->
if (!ch.isLetter()) {
return i
}
}
return node.textLength
}
private inline fun doLocate(node: ASTNode, start: Int, locator: (Int) -> Int): Int =
if (start >= node.textLength) start else locator(start)
| mit | 46ab49af88fa8e3af67023ef0a58c1f8 | 30.484581 | 114 | 0.597733 | 4.114565 | false | false | false | false |
bornest/KotlinUtils | rx2/src/main/java/com/github/kotlinutils/rx2/bus/RxBus.kt | 1 | 12548 | @file:Suppress("NOTHING_TO_INLINE")
package com.github.kotlinutils.rx2.bus
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.ReplaySubject
import io.reactivex.subjects.Subject
import java.util.concurrent.TimeUnit
/**
* [RxBus] based on [PublishSubject] of type [Any]
*/
typealias RxPublishBus = RxBus<PublishSubject<Any>, Any>
/**
* [RxBus] based on [PublishSubject] of type T
*/
typealias RxTypedPublishBus<T> = RxBus<PublishSubject<T>, T>
/**
* [RxBus] based on [BehaviorSubject] of type [Any]
*/
typealias RxBehaviorBus = RxBus<BehaviorSubject<Any>, Any>
/**
* [RxBus] based on [BehaviorSubject] of type T
*/
typealias RxTypedBehaviorBus<T> = RxBus<BehaviorSubject<T>, T>
/**
* [RxBus] based on [ReplaySubject] of type [Any]
*/
typealias RxReplayBus = RxBus<ReplaySubject<Any>, Any>
/**
* [RxBus] based on [ReplaySubject] of type T
*/
typealias RxTypedReplayBus<T> = RxBus<ReplaySubject<T>, T>
/**
* A wrapper for [Subject] which represents an Event Bus.
* Abstracts the functionality of underlying Subject by providing smaller interface relevant to this particular use case.
*
* @param S type of wrapped [Subject<D>]
* @param D type of events to be passed through Bus
* @param subject [Subject<D>] to wrap
* @param serialized [Boolean] that determines whether to serialize the underlying Subject (**true by default**)
*
* @property dataType [Class] that corresponds to type of events to be passed through Bus (**null by default**)
*/
class RxBus<out S, D>(
subject: S,
val dataType: Class<D>? = null,
serialized: Boolean = true
)
where S : Subject<D>, D : Any {
private val _bus = subject.also { if (serialized) it.toSerialized() }
/**
* A Java Class of underlying [Subject]
*/
val busType = subject::class.java
/**
* Send an item through the Bus
*
* @param item item to send
*/
fun send(item: D) = _bus.onNext(item)
/**
* Returns true if the subject has any Observers.
* This method is thread-safe.
*
* @return true if the subject has any Observers
*/
fun hasObservers() = _bus.hasObservers()
/**
* Convert Bus into an Observable that emits events sent through this Bus.
*
* @return [Observable] which you can use to subscribe to events sent through this Bus
*/
fun toObservable(): Observable<D>
= _bus.hide()
/**
* Convert Bus into an Observable that emits events sent through this Bus only if they are of specified type.
*
* @param T the type to filter the items emitted by resulting Observable
*
* @return [Observable] which you can use to subscribe to events type that are sent through this Bus
*/
inline fun <reified T : D> toObservableOfType(): Observable<T>
= toObservableOfType(T::class.java)
/**
* Convert Bus into a Observable that emits events sent through this Bus only if they are of specified type.
*
* @param eventType the [Class<T>] type to filter the items emitted by resulting Observable
*
* @return [Observable] which you can use to subscribe to events type that are sent through this Bus
*/
inline fun <T : D> toObservableOfType(eventType: Class<T>): Observable<T>
= toObservable().ofType(eventType)
/**
* Convert Bus into a Flowable that emits events sent through this Bus.
*
* @return [Flowable] with [BackpressureStrategy.BUFFER] which you can use to subscribe to events sent through this Bus
*/
inline fun toFlowable() = toFlowable(BackpressureStrategy.BUFFER)
/**
* Convert Bus into a Flowable that emits events sent through this Bus
*
* @param backpressureStrategy [BackpressureStrategy] you want to use
*
* @return [Flowable] with specified backpressure strategy which you can use to subscribe to events sent through this Bus
*/
fun toFlowable(backpressureStrategy: BackpressureStrategy) : Flowable<D>
= _bus.toFlowable(backpressureStrategy)
/**
* Convert Bus into a Flowable that emits events sent through this Bus only if they are of specified type.
*
* @param T the type to filter the items emitted by resulting Flowable
* @param backpressureStrategy [BackpressureStrategy] you want to use (**[BackpressureStrategy.BUFFER] by default**)
*
* @return [Flowable] which you can use to subscribe to events type that are sent through this Bus
*/
inline fun <reified T : D> toFlowableOfType(backpressureStrategy: BackpressureStrategy = BackpressureStrategy.BUFFER) : Flowable<T>
= toFlowableOfType(T::class.java, backpressureStrategy)
/**
* Convert Bus into a Flowable that emits events sent through this Bus only if they are of specified type.
*
* @param eventType the [Class<T>] type to filter the items emitted by resulting Flowable
* @param backpressureStrategy [BackpressureStrategy] you want to use (**[BackpressureStrategy.BUFFER] by default**)
*
* @return [Flowable] which you can use to subscribe to events type that are sent through this Bus
*/
inline fun <T : D> toFlowableOfType(eventType: Class<T>, backpressureStrategy: BackpressureStrategy = BackpressureStrategy.BUFFER) : Flowable<T>
= toFlowable(backpressureStrategy).ofType(eventType)
}
//region PublishBus
/**
* Create an [RxPublishBus]
*
* @return new [RxPublishBus]
*/
inline fun rxPublishBus(): RxPublishBus {
return RxPublishBus(
PublishSubject.create<Any>(),
Any::class.java
)
}
/**
* Create an [RxTypedPublishBus]
*
* @param T type of items to be sent through the bus
*
* @return new [RxTypedPublishBus] of specified type T
*/
inline fun <reified T : Any> rxTypedPublishBus(): RxTypedPublishBus<T> {
return RxTypedPublishBus<T>(
PublishSubject.create<T>(),
T::class.java
)
}
//endregion
//region BehaviorBus
/**
* Create an [RxBehaviorBus] with an optional default item
*
* @param defaultValue the item that will be emitted first to any Observer as long as no items have been sent through the bus yet (**none by default**)
*
* @return new [RxBehaviorBus] with specified default item
*/
inline fun rxBehaviorBus(defaultValue: Any? = null): RxBehaviorBus {
return RxBehaviorBus(
if (defaultValue != null)
BehaviorSubject.createDefault<Any>(defaultValue)
else
BehaviorSubject.create<Any>(),
Any::class.java
)
}
/**
* Create an [RxTypedBehaviorBus] with an optional default item
*
* @param T type of items to be sent through the bus
* @param defaultValue the item that will be emitted first to any Observer as long as no items have been sent through the bus yet (**none by default**)
*
* @return new [RxTypedBehaviorBus] of specified type T with specified default item
*/
inline fun <reified T : Any> rxTypedBehaviorBus(defaultValue: T? = null): RxTypedBehaviorBus<T> {
return RxTypedBehaviorBus<T>(
if (defaultValue != null)
BehaviorSubject.createDefault<T>(defaultValue)
else
BehaviorSubject.create<T>(),
T::class.java
)
}
//endregion
//region ReplayBus
/**
* Create an unbounded [RxReplayBus] with an optional initial buffer capacity
*
* @param capacityHint the initial buffer capacity of underlying ReplaySubject (**not set by default**)
*
* @return new [RxReplayBus] with specified initial buffer capacity
*/
inline fun rxReplayBus(capacityHint: Int? = null): RxReplayBus {
return RxReplayBus(
if (capacityHint != null)
ReplaySubject.create<Any>(capacityHint)
else
ReplaySubject.create<Any>(),
Any::class.java
)
}
/**
* Create a size-bounded [RxReplayBus]
*
* @param maxSize the maximum number of buffered items
*
* @return new [RxReplayBus] with specified maximum number of buffered items
*/
inline fun rxReplayBusWithSize(maxSize: Int): RxReplayBus {
return RxReplayBus(
ReplaySubject.createWithSize<Any>(maxSize),
Any::class.java
)
}
/**
* Create a time-bounded [RxReplayBus]
*
* @param maxAge the maximum age of the contained items
* @param unit the unit of time
* @param scheduler the [Scheduler] that provides the current time
*
* @return new [RxReplayBus] with specified time bounds
*/
inline fun rxReplayBusWithTime(maxAge: Long, unit: TimeUnit, scheduler: Scheduler): RxReplayBus {
return RxReplayBus(
ReplaySubject.createWithTime<Any>(maxAge, unit, scheduler),
Any::class.java
)
}
/**
* Create a time- and size-bounded [RxReplayBus]
*
* @param maxAge the maximum age of the contained items
* @param unit the unit of time
* @param scheduler the [Scheduler] that provides the current time
* @param maxSize the maximum number of buffered items
*
* @return new [RxReplayBus] with specified time and size bounds
*/
inline fun rxReplayBusWithTimeAndSize(maxAge: Long, unit: TimeUnit, scheduler: Scheduler, maxSize: Int): RxReplayBus {
return RxReplayBus(
ReplaySubject.createWithTimeAndSize<Any>(maxAge, unit, scheduler, maxSize),
Any::class.java
)
}
/**
* Create an unbounded [RxTypedReplayBus] with an optional initial buffer capacity
*
* @param T type of items to be sent through the bus
* @param capacityHint the initial buffer capacity of underlying ReplaySubject (**not set by default**)
*
* @return new [RxTypedReplayBus] of specified type T with specified initial buffer capacity
*/
inline fun <reified T : Any> rxTypedReplayBus(capacityHint: Int? = null): RxTypedReplayBus<T> {
return RxTypedReplayBus<T>(
if (capacityHint != null)
ReplaySubject.create<T>(capacityHint)
else
ReplaySubject.create<T>(),
T::class.java
)
}
/**
* Create a size-bounded [RxTypedReplayBus]
*
* @param T type of items to be sent through the bus
* @param maxSize the maximum number of buffered items
*
* @return new [RxTypedReplayBus] of specified type T with specified maximum number of buffered items
*/
inline fun <reified T : Any> rxTypedReplayBusWithSize(maxSize: Int): RxTypedReplayBus<T> {
return RxTypedReplayBus<T>(
ReplaySubject.createWithSize<T>(maxSize),
T::class.java
)
}
/**
* Create a time-bounded [RxTypedReplayBus]
*
* @param T type of items to be sent through the bus
* @param maxAge the maximum age of the contained items
* @param unit the unit of time
* @param scheduler the [Scheduler] that provides the current time
*
* @return new [RxTypedReplayBus] of specified type T with specified time bounds
*/
inline fun <reified T : Any> rxTypedReplayBusWithTime(maxAge: Long, unit: TimeUnit, scheduler: Scheduler): RxTypedReplayBus<T> {
return RxTypedReplayBus<T>(
ReplaySubject.createWithTime<T>(maxAge, unit, scheduler),
T::class.java
)
}
/**
* Create a time- and size-bounded [RxTypedReplayBus]
*
* @param T type of items to be sent through the bus
* @param maxAge the maximum age of the contained items
* @param unit the unit of time
* @param scheduler the [Scheduler] that provides the current time
* @param maxSize the maximum number of buffered items
*
* @return new [RxTypedReplayBus] of specified type T with specified time and size bounds
*/
inline fun <reified T : Any> rxTypedReplayBusWithTimeAndSize(maxAge: Long, unit: TimeUnit, scheduler: Scheduler, maxSize: Int): RxTypedReplayBus<T> {
return RxTypedReplayBus<T>(
ReplaySubject.createWithTimeAndSize<T>(maxAge, unit, scheduler, maxSize),
T::class.java
)
}
//endregion
| apache-2.0 | 3a2848585e2994370e44b74125581c41 | 34.647727 | 155 | 0.656599 | 4.375174 | false | false | false | false |
italoag/qksms | presentation/src/main/java/com/moez/QKSMS/feature/conversationinfo/GridSpacingItemDecoration.kt | 3 | 2247 | /*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.feature.conversationinfo
import android.content.Context
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.moez.QKSMS.common.util.extensions.dpToPx
import com.moez.QKSMS.feature.conversationinfo.ConversationInfoItem.ConversationInfoMedia
import com.moez.QKSMS.feature.conversationinfo.ConversationInfoItem.ConversationInfoRecipient
class GridSpacingItemDecoration(
private val adapter: ConversationInfoAdapter,
private val context: Context
) : RecyclerView.ItemDecoration() {
private val spanCount = 3
private val spacing = 2.dpToPx(context)
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val position = parent.getChildAdapterPosition(view)
val item = adapter.getItem(position)
if (item is ConversationInfoRecipient && adapter.getItem(position + 1) !is ConversationInfoRecipient) {
outRect.bottom = 8.dpToPx(context)
} else if (item is ConversationInfoMedia) {
val firstPartIndex = adapter.data.indexOfFirst { it is ConversationInfoMedia }
val localPartIndex = position - firstPartIndex
val column = localPartIndex % spanCount
outRect.top = spacing
outRect.left = column * spacing / spanCount
outRect.right = spacing - (column + 1) * spacing / spanCount
}
}
} | gpl-3.0 | 1fc284c9709a44cff9558d3eee7a6afb | 38.438596 | 111 | 0.730752 | 4.467197 | false | false | false | false |
http4k/http4k | http4k-core/src/main/kotlin/org/http4k/routing/spa.kt | 1 | 2144 | package org.http4k.routing
import org.http4k.core.ContentType
import org.http4k.core.Filter
import org.http4k.core.Method.GET
import org.http4k.core.Method.OPTIONS
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.NOT_FOUND
import org.http4k.routing.RouterMatch.MatchingHandler
import org.http4k.routing.RouterMatch.MethodNotMatched
/**
* For SPAs we serve static content as usual, or fall back to the index page. The resource loader is configured to look at
* /public package (on the Classpath).
*/
fun singlePageApp(
resourceLoader: ResourceLoader = ResourceLoader.Classpath("/public"),
vararg extraFileExtensionToContentTypes: Pair<String, ContentType>
): RoutingHttpHandler =
SinglePageAppRoutingHandler(
"",
StaticRoutingHttpHandler("", resourceLoader, extraFileExtensionToContentTypes.asList().toMap())
)
internal data class SinglePageAppRoutingHandler(
private val pathSegments: String,
private val staticHandler: StaticRoutingHttpHandler
) : RoutingHttpHandler {
override fun invoke(request: Request): Response {
val matchOnStatic = when (val matchResult = staticHandler.match(request)) {
is MatchingHandler -> matchResult(request)
else -> null
}
val matchOnIndex = when (val matchResult = staticHandler.match(Request(GET, pathSegments))) {
is MatchingHandler -> matchResult
else -> null
}
val fallbackHandler = matchOnIndex ?: { Response(NOT_FOUND) }
return matchOnStatic ?: fallbackHandler(Request(GET, pathSegments))
}
override fun match(request: Request) = when (request.method) {
OPTIONS -> MethodNotMatched(RouterDescription("template == '$pathSegments'"))
else -> MatchingHandler(this, description)
}
override fun withFilter(new: Filter) =
copy(staticHandler = staticHandler.withFilter(new) as StaticRoutingHttpHandler)
override fun withBasePath(new: String) =
SinglePageAppRoutingHandler(new + pathSegments, staticHandler.withBasePath(new) as StaticRoutingHttpHandler)
}
| apache-2.0 | dfd0c387f2bf3e8ea66184be34daf0ca | 37.285714 | 122 | 0.730877 | 4.420619 | false | false | false | false |
http4k/http4k | http4k-core/src/main/kotlin/org/http4k/security/CredentialsProvider.kt | 1 | 1874 | package org.http4k.security
import java.time.Clock
import java.time.Duration
import java.time.Duration.ZERO
import java.time.Instant
import java.util.concurrent.atomic.AtomicReference
fun interface CredentialsProvider<T> : () -> T? {
companion object
}
fun interface RefreshCredentials<T> : (T?) -> ExpiringCredentials<T>?
data class ExpiringCredentials<T>(val credentials: T, val expiry: Instant)
fun <T> CredentialsProvider.Companion.Refreshing(
gracePeriod: Duration = Duration.ofSeconds(10),
clock: Clock = Clock.systemUTC(),
refreshFn: RefreshCredentials<T>
) = object : CredentialsProvider<T> {
private val stored = AtomicReference<ExpiringCredentials<T>>(null)
private val isRefreshing = AtomicReference(false)
override fun invoke() = (stored.get()
?.takeIf {
val expiresSoon = it.expiresWithin(gracePeriod)
val expiresReallySoon = it.expiresWithin(gracePeriod.dividedBy(2))
val isAlreadyRefreshing = isRefreshing.get()
(!expiresSoon || isAlreadyRefreshing) && !expiresReallySoon
} ?: refresh())?.credentials
private fun refresh() = synchronized(this) {
isRefreshing.set(true)
try {
val current = stored.get()
when {
current != null && !current.expiresWithin(gracePeriod) -> current
else -> try {
refreshFn(current?.credentials).also(stored::set)
} catch (e: Exception) {
if (current == null || current.expiresWithin(ZERO)) throw e
current
}
}
} finally {
isRefreshing.set(false)
}
}
private fun ExpiringCredentials<T>.expiresWithin(duration: Duration): Boolean =
expiry
.minus(duration)
.isBefore(clock.instant())
}
| apache-2.0 | ae34b67ca1279be9fe57068828da6236 | 31.877193 | 83 | 0.625934 | 4.559611 | false | false | false | false |
RFonzi/RxAware | rxaware-lib/src/main/java/io/github/rfonzi/rxaware/RxAwareFragment.kt | 1 | 1275 | package io.github.rfonzi.rxaware
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentTransaction
import android.support.v7.app.AppCompatActivity
import io.github.rfonzi.rxaware.bus.UIBus
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
/**
* Created by ryan on 9/20/17.
*/
abstract class RxAwareFragment : Fragment(), RxAwareControls {
private val disposables = CompositeDisposable()
fun Disposable.lifecycleAware() = disposables.add(this)
override fun toast(message: String) = UIBus.toast(message)
override fun navigateUp() = UIBus.navigateUp()
override fun fragmentTransaction(operations: FragmentTransaction.() -> Unit) = UIBus.fragmentTransaction(operations)
override fun startActivity(target: Class<out AppCompatActivity>) = UIBus.startActivity(target)
override fun startActivityAndStore(target: Class<out AppCompatActivity>, data: Any) = UIBus.startActivityAndStore(target, data)
override fun store(data: Any) = UIBus.store(data)
override fun receive(): Any = UIBus.receive()
fun <T : Any> postToCurrentActivity(data: T) = UIBus.postToCurrentActivity(data)
override fun onStop() {
super.onStop()
disposables.clear()
}
} | mit | d25827962942cdd8bfe747cb96dcfb9b | 31.717949 | 131 | 0.756078 | 4.180328 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/BackupManager.kt | 1 | 18220 | /***************************************************************************************
* Copyright (c) 2011 Norbert Nagold <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki
import android.content.SharedPreferences
import androidx.annotation.VisibleForTesting
import androidx.core.content.edit
import com.ichi2.compat.CompatHelper
import com.ichi2.libanki.Collection
import com.ichi2.libanki.Utils
import com.ichi2.libanki.utils.Time
import com.ichi2.libanki.utils.Time.Companion.utcOffset
import com.ichi2.libanki.utils.TimeManager
import com.ichi2.utils.FileUtil.getFreeDiskSpace
import timber.log.Timber
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
open class BackupManager {
/**
* Attempts to create a backup in a background thread. Returns `true` if the process is started.
*
* Returns false:
* * If backups are disabled
* * If [interval] hours have not elapsed since the last backup
* * If the filename creation failed
* * If [interval] is 0, and the backup already exists
* * If the user has insufficient space
* * If the collection is too small to be valid
*
* @param colPath The path of the collection file
* @param interval If this amount of hours has not elapsed since last backup, return false and do not create backup. See: [BACKUP_INTERVAL]
*
* @return Whether a thread was started to create a backup
*/
@Suppress("PMD.NPathComplexity")
fun performBackupInBackground(colPath: String, interval: Int, time: Time): Boolean {
val prefs = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.instance.baseContext)
if (hasDisabledBackups(prefs)) {
Timber.w("backups are disabled")
return false
}
val colFile = File(colPath)
val colBackups = getBackups(colFile)
if (isBackupUnnecessary(colFile, colBackups)) {
Timber.d("performBackup: No backup necessary due to no collection changes")
return false
}
// Abort backup if one was already made less than [interval] hours ago (default: 5 hours - BACKUP_INTERVAL)
val lastBackupDate = getLastBackupDate(colBackups)
if (lastBackupDate != null && lastBackupDate.time + interval * 3600000L > time.intTimeMS()) {
Timber.d("performBackup: No backup created. Last backup younger than 5 hours")
return false
}
val backupFilename = getNameForNewBackup(time) ?: return false
// Abort backup if destination already exists (extremely unlikely)
val backupFile = getBackupFile(colFile, backupFilename)
if (backupFile.exists()) {
Timber.d("performBackup: No new backup created. File already exists")
return false
}
// Abort backup if not enough free space
if (!hasFreeDiscSpace(colFile)) {
Timber.e("performBackup: Not enough space on sd card to backup.")
prefs.edit { putBoolean("noSpaceLeft", true) }
return false
}
// Don't bother trying to do backup if the collection is too small to be valid
if (collectionIsTooSmallToBeValid(colFile)) {
Timber.d("performBackup: No backup created as the collection is too small to be valid")
return false
}
// TODO: Probably not a good idea to do the backup while the collection is open
if (CollectionHelper.instance.colIsOpen()) {
Timber.w("Collection is already open during backup... we probably shouldn't be doing this")
}
// Backup collection as Anki package in new thread
performBackupInNewThread(colFile, backupFile)
return true
}
fun isBackupUnnecessary(colFile: File, colBackups: Array<File>): Boolean {
val len = colBackups.size
// If have no backups, then a backup is necessary
return if (len <= 0) {
false
} else colBackups[len - 1].lastModified() == colFile.lastModified()
// no collection changes means we don't need a backup
}
/**
* @return last date in parsable file names or null if all names can't be parsed
* Expects a sorted array of backups, as returned by getBackups()
*/
fun getLastBackupDate(files: Array<File>): Date? {
return files.lastOrNull()?.let {
getBackupDate(it.name)
}
}
fun getBackupFile(colFile: File, backupFilename: String): File {
return File(getBackupDirectory(colFile.parentFile!!), backupFilename)
}
fun performBackupInNewThread(colFile: File, backupFile: File) {
Timber.i("Launching new thread to backup %s to %s", colFile.absolutePath, backupFile.path)
val thread: Thread = object : Thread() {
override fun run() {
performBackup(colFile, backupFile)
}
}
thread.start()
}
private fun performBackup(colFile: File, backupFile: File): Boolean {
val colPath = colFile.absolutePath
// Save collection file as zip archive
return try {
val zos = ZipOutputStream(BufferedOutputStream(FileOutputStream(backupFile)))
val ze = ZipEntry(CollectionHelper.COLLECTION_FILENAME)
zos.putNextEntry(ze)
CompatHelper.compat.copyFile(colPath, zos)
zos.close()
// Delete old backup files if needed
val prefs = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.instance.baseContext)
deleteColBackups(colPath, prefs.getInt("backupMax", 8))
// set timestamp of file in order to avoid creating a new backup unless its changed
if (!backupFile.setLastModified(colFile.lastModified())) {
Timber.w("performBackupInBackground() setLastModified() failed on file %s", backupFile.name)
return false
}
Timber.i("Backup created successfully")
true
} catch (e: IOException) {
Timber.w(e)
false
}
}
fun collectionIsTooSmallToBeValid(colFile: File): Boolean {
return (
colFile.length()
< MIN_BACKUP_COL_SIZE
)
}
fun hasFreeDiscSpace(colFile: File): Boolean {
return getFreeDiscSpace(colFile) >= getRequiredFreeSpace(colFile)
}
@VisibleForTesting
fun hasDisabledBackups(prefs: SharedPreferences): Boolean {
return prefs.getInt("backupMax", 8) == 0
}
companion object {
/**
* Number of MB of
*/
private const val MIN_FREE_SPACE = 10
private const val MIN_BACKUP_COL_SIZE = 10000 // threshold in bytes to backup a col file
private const val BACKUP_SUFFIX = "backup"
const val BROKEN_COLLECTIONS_SUFFIX = "broken"
private val backupNameRegex: Regex by lazy {
Regex("(?:collection|backup)-((\\d{4})-(\\d{2})-(\\d{2})-(\\d{2})[.-](\\d{2}))(?:\\.\\d{2})?.colpkg")
}
/** Number of hours after which a backup new backup is created */
private const val BACKUP_INTERVAL = 5
private val legacyDateFormat = SimpleDateFormat("yyyy-MM-dd-HH-mm")
private val newDateFormat = SimpleDateFormat("yyyy-MM-dd-HH.mm")
val isActivated: Boolean
get() = true
fun getBackupDirectory(ankidroidDir: File): File {
val directory = File(ankidroidDir, BACKUP_SUFFIX)
if (!directory.isDirectory && !directory.mkdirs()) {
Timber.w("getBackupDirectory() mkdirs on %s failed", ankidroidDir)
}
return directory
}
fun getBackupDirectoryFromCollection(colPath: String): String {
return getBackupDirectory(File(colPath).parentFile!!).absolutePath
}
private fun getBrokenDirectory(ankidroidDir: File): File {
val directory = File(ankidroidDir, BROKEN_COLLECTIONS_SUFFIX)
if (!directory.isDirectory && !directory.mkdirs()) {
Timber.w("getBrokenDirectory() mkdirs on %s failed", ankidroidDir)
}
return directory
}
fun performBackupInBackground(path: String, time: Time): Boolean {
return BackupManager().performBackupInBackground(path, BACKUP_INTERVAL, time)
}
/**
* @param colFile The current collection file to backup
* @return the amount of free space required for a backup.
*/
fun getRequiredFreeSpace(colFile: File): Long {
// We add a minimum amount of free space to ensure against
return colFile.length() + MIN_FREE_SPACE * 1024 * 1024
}
fun enoughDiscSpace(path: String?): Boolean {
return getFreeDiscSpace(path) >= MIN_FREE_SPACE * 1024 * 1024
}
/**
* Get free disc space in bytes from path to Collection
*/
fun getFreeDiscSpace(path: String?): Long {
return getFreeDiscSpace(File(path!!))
}
private fun getFreeDiscSpace(file: File): Long {
return getFreeDiskSpace(file, (MIN_FREE_SPACE * 1024 * 1024).toLong())
}
/**
* Run the sqlite3 command-line-tool (if it exists) on the collection to dump to a text file
* and reload as a new database. Recently this command line tool isn't available on many devices
*
* @param col Collection
* @return whether the repair was successful
*/
fun repairCollection(col: Collection): Boolean {
val colPath = col.path
val colFile = File(colPath)
val time = TimeManager.time
Timber.i("BackupManager - RepairCollection - Closing Collection")
col.close()
// repair file
val execString = "sqlite3 $colPath .dump | sqlite3 $colPath.tmp"
Timber.i("repairCollection - Execute: %s", execString)
try {
val cmd = arrayOf("/system/bin/sh", "-c", execString)
val process = Runtime.getRuntime().exec(cmd)
process.waitFor()
if (!File("$colPath.tmp").exists()) {
Timber.e("repairCollection - dump to %s.tmp failed", colPath)
return false
}
if (!moveDatabaseToBrokenDirectory(colPath, false, time)) {
Timber.e("repairCollection - could not move corrupt file to broken directory")
return false
}
Timber.i("repairCollection - moved corrupt file to broken directory")
val repairedFile = File("$colPath.tmp")
return repairedFile.renameTo(colFile)
} catch (e: IOException) {
Timber.e(e, "repairCollection - error")
} catch (e: InterruptedException) {
Timber.e(e, "repairCollection - error")
}
return false
}
fun moveDatabaseToBrokenDirectory(colPath: String, moveConnectedFilesToo: Boolean, time: Time): Boolean {
val colFile = File(colPath)
// move file
val value: Date = time.genToday(utcOffset())
var movedFilename = String.format(
Utils.ENGLISH_LOCALE,
colFile.name.replace(".anki2", "") +
"-corrupt-%tF.anki2",
value
)
var movedFile = File(getBrokenDirectory(colFile.parentFile!!), movedFilename)
var i = 1
while (movedFile.exists()) {
movedFile = File(
getBrokenDirectory(colFile.parentFile!!),
movedFilename.replace(
".anki2",
"-$i.anki2"
)
)
i++
}
movedFilename = movedFile.name
if (!colFile.renameTo(movedFile)) {
return false
}
if (moveConnectedFilesToo) {
// move all connected files (like journals, directories...) too
val colName = colFile.name
val directory = File(colFile.parent!!)
for (f in directory.listFiles()!!) {
if (f.name.startsWith(colName) &&
!f.renameTo(File(getBrokenDirectory(colFile.parentFile!!), f.name.replace(colName, movedFilename)))
) {
return false
}
}
}
return true
}
/**
* Parses a string with backup naming pattern
* @param fileName String with pattern "collection-yyyy-MM-dd-HH-mm.colpkg"
* @return Its dateformat parsable string or null if it doesn't match naming pattern
*/
fun getBackupTimeString(fileName: String): String? {
return backupNameRegex.matchEntire(fileName)?.groupValues?.get(1)
}
/**
* @return date in string if it matches backup naming pattern or null if not
*/
fun parseBackupTimeString(timeString: String): Date? {
return try {
legacyDateFormat.parse(timeString)
} catch (e: ParseException) {
try {
newDateFormat.parse(timeString)
} catch (e: ParseException) {
null
}
}
}
/**
* @return date in fileName if it matches backup naming pattern or null if not
*/
fun getBackupDate(fileName: String): Date? {
return getBackupTimeString(fileName)?.let { parseBackupTimeString(it) }
}
/**
* @return filename with pattern collection-yyyy-MM-dd-HH-mm based on given time parameter
*/
fun getNameForNewBackup(time: Time): String? {
/** Changes in the file name pattern should be updated as well in
* [getBackupTimeString] and [com.ichi2.anki.dialogs.DatabaseErrorDialog.onCreateDialog] */
val cal: Calendar = time.gregorianCalendar()
val backupFilename: String = try {
String.format(Utils.ENGLISH_LOCALE, "collection-%s.colpkg", legacyDateFormat.format(cal.time))
} catch (e: UnknownFormatConversionException) {
Timber.w(e, "performBackup: error on creating backup filename")
return null
}
return backupFilename
}
/**
* @return Array of files with names which matches the backup name pattern,
* in order of creation.
*/
fun getBackups(colFile: File): Array<File> {
val files = getBackupDirectory(colFile.parentFile!!).listFiles() ?: arrayOf()
val backups = files
.mapNotNull { file ->
getBackupTimeString(file.name)?.let { time ->
Pair(time, file)
}
}
.sortedBy { it.first }
.map { it.second }
return backups.toTypedArray()
}
/**
* Returns the most recent backup, or null if no backups exist matching [the backup name pattern][backupNameRegex]
*
* @return the most recent backup, or null if no backups exist
*/
fun getLatestBackup(colFile: File): File? = getBackups(colFile).lastOrNull()
/**
* Deletes the first files until only the given number of files remain
* @param colPath Path of collection file whose backups should be deleted
* @param keepNumber How many files to keep
*/
fun deleteColBackups(colPath: String, keepNumber: Int): Boolean {
return deleteColBackups(getBackups(File(colPath)), keepNumber)
}
private fun deleteColBackups(backups: Array<File>, keepNumber: Int): Boolean {
for (i in 0 until backups.size - keepNumber) {
if (!backups[i].delete()) {
Timber.e("deleteColBackups() failed to delete %s", backups[i].absolutePath)
} else {
Timber.i("deleteColBackups: backup file %s deleted.", backups[i].absolutePath)
}
}
return true
}
fun removeDir(dir: File): Boolean {
if (dir.isDirectory) {
val files = dir.listFiles()
for (aktFile in files!!) {
removeDir(aktFile)
}
}
return dir.delete()
}
@VisibleForTesting(otherwise = VisibleForTesting.NONE)
fun createInstance(): BackupManager {
return BackupManager()
}
}
}
| gpl-3.0 | 54d1637c0914f7c669e48632b2485143 | 40.409091 | 143 | 0.572338 | 4.892589 | false | false | false | false |
akvo/akvo-flow-mobile | utils/src/main/java/org/akvo/flow/utils/entity/Question.kt | 1 | 3802 | /*
* Copyright (C) 2021 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow 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.
*
* Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.flow.utils.entity
import java.util.HashMap
data class Question(
var questionId: String? = null,
var isMandatory: Boolean = false,
var text: String? = null,
var order: Int = 0,
var isAllowOther: Boolean = false,
var questionHelp: MutableList<QuestionHelp> = mutableListOf(),
var type: String? = null,
var options: MutableList<Option>? = null,
var isAllowMultiple: Boolean = false,
var isLocked: Boolean = false,
var languageTranslationMap: HashMap<String?, AltText> = HashMap(),
var dependencies: MutableList<Dependency> = mutableListOf(),
var isLocaleName: Boolean = false,
var isLocaleLocation: Boolean = false,
var isDoubleEntry: Boolean = false,
var isAllowPoints: Boolean = false,
var isAllowLine: Boolean = false,
var isAllowPolygon: Boolean = false,
var caddisflyRes: String? = null,
var cascadeResource: String? = null,
var levels: MutableList<Level> = mutableListOf(),
var validationRule: ValidationRule? = null,
) {
fun addAltText(altText: AltText) {
languageTranslationMap[altText.languageCode] = altText
}
//TODO: this is only useful for repeated question groups, should be removed
/**
* Clone a question and update the question ID. This is only relevant for repeat-question-groups,
* which require different instances of the question for each iteration.
* Note: Excluding dependencies, all non-primitive variables are *not* deep-copied.
*/
fun copy(question: Question, questionId: String): Question {
val q = Question(
questionId = questionId,
text = question.text,
order = question.order,
isMandatory = question.isMandatory,
type = question.type,
isAllowOther = question.isAllowOther,
isAllowMultiple = question.isAllowMultiple,
isLocked = question.isLocked,
isLocaleName = question.isLocaleName,
isLocaleLocation = question.isLocaleLocation,
isDoubleEntry = question.isDoubleEntry,
isAllowPoints = question.isAllowPoints,
isAllowLine = question.isAllowLine,
isAllowPolygon = question.isAllowPolygon,
cascadeResource = question.cascadeResource,
validationRule = question.validationRule,
questionHelp = question.questionHelp,
languageTranslationMap = question.languageTranslationMap,
levels = question.levels,
caddisflyRes = question.caddisflyRes)
// Deep-copy dependencies
q.dependencies = ArrayList()
for (d in question.dependencies) {
q.dependencies.add(Dependency(d.question, d.answer))
}
// Deep-copy options
val options1 = question.options
if (options1 != null) {
q.options = mutableListOf()
for (o in options1) {
q.options!!.add(Option(o.text, o.code, o.isOther, o.altTextMap))
}
}
return q
}
}
| gpl-3.0 | 8a484a467f6e7cffa5ad435f687c8d68 | 37.795918 | 101 | 0.662809 | 4.504739 | false | false | false | false |
sys1yagi/conference-app-2017 | app/src/test/java/io/github/droidkaigi/confsched2017/api/DroidKaigiClientTest.kt | 8 | 2020 | package io.github.droidkaigi.confsched2017.api
import com.sys1yagi.kmockito.invoked
import com.sys1yagi.kmockito.mock
import com.sys1yagi.kmockito.verify
import io.github.droidkaigi.confsched2017.api.service.DroidKaigiService
import io.github.droidkaigi.confsched2017.api.service.GithubService
import io.github.droidkaigi.confsched2017.api.service.GoogleFormService
import io.github.droidkaigi.confsched2017.util.DummyCreator
import io.reactivex.Single
import org.junit.Test
import org.mockito.Mockito
import java.util.*
class DroidKaigiClientTest {
private val droidKaigiService = mock<DroidKaigiService>()
private val githubService = mock<GithubService>()
private val googleFormService = mock<GoogleFormService>()
private val client = DroidKaigiClient(droidKaigiService, githubService, googleFormService)
@Test
@Throws(Exception::class)
fun getSessions() {
val expected = Array(10) { DummyCreator.newSession(it) }.toList()
droidKaigiService.sessionsJa.invoked.thenReturn(Single.just(expected))
droidKaigiService.sessionsEn.invoked.thenReturn(Single.just(expected))
client.getSessions(Locale.JAPANESE).test().run {
assertNoErrors()
assertResult(expected)
assertComplete()
}
client.getSessions(Locale.ENGLISH).test().run {
assertNoErrors()
assertResult(expected)
assertComplete()
}
droidKaigiService.verify(Mockito.times(1)).sessionsJa
droidKaigiService.verify(Mockito.times(1)).sessionsEn
}
@Test
@Throws(Exception::class)
fun getContributors() {
val expected = Array(10) { DummyCreator.newContributor(it) }.toList()
githubService.getContributors("DroidKaigi", "conference-app-2017", 1, 100)
.invoked.thenReturn(Single.just(expected))
client.contributors.test().run {
assertNoErrors()
assertResult(expected)
assertComplete()
}
}
}
| apache-2.0 | 5d7bf3680c14516838b123ba27d74996 | 32.114754 | 94 | 0.705941 | 4.307036 | false | true | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/cause/entity/damage/source/AbstractEntityDamageSourceBuilder.kt | 1 | 1207 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.cause.entity.damage.source
import org.spongepowered.api.entity.Entity
import org.spongepowered.api.event.cause.entity.damage.source.EntityDamageSource
import org.spongepowered.api.event.cause.entity.damage.source.common.AbstractDamageSourceBuilder
@Suppress("UNCHECKED_CAST")
abstract class AbstractEntityDamageSourceBuilder<T : EntityDamageSource, B : EntityDamageSource.EntityDamageSourceBuilder<T, B>> :
AbstractDamageSourceBuilder<T, B>(), EntityDamageSource.EntityDamageSourceBuilder<T, B> {
internal var source: Entity? = null
override fun entity(entity: Entity): B = apply { this.source = entity } as B
override fun reset(): B = apply {
super.reset()
this.source = null
} as B
override fun from(value: T): B = apply {
super.from(value)
this.source = value.source
} as B
}
| mit | 4e46071606f35ae012e3f7916bde4c01 | 34.5 | 130 | 0.724109 | 3.970395 | false | false | false | false |
doubledeath/android.mvvm | mvvm/src/main/java/com/github/doubledeath/android/mvvm/base/MvvmBaseDelegate.kt | 1 | 2092 | package com.github.doubledeath.android.mvvm.base
import android.databinding.ViewDataBinding
import android.os.Bundle
import com.github.doubledeath.android.mvvm.MvvmFacade
import kotlin.reflect.KClass
internal abstract class MvvmBaseDelegate<out VM : MvvmBaseViewModel, out B : ViewDataBinding, out C>
constructor(private val klass: KClass<VM>,
private val navigator: MvvmBaseNavigator<C>) {
protected lateinit var tag: String
private set
private var viewModel: VM? = null
internal abstract fun binding(): B
internal abstract fun context(): C
internal fun onCreate(extras: Bundle?, savedInstanceState: Bundle?) {
val extrasTag = extras?.let { getTag(it) }
val savedInstanceStateTag = savedInstanceState?.let { getTag(it) }
tag = extrasTag ?: savedInstanceStateTag ?: MvvmFacade.tagGenerator.generateTag(klass)
}
internal open fun onViewActive() {
navigator.pool.putContext(tag, context())
viewModel().onViewActive()
}
internal fun onSaveInstanceState(outState: Bundle?) {
outState?.let { applyTag(it, tag) }
}
internal open fun onViewInactive() {
viewModel().onViewInactive()
navigator.pool.cleanContext(tag)
}
internal open fun onDestroy() {
if (!MvvmFacade.viewModelMapper.toSingle(klass)) {
viewModel().onDestroy()
navigator.pool.cleanViewModel(tag)
}
}
@Suppress("UNCHECKED_CAST")
internal fun viewModel(): VM {
val viewModel = viewModel ?: navigator.pool.provideViewModel(tag, klass, null) as VM
if (this.viewModel === null) {
this.viewModel = viewModel
}
return viewModel
}
internal companion object {
private val KEY_TAG: String = "com.github.doubledeath.android.mvvm.KEY_TAG"
internal fun getTag(bundle: Bundle): String? {
return bundle.getString(KEY_TAG)
}
internal fun applyTag(bundle: Bundle, tag: String) {
return bundle.putString(KEY_TAG, tag)
}
}
}
| mit | f4c3bf6b8f8f03f600bf9c145f959a65 | 26.893333 | 100 | 0.65631 | 4.528139 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/compoundmaker/CompoundMakerRecipe.kt | 1 | 5002 | package net.ndrei.teslapoweredthingies.machines.compoundmaker
import com.google.common.collect.Lists
import net.minecraft.item.ItemStack
import net.minecraft.util.ResourceLocation
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fluids.IFluidTank
import net.minecraftforge.items.IItemHandler
import net.ndrei.teslacorelib.utils.equalsIgnoreSize
import net.ndrei.teslacorelib.utils.extractFromCombinedInventory
import net.ndrei.teslacorelib.utils.getCombinedInventory
import net.ndrei.teslacorelib.utils.isEnough
import net.ndrei.teslapoweredthingies.api.compoundmaker.ICompoundMakerRecipe
import net.ndrei.teslapoweredthingies.common.BaseTeslaRegistryEntry
class CompoundMakerRecipe(name: ResourceLocation,
override val output: ItemStack,
val left: FluidStack? = null,
val top: Array<ItemStack> = arrayOf(),
val right: FluidStack? = null,
val bottom: Array<ItemStack> = arrayOf())
: BaseTeslaRegistryEntry<CompoundMakerRecipe>(CompoundMakerRecipe::class.java, name), ICompoundMakerRecipe<CompoundMakerRecipe> {
private fun FluidStack?.matchesFluid(fluid: FluidStack?, ignoreSize: Boolean, nullMatches: Boolean) =
if (nullMatches) {
(this == null) || (this.amount == 0) // this stack doesn't matter
|| this.isEnough(fluid, ignoreSize)
} else (this != null) && (this.amount > 0) && this.isEnough(fluid, ignoreSize)
override fun matchesLeft(fluid: FluidStack?, ignoreSize: Boolean, nullMatches: Boolean) = this.left.matchesFluid(fluid, ignoreSize, nullMatches)
override fun matchedRight(fluid: FluidStack?, ignoreSize: Boolean, nullMatches: Boolean) = this.right.matchesFluid(fluid, ignoreSize, nullMatches)
private fun Array<ItemStack>.getCombinedInventory(): List<ItemStack> {
val list = Lists.newArrayList<ItemStack>()
for (stack in this) {
if (stack.isEmpty) {
continue
}
val match: ItemStack? = list.firstOrNull { it.equalsIgnoreSize(stack) }
if (match == null) {
list.add(stack.copy())
} else {
match.count = match.count + stack.count
}
}
return list
}
private fun Array<ItemStack>.matchesInventory(holder: IItemHandler, ignoreSize: Boolean, emptyMatches: Boolean): Boolean {
if (this.isEmpty())
return emptyMatches
val inventory = holder.getCombinedInventory()
return this.getCombinedInventory().all { test ->
inventory.any { it.equalsIgnoreSize(test) && (ignoreSize || (it.count >= test.count)) }
}
}
private fun matchesTop(holder: IItemHandler, ignoreSize: Boolean) = this.top.matchesInventory(holder, ignoreSize, true)
private fun matchesBottom(holder: IItemHandler, ignoreSize: Boolean) = this.bottom.matchesInventory(holder, ignoreSize, true)
override fun matchesTop(stack: ItemStack, ignoreSize: Boolean, emptyMatcher: Boolean) =
(emptyMatcher && this.top.isEmpty()) || this.top.getCombinedInventory().any {
it.equalsIgnoreSize(stack) && (ignoreSize || (stack.count >= it.count))
}
override fun matchesBottom(stack: ItemStack, ignoreSize: Boolean, emptyMatcher: Boolean) =
(emptyMatcher && this.bottom.isEmpty()) || this.bottom.getCombinedInventory().any {
it.equalsIgnoreSize(stack) && (ignoreSize || (stack.count >= it.count))
}
override fun matches(left: IFluidTank, top: IItemHandler, right: IFluidTank, bottom: IItemHandler) =
this.matchesLeft(left.fluid, false, true)
&& this.matchedRight(right.fluid, false, true)
&& this.matchesTop(top, false)
&& this.matchesBottom(bottom, false)
private fun FluidStack?.drainFluid(tank: IFluidTank, doDrain: Boolean): Boolean {
if ((this == null) || (this.amount == 0))
return true
return this.isEnough(tank.drain(this.amount, doDrain), false)
}
private fun Array<ItemStack>.takeFrom(handler: IItemHandler, doTake: Boolean): Boolean {
if (this.isEmpty())
return true
return this.getCombinedInventory().all { handler.extractFromCombinedInventory(it, it.count, !doTake) == it.count }
}
override fun processInventories(left: IFluidTank, top: IItemHandler, right: IFluidTank, bottom: IItemHandler): Boolean {
if (!this.matches(left, top, right, bottom))
return false
if (this.left.drainFluid(left, false) && this.right.drainFluid(right, false) &&
this.top.takeFrom(top, false) && this.bottom.takeFrom(bottom, false)) {
this.left.drainFluid(left, true)
this.top.takeFrom(top, true)
this.right.drainFluid(right, true)
this.bottom.takeFrom(bottom, true)
return true
}
return false
}
}
| mit | 6dc24868297b400160c290c6f5823ac1 | 44.889908 | 150 | 0.664134 | 4.414828 | false | false | false | false |
grassrootza/grassroot-android-v2 | app/src/main/kotlin/za/org/grassroot2/presenter/ForgottenPasswordPresenter.kt | 1 | 3181 | package za.org.grassroot2.presenter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import za.org.grassroot2.BuildConfig
import za.org.grassroot2.R
import za.org.grassroot2.presenter.activity.BasePresenter
import za.org.grassroot2.services.UserDetailsService
import za.org.grassroot2.services.rest.GrassrootAuthApi
import za.org.grassroot2.view.ForgottenPasswordView
import javax.inject.Inject
class ForgottenPasswordPresenter @Inject constructor(val grassrootAuthApi: GrassrootAuthApi,
val userDetailsService: UserDetailsService) : BasePresenter<ForgottenPasswordView>() {
private var phoneNumber: String = ""
private var newPassword: String = ""
fun handlePhoneNumberInput(value: String) {
if (value.isNotEmpty() && value.length >= 6) {
this.phoneNumber = value
view.switchToPasswordInput()
} else {
view.hideKeyboard()
view.showErrorSnackbar(R.string.reset_password_number_error)
}
}
fun handlePasswordInput(value: String) {
if (value.isNotEmpty() && value.length >= 6) {
this.newPassword = value //store password to variable and get otp
view.showProgressBar()
disposableOnDetach(grassrootAuthApi
.resetPasswordRequest(phoneNumber)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ stringRestResponse ->
view.closeProgressBar()
view.switchToOtpInput(if (BuildConfig.DEBUG) stringRestResponse.data!! else "")
}) { throwable ->
throwable.printStackTrace()
view.closeProgressBar()
view.hideKeyboard()
view.showErrorSnackbar(R.string.reset_password_request_failed)
})
} else {
view.hideKeyboard()
view.showErrorSnackbar(R.string.reset_password_password_error)
}
}
fun handleOtpInput(value: String) {
if (value.isNotEmpty() && value.length >= 6) {
view.showProgressBar()
disposableOnDetach(grassrootAuthApi
.resetPasswordConfirm(phoneNumber, newPassword, value)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ stringRestResponse ->
view.closeProgressBar()
view.passwordChangeSuccess(if (BuildConfig.DEBUG) this.newPassword else "")
}) { throwable ->
throwable.printStackTrace()
view.closeProgressBar()
view.hideKeyboard()
view.showErrorSnackbar(R.string.reset_password_otp_verification_failed)
})
} else {
view.hideKeyboard()
view.showErrorSnackbar(R.string.reset_password_otp_error)
}
}
} | bsd-3-clause | db7560fa5cfd391029ae63cfd6fd2880 | 38.283951 | 139 | 0.592581 | 5.382403 | false | false | false | false |
googlesamples/mlkit | android/material-showcase/app/src/main/java/com/google/mlkit/md/objectdetection/ObjectConfirmationGraphic.kt | 1 | 4349 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.mlkit.md.objectdetection
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Paint.Cap
import android.graphics.Paint.Style
import android.graphics.RectF
import androidx.core.content.ContextCompat
import com.google.mlkit.md.camera.GraphicOverlay
import com.google.mlkit.md.camera.GraphicOverlay.Graphic
import com.google.mlkit.md.R
import com.google.mlkit.md.settings.PreferenceUtils
/**
* Similar to the camera reticle but with additional progress ring to indicate an object is getting
* confirmed for a follow up processing, e.g. product search.
*/
class ObjectConfirmationGraphic internal constructor(
overlay: GraphicOverlay,
private val confirmationController: ObjectConfirmationController
) : Graphic(overlay) {
private val outerRingFillPaint: Paint
private val outerRingStrokePaint: Paint
private val innerRingPaint: Paint
private val progressRingStrokePaint: Paint
private val outerRingFillRadius: Int
private val outerRingStrokeRadius: Int
private val innerRingStrokeRadius: Int
init {
val resources = overlay.resources
outerRingFillPaint = Paint().apply {
style = Style.FILL
color = ContextCompat.getColor(context, R.color.object_reticle_outer_ring_fill)
}
outerRingStrokePaint = Paint().apply {
style = Style.STROKE
strokeWidth = resources.getDimensionPixelOffset(R.dimen.object_reticle_outer_ring_stroke_width).toFloat()
strokeCap = Cap.ROUND
color = ContextCompat.getColor(context, R.color.object_reticle_outer_ring_stroke)
}
progressRingStrokePaint = Paint().apply {
style = Style.STROKE
strokeWidth = resources.getDimensionPixelOffset(R.dimen.object_reticle_outer_ring_stroke_width).toFloat()
strokeCap = Cap.ROUND
color = ContextCompat.getColor(context, R.color.white)
}
innerRingPaint = Paint()
if (PreferenceUtils.isMultipleObjectsMode(overlay.context)) {
innerRingPaint.style = Style.FILL
innerRingPaint.color = ContextCompat.getColor(context, R.color.object_reticle_inner_ring)
} else {
innerRingPaint.style = Style.STROKE
innerRingPaint.strokeWidth =
resources.getDimensionPixelOffset(R.dimen.object_reticle_inner_ring_stroke_width).toFloat()
innerRingPaint.strokeCap = Cap.ROUND
innerRingPaint.color = ContextCompat.getColor(context, R.color.white)
}
outerRingFillRadius = resources.getDimensionPixelOffset(R.dimen.object_reticle_outer_ring_fill_radius)
outerRingStrokeRadius = resources.getDimensionPixelOffset(R.dimen.object_reticle_outer_ring_stroke_radius)
innerRingStrokeRadius = resources.getDimensionPixelOffset(R.dimen.object_reticle_inner_ring_stroke_radius)
}
override fun draw(canvas: Canvas) {
val cx = canvas.width / 2f
val cy = canvas.height / 2f
canvas.drawCircle(cx, cy, outerRingFillRadius.toFloat(), outerRingFillPaint)
canvas.drawCircle(cx, cy, outerRingStrokeRadius.toFloat(), outerRingStrokePaint)
canvas.drawCircle(cx, cy, innerRingStrokeRadius.toFloat(), innerRingPaint)
val progressRect = RectF(
cx - outerRingStrokeRadius,
cy - outerRingStrokeRadius,
cx + outerRingStrokeRadius,
cy + outerRingStrokeRadius
)
val sweepAngle = confirmationController.progress * 360
canvas.drawArc(
progressRect,
/* startAngle= */ 0f,
sweepAngle,
/* useCenter= */ false,
progressRingStrokePaint
)
}
}
| apache-2.0 | c42a3b4f377557b9ed7adc1636de9524 | 39.268519 | 117 | 0.701541 | 4.451382 | false | false | false | false |
alfiewm/Keddit | app/src/main/java/meng/keddit/features/news/NewsFragment.kt | 1 | 2973 | package meng.keddit.features.news
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.news_fragment.*
import meng.keddit.R
import meng.keddit.commons.InfiniteScrollListener
import meng.keddit.commons.RedditNews
import meng.keddit.commons.adapter.RxBaseFragment
import meng.keddit.commons.extensions.inflate
import meng.keddit.features.news.adapter.NewsAdapter
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
/**
* Created by meng on 2017/7/31.
*/
class NewsFragment : RxBaseFragment() {
companion object {
private val KEY_REDDIT_NEWS = "redditNews"
}
private val newsList by lazy {
news_list
}
private var redditNews: RedditNews? = null
private val newsManager by lazy { NewsManager() }
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return container?.inflate(R.layout.news_fragment)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
news_list.apply {
setHasFixedSize(true)
val linearLayout = LinearLayoutManager(context)
layoutManager = linearLayout
clearOnScrollListeners()
addOnScrollListener(InfiniteScrollListener({ requestNews() }, linearLayout))
}
initAdapter()
if (savedInstanceState != null && savedInstanceState.containsKey(KEY_REDDIT_NEWS)) {
redditNews = savedInstanceState.get(KEY_REDDIT_NEWS) as RedditNews
(newsList.adapter as NewsAdapter).clearAndAddNews(redditNews!!.news)
} else {
requestNews()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val news = (newsList.adapter as NewsAdapter).getNews()
if (redditNews != null && news.isNotEmpty()) {
outState.putParcelable(KEY_REDDIT_NEWS, redditNews?.copy(news = news))
}
}
private fun requestNews() {
val subscription = newsManager.getNews(redditNews?.after ?: "")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ retrievedNews ->
redditNews = retrievedNews
(newsList.adapter as NewsAdapter).addNews(retrievedNews.news)
},
{ e -> Snackbar.make(newsList, e.message ?: "", Snackbar.LENGTH_LONG).show() }
)
subscriptions.add(subscription)
}
private fun initAdapter() {
if (newsList.adapter == null) {
newsList.adapter = NewsAdapter()
}
}
} | mit | 69b3ff146487ae615c440280083cc0ad | 33.988235 | 117 | 0.655567 | 4.818476 | false | false | false | false |
Ray-Eldath/Avalon | src/main/kotlin/avalon/group/Manager.kt | 1 | 2491 | package avalon.group
import avalon.api.Flag.at
import avalon.tool.pool.APISurvivePool
import avalon.tool.pool.Constants
import avalon.tool.pool.Constants.Basic.LANG
import avalon.util.GroupConfig
import avalon.util.GroupMessage
import org.slf4j.LoggerFactory
import java.util.regex.Pattern
object Manager : GroupMessageResponder() {
private val logger = LoggerFactory.getLogger(Manager.javaClass)
override fun doPost(message: GroupMessage, groupConfig: GroupConfig) {
val content = message.content
val sender = message.senderNickName
val senderUid = message.senderUid
val incorrect = "${at(message)} ${LANG.getString("group.manager.incorrect_e")}"
if (" " !in content) {
message.response(incorrect)
return
}
val split = content.toLowerCase().split(" ")
if (split.size <= 3) {
message.response(incorrect)
return
}
val action = split[2]
val apiName = split.subList(3, split.size).joinToString(separator = " ")
if (Constants.Basic.DEBUG)
println("$action $apiName")
var thisAPI = GroupMessageHandler.getGroupResponderByKeywordRegex(apiName)
if (thisAPI == null) {
thisAPI = GroupMessageHandler.getGroupResponderByKeywordRegex("$apiName ")
if (thisAPI == null) {
message.response("${at(message)} ${LANG.getString("group.manager.not_exist")}")
return
}
}
if (!thisAPI.responderInfo().manageable) {
message.response("${at(message)} ${LANG.getString("group.manager.can_not_stop")}")
return
}
when (action) {
"start" -> {
APISurvivePool.getInstance().setAPISurvive(thisAPI, true)
message.response("${at(message)} ${LANG.getString("group.manager.start")}")
Manager.logger.info("GroupMessageResponder ${thisAPI.javaClass.simpleName} is reopened by $senderUid : $sender.")
}
"stop" -> {
APISurvivePool.getInstance().setAPISurvive(thisAPI, false)
message.response("${at(message)} ${LANG.getString("group.manager.stop")}")
Manager.logger.info("GroupMessageResponder ${thisAPI.javaClass.simpleName} is closed by $senderUid : $sender.")
}
else -> message.response("${at(message)} ${LANG.getString("group.manager.incorrect")}")
}
}
override fun responderInfo(): ResponderInfo =
ResponderInfo(
Pair("manager (start|stop) ${LANG.getString("group.manager.help.first")}", LANG.getString("group.manager.help.second")),
Pattern.compile("manager (start|stop) "),
manageable = false,
permission = ResponderPermission.ADMIN
)
override fun instance() = this
} | agpl-3.0 | d2e18f43ae3dfcb7072bf599ff784787 | 32.226667 | 125 | 0.714572 | 3.518362 | false | false | false | false |
alphafoobar/intellij-community | platform/platform-impl/src/com/intellij/openapi/application/actions.kt | 6 | 1733 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.application
import com.intellij.openapi.components.impl.stores.BatchUpdateListener
import com.intellij.util.messages.MessageBus
import javax.swing.SwingUtilities
public inline fun <T> runWriteAction(runnable: () -> T): T {
val token = WriteAction.start()
try {
return runnable()
}
finally {
token.finish()
}
}
public inline fun runReadAction(runnable: () -> Unit) {
val token = ReadAction.start()
try {
runnable()
}
finally {
token.finish()
}
}
public inline fun <T> runBatchUpdate(messageBus: MessageBus, runnable: () -> T): T {
val publisher = messageBus.syncPublisher(BatchUpdateListener.TOPIC)
publisher.onBatchUpdateStarted()
try {
return runnable()
}
finally {
publisher.onBatchUpdateFinished()
}
}
/**
* @exclude Internal use only
*/
public fun invokeAndWaitIfNeed(runnable: () -> Unit) {
val app = ApplicationManager.getApplication()
if (app == null) {
if (SwingUtilities.isEventDispatchThread()) runnable() else SwingUtilities.invokeAndWait(runnable)
}
else {
app.invokeAndWait(runnable, ModalityState.any())
}
}
| apache-2.0 | e3ff0662394bd58915a6be16787b2e75 | 26.078125 | 102 | 0.717253 | 4.106635 | false | false | false | false |
tasks/tasks | app/src/main/java/com/todoroo/andlib/data/Table.kt | 1 | 518 | package com.todoroo.andlib.data
import com.todoroo.andlib.sql.DBObject
class Table private constructor(private val name: String, alias: String?) : DBObject(name) {
constructor(name: String) : this(name, null)
fun column(column: String): Property = Property(this, column)
override fun `as`(newAlias: String) = Table(name, newAlias)
override fun toString(): String = alias?.let { "$expression AS $alias" } ?: expression
fun name() = alias ?: name
init {
this.alias = alias
}
} | gpl-3.0 | 908c6f069a5b3a8bcf7919370c1712bd | 24.95 | 92 | 0.673745 | 3.894737 | false | false | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/AbstractKit.kt | 1 | 2039 | package com.didichuxing.doraemonkit.kit
import android.app.Activity
import android.content.Context
import android.os.Bundle
import com.didichuxing.doraemonkit.DoKit
import com.didichuxing.doraemonkit.util.ActivityUtils
import com.didichuxing.doraemonkit.kit.core.BaseFragment
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2019-11-20-15:29
* 描 述:内置工具必须重写innerKitId而且需要和doraemonkit模块下的assets/dokit_system_kits.json文件中的innerKitId保持一致
* 否则该工具无法在工具面板中显示
* 修订历史:
* ================================================
*/
abstract class AbstractKit : IKit {
/**
* 启动UniversalActivity
*
* @param fragmentClass
* @param context
* @param bundle
* @param isSystemFragment 是否是内置kit
*/
fun startUniversalActivity(
fragmentClass: Class<out BaseFragment>,
context: Context?,
bundle: Bundle? = null,
isSystemFragment: Boolean = false
) {
DoKit.launchFullScreen(fragmentClass, context, bundle, isSystemFragment)
}
/**
* 是否是内置kit 外部kit不需要实现
*
* @return
*/
open val isInnerKit: Boolean
get() = false
/**
* 是否可以显示在工具面板上
*/
var canShow: Boolean = true
/**
* 返回kitId
* 内置工具必须返回而且需要和doraemonkit模块下的assets/dokit_system_kits.json文件中的innerKitId保持一致
* 否则该工具无法在工具面板中显示
* @return
*/
open fun innerKitId(): String {
return ""
}
/**
* 返回当前栈顶的activity
* @return activity
*/
fun currentActivity(): Activity? {
return ActivityUtils.getTopActivity()
}
@Deprecated("已废弃,重不重写都不影响功能", ReplaceWith(""))
override val category: Int
get() = Category.DEFAULT
}
| apache-2.0 | 375973c932f8b25e787f233d237f47ff | 21.697368 | 95 | 0.606377 | 3.85906 | false | false | false | false |
arturbosch/detekt | detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/optional/PreferToOverPairSyntaxSpec.kt | 1 | 2482 | package io.gitlab.arturbosch.detekt.rules.style.optional
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object PreferToOverPairSyntaxSpec : Spek({
setupKotlinEnvironment()
val env: KotlinCoreEnvironment by memoized()
val subject by memoized { PreferToOverPairSyntax(Config.empty) }
describe("PreferToOverPairSyntax rule") {
it("reports if pair is created using pair constructor") {
val code = """
val pair1 = Pair(1, 2)
val pair2: Pair<Int, Int> = Pair(1, 2)
val pair3 = Pair(Pair(1, 2), Pair(3, 4))
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(5)
assertThat(findings[0].message).endsWith("`1 to 2`")
}
it("reports if pair is created using a function that uses pair constructor") {
val code = """
val pair = createPair()
fun createPair() = Pair(1, 2)
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings[0].message).endsWith("`1 to 2`")
}
it("does not report if it is created using the to syntax") {
val code = "val pair = 1 to 2"
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report if a non-Kotlin Pair class was used") {
val code = """
val pair1 = Pair(1, 2)
val pair2: Pair<Int, Int> = Pair(1, 2)
val pair3 = Pair(Pair(1, 2), Pair(3, 4))
data class Pair<T, Z>(val int1: T, val int2: Z)
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report if pair is created using a function that uses the to syntax") {
val code = """
val pair = createPair()
fun createPair() = 1 to 2
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
})
| apache-2.0 | 5b31f2ec3515cc53443f7fed36d28117 | 37.184615 | 91 | 0.601934 | 4.432143 | false | false | false | false |
neo4j-contrib/neo4j-apoc-procedures | extended/src/test/kotlin/apoc/nlp/azure/AzureVirtualEntitiesGraphTest.kt | 1 | 17406 | package apoc.nlp.azure
import apoc.nlp.NodeMatcher
import apoc.nlp.RelationshipMatcher
import apoc.result.VirtualNode
import junit.framework.Assert.assertEquals
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.hasItem
import org.junit.Test
import org.neo4j.graphdb.Label
import org.neo4j.graphdb.RelationshipType
class AzureVirtualEntitiesGraphTest {
@Test
fun `create virtual graph from result with one entity`() {
val sourceNode = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val res = listOf(
mapOf("id" to sourceNode.id.toString(), "entities" to listOf(mapOf(
"name" to "foo",
"type" to "Person",
"matches" to listOf(
mapOf("entityTypeScore" to 0.9, "text" to "foo"),
mapOf("entityTypeScore" to 0.8, "text" to "foobar")
)
)))
)
val virtualGraph = AzureVirtualEntitiesGraph(res, listOf(sourceNode), RelationshipType { "ENTITY" }, "score", 0.0).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(2, nodes.size)
assertThat(nodes, hasItem(sourceNode))
val barLabels = listOf(Label { "Person" }, Label { "Entity" })
val barProperties = mapOf("text" to "foo", "type" to "Person")
assertThat(nodes, hasItem(NodeMatcher(barLabels, barProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(1, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode, VirtualNode(barLabels.toTypedArray(), barProperties), "ENTITY", mapOf("score" to 0.9))))
}
@Test
fun `create virtual graph from result with multiple entities`() {
val sourceNode = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val res = listOf(
mapOf("id" to sourceNode.id.toString(), "entities" to listOf(
mapOf(
"name" to "The Matrix",
"type" to "Other",
"matches" to listOf(
mapOf("entityTypeScore" to 0.6, "text" to "foo"),
mapOf("entityTypeScore" to 0.5, "text" to "foobar")
)
),
mapOf(
"name" to "The Notebook",
"type" to "Other",
"matches" to listOf(
mapOf("entityTypeScore" to 0.7, "text" to "foo"),
mapOf("entityTypeScore" to 0.5, "text" to "foobar")
)
)))
)
val virtualGraph = AzureVirtualEntitiesGraph(res, listOf(sourceNode), RelationshipType { "ENTITY" },"score", 0.0).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(3, nodes.size)
assertThat(nodes, hasItem(sourceNode))
val matrixNode = VirtualNode(arrayOf(Label{"Other"}, Label{"Entity"}), mapOf("text" to "The Matrix", "type" to "Other"))
val notebookNode = VirtualNode(arrayOf(Label{"Other"}, Label{"Entity"}), mapOf("text" to "The Notebook", "type" to "Other"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(notebookNode.labels.toList(), notebookNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(2, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode, matrixNode, "ENTITY", mapOf("score" to 0.6))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode, notebookNode, "ENTITY", mapOf("score" to 0.7))))
}
@Test
fun `create virtual graph from result with duplicate entities`() {
val sourceNode = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val res = listOf(
mapOf("id" to sourceNode.id.toString(), "entities" to listOf(
mapOf(
"name" to "The Matrix",
"type" to "Other",
"matches" to listOf(
mapOf("entityTypeScore" to 0.6, "text" to "foo"),
mapOf("entityTypeScore" to 0.5, "text" to "foobar")
)
),
mapOf(
"name" to "The Matrix",
"type" to "Other",
"matches" to listOf(
mapOf("entityTypeScore" to 0.7, "text" to "foo"),
mapOf("entityTypeScore" to 0.5, "text" to "foobar")
)
)))
)
val virtualGraph = AzureVirtualEntitiesGraph(res, listOf(sourceNode), RelationshipType { "ENTITY" },"score", 0.0).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(2, nodes.size)
assertThat(nodes, hasItem(sourceNode))
val matrixNode = VirtualNode(arrayOf(Label{"Other"}, Label{"Entity"}), mapOf("text" to "The Matrix", "type" to "Other"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(1, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode, matrixNode, "ENTITY", mapOf("score" to 0.7))))
}
@Test
fun `create virtual graph from result with multiple source nodes`() {
val sourceNode1 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val sourceNode2 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 5678L))
val res = listOf(
mapOf("id" to sourceNode1.id.toString(), "entities" to listOf(
mapOf(
"name" to "The Matrix",
"type" to "Other",
"matches" to listOf(
mapOf("entityTypeScore" to 0.2)
)
),
mapOf(
"name" to "The Notebook",
"type" to "PhoneNumber",
"matches" to listOf(
mapOf("entityTypeScore" to 0.3)
)
))),
mapOf("id" to sourceNode2.id.toString(), "entities" to listOf(
mapOf(
"name" to "Toy Story",
"type" to "Other",
"matches" to listOf(
mapOf("entityTypeScore" to 0.4)
)
),
mapOf(
"name" to "Titanic",
"type" to "Quantity",
"matches" to listOf(
mapOf("entityTypeScore" to 0.5)
)
)))
)
val virtualGraph = AzureVirtualEntitiesGraph(res, listOf(sourceNode1, sourceNode2), RelationshipType { "ENTITY" },"score", 0.0).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(6, nodes.size)
assertThat(nodes, hasItem(sourceNode1))
assertThat(nodes, hasItem(sourceNode2))
val matrixNode = VirtualNode(arrayOf(Label{"Other"}, Label{"Entity"}), mapOf("text" to "The Matrix", "type" to "Other"))
val notebookNode = VirtualNode(arrayOf(Label{"PhoneNumber"}, Label{"Entity"}), mapOf("text" to "The Notebook", "type" to "PhoneNumber"))
val toyStoryNode = VirtualNode(arrayOf(Label{"Other"}, Label{"Entity"}), mapOf("text" to "Toy Story", "type" to "Other"))
val titanicNode = VirtualNode(arrayOf(Label{"Quantity"}, Label{"Entity"}), mapOf("text" to "Titanic", "type" to "Quantity"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(notebookNode.labels.toList(), notebookNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(toyStoryNode.labels.toList(), toyStoryNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(titanicNode.labels.toList(), titanicNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(4, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, matrixNode, "ENTITY", mapOf("score" to 0.2))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, notebookNode, "ENTITY", mapOf("score" to 0.3))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, toyStoryNode, "ENTITY", mapOf("score" to 0.4))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, titanicNode, "ENTITY", mapOf("score" to 0.5))))
}
@Test
fun `create virtual graph from result with multiple source nodes with overlapping entities`() {
val sourceNode1 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val sourceNode2 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 5678L))
val res = listOf(
mapOf("id" to sourceNode1.id.toString(), "entities" to listOf(
mapOf(
"name" to "The Matrix",
"type" to "Other",
"matches" to listOf(
mapOf("entityTypeScore" to 0.7)
)
),
mapOf(
"name" to "The Notebook",
"type" to "PhoneNumber",
"matches" to listOf(
mapOf("entityTypeScore" to 0.8)
)
))),
mapOf("id" to sourceNode2.id.toString(), "entities" to listOf(
mapOf(
"name" to "Titanic",
"type" to "Skill",
"matches" to listOf(
mapOf("entityTypeScore" to 0.75)
)
),
mapOf(
"name" to "The Matrix",
"type" to "Other",
"matches" to listOf(
mapOf("entityTypeScore" to 0.9)
)
),
mapOf(
"name" to "Top Boy",
"type" to "Email",
"matches" to listOf(
mapOf("entityTypeScore" to 0.4)
)
)
))
)
val virtualGraph = AzureVirtualEntitiesGraph(res, listOf(sourceNode1, sourceNode2), RelationshipType { "ENTITY" },"score", 0.0).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(6, nodes.size)
assertThat(nodes, hasItem(sourceNode1))
assertThat(nodes, hasItem(sourceNode2))
val matrixNode = VirtualNode(arrayOf(Label{"Other"}, Label{"Entity"}), mapOf("text" to "The Matrix", "type" to "Other"))
val notebookNode = VirtualNode(arrayOf(Label{"PhoneNumber"}, Label{"Entity"}), mapOf("text" to "The Notebook", "type" to "PhoneNumber"))
val titanicNode = VirtualNode(arrayOf(Label{"Skill"}, Label{"Entity"}), mapOf("text" to "Titanic", "type" to "Skill"))
val topBoyNode = VirtualNode(arrayOf(Label{"Email"}, Label{"Entity"}), mapOf("text" to "Top Boy", "type" to "Email"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(notebookNode.labels.toList(), notebookNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(titanicNode.labels.toList(), titanicNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(topBoyNode.labels.toList(), topBoyNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(5, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, matrixNode, "ENTITY", mapOf("score" to 0.7))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, notebookNode, "ENTITY", mapOf("score" to 0.8))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, titanicNode, "ENTITY", mapOf("score" to 0.75))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, matrixNode, "ENTITY", mapOf("score" to 0.9))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, topBoyNode, "ENTITY", mapOf("score" to 0.4))))
}
@Test
fun `create graph based on confidence cut off`() {
val sourceNode1 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val sourceNode2 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 5678L))
val res = listOf(
mapOf("id" to sourceNode1.id.toString(), "entities" to listOf(
mapOf(
"name" to "The Matrix",
"type" to "Other",
"matches" to listOf(
mapOf("entityTypeScore" to 0.7)
)
),
mapOf(
"name" to "The Notebook",
"type" to "PhoneNumber",
"matches" to listOf(
mapOf("wikipediaScore" to 0.8)
)
))),
mapOf("id" to sourceNode2.id.toString(), "entities" to listOf(
mapOf(
"name" to "Titanic",
"type" to "Skill",
"matches" to listOf(
mapOf("wikipediaScore" to 0.75)
)
),
mapOf(
"name" to "The Matrix",
"type" to "Other",
"matches" to listOf(
mapOf("entityTypeScore" to 0.9)
)
),
mapOf(
"name" to "Top Boy",
"type" to "Email",
"matches" to listOf(
mapOf("wikipediaScore" to 0.4)
)
)
))
)
val virtualGraph = AzureVirtualEntitiesGraph(res, listOf(sourceNode1, sourceNode2), RelationshipType { "ENTITY" },"score", 0.75).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(5, nodes.size)
assertThat(nodes, hasItem(sourceNode1))
assertThat(nodes, hasItem(sourceNode2))
val matrixNode = VirtualNode(arrayOf(Label{"Other"}, Label{"Entity"}), mapOf("text" to "The Matrix", "type" to "Other"))
val notebookNode = VirtualNode(arrayOf(Label{"PhoneNumber"}, Label{"Entity"}), mapOf("text" to "The Notebook", "type" to "PhoneNumber"))
val titanicNode = VirtualNode(arrayOf(Label{"Skill"}, Label{"Entity"}), mapOf("text" to "Titanic", "type" to "Skill"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(notebookNode.labels.toList(), notebookNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(titanicNode.labels.toList(), titanicNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(3, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, notebookNode, "ENTITY", mapOf("score" to 0.8))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, titanicNode, "ENTITY", mapOf("score" to 0.75))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, matrixNode, "ENTITY", mapOf("score" to 0.9))))
}
}
| apache-2.0 | 134e543d5be85b18756b9a3d3d0c4210 | 50.043988 | 162 | 0.51149 | 4.990252 | false | false | false | false |
aglne/mycollab | mycollab-servlet/src/main/java/com/mycollab/module/page/servlet/FileUploadServlet.kt | 3 | 3826 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.module.page.servlet
import com.mycollab.module.ecm.domain.Content
import com.mycollab.module.ecm.service.ResourceService
import com.mycollab.servlet.GenericHttpServlet
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import java.io.FileNotFoundException
import java.io.IOException
import java.util.*
import javax.servlet.ServletException
import javax.servlet.annotation.MultipartConfig
import javax.servlet.annotation.WebServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.Part
/**
* @author MyCollab Ltd.
* @since 4.4.0
*/
@WebServlet(urlPatterns = ["/page/upload"], name = "pageUploadServlet")
@MultipartConfig(maxFileSize = 24657920, maxRequestSize = 24657920, fileSizeThreshold = 1024)
class FileUploadServlet : GenericHttpServlet() {
@Autowired
private lateinit var resourceService: ResourceService
@Throws(ServletException::class, IOException::class)
override fun onHandleRequest(request: HttpServletRequest, response: HttpServletResponse) {
response.contentType = "text/html;charset=UTF-8"
val path = request.getParameter("path")
val ckEditorFuncNum = request.getParameter("CKEditorFuncNum")
// Create path components to save the file
val filePart = request.getPart("upload")
val fileName = getFileName(filePart) ?: return
val writer = response.writer
try {
filePart.inputStream.use {
val content = Content("$path/$fileName")
resourceService.saveContent(content, "", it, 1)
val filePath = ""
val responseHtml = "<html><body><script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction('$ckEditorFuncNum','$filePath','');</script></body></html>"
writer.write(responseHtml)
}
} catch (fne: FileNotFoundException) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.")
writer.println("<br/> ERROR: ${fne.message}")
LOG.error("Problems during file upload. Error: ${fne.message}")
}
}
private fun getFileName(part: Part): String? {
for (content in part.getHeader("content-disposition").split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) {
if (content.trim { it <= ' ' }.startsWith("filename")) {
var fileName = content.substring(content.indexOf('=') + 1).trim { it <= ' ' }.replace("\"", "")
val index = fileName.lastIndexOf(".")
if (index != -1) {
fileName = "${fileName.substring(0, index - 1)}${System.currentTimeMillis()}${fileName.substring(index)}"
return fileName
}
}
}
return null
}
companion object {
private val LOG = LoggerFactory.getLogger(FileUploadServlet::class.java)
}
}
| agpl-3.0 | be154ca204d6282b9cfc864f9ed62854 | 41.032967 | 180 | 0.668758 | 4.515939 | false | false | false | false |
olonho/carkot | translator/src/test/kotlin/tests/proto_varint/proto_varint.kt | 1 | 15260 | class MessageVarints private constructor (var int: Int, var long: Long, var sint: Int, var slong: Long, var bl: Boolean, var enumField: MessageVarints.TestEnum, var uint: Int, var ulong: Long) {
//========== Properties ===========
//int32 int = 1
//int64 long = 2
//sint32 sint = 3
//sint64 slong = 4
//bool bl = 5
//enum enumField = 6
//uint32 uint = 7
//uint64 ulong = 8
var errorCode: Int = 0
//========== Nested enums declarations ===========
enum class TestEnum(val id: Int) {
firstVal (0),
secondVal (1),
thirdVal (2),
Unexpected(3);
companion object {
fun fromIntToTestEnum (ord: Int): TestEnum {
return when (ord) {
0 -> TestEnum.firstVal
1 -> TestEnum.secondVal
2 -> TestEnum.thirdVal
else -> Unexpected
}
}
}
}
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//int32 int = 1
if (int != 0) {
output.writeInt32 (1, int)
}
//int64 long = 2
if (long != 0L) {
output.writeInt64 (2, long)
}
//sint32 sint = 3
if (sint != 0) {
output.writeSInt32 (3, sint)
}
//sint64 slong = 4
if (slong != 0L) {
output.writeSInt64 (4, slong)
}
//bool bl = 5
if (bl != false) {
output.writeBool (5, bl)
}
//enum enumField = 6
if (enumField.id != MessageVarints.TestEnum.fromIntToTestEnum(0).id) {
output.writeEnum (6, enumField.id)
}
//uint32 uint = 7
if (uint != 0) {
output.writeUInt32 (7, uint)
}
//uint64 ulong = 8
if (ulong != 0L) {
output.writeUInt64 (8, ulong)
}
}
fun mergeWith (other: MessageVarints) {
int = other.int
long = other.long
sint = other.sint
slong = other.slong
bl = other.bl
enumField = other.enumField
uint = other.uint
ulong = other.ulong
this.errorCode = other.errorCode
}
fun mergeFromWithSize (input: CodedInputStream, expectedSize: Int) {
val builder = MessageVarints.BuilderMessageVarints(0, 0L, 0, 0L, false, MessageVarints.TestEnum.fromIntToTestEnum(0), 0, 0L)
mergeWith(builder.parseFromWithSize(input, expectedSize).build())
}
fun mergeFrom (input: CodedInputStream) {
val builder = MessageVarints.BuilderMessageVarints(0, 0L, 0, 0L, false, MessageVarints.TestEnum.fromIntToTestEnum(0), 0, 0L)
mergeWith(builder.parseFrom(input).build())
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (int != 0) {
size += WireFormat.getInt32Size(1, int)
}
if (long != 0L) {
size += WireFormat.getInt64Size(2, long)
}
if (sint != 0) {
size += WireFormat.getSInt32Size(3, sint)
}
if (slong != 0L) {
size += WireFormat.getSInt64Size(4, slong)
}
if (bl != false) {
size += WireFormat.getBoolSize(5, bl)
}
if (enumField != MessageVarints.TestEnum.fromIntToTestEnum(0)) {
size += WireFormat.getEnumSize(6, enumField.id)
}
if (uint != 0) {
size += WireFormat.getUInt32Size(7, uint)
}
if (ulong != 0L) {
size += WireFormat.getUInt64Size(8, ulong)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (int != 0) {
size += WireFormat.getInt32Size(1, int)
}
if (long != 0L) {
size += WireFormat.getInt64Size(2, long)
}
if (sint != 0) {
size += WireFormat.getSInt32Size(3, sint)
}
if (slong != 0L) {
size += WireFormat.getSInt64Size(4, slong)
}
if (bl != false) {
size += WireFormat.getBoolSize(5, bl)
}
if (enumField != MessageVarints.TestEnum.fromIntToTestEnum(0)) {
size += WireFormat.getEnumSize(6, enumField.id)
}
if (uint != 0) {
size += WireFormat.getUInt32Size(7, uint)
}
if (ulong != 0L) {
size += WireFormat.getUInt64Size(8, ulong)
}
return size
}
//========== Builder ===========
class BuilderMessageVarints constructor (var int: Int, var long: Long, var sint: Int, var slong: Long, var bl: Boolean, var enumField: MessageVarints.TestEnum, var uint: Int, var ulong: Long) {
//========== Properties ===========
//int32 int = 1
fun setInt(value: Int): MessageVarints.BuilderMessageVarints {
int = value
return this
}
//int64 long = 2
fun setLong(value: Long): MessageVarints.BuilderMessageVarints {
long = value
return this
}
//sint32 sint = 3
fun setSint(value: Int): MessageVarints.BuilderMessageVarints {
sint = value
return this
}
//sint64 slong = 4
fun setSlong(value: Long): MessageVarints.BuilderMessageVarints {
slong = value
return this
}
//bool bl = 5
fun setBl(value: Boolean): MessageVarints.BuilderMessageVarints {
bl = value
return this
}
//enum enumField = 6
fun setEnumField(value: MessageVarints.TestEnum): MessageVarints.BuilderMessageVarints {
enumField = value
return this
}
//uint32 uint = 7
fun setUint(value: Int): MessageVarints.BuilderMessageVarints {
uint = value
return this
}
//uint64 ulong = 8
fun setUlong(value: Long): MessageVarints.BuilderMessageVarints {
ulong = value
return this
}
var errorCode: Int = 0
//========== Serialization methods ===========
fun writeTo (output: CodedOutputStream) {
//int32 int = 1
if (int != 0) {
output.writeInt32 (1, int)
}
//int64 long = 2
if (long != 0L) {
output.writeInt64 (2, long)
}
//sint32 sint = 3
if (sint != 0) {
output.writeSInt32 (3, sint)
}
//sint64 slong = 4
if (slong != 0L) {
output.writeSInt64 (4, slong)
}
//bool bl = 5
if (bl != false) {
output.writeBool (5, bl)
}
//enum enumField = 6
if (enumField.id != MessageVarints.TestEnum.fromIntToTestEnum(0).id) {
output.writeEnum (6, enumField.id)
}
//uint32 uint = 7
if (uint != 0) {
output.writeUInt32 (7, uint)
}
//uint64 ulong = 8
if (ulong != 0L) {
output.writeUInt64 (8, ulong)
}
}
//========== Mutating methods ===========
fun build(): MessageVarints {
val res = MessageVarints(int, long, sint, slong, bl, enumField, uint, ulong)
res.errorCode = errorCode
return res
}
fun parseFieldFrom(input: CodedInputStream): Boolean {
if (input.isAtEnd()) { return false }
val tag = input.readInt32NoTag()
if (tag == 0) { return false }
val fieldNumber = WireFormat.getTagFieldNumber(tag)
val wireType = WireFormat.getTagWireType(tag)
when(fieldNumber) {
1 -> {
if (wireType.id != WireType.VARINT.id) {
errorCode = 1
return false
}
int = input.readInt32NoTag()
}
2 -> {
if (wireType.id != WireType.VARINT.id) {
errorCode = 1
return false
}
long = input.readInt64NoTag()
}
3 -> {
if (wireType.id != WireType.VARINT.id) {
errorCode = 1
return false
}
sint = input.readSInt32NoTag()
}
4 -> {
if (wireType.id != WireType.VARINT.id) {
errorCode = 1
return false
}
slong = input.readSInt64NoTag()
}
5 -> {
if (wireType.id != WireType.VARINT.id) {
errorCode = 1
return false
}
bl = input.readBoolNoTag()
}
6 -> {
if (wireType.id != WireType.VARINT.id) {
errorCode = 1
return false
}
enumField = MessageVarints.TestEnum.fromIntToTestEnum(input.readEnumNoTag())
}
7 -> {
if (wireType.id != WireType.VARINT.id) {
errorCode = 1
return false
}
uint = input.readUInt32NoTag()
}
8 -> {
if (wireType.id != WireType.VARINT.id) {
errorCode = 1
return false
}
ulong = input.readUInt64NoTag()
}
else -> errorCode = 4
}
return true
}
fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): MessageVarints.BuilderMessageVarints {
while(getSizeNoTag() < expectedSize) {
parseFieldFrom(input)
}
if (getSizeNoTag() > expectedSize) { errorCode = 2 }
return this
}
fun parseFrom(input: CodedInputStream): MessageVarints.BuilderMessageVarints {
while(parseFieldFrom(input)) {}
return this
}
//========== Size-related methods ===========
fun getSize(fieldNumber: Int): Int {
var size = 0
if (int != 0) {
size += WireFormat.getInt32Size(1, int)
}
if (long != 0L) {
size += WireFormat.getInt64Size(2, long)
}
if (sint != 0) {
size += WireFormat.getSInt32Size(3, sint)
}
if (slong != 0L) {
size += WireFormat.getSInt64Size(4, slong)
}
if (bl != false) {
size += WireFormat.getBoolSize(5, bl)
}
if (enumField != MessageVarints.TestEnum.fromIntToTestEnum(0)) {
size += WireFormat.getEnumSize(6, enumField.id)
}
if (uint != 0) {
size += WireFormat.getUInt32Size(7, uint)
}
if (ulong != 0L) {
size += WireFormat.getUInt64Size(8, ulong)
}
size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED)
return size
}
fun getSizeNoTag(): Int {
var size = 0
if (int != 0) {
size += WireFormat.getInt32Size(1, int)
}
if (long != 0L) {
size += WireFormat.getInt64Size(2, long)
}
if (sint != 0) {
size += WireFormat.getSInt32Size(3, sint)
}
if (slong != 0L) {
size += WireFormat.getSInt64Size(4, slong)
}
if (bl != false) {
size += WireFormat.getBoolSize(5, bl)
}
if (enumField != MessageVarints.TestEnum.fromIntToTestEnum(0)) {
size += WireFormat.getEnumSize(6, enumField.id)
}
if (uint != 0) {
size += WireFormat.getUInt32Size(7, uint)
}
if (ulong != 0L) {
size += WireFormat.getUInt64Size(8, ulong)
}
return size
}
}
}
fun compareVarints(kt1: MessageVarints, kt2: MessageVarints): Boolean {
return (kt1.int == kt2.int) and
(kt1.long == kt2.long) and
(kt1.sint == kt2.sint) and
(kt1.slong == kt2.slong) and
(kt1.bl == kt2.bl) and
(kt1.uint == kt2.uint) and
(kt1.ulong == kt2.ulong) and
(kt1.enumField.id == kt2.enumField.id)
}
fun checkVarintsSerializationIdentity(msg: MessageVarints): Int {
val outs = CodedOutputStream(ByteArray(msg.getSizeNoTag()))
msg.writeTo(outs)
val ins = CodedInputStream(outs.buffer)
val readMsg = MessageVarints.BuilderMessageVarints(0, 0L, 0, 0L, false, MessageVarints.TestEnum.fromIntToTestEnum(0), 0, 0L)
.parseFrom(ins).build()
if (readMsg.errorCode != 0) {
return 1
}
if (compareVarints(msg, readMsg)) {
return 0
} else {
return 1
}
}
fun testVarintDefaultMessage(): Int {
val msg = MessageVarints.BuilderMessageVarints(0, 0L, 0, 0L, false, MessageVarints.TestEnum.fromIntToTestEnum(0), 0, 0L).build()
return checkVarintsSerializationIdentity(msg)
}
fun testVarintTrivialMessage(): Int {
val msg = MessageVarints.BuilderMessageVarints(
21312, -2131231231L, 5346734, 42121313211L, true, MessageVarints.TestEnum.fromIntToTestEnum(2), 3672356, 3478787863467834678L
).build()
return checkVarintsSerializationIdentity(msg)
}
fun testVarintNegativeMessage(): Int {
val msg = MessageVarints.BuilderMessageVarints(
-312732, -2131231231L, -5346734, -42121313211L, true, MessageVarints.TestEnum.fromIntToTestEnum(3), 3672356, 3478787863467834678L
).build()
return checkVarintsSerializationIdentity(msg)
}
fun testVarintMaxValues(): Int {
val msg = MessageVarints.BuilderMessageVarints(
2147483647,
9223372036854775807L,
2147483647,
9223372036854775807L,
true,
MessageVarints.TestEnum.fromIntToTestEnum(3),
2147483647,
9223372036854775807L
).build()
return checkVarintsSerializationIdentity(msg)
}
fun testVarintMinValues(): Int {
val msg = MessageVarints.BuilderMessageVarints(
-2147483647,
-9223372036854775807L,
-2147483647,
-9223372036854775807L,
false,
MessageVarints.TestEnum.fromIntToTestEnum(0),
-2147483647,
-9223372036854775807L
).build()
return checkVarintsSerializationIdentity(msg)
} | mit | 40e9ce5f66e01644dfc8530bf5f9ba61 | 30.081466 | 197 | 0.491547 | 4.335227 | false | true | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/utils/BOINCUtils.kt | 2 | 4839 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
@file:JvmName("BOINCUtils")
package edu.berkeley.boinc.utils
import android.content.Context
import android.graphics.Bitmap
import android.net.ConnectivityManager
import android.os.Build
import android.util.Log
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import edu.berkeley.boinc.BOINCActivity
import edu.berkeley.boinc.R
import java.io.IOException
import java.io.Reader
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.concurrent.Callable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
val ConnectivityManager.isOnline: Boolean
get() {
return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
@Suppress("DEPRECATION")
activeNetworkInfo?.isConnectedOrConnecting == true
} else {
activeNetwork != null
}
}
fun setAppTheme(theme: String) {
when (theme) {
"light" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
"dark" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
"system" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
}
fun writeClientModeAsync(mode: Int): Boolean {
val runMode = BOINCActivity.monitor!!.setRunModeAsync(mode)
val networkMode = BOINCActivity.monitor!!.setNetworkModeAsync(mode)
return runMode.await() && networkMode.await()
}
//from https://stackoverflow.com/questions/33696488/getting-bitmap-from-vector-drawable
fun Context.getBitmapFromVectorDrawable(@DrawableRes drawableId: Int): Bitmap {
val drawable = AppCompatResources.getDrawable(this, drawableId)!!
return drawable.toBitmap()
}
@Throws(IOException::class)
fun Reader.readLineLimit(limit: Int): String? {
val sb = StringBuilder()
for (i in 0 until limit) {
val c = read() //Read in single character
if (c == -1) {
return if (sb.isNotEmpty()) sb.toString() else null
}
if (c.toChar() == '\n' || c.toChar() == '\r') { //Found end of line, break loop.
break
}
sb.append(c.toChar()) // String is not over and end line not found
}
return sb.toString() //end of line was found.
}
fun Context.translateRPCReason(reason: Int) = when (reason) {
RPC_REASON_USER_REQ -> resources.getString(R.string.rpcreason_userreq)
RPC_REASON_NEED_WORK -> resources.getString(R.string.rpcreason_needwork)
RPC_REASON_RESULTS_DUE -> resources.getString(R.string.rpcreason_resultsdue)
RPC_REASON_TRICKLE_UP -> resources.getString(R.string.rpcreason_trickleup)
RPC_REASON_ACCT_MGR_REQ -> resources.getString(R.string.rpcreason_acctmgrreq)
RPC_REASON_INIT -> resources.getString(R.string.rpcreason_init)
RPC_REASON_PROJECT_REQ -> resources.getString(R.string.rpcreason_projectreq)
else -> resources.getString(R.string.rpcreason_unknown)
}
fun Long.secondsToLocalDateTime(
zoneId: ZoneId = ZoneId.systemDefault()
): LocalDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(this), zoneId)
fun Context.getColorCompat(@ColorRes colorId: Int) = ContextCompat.getColor(this, colorId)
class TaskRunner<V>(private val callback: ((V) -> Unit)?, private val callable: Callable<V>) {
val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val deferred = applicationScope.async {
try {
val result = callable.call()
callback?.invoke(result)
result
} catch (e: Exception) {
Logging.logException(Logging.Category.CLIENT, "BOINCUtils.TaskRunner error: ", e)
throw e
}
}
fun await(): V = runBlocking {
deferred.await()
}
}
| lgpl-3.0 | efd8ca1f516b7a24f367d8443ee4a03a | 36.804688 | 101 | 0.723497 | 4.118298 | false | false | false | false |
android/health-samples | health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/presentation/component/ExerciseSessionInfoColumn.kt | 1 | 3137 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.healthconnectsample.presentation.component
import android.graphics.drawable.Drawable
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.health.connect.client.records.ExerciseSessionRecord
import com.example.healthconnectsample.presentation.theme.HealthConnectTheme
import com.google.accompanist.drawablepainter.rememberDrawablePainter
import java.time.ZonedDateTime
import java.util.UUID
/**
* Displays summary information about the [ExerciseSessionRecord]
*/
@Composable
fun ExerciseSessionInfoColumn(
start: ZonedDateTime,
end: ZonedDateTime,
uid: String,
name: String,
sourceAppName: String,
sourceAppIcon: Drawable?,
onClick: (String) -> Unit = {}
) {
Column(
modifier = Modifier.clickable {
onClick(uid)
}
) {
Text(
color = MaterialTheme.colors.primary,
text = "${start.toLocalTime()} - ${end.toLocalTime()}",
style = MaterialTheme.typography.caption
)
Text(name)
Row(
verticalAlignment = Alignment.CenterVertically
) {
Image(
modifier = Modifier
.padding(4.dp, 2.dp)
.height(16.dp)
.width(16.dp),
painter = rememberDrawablePainter(drawable = sourceAppIcon),
contentDescription = "App Icon"
)
Text(
text = sourceAppName,
fontStyle = FontStyle.Italic
)
}
Text(uid)
}
}
@Preview
@Composable
fun ExerciseSessionInfoColumnPreview() {
HealthConnectTheme {
ExerciseSessionInfoColumn(
ZonedDateTime.now().minusMinutes(30),
ZonedDateTime.now(),
UUID.randomUUID().toString(),
"Running",
"My Fitness App",
null
)
}
}
| apache-2.0 | 6c5938d730412ac4da3da6732eb1c82a | 31.010204 | 76 | 0.680905 | 4.717293 | false | false | false | false |
Popalay/Cardme | presentation/src/main/kotlin/com/popalay/cardme/presentation/widget/SettingTextView.kt | 1 | 1868 | package com.popalay.cardme.presentation.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.support.v4.content.ContextCompat
import android.support.v7.widget.AppCompatTextView
import android.text.TextPaint
import android.util.AttributeSet
import com.popalay.cardme.R
class SettingTextView(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0)
private var settingText: String? = null
private val textPaint: TextPaint by lazy {
val lazyPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
lazyPaint.color = ContextCompat.getColor(context, R.color.accent)
lazyPaint.textSize = textSize
lazyPaint
}
init {
attrs?.let {
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.SettingTextView, defStyleAttr, 0)
try {
settingText = a.getString(R.styleable.SettingTextView_settingText)
} finally {
a.recycle()
}
}
}
fun setSettingText(settingText: String?) {
this.settingText = settingText
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
settingText?.let {
canvas.save()
canvas.translate(paddingLeft.toFloat(), paddingTop.toFloat())
val width = canvas.width
.minus(textPaint.measureText(settingText))
.minus(paddingEnd)
.minus(paddingStart)
val height = -textPaint.ascent() + textPaint.descent()
canvas.drawText(settingText, width, height, textPaint)
canvas.restore()
}
}
}
| apache-2.0 | c59fd94ac13d067c147443311e9e492e | 31.206897 | 109 | 0.638116 | 4.635236 | false | false | false | false |
zathras/misc | voteserv/src/SimpleHttp.kt | 1 | 4550 | /**
* Simple HTTP server, using code swiped from simples, whic was swiped from hat.
* This has been hacked to be a voting server.
*
* @author Bill Foote
*/
import java.net.InetAddress
import java.security.SecureRandom
import server.ErrorQueryHandler
import server.QueryHandler
import server.QueryListener
import java.io.*
import java.net.NetworkInterface
import java.net.Inet4Address;
import java.util.*
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.Lock
import kotlin.concurrent.withLock
public val localInetAddress = getAddress()
private fun getAddress() : InetAddress {
for (ne in NetworkInterface.getNetworkInterfaces()) {
for (ie in ne.getInetAddresses()) {
if (!ie.isLoopbackAddress() && ie is Inet4Address) {
return ie;
}
}
}
for (ne in NetworkInterface.getNetworkInterfaces()) {
for (ie in ne.getInetAddresses()) {
if (!ie.isLoopbackAddress()) {
return ie;
}
}
}
return InetAddress.getLocalHost()
}
class SimpleHttp(
val ballot : Ballot,
val lock : Lock,
val voteReceived : Condition) : QueryListener(6001, false)
{
override fun getHandler(query: String, rawOut: OutputStream, out: PrintWriter,
user : InetAddress): QueryHandler?
{
return BallotQuery(ballot, rawOut, out, user, lock)
}
override fun handlePost(headers: HashMap<String, String>, input: BufferedInputStream,
rawOut: OutputStream, out: PrintWriter,
user : InetAddress) : QueryHandler?
{
var remaining = headers["Content-Length"]?.toLong()
val contentType = headers["Content-Type"]
if (remaining == null) {
println("POST error: No content length")
return null;
}
if (contentType != "text/plain") {
println("POST warning: contentType is $contentType, not text/plain.")
println("I'll process it, but you get what you get.")
}
var found : Long? = null
var round : Int? = null
var timestamp : Long? = null
val votes = mutableSetOf<Int>()
while (remaining > 0) {
val ch = input.read();
if (ch in '0'.toInt() .. '9'.toInt()) {
val d = ch - '0'.toInt()
found = if (found == null) d.toLong() else found * 10 + d
} else if (ch == '='.toInt()) {
if (found == null) {
println("parse error: found is null")
} else {
if (found >= 0) { // If this isn't -1 from below
votes.add(found.toInt())
}
found = null
}
} else if (ch == 't'.toInt()) {
if (found == null) {
println("parse error: found is null for timestamp")
} else {
timestamp = found
found = -1 // Skip error when we see the '='
}
} else if (ch == 'r'.toInt()) {
if (found == null) {
println("parse error: found is null for round")
} else {
round = found.toInt()
found = -1 // Skip error when we see the '='
}
} else if (found != null) {
println("""parse error: no "=" after number""")
found = null;
}
remaining--;
}
lock.withLock {
if (ballot.timestamp != timestamp) {
println("Error: $user tried to vote on a different (older?) ballot.")
} else if (ballot.round != round) {
println("Error: $user tried to vote in round $round.")
} else if (ballot.voted.contains(user)) {
println("Error: $user tried to vote twice.")
} else {
for (i in votes) {
ballot.candidates[i].votes++
}
ballot.voted.add(user)
voteReceived.signalAll()
}
}
return BallotQuery(ballot, rawOut, out, user, lock)
}
val publicURL: String @Throws(IOException::class)
get() {
val scheme = if (enableSsl) "https" else "http"
return scheme + "://" + localInetAddress.hostAddress + ":" + port + "/"
}
}
| mit | a8334c8b2df5db28e610be9148345a4d | 34.271318 | 89 | 0.51011 | 4.568273 | false | false | false | false |
BilledTrain380/sporttag-psa | app/psa-runtime-service/psa-service-standard/src/main/kotlin/ch/schulealtendorf/psa/service/standard/entity/ParticipationEntity.kt | 1 | 2341 | /*
* Copyright (c) 2017 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.service.standard.entity
import ch.schulealtendorf.psa.dto.participation.ParticipationStatusType
import org.jetbrains.annotations.NotNull
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
import javax.validation.constraints.Size
/**
* @author nmaerchy
* @version 1.0.0
*/
@Entity
@Table(name = "PARTICIPATION")
data class ParticipationEntity @JvmOverloads constructor(
@Id
@NotNull
@Size(min = 1, max = 10)
var name: String = MAIN_PARTICIPATION,
@NotNull
@Size(min = 1, max = 10)
var status: String = ParticipationStatusType.OPEN.name
) {
val statusType: ParticipationStatusType
get() = ParticipationStatusType.valueOf(status)
companion object {
const val MAIN_PARTICIPATION = "main"
}
}
| gpl-3.0 | 43f8e5587bb8d9b15efb592616faa3b3 | 33.279412 | 77 | 0.745603 | 4.21519 | false | false | false | false |
AromaTech/banana-data-operations | src/main/java/tech/aroma/data/GuicePlus.kt | 3 | 1418 | /*
* Copyright 2017 RedRoma, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.aroma.data
import com.google.inject.*
import com.google.inject.binder.AnnotatedBindingBuilder
import com.google.inject.binder.ScopedBindingBuilder
/*
Shortcut functions for handling Guice with Kotlin.
*/
/**
*
* @author SirWellington
*/
internal inline fun <reified T : Any> Binder.bind(): AnnotatedBindingBuilder<T>
{
val literal = object : TypeLiteral<T>() {}
return bind(literal)
}
internal inline fun <reified T : Any> AnnotatedBindingBuilder<in T>.to(): ScopedBindingBuilder = to(T::class.java)
internal inline fun <reified T : Any> Injector.getInstance() = getInstance(T::class.java)
internal inline fun <reified T> Injector.hasInstance(): Boolean
{
val literal = object : TypeLiteral<T>() {}
val result = this.getInstance(Key.get(literal))
return result != null
} | apache-2.0 | 771e33f7b0a432f83db63aa59be81d48 | 28.5625 | 114 | 0.729196 | 4.039886 | false | false | false | false |
AndroidX/androidx | room/room-compiler/src/main/kotlin/androidx/room/vo/Database.kt | 3 | 4918 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.vo
import androidx.room.RoomMasterTable
import androidx.room.compiler.codegen.XClassName
import androidx.room.compiler.processing.XType
import androidx.room.compiler.processing.XTypeElement
import androidx.room.migration.bundle.DatabaseBundle
import androidx.room.migration.bundle.SchemaBundle
import java.io.File
import org.apache.commons.codec.digest.DigestUtils
/**
* Holds information about a class annotated with Database.
*/
data class Database(
val element: XTypeElement,
val type: XType,
val entities: List<Entity>,
val views: List<DatabaseView>,
val daoMethods: List<DaoMethod>,
val version: Int,
val exportSchema: Boolean,
val enableForeignKeys: Boolean
) {
// This variable will be set once auto-migrations are processed given the DatabaseBundle from
// this object. This is necessary for tracking the versions involved in the auto-migration.
lateinit var autoMigrations: List<AutoMigration>
val typeName: XClassName by lazy { element.asClassName() }
private val implClassName by lazy {
"${typeName.simpleNames.joinToString("_")}_Impl"
}
val implTypeName: XClassName by lazy {
XClassName.get(typeName.packageName, implClassName)
}
val bundle by lazy {
DatabaseBundle(
version, identityHash, entities.map(Entity::toBundle),
views.map(DatabaseView::toBundle),
listOf(
RoomMasterTable.CREATE_QUERY,
RoomMasterTable.createInsertQuery(identityHash)
)
)
}
/**
* Create a has that identifies this database definition so that at runtime we can check to
* ensure developer didn't forget to update the version.
*/
val identityHash: String by lazy {
val idKey = SchemaIdentityKey()
idKey.appendSorted(entities)
idKey.appendSorted(views)
idKey.hash()
}
val legacyIdentityHash: String by lazy {
val entityDescriptions = entities
.sortedBy { it.tableName }
.map { it.createTableQuery }
val indexDescriptions = entities
.flatMap { entity ->
entity.indices.map { index ->
// For legacy purposes we need to remove the later added 'IF NOT EXISTS'
// part of the create statement, otherwise old valid legacy hashes stop
// being accepted even though the schema has not changed. b/139306173
if (index.unique) {
"CREATE UNIQUE INDEX"
} else {
// The extra space between 'CREATE' and 'INDEX' is on purpose, this
// is a typo we have to live with.
"CREATE INDEX"
} + index.createQuery(entity.tableName).substringAfter("IF NOT EXISTS")
}
}
val viewDescriptions = views
.sortedBy { it.viewName }
.map { it.viewName + it.query.original }
val input = (entityDescriptions + indexDescriptions + viewDescriptions)
.joinToString("¯\\_(ツ)_/¯")
DigestUtils.md5Hex(input)
}
fun exportSchema(file: File) {
val schemaBundle = SchemaBundle(SchemaBundle.LATEST_FORMAT, bundle)
if (file.exists()) {
val existing = try {
file.inputStream().use {
SchemaBundle.deserialize(it)
}
} catch (th: Throwable) {
throw IllegalStateException(
"""
Cannot parse existing schema file: ${file.absolutePath}.
If you've modified the file, you might've broken the JSON format, try
deleting the file and re-running the compiler.
If you've not modified the file, please file a bug at
https://issuetracker.google.com/issues/new?component=413107&template=1096568
with a sample app to reproduce the issue.
""".trimIndent()
)
}
if (existing.isSchemaEqual(schemaBundle)) {
return
}
}
SchemaBundle.serialize(schemaBundle, file)
}
}
| apache-2.0 | 7dcb157b1067fa10d821a517e4f5cac5 | 37.390625 | 97 | 0.616402 | 4.938693 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/socketing/SocketItem.kt | 1 | 4496 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.socketing
import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.socketing.items.SocketGemOptions
import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.SocketGem
import com.tealcube.minecraft.bukkit.mythicdrops.replaceArgs
import com.tealcube.minecraft.bukkit.mythicdrops.replaceWithCollections
import com.tealcube.minecraft.bukkit.mythicdrops.setDisplayNameChatColorized
import com.tealcube.minecraft.bukkit.mythicdrops.setLoreChatColorized
import com.tealcube.minecraft.bukkit.mythicdrops.splitOnNewlines
import com.tealcube.minecraft.bukkit.mythicdrops.trimEmpty
import io.pixeloutlaw.minecraft.spigot.hilt.addItemFlags
import io.pixeloutlaw.minecraft.spigot.mythicdrops.mythicDropsSocketGem
import io.pixeloutlaw.minecraft.spigot.mythicdrops.setPersistentDataString
import org.bukkit.Material
import org.bukkit.enchantments.Enchantment
import org.bukkit.inventory.ItemFlag
import org.bukkit.inventory.ItemStack
class SocketItem(
material: Material,
socketGem: SocketGem,
socketGemOptions: SocketGemOptions
) : ItemStack(material, 1) {
init {
this.setDisplayNameChatColorized(
socketGemOptions.name.replaceArgs(
"%socketgem%" to socketGem.name
)
)
val combinedTypeLore = socketGem.getPresentableType(
socketGemOptions.allOfSocketTypeLore,
socketGemOptions.anyOfSocketTypeLore,
socketGemOptions.noneOfSocketTypeLore
).joinToString(separator = "\n", prefix = "\n") // leaving prefix for backwards compatibility
val allOfTypeLore = socketGem.getPresentableType(socketGemOptions.allOfSocketTypeLore, emptyList(), emptyList())
.filterNot { it.isBlank() }.joinToString(separator = "\n")
val anyOfTypeLore = socketGem.getPresentableType(emptyList(), socketGemOptions.anyOfSocketTypeLore, emptyList())
.filterNot { it.isBlank() }.joinToString(separator = "\n")
val noneOfTypeLore =
socketGem.getPresentableType(emptyList(), emptyList(), socketGemOptions.noneOfSocketTypeLore)
.filterNot { it.isBlank() }.joinToString(separator = "\n")
val typeLore = socketGemOptions.socketTypeLore.replaceArgs(
"%type%" to combinedTypeLore,
"%alloftype%" to allOfTypeLore,
"%anyoftype%" to anyOfTypeLore,
"%noneoftype%" to noneOfTypeLore
).splitOnNewlines()
val familyLore = if (socketGem.family.isNotBlank()) {
socketGemOptions.familyLore.replaceArgs(
"%family%" to socketGem.family,
"%level%" to socketGem.level.toString()
)
} else {
emptyList()
}
val socketGemLore = socketGem.lore
val lore = socketGemOptions.lore.replaceWithCollections(
"%sockettypelore%" to typeLore,
"%socketfamilylore%" to familyLore,
"%socketgemlore%" to socketGemLore
).trimEmpty()
this.setLoreChatColorized(lore)
if (socketGemOptions.isGlow) {
this.addUnsafeEnchantment(Enchantment.DURABILITY, 1)
this.addItemFlags(ItemFlag.HIDE_ENCHANTS)
}
setPersistentDataString(mythicDropsSocketGem, socketGem.name)
}
}
| mit | d4982164915386f39cc195b6c765ebb1 | 47.344086 | 120 | 0.724644 | 4.550607 | false | false | false | false |
Undin/intellij-rust | toml/src/main/kotlin/org/rust/toml/intentions/ExpandDependencySpecificationIntention.kt | 2 | 1816 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.toml.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import org.rust.lang.core.psi.ext.endOffset
import org.rust.toml.isCargoToml
import org.rust.toml.isDependencyListHeader
import org.toml.lang.psi.TomlKeyValue
import org.toml.lang.psi.TomlLiteral
import org.toml.lang.psi.TomlPsiFactory
import org.toml.lang.psi.TomlTable
import org.toml.lang.psi.ext.TomlLiteralKind
import org.toml.lang.psi.ext.kind
class ExpandDependencySpecificationIntention : RsTomlElementBaseIntentionAction<TomlKeyValue>() {
override fun getText() = "Expand dependency specification"
override fun getFamilyName(): String = text
override fun findApplicableContextInternal(project: Project, editor: Editor, element: PsiElement): TomlKeyValue? {
if (!element.containingFile.isCargoToml) return null
val keyValue = element.parentOfType<TomlKeyValue>() ?: return null
val table = keyValue.parent as? TomlTable ?: return null
if (!table.header.isDependencyListHeader) return null
val value = keyValue.value
if (value !is TomlLiteral || value.kind !is TomlLiteralKind.String) return null
return keyValue
}
override fun invoke(project: Project, editor: Editor, ctx: TomlKeyValue) {
val crateName = ctx.key.text
val crateVersion = ctx.value?.text ?: "\"\""
val newKeyValue = TomlPsiFactory(project).createKeyValue("$crateName = { version = $crateVersion }")
val newKeyValueOffset = ctx.replace(newKeyValue).endOffset
editor.caretModel.moveToOffset(newKeyValueOffset)
}
}
| mit | 4a22a91bf637572e805123428888cfbd | 38.478261 | 118 | 0.748348 | 4.242991 | false | false | false | false |
ioc1778/incubator | incubator-crypto/src/test/java/com/riaektiv/crypto/tree/AccountTreeTest.kt | 2 | 1530 | package com.riaektiv.crypto.tree
import org.junit.Assert.assertEquals
import org.junit.Test
import java.math.BigDecimal
/**
* Coding With Passion Since 1991
* Created: 7/10/2016, 8:24 AM Eastern Time
* @author Sergey Chuykov
*/
class AccountTreeTest {
var tree = AccountTreeFactory().tree()
lateinit var account: Account
fun bd(value: Double): BigDecimal
= BigDecimal.valueOf(value)
fun account(number: String, balance: Double)
= tree.entity(number, bd(balance))
@Test
fun message() {
account = account("1", 0.00)
assertEquals("1:0.00", tree.message(account))
assertEquals("ce9d02a86390870f09658d8c46ad3805671f7ff06d73f6e17e35e00e", account.hash())
account = account("3", 17.03)
assertEquals("3:17.03", tree.message(account))
assertEquals("e6c59ea5a948ae0856537d5a0da10dd8d254d7b887c2906d76ad6cfc", account.hash())
}
@Test
fun putGetValidate() {
tree.validate()
val accounts = arrayOf(
account("1", 101.01),
account("3", 303.03),
account("77A9F", 777.77)
)
for (i in 0..2) {
tree.put(accounts[i])
tree.validate()
}
val expected = arrayOf(
account("1", 101.01),
account("3", 303.03),
account("77A9F", 777.77)
)
for (i in 0..2) {
assertEquals(expected[i], tree.get(accounts[i].number))
}
}
}
| bsd-3-clause | f2c21caf3a640be14df1f8cabfbd1483 | 21.835821 | 96 | 0.57451 | 3.566434 | false | true | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/Helpers.kt | 1 | 1307 | package com.github.jk1.ytplugin
import com.google.gson.JsonElement
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import java.awt.Color
import java.text.SimpleDateFormat
import java.util.*
val logger: Logger
get() = Logger.getInstance("com.github.jk1.ytplugin")
fun String.runAction() {
val action = ActionManager.getInstance().getAction(this)
DataManager.getInstance().dataContextFromFocusAsync.onSuccess { context ->
val event = AnActionEvent.createFromAnAction(action, null, ActionPlaces.UNKNOWN, context)
action.actionPerformed(event)
}
}
fun AnActionEvent.whenActive(closure: (project: Project) -> Unit) {
val project = project
if (project != null && project.isInitialized && !project.isDisposed) {
closure.invoke(project)
}
}
fun Date.format(): String = SimpleDateFormat("dd MMM yyyy HH:mm").format(this)
// #F0A -> #FF00AA
fun JsonElement.asColor(): Color = when (asString.length) {
4 -> Color.decode(asString.drop(1).map { "$it$it" }.joinToString("", "#"))
else -> Color.decode(asString)
}
| apache-2.0 | 59faf11d6170be20fbf406b7174138b0 | 33.394737 | 97 | 0.744453 | 3.984756 | false | false | false | false |
neva-dev/gradle-osgi-plugin | plugins/gradle-plugin/src/main/kotlin/com/neva/osgi/toolkit/gradle/instance/DistributionTask.kt | 1 | 4789 | package com.neva.osgi.toolkit.gradle.instance
import com.neva.osgi.toolkit.commons.domain.Instance
import com.neva.osgi.toolkit.gradle.internal.Formats
import com.neva.osgi.toolkit.gradle.internal.ResourceOperations
import org.apache.commons.io.FileUtils
import org.gradle.api.Project
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.bundling.Zip
import org.gradle.util.GFileUtils
import org.zeroturnaround.zip.ZipUtil
import java.io.File
open class DistributionTask : Zip() {
companion object {
const val NAME = "osgiDistribution"
}
init {
group = "OSGi"
description = "Create self-extractable OSGi distribution"
destinationDir = project.file("build/osgi/distributions")
extension = "jar"
project.afterEvaluate {
from(project.zipTree(project.resolveDependency(distributionLauncher)))
from(distributionDir, { it.into(Instance.DISTRIBUTION_PATH) })
}
}
@Input
var distribution: Any = mapOf(
"group" to "org.apache.felix",
"name" to "org.apache.felix.main.distribution",
"version" to "5.6.10",
"ext" to "zip"
)
@Input
var distributionLauncher: Any = "com.neva.osgi.toolkit:distribution-launcher:1.0.0"
@Input
var frameworkLauncher: Any = "com.neva.osgi.toolkit:framework-launcher:1.0.0"
@Input
var frameworkLauncherMainClass: String = "com.neva.osgi.toolkit.framework.launcher.Launcher"
@Input
var baseBundles: List<Any> = mutableListOf(
"org.osgi:osgi.core:6.0.0",
"org.apache.felix:org.apache.felix.scr:2.0.14",
"org.apache.felix:org.apache.felix.fileinstall:3.6.4",
"com.neva.osgi.toolkit:web-manager:1.0.0"
)
@get:OutputDirectory
val distributionDir: File
get() = project.file("${InstancePlugin.TMP_PATH}/${Instance.DISTRIBUTION_PATH}")
@get:OutputFile
val metadataFile: File
get() = project.file("${InstancePlugin.TMP_PATH}/${Instance.METADATA_FILE}")
@TaskAction
override fun copy() {
logger.info("Creating OSGi distribution.")
unpackDistribution()
includeFrameworkLauncherJar()
includeFrameworkLauncherScripts()
includeBaseBundles()
generateMetadataFile()
packDistribution()
logger.info("Created OSGi distribution successfully.")
}
private fun packDistribution() {
logger.info("Composing distribution jar")
super.copy()
}
// TODO detect if zip has at first level only dir (if yes, skip it, currently hardcoded)
private fun unpackDistribution() {
logger.info("Downloading and extracting distribution")
val distributionZip = project.resolveDependency(distribution)
ZipUtil.unpack(distributionZip, distributionDir, { it.substringAfter("/") })
}
private fun includeFrameworkLauncherJar() {
logger.info("Downloading framework launcher and including it into distribution")
project.includeDependency(frameworkLauncher, "bin")
}
private fun includeFrameworkLauncherScripts() {
logger.info("Including framework launcher scripts")
ResourceOperations.copyDir("OSGI-INF/toolkit/distribution", distributionDir, true)
}
private fun includeBaseBundles() {
logger.info("Downloading base bundles and including them into distribution")
baseBundles.forEach { project.includeDependency(it, "bundle") }
}
private fun generateMetadataFile() {
logger.info("Generating metadata file")
GFileUtils.mkdirs(metadataFile.parentFile)
val metadata = DistributionMetadata.of(project)
val json = Formats.toJson(metadata)
metadataFile.printWriter().use { it.print(json) }
}
private fun Project.includeDependency(dependencyNotation: Any, path: String) {
val source = project.resolveDependency(dependencyNotation)
val target = File(distributionDir, "$path/${source.name}")
logger.info("Copying distribution dependency '${source.name}' into '$path'")
GFileUtils.mkdirs(source.parentFile)
FileUtils.copyFile(source, target)
}
private fun Project.resolveDependency(dependencyNotation: Any): File {
logger.info("Resolving distribution dependency '$dependencyNotation' into '$path'")
val dependency = dependencies.create(dependencyNotation)
val config = configurations.detachedConfiguration(dependency).apply {
description = dependencyNotation.toString()
isTransitive = false
}
return config.singleFile
}
}
| apache-2.0 | 2f1020f8b6e3159dd934b8e05a95c318 | 31.80137 | 96 | 0.684694 | 4.463187 | false | false | false | false |
google/dokka | core/src/main/kotlin/Formats/DacHtmlFormat.kt | 1 | 35539 | package org.jetbrains.dokka.Formats
import com.google.inject.Inject
import com.google.inject.name.Named
import kotlinx.html.*
import org.jetbrains.dokka.*
import org.jetbrains.dokka.Utilities.firstSentence
import org.w3c.dom.html.HTMLElement
import java.lang.Math.max
import java.net.URI
import java.util.Collections.emptyMap
import kotlin.reflect.KClass
/**
* On Devsite, certain headers and footers are needed for generating Devsite metadata.
*/
class DevsiteHtmlTemplateService @Inject constructor(
@Named("outlineRoot") val outlineRoot: String,
@Named("dacRoot") val dacRoot: String
) : JavaLayoutHtmlTemplateService {
override fun composePage(page: JavaLayoutHtmlFormatOutputBuilder.Page, tagConsumer: TagConsumer<Appendable>, headContent: HEAD.() -> Unit, bodyContent: BODY.() -> Unit) {
tagConsumer.html {
attributes["devsite"] = "true"
head {
headContent()
title {
+when (page) {
is JavaLayoutHtmlFormatOutputBuilder.Page.ClassIndex -> "Class Index"
is JavaLayoutHtmlFormatOutputBuilder.Page.ClassPage -> page.node.nameWithOuterClass()
is JavaLayoutHtmlFormatOutputBuilder.Page.PackageIndex -> "Package Index"
is JavaLayoutHtmlFormatOutputBuilder.Page.PackagePage -> page.node.nameWithOuterClass()
}
}
unsafe { +"{% setvar book_path %}${dacRoot}/${outlineRoot}_book.yaml{% endsetvar %}\n{% include \"_shared/_reference-head-tags.html\" %}\n" }
}
body {
bodyContent()
}
}
}
}
class DevsiteLayoutHtmlFormatOutputBuilderFactoryImpl @javax.inject.Inject constructor(
val uriProvider: JavaLayoutHtmlUriProvider,
val languageService: LanguageService,
val templateService: JavaLayoutHtmlTemplateService,
val logger: DokkaLogger
) : JavaLayoutHtmlFormatOutputBuilderFactory {
override fun createOutputBuilder(output: Appendable, node: DocumentationNode): JavaLayoutHtmlFormatOutputBuilder {
return createOutputBuilder(output, uriProvider.mainUri(node))
}
override fun createOutputBuilder(output: Appendable, uri: URI): JavaLayoutHtmlFormatOutputBuilder {
return DevsiteLayoutHtmlFormatOutputBuilder(output, languageService, uriProvider, templateService, logger, uri)
}
}
class DevsiteLayoutHtmlFormatOutputBuilder(
output: Appendable,
languageService: LanguageService,
uriProvider: JavaLayoutHtmlUriProvider,
templateService: JavaLayoutHtmlTemplateService,
logger: DokkaLogger,
uri: URI
) : JavaLayoutHtmlFormatOutputBuilder(output, languageService, uriProvider, templateService, logger, uri) {
override fun FlowContent.fullMemberDocs(node: DocumentationNode) {
fullMemberDocs(node, node)
}
override fun FlowContent.fullMemberDocs(node: DocumentationNode, uriNode: DocumentationNode) {
a {
attributes["name"] = uriNode.signatureForAnchor(logger).anchorEncoded()
}
div(classes = "api apilevel-${node.apiLevel.name}") {
attributes["data-version-added"] = node.apiLevel.name
h3(classes = "api-name") {
//id = node.signatureForAnchor(logger).urlEncoded()
+node.name
}
apiAndDeprecatedVersions(node)
pre(classes = "api-signature no-pretty-print") { renderedSignature(node, LanguageService.RenderMode.FULL) }
deprecationWarningToMarkup(node, prefix = true)
nodeContent(node, uriNode)
node.constantValue()?.let { value ->
pre {
+"Value: "
code { +value }
}
}
for ((name, sections) in node.content.sections.groupBy { it.tag }) {
when (name) {
ContentTags.Return -> {
table(classes = "responsive") {
tbody {
tr {
th {
colSpan = "2"
+name
}
}
sections.forEach {
tr {
td {
colSpan = "2"
metaMarkup(it.children)
}
}
}
}
}
}
ContentTags.Parameters -> {
table(classes = "responsive") {
tbody {
tr {
th {
colSpan = "2"
+name
}
}
sections.forEach {
tr {
td {
code {
it.subjectName?.let { +it }
}
}
td {
metaMarkup(it.children)
}
}
}
}
}
}
ContentTags.SeeAlso -> {
div {
p {
b {
+name
}
}
ul(classes = "nolist") {
sections.forEach {
li {
code {
metaMarkup(it.children)
}
}
}
}
}
}
ContentTags.Exceptions -> {
table(classes = "responsive") {
tbody {
tr {
th {
colSpan = "2"
+name
}
}
sections.forEach {
tr {
td {
code {
it.subjectName?.let { +it }
}
}
td {
metaMarkup(it.children)
}
}
}
}
}
}
}
}
}
}
override fun summary(node: DocumentationNode) = node.firstSentenceOfSummary()
fun TBODY.xmlAttributeRow(attr: DocumentationNode) = tr {
td {
a(href = attr) {
code {
+attr.attributeRef!!.name
}
}
}
td {
+attr.attributeRef!!.firstSentence()
}
}
protected fun FlowContent.fullAttributeDocs(
attributes: List<DocumentationNode>,
header: String
) {
if (attributes.none()) return
h2 {
+header
}
attributes.forEach {
fullMemberDocs(it.attributeRef!!, it)
}
}
override fun FlowContent.classLikeFullMemberDocs(page: Page.ClassPage) = with(page) {
fullAttributeDocs(attributes, "XML attributes")
fullMemberDocs(enumValues, "Enum values")
fullMemberDocs(constants, "Constants")
constructors.forEach { (visibility, group) ->
fullMemberDocs(group, "${visibility.capitalize()} constructors")
}
functions.forEach { (visibility, group) ->
fullMemberDocs(group, "${visibility.capitalize()} methods")
}
fullMemberDocs(properties, "Properties")
fields.forEach { (visibility, group) ->
fullMemberDocs(group, "${visibility.capitalize()} fields")
}
if (!hasMeaningfulCompanion) {
fullMemberDocs(companionFunctions, "Companion functions")
fullMemberDocs(companionProperties, "Companion properties")
}
}
override fun FlowContent.classLikeSummaries(page: Page.ClassPage) = with(page) {
summaryNodeGroup(
nestedClasses,
header = "Nested classes",
summaryId = "nestedclasses",
tableClass = "responsive",
headerAsRow = true
) {
nestedClassSummaryRow(it)
}
summaryNodeGroup(
attributes,
header="XML attributes",
summaryId="lattrs",
tableClass = "responsive",
headerAsRow = true
) {
xmlAttributeRow(it)
}
expandableSummaryNodeGroupForInheritedMembers(
superClasses = inheritedAttributes.entries,
header="Inherited XML attributes",
tableId="inhattrs",
tableClass = "responsive",
row = { inheritedXmlAttributeRow(it)}
)
summaryNodeGroup(
constants,
header = "Constants",
summaryId = "constants",
tableClass = "responsive",
headerAsRow = true
) { propertyLikeSummaryRow(it) }
expandableSummaryNodeGroupForInheritedMembers(
superClasses = inheritedConstants.entries,
header = "Inherited constants",
tableId = "inhconstants",
tableClass = "responsive constants inhtable",
row = { inheritedMemberRow(it) }
)
constructors.forEach { (visibility, group) ->
summaryNodeGroup(
group,
header = "${visibility.capitalize()} constructors",
summaryId = "${visibility.take(3)}ctors",
tableClass = "responsive",
headerAsRow = true
) {
functionLikeSummaryRow(it)
}
}
summaryNodeGroup(
enumValues,
header = "Enum values",
summaryId = "enumvalues",
tableClass = "responsive",
headerAsRow = true
) {
propertyLikeSummaryRow(it, showSignature = false)
}
functions.forEach { (visibility, group) ->
summaryNodeGroup(
group,
header = "${visibility.capitalize()} methods",
summaryId = "${visibility.take(3)}methods",
tableClass = "responsive",
headerAsRow = true
) {
functionLikeSummaryRow(it)
}
}
summaryNodeGroup(
companionFunctions,
header = "Companion functions",
summaryId = "compmethods",
tableClass = "responsive",
headerAsRow = true
) {
functionLikeSummaryRow(it)
}
expandableSummaryNodeGroupForInheritedMembers(
superClasses = inheritedFunctionsByReceiver.entries,
header = "Inherited functions",
tableId = "inhmethods",
tableClass = "responsive",
row = { inheritedMemberRow(it) }
)
summaryNodeGroup(
extensionFunctions.entries,
header = "Extension functions",
summaryId = "extmethods",
tableClass = "responsive",
headerAsRow = true
) {
extensionRow(it) {
functionLikeSummaryRow(it)
}
}
summaryNodeGroup(
inheritedExtensionFunctions.entries,
header = "Inherited extension functions",
summaryId = "inhextmethods",
tableClass = "responsive",
headerAsRow = true
) {
extensionRow(it) {
functionLikeSummaryRow(it)
}
}
fields.forEach { (visibility, group) ->
summaryNodeGroup(
group,
header = "${visibility.capitalize()} fields",
summaryId = "${visibility.take(3)}fields",
tableClass = "responsive",
headerAsRow = true
) { propertyLikeSummaryRow(it) }
}
expandableSummaryNodeGroupForInheritedMembers(
superClasses = inheritedFieldsByReceiver.entries,
header = "Inherited fields",
tableId = "inhfields",
tableClass = "responsive properties inhtable",
row = { inheritedMemberRow(it) }
)
summaryNodeGroup(
properties,
header = "Properties",
summaryId = "properties",
tableClass = "responsive",
headerAsRow = true
) { propertyLikeSummaryRow(it) }
summaryNodeGroup(
companionProperties,
"Companion properties",
headerAsRow = true
) {
propertyLikeSummaryRow(it)
}
expandableSummaryNodeGroupForInheritedMembers(
superClasses = inheritedPropertiesByReceiver.entries,
header = "Inherited properties",
tableId = "inhfields",
tableClass = "responsive properties inhtable",
row = { inheritedMemberRow(it) }
)
summaryNodeGroup(
extensionProperties.entries,
"Extension properties",
headerAsRow = true
) {
extensionRow(it) {
propertyLikeSummaryRow(it)
}
}
summaryNodeGroup(
inheritedExtensionProperties.entries,
"Inherited extension properties",
headerAsRow = true
) {
extensionRow(it) {
propertyLikeSummaryRow(it)
}
}
}
fun <T> FlowContent.summaryNodeGroup(
nodes: Iterable<T>,
header: String,
headerAsRow: Boolean,
summaryId: String,
tableClass: String = "responsive",
row: TBODY.(T) -> Unit
) {
if (nodes.none()) return
if (!headerAsRow) {
h2 { +header }
}
table(classes = tableClass) {
id = summaryId
tbody {
if (headerAsRow) {
developerHeading(header, summaryId)
}
nodes.forEach { node ->
row(node)
}
}
}
}
override fun generatePackage(page: Page.PackagePage) = templateService.composePage(
page,
htmlConsumer,
headContent = {
},
bodyContent = {
h1 { +page.node.name }
nodeContent(page.node)
summaryNodeGroup(page.classes.sortedBy { it.nameWithOuterClass().toLowerCase() }, "Classes", headerAsRow = false) { classLikeRow(it) }
summaryNodeGroup(page.exceptions.sortedBy { it.nameWithOuterClass().toLowerCase() }, "Exceptions", headerAsRow = false) { classLikeRow(it) }
summaryNodeGroup(page.typeAliases.sortedBy { it.nameWithOuterClass().toLowerCase() }, "Type-aliases", headerAsRow = false) { classLikeRow(it) }
summaryNodeGroup(page.annotations.sortedBy { it.nameWithOuterClass().toLowerCase() }, "Annotations", headerAsRow = false) { classLikeRow(it) }
summaryNodeGroup(page.enums.sortedBy { it.nameWithOuterClass().toLowerCase() }, "Enums", headerAsRow = false) { classLikeRow(it) }
summaryNodeGroup(
page.constants.sortedBy { it.name },
"Top-level constants summary",
headerAsRow = false
) {
propertyLikeSummaryRow(it)
}
summaryNodeGroup(
page.functions.sortedBy { it.name },
"Top-level functions summary",
headerAsRow = false
) {
functionLikeSummaryRow(it)
}
summaryNodeGroup(
page.properties.sortedBy { it.name },
"Top-level properties summary",
headerAsRow = false
) {
propertyLikeSummaryRow(it)
}
summaryNodeGroupForExtensions("Extension functions summary", page.extensionFunctions.entries)
summaryNodeGroupForExtensions("Extension properties summary", page.extensionProperties.entries)
fullMemberDocs(page.constants.sortedBy { it.name }, "Top-level constants")
fullMemberDocs(page.functions.sortedBy { it.name }, "Top-level functions")
fullMemberDocs(page.properties.sortedBy { it.name }, "Top-level properties")
fullMemberDocs(page.extensionFunctions.values.flatten().sortedBy { it.name }, "Extension functions")
fullMemberDocs(page.extensionProperties.values.flatten().sortedBy { it.name }, "Extension properties")
}
)
private fun TBODY.inheritedXmlAttributeRow(inheritedMember: DocumentationNode) {
tr(classes = "api apilevel-${inheritedMember.attributeRef!!.apiLevel.name}") {
attributes["data-version-added"] = "${inheritedMember.apiLevel}"
td {
code {
a(href = inheritedMember) { +inheritedMember.attributeRef!!.name }
}
}
td {
attributes["width"] = "100%"
p {
nodeContent(inheritedMember.attributeRef!!, inheritedMember)
}
}
}
}
private fun TBODY.inheritedMemberRow(inheritedMember: DocumentationNode) {
tr(classes = "api apilevel-${inheritedMember.apiLevel.name}") {
attributes["data-version-added"] = "${inheritedMember.apiLevel}"
val type = inheritedMember.detailOrNull(NodeKind.Type)
td {
code {
type?.let {
renderedSignature(it, LanguageService.RenderMode.SUMMARY)
}
}
}
td {
attributes["width"] = "100%"
code {
a(href = inheritedMember) { +inheritedMember.name }
if (inheritedMember.kind == NodeKind.Function) {
shortFunctionParametersList(inheritedMember)
}
}
p {
nodeContent(inheritedMember)
}
}
}
}
private fun FlowContent.expandableSummaryNodeGroupForInheritedMembers(
tableId: String,
header: String,
tableClass: String,
superClasses: Set<Map.Entry<DocumentationNode, List<DocumentationNode>>>,
row: TBODY.(inheritedMember: DocumentationNode) -> Unit
) {
if (superClasses.none()) return
table(classes = tableClass) {
attributes["id"] = tableId
tbody {
developerHeading(header)
superClasses.forEach { (superClass, members) ->
tr(classes = "api apilevel-${superClass.apiLevel.name}") {
td {
attributes["colSpan"] = "2"
div(classes = "expandable jd-inherited-apis") {
span(classes = "expand-control exw-expanded") {
+"From class "
code {
a(href = superClass) { +superClass.name }
}
}
table(classes = "responsive exw-expanded-content") {
tbody {
members.forEach { inheritedMember ->
row(inheritedMember)
}
}
}
}
}
}
}
}
}
}
private fun FlowContent.summaryNodeGroupForExtensions(
header: String,
receivers: Set<Map.Entry<DocumentationNode, List<DocumentationNode>>>
) {
if (receivers.none()) return
h2 { +header }
div {
receivers.forEach {
table {
tr {
td {
attributes["colSpan"] = "2"
+"For "
a(href = it.key) { +it.key.name }
}
}
it.value.forEach { node ->
tr {
if (node.kind != NodeKind.Constructor) {
td {
modifiers(node)
renderedSignature(node.detail(NodeKind.Type), LanguageService.RenderMode.SUMMARY)
}
}
td {
div {
code {
val receiver = node.detailOrNull(NodeKind.Receiver)
if (receiver != null) {
renderedSignature(receiver.detail(NodeKind.Type), LanguageService.RenderMode.SUMMARY)
+"."
}
a(href = node) { +node.name }
shortFunctionParametersList(node)
}
}
nodeSummary(node)
}
}
}
}
}
}
}
override fun generatePackageIndex(page: Page.PackageIndex) = templateService.composePage(
page,
htmlConsumer,
headContent = {
},
bodyContent = {
h1 { +"Package Index" }
table {
tbody {
for (node in page.packages) {
tr {
td {
a(href = uriProvider.linkTo(node, uri)) { +node.name }
}
}
}
}
}
}
)
override fun generateClassIndex(page: Page.ClassIndex) = templateService.composePage(
page,
htmlConsumer,
headContent = {
},
bodyContent = {
h1 { +"Class Index" }
p {
+"These are all the API classes. See all "
a(href="packages.html") {
+"API packages."
}
}
div(classes = "jd-letterlist") {
page.classesByFirstLetter.forEach { (letter) ->
+"\n "
a(href = "#letter_$letter") { +letter }
unsafe {
raw(" ")
}
}
+"\n "
}
page.classesByFirstLetter.forEach { (letter, classes) ->
h2 {
id = "letter_$letter"
+letter
}
table {
tbody {
for (node in classes) {
tr {
td {
a(href = uriProvider.linkTo(node, uri)) { +node.classNodeNameWithOuterClass() }
}
td {
if (!deprecatedIndexSummary(node)) {
nodeSummary(node)
}
}
}
}
}
}
}
}
)
override fun FlowContent.classHierarchy(superclasses: List<DocumentationNode>) {
table(classes = "jd-inheritance-table") {
var level = superclasses.size
superclasses.forEach {
tr {
var spaceColumns = max(superclasses.size - 1 - level, 0)
while (spaceColumns > 0) {
td(classes = "jd-inheritance-space") {
+" "
}
spaceColumns--
}
if (it != superclasses.first()) {
td(classes = "jd-inheritance-space") {
+" ↳"
}
}
td(classes = "jd-inheritance-class-cell") {
attributes["colSpan"] = "$level"
qualifiedTypeReference(it)
}
}
level--
}
}
}
override fun FlowContent.subclasses(inheritors: List<DocumentationNode>, direct: Boolean) {
if (inheritors.isEmpty()) return
// The number of subclasses in collapsed view before truncating and adding a "and xx others".
// See https://developer.android.com/reference/android/view/View for an example.
val numToShow = 12
table(classes = "jd-sumtable jd-sumtable-subclasses") {
tbody {
tr {
td {
div(classes = "expandable") {
span(classes = "expand-control") {
if (direct)
+"Known Direct Subclasses"
else
+"Known Indirect Subclasses"
}
div(classes = "showalways") {
attributes["id"] = if (direct) "subclasses-direct" else "subclasses-indirect"
inheritors.take(numToShow).forEach { inheritor ->
a(href = inheritor) { +inheritor.classNodeNameWithOuterClass() }
if (inheritor != inheritors.last()) +", "
}
if (inheritors.size > numToShow) {
+"and ${inheritors.size - numToShow} others."
}
}
div(classes = "exw-expanded-content") {
attributes["id"] = if (direct) "subclasses-direct-summary" else "subclasses-indirect-summary"
table(classes = "jd-sumtable-expando") {
inheritors.forEach { inheritor ->
tr(classes = "api api-level-${inheritor.apiLevel.name}") {
attributes["data-version-added"] = inheritor.apiLevel.name
td(classes = "jd-linkcol") {
a(href = inheritor) { +inheritor.classNodeNameWithOuterClass() }
}
td(classes = "jd-descrcol") {
attributes["width"] = "100%"
nodeSummary(inheritor)
}
}
}
}
}
}
}
}
}
}
}
fun DocumentationNode.firstSentenceOfSummary(): ContentNode {
fun Sequence<ContentNode>.flatten(): Sequence<ContentNode> {
return flatMap {
when (it) {
is ContentParagraph -> it.children.asSequence().flatten()
else -> sequenceOf(it)
}
}
}
fun ContentNode.firstSentence(): ContentText? = when(this) {
is ContentText -> ContentText(text.firstSentence())
else -> null
}
val elements = sequenceOf(summary).flatten()
fun containsDot(it: ContentNode) = (it as? ContentText)?.text?.contains(".") == true
val paragraph = ContentParagraph()
(elements.takeWhile { !containsDot(it) } + elements.firstOrNull { containsDot(it) }?.firstSentence()).forEach {
if (it != null) {
paragraph.append(it)
}
}
if (paragraph.isEmpty()) {
return ContentEmpty
}
return paragraph
}
fun DocumentationNode.firstSentence(): String {
val sb = StringBuilder()
addContentNodeToStringBuilder(content, sb)
return sb.toString().firstSentence()
}
private fun addContentNodesToStringBuilder(content: List<ContentNode>, sb: StringBuilder): Unit =
content.forEach { addContentNodeToStringBuilder(it, sb) }
private fun addContentNodeToStringBuilder(content: ContentNode, sb: StringBuilder) {
when (content) {
is ContentText -> sb.appendWith(content.text)
is ContentSymbol -> sb.appendWith(content.text)
is ContentKeyword -> sb.appendWith(content.text)
is ContentIdentifier -> sb.appendWith(content.text)
is ContentEntity -> sb.appendWith(content.text)
is ContentHeading -> addContentNodesToStringBuilder(content.children, sb)
is ContentStrong -> addContentNodesToStringBuilder(content.children, sb)
is ContentStrikethrough -> addContentNodesToStringBuilder(content.children, sb)
is ContentEmphasis -> addContentNodesToStringBuilder(content.children, sb)
is ContentOrderedList -> addContentNodesToStringBuilder(content.children, sb)
is ContentUnorderedList -> addContentNodesToStringBuilder(content.children, sb)
is ContentListItem -> addContentNodesToStringBuilder(content.children, sb)
is ContentCode -> addContentNodesToStringBuilder(content.children, sb)
is ContentBlockSampleCode -> addContentNodesToStringBuilder(content.children, sb)
is ContentBlockCode -> addContentNodesToStringBuilder(content.children, sb)
is ContentParagraph -> addContentNodesToStringBuilder(content.children, sb)
is ContentNodeLink -> addContentNodesToStringBuilder(content.children, sb)
is ContentBookmark -> addContentNodesToStringBuilder(content.children, sb)
is ContentExternalLink -> addContentNodesToStringBuilder(content.children, sb)
is ContentLocalLink -> addContentNodesToStringBuilder(content.children, sb)
is ContentSection -> { }
is ContentBlock -> addContentNodesToStringBuilder(content.children, sb)
}
}
private fun StringBuilder.appendWith(text: String, delimiter: String = " ") {
if (this.length == 0) {
append(text)
} else {
append(delimiter)
append(text)
}
}
}
fun TBODY.developerHeading(
header: String,
summaryId: String? = null
) {
tr {
th {
attributes["colSpan"] = "2"
dheading {
attributes["ds-is"] = "heading"
attributes["text"] = header
attributes["id"] = summaryId ?: header.replace("\\s".toRegex(), "-").toLowerCase()
attributes["level"] = "h3"
attributes["toc"] = ""
attributes["class"] = ""
h3 {
attributes["is-upgraded"] = ""
+header
}
}
}
}
}
class DacFormatDescriptor : JavaLayoutHtmlFormatDescriptorBase(), DefaultAnalysisComponentServices by KotlinAsKotlin {
override val templateServiceClass: KClass<out JavaLayoutHtmlTemplateService> = DevsiteHtmlTemplateService::class
override val outlineFactoryClass = DacOutlineFormatter::class
override val languageServiceClass = KotlinLanguageService::class
override val packageListServiceClass: KClass<out PackageListService> = JavaLayoutHtmlPackageListService::class
override val outputBuilderFactoryClass: KClass<out JavaLayoutHtmlFormatOutputBuilderFactory> = DevsiteLayoutHtmlFormatOutputBuilderFactoryImpl::class
}
class DacAsJavaFormatDescriptor : JavaLayoutHtmlFormatDescriptorBase(), DefaultAnalysisComponentServices by KotlinAsJava {
override val templateServiceClass: KClass<out JavaLayoutHtmlTemplateService> = DevsiteHtmlTemplateService::class
override val outlineFactoryClass = DacOutlineFormatter::class
override val languageServiceClass = NewJavaLanguageService::class
override val packageListServiceClass: KClass<out PackageListService> = JavaLayoutHtmlPackageListService::class
override val outputBuilderFactoryClass: KClass<out JavaLayoutHtmlFormatOutputBuilderFactory> = DevsiteLayoutHtmlFormatOutputBuilderFactoryImpl::class
}
fun FlowOrPhrasingContent.dheading(block : DHEADING.() -> Unit = {}) : Unit = DHEADING(consumer).visit(block)
class DHEADING(consumer: TagConsumer<*>) :
HTMLTag("devsite-heading", consumer, emptyMap(), inlineTag = false, emptyTag = false), HtmlBlockTag
| apache-2.0 | 5162692b755ce55caed634b3699aeba2 | 38.394678 | 174 | 0.462768 | 5.855001 | false | false | false | false |
rarspace01/pirateboat | src/main/java/boat/info/QueueService.kt | 1 | 1747 | package boat.info
import org.springframework.stereotype.Service
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.util.*
import java.util.function.Consumer
@Service
class QueueService {
private val properties: Properties = initQueue()
private fun initQueue(): Properties {
val propertiesInit = Properties()
return try {
val queueListFile: InputStream = FileInputStream("queue.list")
propertiesInit.load(queueListFile)
propertiesInit
} catch (exception: FileNotFoundException) {
propertiesInit
}
}
fun addAll(listOfMediaItems: List<MediaItem>) {
listOfMediaItems.forEach(Consumer { t -> add(t) })
saveProperties()
}
fun add(mediaItem: MediaItem) {
properties.setProperty(mediaItem.title, mediaItem.year.toString())
}
fun addAndSave(mediaItem: MediaItem) {
properties.setProperty(mediaItem.title, mediaItem.year.toString())
saveProperties()
}
fun remove(mediaItem: MediaItem) {
properties.remove(mediaItem.title)
}
fun getQueue(): List<MediaItem> {
return properties
.entries
.map { mutableEntry ->
MediaItem(
title = mutableEntry.key.toString(),
year = mutableEntry.value.toString().toInt()
)
}
}
fun saveProperties() {
try {
val queueListFile: OutputStream = FileOutputStream("queue.list")
properties.store(queueListFile, null)
} catch (exception: Exception) {
}
}
} | apache-2.0 | 2224432d5b70fce3f33d45c637897e7a | 25.484848 | 76 | 0.626789 | 4.935028 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/benchmark/src/androidTest/java/androidx/compose/foundation/benchmark/lazy/LazyStaggeredGridScrollingBenchmark.kt | 3 | 9362 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.benchmark.lazy
import android.os.Build
import android.view.MotionEvent
import android.view.View
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.lazy.staggeredgrid.LazyHorizontalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.LazyStaggeredGridState
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.foundation.lazy.staggeredgrid.rememberLazyStaggeredGridState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.testutils.benchmark.ComposeBenchmarkRule
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.LocalViewConfiguration
import androidx.compose.ui.unit.dp
import androidx.test.filters.LargeTest
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assume
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@OptIn(ExperimentalFoundationApi::class)
@LargeTest
@RunWith(Parameterized::class)
class LazyStaggeredGridScrollingBenchmark(
private val testCase: LazyStaggeredGridScrollingTestCase
) {
@get:Rule
val benchmarkRule = ComposeBenchmarkRule()
@Test
fun scrollProgrammatically_noNewItems() {
benchmarkRule.toggleStateBenchmark {
StaggeredGridRemeasureTestCase(
addNewItemOnToggle = false,
content = testCase.content,
isVertical = testCase.isVertical
)
}
}
@Test
fun scrollProgrammatically_newItemComposed() {
benchmarkRule.toggleStateBenchmark {
StaggeredGridRemeasureTestCase(
addNewItemOnToggle = true,
content = testCase.content,
isVertical = testCase.isVertical
)
}
}
@Test
fun scrollViaPointerInput_noNewItems() {
benchmarkRule.toggleStateBenchmark {
StaggeredGridRemeasureTestCase(
addNewItemOnToggle = false,
content = testCase.content,
isVertical = testCase.isVertical,
usePointerInput = true
)
}
}
@Test
fun scrollViaPointerInput_newItemComposed() {
benchmarkRule.toggleStateBenchmark {
StaggeredGridRemeasureTestCase(
addNewItemOnToggle = true,
content = testCase.content,
isVertical = testCase.isVertical,
usePointerInput = true
)
}
}
@Test
fun drawAfterScroll_noNewItems() {
// this test makes sense only when run on the Android version which supports RenderNodes
// as this tests how efficiently we move RenderNodes.
Assume.assumeTrue(supportsRenderNode || supportsMRenderNode)
benchmarkRule.toggleStateBenchmarkDraw {
StaggeredGridRemeasureTestCase(
addNewItemOnToggle = false,
content = testCase.content,
isVertical = testCase.isVertical
)
}
}
@Test
fun drawAfterScroll_newItemComposed() {
// this test makes sense only when run on the Android version which supports RenderNodes
// as this tests how efficiently we move RenderNodes.
Assume.assumeTrue(supportsRenderNode || supportsMRenderNode)
benchmarkRule.toggleStateBenchmarkDraw {
StaggeredGridRemeasureTestCase(
addNewItemOnToggle = true,
content = testCase.content,
isVertical = testCase.isVertical
)
}
}
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun initParameters(): Array<LazyStaggeredGridScrollingTestCase> =
arrayOf(
Vertical,
Horizontal
)
// Copied from AndroidComposeTestCaseRunner
private val supportsRenderNode = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
private val supportsMRenderNode = Build.VERSION.SDK_INT < Build.VERSION_CODES.P &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
}
}
@OptIn(ExperimentalFoundationApi::class)
class LazyStaggeredGridScrollingTestCase(
private val name: String,
val isVertical: Boolean,
val content: @Composable StaggeredGridRemeasureTestCase.(LazyStaggeredGridState) -> Unit
) {
override fun toString(): String {
return name
}
}
@OptIn(ExperimentalFoundationApi::class)
private val Vertical = LazyStaggeredGridScrollingTestCase(
"Vertical",
isVertical = true
) { state ->
LazyVerticalStaggeredGrid(
columns = StaggeredGridCells.Fixed(2),
state = state,
modifier = Modifier.requiredHeight(400.dp).fillMaxWidth(),
flingBehavior = NoFlingBehavior
) {
items(2) {
FirstLargeItem()
}
items(items) {
RegularItem()
}
}
}
@OptIn(ExperimentalFoundationApi::class)
private val Horizontal = LazyStaggeredGridScrollingTestCase(
"Horizontal",
isVertical = false
) { state ->
LazyHorizontalStaggeredGrid(
rows = StaggeredGridCells.Fixed(2),
state = state,
modifier = Modifier.requiredHeight(400.dp).fillMaxWidth(),
flingBehavior = NoFlingBehavior
) {
items(2) {
FirstLargeItem()
}
items(items) {
RegularItem()
}
}
}
@OptIn(ExperimentalFoundationApi::class)
class StaggeredGridRemeasureTestCase(
val addNewItemOnToggle: Boolean,
val content: @Composable StaggeredGridRemeasureTestCase.(LazyStaggeredGridState) -> Unit,
val isVertical: Boolean,
val usePointerInput: Boolean = false
) : LazyBenchmarkTestCase {
val items = List(300) { LazyItem(it) }
private lateinit var state: LazyStaggeredGridState
private lateinit var view: View
private lateinit var motionEventHelper: MotionEventHelper
private var touchSlop: Float = 0f
private var scrollBy: Int = 0
@Composable
fun FirstLargeItem() {
Box(Modifier.requiredSize(30.dp))
}
@Composable
override fun Content() {
scrollBy = if (addNewItemOnToggle) {
with(LocalDensity.current) { 15.dp.roundToPx() }
} else {
5
}
view = LocalView.current
if (!::motionEventHelper.isInitialized) motionEventHelper = MotionEventHelper(view)
touchSlop = LocalViewConfiguration.current.touchSlop
state = rememberLazyStaggeredGridState()
content(state)
}
@Composable
fun RegularItem() {
Box(Modifier.requiredSize(20.dp).background(Color.Red, RoundedCornerShape(8.dp)))
}
override fun beforeToggle() {
runBlocking {
state.scrollToItem(0, 0)
}
if (usePointerInput) {
val size = if (isVertical) view.measuredHeight else view.measuredWidth
motionEventHelper.sendEvent(MotionEvent.ACTION_DOWN, (size / 2f).toSingleAxisOffset())
motionEventHelper.sendEvent(MotionEvent.ACTION_MOVE, touchSlop.toSingleAxisOffset())
}
assertEquals(0, state.firstVisibleItemIndex)
assertEquals(0, state.firstVisibleItemScrollOffset)
}
override fun toggle() {
if (usePointerInput) {
motionEventHelper
.sendEvent(MotionEvent.ACTION_MOVE, -scrollBy.toFloat().toSingleAxisOffset())
} else {
runBlocking {
state.scrollBy(scrollBy.toFloat())
}
}
}
override fun afterToggle() {
assertEquals(0, state.firstVisibleItemIndex)
assertEquals(scrollBy, state.firstVisibleItemScrollOffset)
if (usePointerInput) {
motionEventHelper.sendEvent(MotionEvent.ACTION_UP, Offset.Zero)
}
}
private fun Float.toSingleAxisOffset(): Offset =
Offset(x = if (isVertical) 0f else this, y = if (isVertical) this else 0f)
}
| apache-2.0 | 7c0034817a8adc9f44bd84aa75f7d549 | 32.676259 | 98 | 0.683615 | 4.963945 | false | true | false | false |
androidx/androidx | wear/compose/compose-material/src/commonMain/kotlin/androidx/wear/compose/material/RangeDefaults.kt | 3 | 3440 | /*
* 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.wear.compose.material
import androidx.compose.foundation.progressSemantics
import androidx.compose.material.icons.materialIcon
import androidx.compose.material.icons.materialPath
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.semantics.disabled
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.setProgress
import androidx.compose.ui.util.lerp
import kotlin.math.roundToInt
/**
* Icons which are used by Range controls like slider and stepper
*/
internal object RangeIcons {
/**
* An [ImageVector] with a minus sign.
*/
val Minus: ImageVector
get() = if (_minus != null) _minus!!
else {
_minus = materialIcon(name = "MinusIcon") {
materialPath {
moveTo(19.0f, 13.0f)
horizontalLineTo(5.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(14.0f)
verticalLineToRelative(2.0f)
close()
}
}
_minus!!
}
private var _minus: ImageVector? = null
}
/**
* Defaults used by range controls like slider and stepper
*/
internal object RangeDefaults {
/**
* Calculates value of [currentStep] in [valueRange] depending on number of [steps]
*/
fun calculateCurrentStepValue(
currentStep: Int,
steps: Int,
valueRange: ClosedFloatingPointRange<Float>
): Float = lerp(
valueRange.start, valueRange.endInclusive,
currentStep.toFloat() / (steps + 1).toFloat()
).coerceIn(valueRange)
/**
* Snaps [value] to the closest [step] in the [valueRange]
*/
fun snapValueToStep(
value: Float,
valueRange: ClosedFloatingPointRange<Float>,
steps: Int
): Int = ((value - valueRange.start) /
(valueRange.endInclusive - valueRange.start) * (steps + 1))
.roundToInt().coerceIn(0, steps + 1)
}
internal fun Modifier.rangeSemantics(
step: Int,
enabled: Boolean,
onValueChange: (Float) -> Unit,
valueRange: ClosedFloatingPointRange<Float>,
steps: Int
): Modifier = semantics(mergeDescendants = true) {
if (!enabled) disabled()
setProgress(
action = { targetValue ->
val newStepIndex = RangeDefaults.snapValueToStep(targetValue, valueRange, steps)
if (step == newStepIndex) {
false
} else {
onValueChange(targetValue)
true
}
}
)
}.progressSemantics(
RangeDefaults.calculateCurrentStepValue(step, steps, valueRange),
valueRange, steps
)
internal fun IntProgression.stepsNumber(): Int = (last - first) / step - 1
| apache-2.0 | 20ebc0d3b335b343a5b63cdf02018aa9 | 30.559633 | 92 | 0.647674 | 4.461738 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/StretchOverscrollTest.kt | 3 | 3476 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation
import android.os.Build
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalViewConfiguration
import androidx.compose.ui.platform.ViewConfiguration
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performTouchInput
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.test.filters.SdkSuppress
import androidx.testutils.AnimationDurationScaleRule
import com.google.common.truth.Truth.assertThat
import kotlin.math.abs
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
@RunWith(AndroidJUnit4::class)
class StretchOverscrollTest {
@get:Rule
val rule = createComposeRule()
@get:Rule
val animationScaleRule: AnimationDurationScaleRule =
AnimationDurationScaleRule.createForAllTests(1f)
@Test
fun stretchOverscroll_whenPulled_consumesOppositePreScroll() {
val color = listOf(Color.Red, Color.Yellow, Color.Blue, Color.Green)
val lazyState = LazyListState()
animationScaleRule.setAnimationDurationScale(1f)
var viewConfiguration: ViewConfiguration? = null
rule.setContent {
viewConfiguration = LocalViewConfiguration.current
LazyRow(
state = lazyState,
modifier = Modifier.size(300.dp).testTag(OverscrollBox)
) {
items(10) { index ->
Box(Modifier.size(50.dp, 300.dp).background(color[index % color.size]))
}
}
}
rule.onNodeWithTag(OverscrollBox).performTouchInput {
down(center)
moveBy(Offset(-(200f + (viewConfiguration?.touchSlop ?: 0f)), 0f))
// pull in the opposite direction. Since we pulled overscroll with positive delta
// it will consume negative delta before scroll happens
// assert in the ScrollableState lambda will check it
moveBy(Offset(200f, 0f))
up()
}
rule.runOnIdle {
// no scroll happened as it was consumed by the overscroll logic
assertThat(abs(lazyState.firstVisibleItemScrollOffset)).isLessThan(2) // round error
assertThat(lazyState.firstVisibleItemIndex).isEqualTo(0)
}
}
}
private const val OverscrollBox = "box" | apache-2.0 | d9cfbafe73b44d0cccb5f43c7c79bcf3 | 37.208791 | 96 | 0.722957 | 4.537859 | false | true | false | false |
oleksiyp/mockk | mockk/common/src/main/kotlin/io/mockk/impl/stub/MockKStub.kt | 1 | 9909 | package io.mockk.impl.stub
import io.mockk.*
import io.mockk.impl.InternalPlatform
import io.mockk.impl.InternalPlatform.customComputeIfAbsent
import io.mockk.impl.log.Logger
import kotlin.reflect.KClass
open class MockKStub(
override val type: KClass<*>,
override val name: String,
val relaxed: Boolean = false,
val relaxUnitFun: Boolean = false,
val gatewayAccess: StubGatewayAccess,
val recordPrivateCalls: Boolean,
val mockType: MockType
) : Stub {
val log = gatewayAccess.safeToString(Logger<MockKStub>())
private val answers = InternalPlatform.synchronizedMutableList<InvocationAnswer>()
private val childs = InternalPlatform.synchronizedMutableMap<InvocationMatcher, Any>()
private val recordedCalls = InternalPlatform.synchronizedMutableList<Invocation>()
private val recordedCallsByMethod =
InternalPlatform.synchronizedMutableMap<MethodDescription, MutableList<Invocation>>()
private val exclusions = InternalPlatform.synchronizedMutableList<InvocationMatcher>()
private val verifiedCalls = InternalPlatform.synchronizedMutableList<Invocation>()
lateinit var hashCodeStr: String
var disposeRoutine: () -> Unit = {}
override fun addAnswer(matcher: InvocationMatcher, answer: Answer<*>) {
val invocationAnswer = InvocationAnswer(matcher, answer)
answers.add(invocationAnswer)
}
override fun answer(invocation: Invocation): Any? {
val invocationAndMatcher = synchronized(answers) {
answers
.reversed()
.firstOrNull { it.matcher.match(invocation) }
} ?: return defaultAnswer(invocation)
return with(invocationAndMatcher) {
matcher.captureAnswer(invocation)
val call = Call(
invocation.method.returnType,
invocation,
matcher,
invocation.fieldValueProvider
)
answer.answer(call)
}
}
protected inline fun stdObjectFunctions(
self: Any,
method: MethodDescription,
args: List<Any?>,
otherwise: () -> Any?
): Any? {
if (method.isToString()) {
return toStr()
} else if (method.isHashCode()) {
return InternalPlatformDsl.identityHashCode(self)
} else if (method.isEquals()) {
return self === args[0]
} else {
return otherwise()
}
}
override fun stdObjectAnswer(invocation: Invocation): Any? {
return stdObjectFunctions(invocation.self, invocation.method, invocation.args) {
throw MockKException("No other calls allowed in stdObjectAnswer than equals/hashCode/toString")
}
}
protected open fun defaultAnswer(invocation: Invocation): Any? {
return stdObjectFunctions(invocation.self, invocation.method, invocation.args) {
if (shouldRelax(invocation)) {
if (invocation.method.returnsUnit) return Unit
return gatewayAccess.anyValueGenerator.anyValue(invocation.method.returnType) {
childMockK(invocation.allEqMatcher(), invocation.method.returnType)
}
} else {
throw MockKException("no answer found for: ${gatewayAccess.safeToString.exec { invocation.toString() }}")
}
}
}
private fun shouldRelax(invocation: Invocation) = when {
relaxed -> true
relaxUnitFun &&
invocation.method.returnsUnit -> true
else -> false
}
override fun recordCall(invocation: Invocation) {
val record = when {
checkExcluded(invocation) -> {
log.debug { "Call excluded: $invocation" }
false
}
recordPrivateCalls -> true
else -> !invocation.method.privateCall
}
if (record) {
recordedCalls.add(invocation)
synchronized(recordedCallsByMethod) {
recordedCallsByMethod.getOrPut(invocation.method) { mutableListOf() }
.add(invocation)
}
gatewayAccess.stubRepository.notifyCallRecorded(this)
}
}
private fun checkExcluded(invocation: Invocation) = synchronized(exclusions) {
exclusions.any { it.match(invocation) }
}
override fun allRecordedCalls(): List<Invocation> {
synchronized(recordedCalls) {
return recordedCalls.toList()
}
}
override fun allRecordedCalls(method: MethodDescription): List<Invocation> {
synchronized(recordedCallsByMethod) {
return recordedCallsByMethod[method]?.toList() ?: listOf()
}
}
override fun excludeRecordedCalls(
params: MockKGateway.ExclusionParameters,
matcher: InvocationMatcher
) {
exclusions.add(matcher)
if (params.current) {
synchronized(recordedCalls) {
val callsToExclude = recordedCalls
.filter(matcher::match)
if (callsToExclude.isNotEmpty()) {
log.debug {
"Calls excluded: " + callsToExclude.joinToString(", ")
}
}
callsToExclude
.forEach { recordedCalls.remove(it) }
synchronized(recordedCallsByMethod) {
recordedCallsByMethod[matcher.method]?.apply {
filter(matcher::match)
.forEach { remove(it) }
}
}
synchronized(verifiedCalls) {
verifiedCalls
.filter(matcher::match)
.forEach { verifiedCalls.remove(it) }
}
}
}
}
override fun markCallVerified(invocation: Invocation) {
verifiedCalls.add(invocation)
}
override fun verifiedCalls(): List<Invocation> {
synchronized(verifiedCalls) {
return verifiedCalls.toList()
}
}
override fun toStr() = "${type.simpleName}($name)"
override fun childMockK(matcher: InvocationMatcher, childType: KClass<*>): Any {
return synchronized(childs) {
gatewayAccess.safeToString.exec {
childs.customComputeIfAbsent(matcher) {
gatewayAccess.mockFactory!!.mockk(
childType,
childName(this.name),
moreInterfaces = arrayOf(),
relaxed = relaxed,
relaxUnitFun = relaxUnitFun
)
}
}
}
}
private fun childName(name: String): String {
val result = childOfRegex.matchEntire(name)
return if (result != null) {
val group = result.groupValues[2]
val childN = if (group.isEmpty()) 1 else group.toInt()
"child^" + (childN + 1) + " of " + result.groupValues[3]
} else {
"child of " + name
}
}
override fun handleInvocation(
self: Any,
method: MethodDescription,
originalCall: () -> Any?,
args: Array<out Any?>,
fieldValueProvider: BackingFieldValueProvider
): Any? {
val originalPlusToString = {
if (method.isToString()) {
toStr()
} else {
originalCall()
}
}
fun List<StackElement>.cutMockKCallProxyCall(): List<StackElement> {
fun search(cls: String, mtd: String): Int? {
return indexOfFirst {
it.className == cls && it.methodName == mtd
}.let { if (it == -1) null else it }
}
val idx = search("io.mockk.proxy.MockKCallProxy", "call")
?: search("io.mockk.proxy.MockKProxyInterceptor", "intercept")
?: search("io.mockk.proxy.MockKProxyInterceptor", "interceptNoSuper")
?: return this
return this.drop(idx + 1)
}
val stackTraceHolder = InternalPlatform.captureStackTrace()
val invocation = Invocation(
self,
this,
method,
args.toList(),
InternalPlatform.time(),
{
stackTraceHolder()
.cutMockKCallProxyCall()
},
originalPlusToString,
fieldValueProvider
)
return gatewayAccess.callRecorder().call(invocation)
}
override fun clear(options: MockKGateway.ClearOptions) {
if (options.answers) {
this.answers.clear()
}
if (options.recordedCalls) {
this.recordedCalls.clear()
this.recordedCallsByMethod.clear()
}
if (options.childMocks) {
this.childs.clear()
}
if (options.verificationMarks) {
this.verifiedCalls.clear()
}
if (options.exclusionRules) {
this.exclusions.clear()
}
}
companion object {
val childOfRegex = Regex("child(\\^(\\d+))? of (.+)")
}
private data class InvocationAnswer(val matcher: InvocationMatcher, val answer: Answer<*>)
protected fun Invocation.allEqMatcher() =
InvocationMatcher(
self,
method,
args.map {
if (it == null)
NullCheckMatcher<Any>()
else
EqMatcher(it)
}, false
)
override fun dispose() {
clear(
MockKGateway.ClearOptions(
true,
true,
true,
true,
true
)
)
disposeRoutine.invoke()
}
}
| apache-2.0 | b60d8ec3c036f5c2403de4ad150a8bce | 30.457143 | 121 | 0.557473 | 5.220759 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/system/jemalloc/macros.kt | 1 | 3293 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.system.jemalloc
import org.lwjgl.generator.*
val jemalloc_macros = Generator.register(object : GeneratorTarget(JEMALLOC_PACKAGE, "JEmacros") {
init {
documentation = "Macros for jemalloc."
}
override fun java.io.PrintWriter.generateJava() {
generateJavaPreamble()
print("""public final class JEmacros {
private JEmacros() {}
/** The major version. */
public static final int JEMALLOC_VERSION_MAJOR = 4;
/** The minor version. */
public static final int JEMALLOC_VERSION_MINOR = 2;
/** The bugfix version. */
public static final int JEMALLOC_VERSION_BUGFIX = 1;
/** Tthe revision number. */
public static final int JEMALLOC_VERSION_NREV = 0;
/** The globally unique identifier (git commit hash). */
public static final String JEMALLOC_VERSION_GID = "3de035335255d553bdb344c32ffdb603816195d8";
/** Returns the version string. */
public static final String JEMALLOC_VERSION =
JEMALLOC_VERSION_MAJOR + "." + JEMALLOC_VERSION_MINOR + "." + JEMALLOC_VERSION_BUGFIX + "-" + JEMALLOC_VERSION_NREV + "-g" + JEMALLOC_VERSION_GID;
/**
* Align the memory allocation to start at an address that is a multiple of {@code (1 << la)}. This macro does not validate that {@code la} is within the
* valid range.
*
* @param la the alignment shift
*/
public static int MALLOCX_LG_ALIGN(int la) {
return la;
}
/**
* Align the memory allocation to start at an address that is a multiple of {@code a}, where {@code a} is a power of two. This macro does not validate
* that {@code a} is a power of 2.
*
* @param a the alignment
*/
public static int MALLOCX_ALIGN(int a) {
return Integer.numberOfTrailingZeros(a);
}
/**
* Initialize newly allocated memory to contain zero bytes. In the growing reallocation case, the real size prior to reallocation defines the boundary
* between untouched bytes and those that are initialized to contain zero bytes. If this macro is absent, newly allocated memory is uninitialized.
*/
public static final int MALLOCX_ZERO = 0x40;
/**
* Use the thread-specific cache (tcache) specified by the identifier {@code tc}, which must have been acquired via the {@code tcache.create} mallctl.
* This macro does not validate that {@code tc} specifies a valid identifier.
*
* @param tc the thread-specific cache
*/
public static int MALLOCX_TCACHE(int tc) {
return (tc + 2) << 8;
}
/**
* Do not use a thread-specific cache (tcache). Unless {@link #MALLOCX_TCACHE} or {@code MALLOCX_TCACHE_NONE} is specified, an automatically managed
* tcache
* will be used under many circumstances. This macro cannot be used in the same {@code flags} argument as {@code MALLOCX_TCACHE(tc)}.
*/
public static final int MALLOCX_TCACHE_NONE = MALLOCX_TCACHE(-1);
/**
* Use the arena specified by the index {@code a} (and by necessity bypass the thread cache). This macro has no effect for huge regions, nor for regions
* that were allocated via an arena other than the one specified. This macro does not validate that {@code a} specifies an arena index in the valid range.
*
* @param a the arena index
*/
public static int MALLOCX_ARENA(int a) {
return (a + 1) << 20;
}
}""")
}
}) | bsd-3-clause | 1ac995904b2567e7868281ea1fcff73f | 34.042553 | 155 | 0.70908 | 3.521925 | false | false | false | false |
patorash/KotlinFX | src/PatternTextField.kt | 1 | 1183 | package com.okolabo.kotlinfx
import javafx.beans.property.ObjectProperty
import java.util.regex.Pattern
import kotlin.properties.Delegates
import javafx.beans.property.SimpleObjectProperty
public open class PatternTextField : javafx.scene.control.TextField() {
class object {
val NUMBER_ONLY by Delegates.lazy { Pattern.compile("[0-9]") }
val ALPHABET_ONLY by Delegates.lazy { Pattern.compile("[a-z]", Pattern.CASE_INSENSITIVE) }
}
private val verifier : ObjectProperty<Pattern> = SimpleObjectProperty(this, "Verifier")
public fun setVerifier(pattern: Pattern): Unit = verifier.set(pattern)
public fun getVerifier(): Pattern = verifier.get()!!
public override fun replaceText(start: Int, end: Int, text: String?) {
if (text != null) {
if (text.equals("") || getVerifier().matcher(text).find()) {
super.replaceText(start, end, text);
}
}
}
public override fun replaceSelection(text: String?) {
if (text != null) {
if (text.equals("") || getVerifier().matcher(text!!).find()) {
super.replaceSelection(text)
}
}
}
} | mit | 0e4c8e793bf997a2e890b1616c893773 | 32.828571 | 98 | 0.639053 | 4.333333 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/external/GhcModi.kt | 1 | 5540 | package org.jetbrains.haskell.external
import com.intellij.openapi.project.Project
import com.intellij.openapi.components.ProjectComponent
import org.jetbrains.haskell.config.HaskellSettings
import java.io.InputStream
import java.io.OutputStream
import java.io.Writer
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import com.intellij.openapi.module.ModuleManager
import java.io.File
import java.util.regex.Pattern
import java.util.ArrayList
import com.intellij.notification.Notifications
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.ProgressIndicator
import org.jetbrains.haskell.util.ProcessRunner
import com.intellij.notification.NotificationListener
import javax.swing.event.HyperlinkEvent
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.roots.ProjectRootManager
import org.jetbrains.haskell.sdk.HaskellSdkType
import org.jetbrains.haskell.external.tool.GhcModConsole
import org.jetbrains.haskell.util.OSUtil
/**
* Created by atsky on 15/06/14.
*/
public class GhcModi(val project: Project, val settings: HaskellSettings) : ProjectComponent {
var process: Process? = null;
override fun projectOpened() {}
override fun projectClosed() {
val process = process
if (process != null) {
ProgressManager.getInstance().runProcessWithProgressSynchronously({
synchronized(process) {
val output = OutputStreamWriter(process.getOutputStream()!!)
output.write("\n")
output.flush()
process.waitFor()
}
}, "stopping ghc-modi", false, project)
this.process = null
}
}
fun startProcess() {
assert(process == null)
val sdk = ProjectRootManager.getInstance(project).getProjectSdk()
val ghcHome = if (sdk != null && sdk.getSdkType() is HaskellSdkType) {
sdk.getHomePath() + File.separator + "bin"
} else {
null
}
process = ProcessRunner(project.getBaseDir()!!.getPath()).getProcess(listOf(getPath()), ghcHome)
GhcModConsole.getInstance(project).append("start ${getPath()}\n", GhcModConsole.MessageType.INFO)
}
fun getPath(): String {
return settings.getState().ghcModiPath!!
}
override fun initComponent() {
}
override fun disposeComponent() {
}
override fun getComponentName(): String = "ghc-modi"
fun isStopped(): Boolean {
try {
process!!.exitValue()
return true
} catch(e: IllegalThreadStateException) {
return false
}
}
fun runCommand(command: String): List<String> {
if (process == null) {
startProcess()
}
GhcModConsole.getInstance(project).append(command + "\n", GhcModConsole.MessageType.INPUT)
val result = synchronized(process!!) {
if (isStopped()) {
process = null
startProcess();
}
val process = process
if (process == null) {
listOf<String>()
} else {
val input = InputStreamReader(process.getInputStream()!!)
val output = OutputStreamWriter(process.getOutputStream()!!)
output.write(command + "\n")
output.flush()
val lines = ArrayList<String>()
while (lines.size() < 2 ||
(!lines[lines.size() - 2].startsWith("OK") &&
!lines[lines.size() - 2].startsWith("NG"))) {
val char = CharArray(16 * 1024)
val size = input.read(char)
val result = java.lang.String(char, 0, size)
val split = result.split(OSUtil.newLine, -1)
if (lines.isEmpty()) {
lines.add(split[0])
} else {
val last = lines.size() - 1
lines[last] = lines[last] + split[0]
}
lines.addAll(split.toList().subList(1, split.size()))
}
if (lines[lines.size() - 2].startsWith("NG")) {
val hyperlinkHandler = object : NotificationListener.Adapter() {
override fun hyperlinkActivated(notification: Notification, e: HyperlinkEvent) {
notification.expire()
if (!project.isDisposed()) {
ShowSettingsUtil.getInstance()?.showSettingsDialog(project, "Haskell")
}
}
}
Notifications.Bus.notify(Notification(
"ghc.modi",
"ghc-modi failed",
"ghc-modi failed with error: " + lines[lines.size() - 2] +
"<br/>You can disable ghc-modi in <a href=\"#\">Settings | Haskell</a>",
NotificationType.ERROR, hyperlinkHandler))
}
lines
}
}
for (line in result) {
GhcModConsole.getInstance(project).append(line + "\n", GhcModConsole.MessageType.OUTPUT)
}
return result
}
} | apache-2.0 | c58f48bda5cb2fa96b177bbfba67e5b5 | 35.453947 | 105 | 0.572383 | 4.97307 | false | false | false | false |
felipebz/sonar-plsql | zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/CollapsibleIfStatementsCheck.kt | 1 | 2261 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import org.sonar.plsqlopen.asTree
import org.sonar.plsqlopen.sslr.IfStatement
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.annotations.*
@Rule(priority = Priority.MAJOR, tags = [Tags.CLUMSY])
@ConstantRemediation("5min")
@RuleInfo(scope = RuleInfo.Scope.ALL)
@ActivatedByDefault
class CollapsibleIfStatementsCheck : AbstractBaseCheck() {
override fun init() {
subscribeTo(PlSqlGrammar.IF_STATEMENT)
}
override fun visitNode(node: AstNode) {
val ifStatement = node.asTree<IfStatement>()
val singleIfChild = singleIfChild(ifStatement)
if (singleIfChild != null && !hasElseOrElsif(ifStatement) && !hasElseOrElsif(singleIfChild)) {
addIssue(singleIfChild, getLocalizedMessage())
}
}
private fun hasElseOrElsif(ifStatement: IfStatement): Boolean {
return ifStatement.elsifClauses.isNotEmpty() || ifStatement.elseClause != null
}
private fun singleIfChild(ifStatement: IfStatement): IfStatement? {
val statements = ifStatement.statements
if (statements.size == 1) {
val nestedIf = statements[0].getChildren(PlSqlGrammar.IF_STATEMENT)
if (nestedIf.size == 1) {
return nestedIf[0].asTree()
}
}
return null
}
}
| lgpl-3.0 | e3169b59bf2b7cb42291a15c28012a5f | 36.065574 | 102 | 0.710747 | 4.266038 | false | false | false | false |
campos20/tnoodle | webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/wcif/WCIFDataBuilder.kt | 1 | 6567 | package org.worldcubeassociation.tnoodle.server.webscrambles.wcif
import org.worldcubeassociation.tnoodle.server.model.EventData
import org.worldcubeassociation.tnoodle.server.webscrambles.Translate
import org.worldcubeassociation.tnoodle.server.webscrambles.pdf.*
import org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util.OutlineConfiguration
import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.model.*
import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.model.extension.*
import org.worldcubeassociation.tnoodle.server.webscrambles.zip.CompetitionZippingData
import org.worldcubeassociation.tnoodle.server.webscrambles.zip.ScrambleZip
import org.worldcubeassociation.tnoodle.server.webscrambles.zip.model.ZipArchive
import org.worldcubeassociation.tnoodle.server.webscrambles.zip.model.ZipArchive.Companion.withUniqueTitles
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.*
object WCIFDataBuilder {
private val PDF_CACHE = mutableMapOf<ScrambleDrawingData, PdfContent>()
const val WATERMARK_STAGING = "STAGING"
const val WATERMARK_OUTDATED = "OUTDATED"
const val WATERMARK_UNOFFICIAL = "UNOFFICIAL"
fun Competition.toScrambleSetData(): CompetitionDrawingData {
val frontendStatus = findExtension<TNoodleStatusExtension>()
val frontendWatermark = frontendStatus?.pickWatermarkPhrase()
val sheets = events.flatMap { e ->
e.rounds.flatMap { r ->
val copyCountExtension = r.findExtension<SheetCopyCountExtension>()
r.scrambleSets.withIndex()
.flatMap { splitAttemptBasedEvents(e, r, it.index, it.value) }
.map {
val extendedScrSet = it.scrambleSet.copy(extensions = it.scrambleSet.withExtension(copyCountExtension))
it.copy(scrambleSet = extendedScrSet, watermark = frontendWatermark)
}
}
}
return CompetitionDrawingData(shortName, sheets)
}
private fun splitAttemptBasedEvents(event: Event, round: Round, group: Int, set: ScrambleSet): List<ScrambleDrawingData> {
val baseCode = round.idCode.copyParts(groupNumber = group)
// 333mbf is handled pretty specially: each "scramble" is actually a newline separated
// list of 333ni scrambles.
// If we detect that we're dealing with 333mbf, then we will generate 1 sheet per attempt,
// rather than 1 sheet per round (as we do with every other event).
if (event.eventModel in EventData.ATTEMPT_BASED_EVENTS) {
return set.scrambles.mapIndexed { nthAttempt, scrambleStr ->
val scrambles = scrambleStr.allScrambleStrings.map { Scramble(it) }
val attemptScrambles = set.copy(
scrambles = scrambles,
extraScrambles = listOf()
)
val pseudoCode = baseCode.copyParts(attemptNumber = nthAttempt)
defaultScrambleDrawingData(event, round, attemptScrambles, pseudoCode)
}
}
return listOf(defaultScrambleDrawingData(event, round, set, baseCode))
}
private fun defaultScrambleDrawingData(event: Event, round: Round, set: ScrambleSet, ac: ActivityCode): ScrambleDrawingData {
val defaultExtensions = computeDefaultExtensions(event, round, set.scrambles)
val extendedSet = set.copy(extensions = set.withExtensions(defaultExtensions))
return ScrambleDrawingData(extendedSet, ac, hasGroupID = round.scrambleSetCount > 1)
}
private fun computeDefaultExtensions(event: Event, round: Round, scrambles: List<Scramble>): List<ExtensionBuilder> {
return when (event.eventModel) {
EventData.THREE_FM -> {
val formatExtension = FmcAttemptCountExtension(round.expectedAttemptNum)
val languageExtension = round.findExtension<FmcLanguagesExtension>()
listOfNotNull(formatExtension, languageExtension)
}
EventData.THREE_MULTI_BLD -> listOf(FmcExtension(false), MultiScrambleCountExtension(scrambles.size))
else -> listOf()
}
}
fun TNoodleStatusExtension.pickWatermarkPhrase(): String? {
return if (!isOfficialBuild) {
WATERMARK_UNOFFICIAL
} else if (!isRecentVersion) {
WATERMARK_OUTDATED
} else if (isStaging) {
WATERMARK_STAGING
} else null
}
fun wcifToZip(wcif: Competition, pdfPassword: String?, generationDate: LocalDateTime, versionTag: String, generationUrl: String): ZipArchive {
val drawingData = wcif.toScrambleSetData()
val namedSheets = drawingData.scrambleSheets
.withUniqueTitles { it.compileTitleString(Translate.DEFAULT_LOCALE) }
val zippingData = CompetitionZippingData(wcif, namedSheets)
return requestsToZip(zippingData, pdfPassword, generationDate, versionTag, generationUrl)
}
fun requestsToZip(zipRequest: CompetitionZippingData, pdfPassword: String?, generationDate: LocalDateTime, versionTag: String, generationUrl: String): ZipArchive {
val scrambleZip = ScrambleZip(zipRequest.namedSheets, zipRequest.wcif)
return scrambleZip.assemble(generationDate, versionTag, pdfPassword, generationUrl)
}
fun wcifToCompletePdf(wcif: Competition, generationDate: LocalDate, versionTag: String, locale: Locale): PdfContent {
val drawingData = wcif.toScrambleSetData()
return requestsToCompletePdf(drawingData, generationDate, versionTag, locale)
}
fun requestsToCompletePdf(sheetRequest: CompetitionDrawingData, generationDate: LocalDate, versionTag: String, locale: Locale): PdfContent {
val scrambleRequests = sheetRequest.scrambleSheets
val originalPdfs = scrambleRequests.map {
it.getCachedPdf(generationDate, versionTag, sheetRequest.competitionTitle, Translate.DEFAULT_LOCALE)
}
val configurations = scrambleRequests.map {
OutlineConfiguration(it.compileTitleString(locale, false), it.activityCode.eventModel?.description.orEmpty(), it.numCopies)
}
return MergedPdfWithOutline(originalPdfs, configurations)
}
// register in cache to speed up overall generation process
fun ScrambleDrawingData.getCachedPdf(creationDate: LocalDate, versionTag: String, sheetTitle: String, locale: Locale) =
PDF_CACHE.getOrPut(this) { createPdf(creationDate, versionTag, sheetTitle, locale) }
}
| gpl-3.0 | 0790f083a18cb1e0dc348abac6a2fadc | 47.644444 | 167 | 0.711893 | 4.721064 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/history/components/HistoryDialog.kt | 1 | 3486 | package eu.kanade.presentation.history.components
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import eu.kanade.tachiyomi.R
@Composable
fun HistoryDeleteDialog(
onDismissRequest: () -> Unit,
onDelete: (Boolean) -> Unit,
) {
var removeEverything by remember { mutableStateOf(false) }
AlertDialog(
title = {
Text(text = stringResource(R.string.action_remove))
},
text = {
Column {
Text(text = stringResource(R.string.dialog_with_checkbox_remove_description))
Row(
modifier = Modifier
.padding(top = 16.dp)
.toggleable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
value = removeEverything,
onValueChange = { removeEverything = it },
),
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(
checked = removeEverything,
onCheckedChange = null,
)
Text(
modifier = Modifier.padding(start = 4.dp),
text = stringResource(R.string.dialog_with_checkbox_reset),
)
}
}
},
onDismissRequest = onDismissRequest,
confirmButton = {
TextButton(onClick = {
onDelete(removeEverything)
onDismissRequest()
},) {
Text(text = stringResource(R.string.action_remove))
}
},
dismissButton = {
TextButton(onClick = onDismissRequest) {
Text(text = stringResource(android.R.string.cancel))
}
},
)
}
@Composable
fun HistoryDeleteAllDialog(
onDismissRequest: () -> Unit,
onDelete: () -> Unit,
) {
AlertDialog(
title = {
Text(text = stringResource(R.string.action_remove_everything))
},
text = {
Text(text = stringResource(R.string.clear_history_confirmation))
},
onDismissRequest = onDismissRequest,
confirmButton = {
TextButton(onClick = {
onDelete()
onDismissRequest()
},) {
Text(text = stringResource(android.R.string.ok))
}
},
dismissButton = {
TextButton(onClick = onDismissRequest) {
Text(text = stringResource(android.R.string.cancel))
}
},
)
}
| apache-2.0 | fb98f6c85c4d9f32fb1eb91f4b060aeb | 32.84466 | 93 | 0.57401 | 5.37963 | false | false | false | false |
apollostack/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/responsefields/ResponseFieldsBuilder.kt | 1 | 8444 | package com.apollographql.apollo3.compiler.codegen.responsefields
import com.apollographql.apollo3.api.ResponseField
import com.apollographql.apollo3.api.Variable
import com.apollographql.apollo3.compiler.codegen.Identifier
import com.apollographql.apollo3.compiler.codegen.CgLayout.Companion.modelName
import com.apollographql.apollo3.api.BooleanExpression
import com.apollographql.apollo3.compiler.unified.ir.IrArgument
import com.apollographql.apollo3.compiler.unified.ir.IrBooleanValue
import com.apollographql.apollo3.compiler.unified.ir.IrEnumValue
import com.apollographql.apollo3.compiler.unified.ir.IrField
import com.apollographql.apollo3.compiler.unified.ir.IrFieldSet
import com.apollographql.apollo3.compiler.unified.ir.IrFloatValue
import com.apollographql.apollo3.compiler.unified.ir.IrIntValue
import com.apollographql.apollo3.compiler.unified.ir.IrListType
import com.apollographql.apollo3.compiler.unified.ir.IrListValue
import com.apollographql.apollo3.compiler.unified.ir.IrModelType
import com.apollographql.apollo3.compiler.unified.ir.IrNonNullType
import com.apollographql.apollo3.compiler.unified.ir.IrNullValue
import com.apollographql.apollo3.compiler.unified.ir.IrObjectValue
import com.apollographql.apollo3.compiler.unified.ir.IrStringValue
import com.apollographql.apollo3.compiler.unified.ir.IrType
import com.apollographql.apollo3.compiler.unified.ir.IrValue
import com.apollographql.apollo3.compiler.unified.ir.IrVariableValue
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.MemberName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.asTypeName
import com.squareup.kotlinpoet.joinToCode
class ResponseFieldsBuilder(
private val rootField: IrField,
private val rootName: String,
) {
fun build(): TypeSpec {
return fieldSetTypeSpec(rootName, listOf(rootField))
}
private fun objectName(field: IrField, fieldSet: IrFieldSet): String {
return modelName(field.info, fieldSet.typeSet, false)
}
private fun IrField.possibleFieldSets() = fieldSets.filter {
it.typeSet.size == 1 // the fallback field set (can contain possible types too)
|| it.possibleTypes.isNotEmpty()
}
private fun fieldSetsCodeBlock(field: IrField): CodeBlock {
return CodeBlock.builder().apply {
addStatement("listOf(")
indent()
field.possibleFieldSets().flatMap { fieldSet ->
if (fieldSet.typeSet.size == 1) {
listOf(null to fieldSet)
} else {
fieldSet.possibleTypes.map {
it to fieldSet
}
}
}.forEach { pair ->
addStatement(
"%T(%L, %L),",
ResponseField.FieldSet::class,
pair.first?.let { "\"$it\"" },
// This doesn't use %M on purpose as fields will name clash
"${objectName(field, pair.second)}.fields"
)
}
unindent()
add(")")
}.build()
}
private fun fieldSetTypeSpec(name: String, fields: List<IrField>): TypeSpec {
return TypeSpec.objectBuilder(name)
.addProperty(responseFieldsPropertySpec(fields))
.addTypes(fields.flatMap { field ->
field.possibleFieldSets().map {
fieldSetTypeSpec(
objectName(field, it),
it.fields
)
}
})
.build()
}
private fun responseFieldsPropertySpec(fields: List<IrField>): PropertySpec {
return PropertySpec.builder(Identifier.fields, Array::class.parameterizedBy(ResponseField::class))
.initializer(responseFieldsCodeBlock(fields))
.build()
}
private fun responseFieldsCodeBlock(fields: List<IrField>): CodeBlock {
val builder = CodeBlock.builder()
builder.addStatement("arrayOf(")
builder.indent()
fields.forEach {
builder.add("%L,\n", it.responseFieldsCodeBlock())
}
builder.unindent()
builder.addStatement(")")
return builder.build()
}
private fun IrType.codeBlock(): CodeBlock {
return when (this) {
is IrNonNullType -> {
val notNullFun = MemberName("com.apollographql.apollo3.api", "notNull")
CodeBlock.of("%L.%M()", ofType.codeBlock(), notNullFun)
}
is IrListType -> {
val listFun = MemberName("com.apollographql.apollo3.api", "list")
CodeBlock.of("%L.%M()", ofType.codeBlock(), listFun)
}
is IrModelType -> CodeBlock.of("%T(%S)", ResponseField.Type.Named.Object::class, "unused")
else -> CodeBlock.of("%T(%S)", ResponseField.Type.Named.Other::class, "unused")
}
}
private fun IrListValue.codeBlock(): CodeBlock {
if (values.isEmpty()) {
// TODO: Is Nothing correct here?
return CodeBlock.of("emptyList<Nothing>()")
}
return CodeBlock.builder().apply {
add("listOf(\n")
indent()
values.forEach {
add("%L,\n", it.codeBlock())
}
unindent()
add(")")
}.build()
}
private fun IrObjectValue.codeBlock(): CodeBlock {
if (fields.isEmpty()) {
// TODO: Is Nothing correct here?
return CodeBlock.of("emptyMap<Nothing, Nothing>()")
}
return CodeBlock.builder().apply {
add("mapOf(\n")
indent()
fields.forEach {
add("%S to %L,\n", it.name, it.value.codeBlock())
}
unindent()
add(")")
}.build()
}
private fun IrValue.codeBlock(): CodeBlock {
return when (this) {
is IrObjectValue -> codeBlock()
is IrListValue -> codeBlock()
is IrEnumValue -> CodeBlock.of("%S", value) // FIXME
is IrIntValue -> CodeBlock.of("%L", value)
is IrFloatValue -> CodeBlock.of("%L", value)
is IrBooleanValue -> CodeBlock.of("%L", value)
is IrStringValue -> CodeBlock.of("%S", value)
is IrVariableValue -> CodeBlock.of("%T(%S)", Variable::class, name)
is IrNullValue -> CodeBlock.of("null")
}
}
private fun List<IrArgument>.codeBlock(): CodeBlock {
if (isEmpty()) {
return CodeBlock.of("emptyMap()")
}
val builder = CodeBlock.builder()
builder.add("mapOf(")
builder.indent()
builder.add(
map {
CodeBlock.of("%S to %L", it.name, it.value.codeBlock())
}.joinToCode(separator = ",\n", suffix = "\n")
)
builder.unindent()
builder.add(")")
return builder.build()
}
private fun IrField.responseFieldsCodeBlock(): CodeBlock {
if (info.name == "__typename" && info.alias == null) {
return CodeBlock.of("%T.Typename", ResponseField::class.asTypeName())
}
val builder = CodeBlock.builder().add("%T(\n", ResponseField::class)
builder.indent()
builder.add("type = %L,\n", info.type.codeBlock())
builder.add("fieldName = %S,\n", info.name)
if (info.responseName != info.name) {
builder.add("responseName = %S,\n", info.responseName)
}
if (info.arguments.isNotEmpty()) {
builder.add("arguments = %L,\n", info.arguments.codeBlock())
}
if (condition != BooleanExpression.True) {
builder.add("condition = %L,\n", condition.codeBlock())
}
if (possibleFieldSets().isNotEmpty()) {
builder.add("fieldSets = %L,\n", fieldSetsCodeBlock(this))
}
builder.unindent()
builder.add(")")
return builder.build()
}
}
private fun BooleanExpression.codeBlock(): CodeBlock {
return when(this) {
is BooleanExpression.False -> CodeBlock.of("%T", BooleanExpression.False::class.asTypeName())
is BooleanExpression.True -> CodeBlock.of("%T", BooleanExpression.True::class.asTypeName())
is BooleanExpression.And -> {
val parameters = booleanExpressions.map {
it.codeBlock()
}.joinToCode(",")
CodeBlock.of("%T(setOf(%L))", BooleanExpression.And::class.asTypeName(), parameters)
}
is BooleanExpression.Or -> {
val parameters = booleanExpressions.map {
it.codeBlock()
}.joinToCode(",")
CodeBlock.of("%T(setOf(%L))", BooleanExpression.Or::class.asTypeName(), parameters)
}
is BooleanExpression.Not -> CodeBlock.of("%T(%L)", BooleanExpression.Not::class.asTypeName(), booleanExpression.codeBlock())
is BooleanExpression.Type -> CodeBlock.of("%T(%S)", BooleanExpression.Type::class.asTypeName(), name)
is BooleanExpression.Variable -> CodeBlock.of("%T(%S)", BooleanExpression.Variable::class.asTypeName(), name)
}
} | mit | 6c53ad6176f69f503439c02492319566 | 34.1875 | 128 | 0.670535 | 4.188492 | false | false | false | false |
exponentjs/exponent | packages/expo-calendar/android/src/main/java/expo/modules/calendar/CalendarEventBuilder.kt | 2 | 2560 | package expo.modules.calendar
import android.content.ContentValues
import android.text.TextUtils
import expo.modules.core.arguments.ReadableArguments
import java.util.*
class CalendarEventBuilder(
private val eventDetails: ReadableArguments
) {
private val eventValues = ContentValues()
fun getAsLong(key: String): Long = eventValues.getAsLong(key)
fun put(key: String, value: String) = apply {
eventValues.put(key, value)
}
fun put(key: String, value: Int) = apply {
eventValues.put(key, value)
}
fun put(key: String, value: Long) = apply {
eventValues.put(key, value)
}
fun put(key: String, value: Boolean) = apply {
eventValues.put(key, value)
}
fun putNull(key: String) = apply {
eventValues.putNull(key)
}
fun checkIfContainsRequiredKeys(vararg keys: String) = apply {
keys.forEach { checkDetailsContainsRequiredKey(it) }
}
fun putEventString(eventKey: String, detailsKey: String) = apply {
if (eventDetails.containsKey(detailsKey)) {
eventValues.put(eventKey, eventDetails.getString(detailsKey))
}
}
fun putEventString(eventKey: String, detailsKey: String, mapper: (String) -> Int) = apply {
if (eventDetails.containsKey(detailsKey)) {
eventValues.put(eventKey, mapper(eventDetails.getString(detailsKey)))
}
}
fun putEventBoolean(eventKey: String, detailsKey: String) = apply {
if (eventDetails.containsKey(detailsKey)) {
eventValues.put(eventKey, if (eventDetails.getBoolean(detailsKey)) 1 else 0)
}
}
fun putEventBoolean(eventKey: String, detailsKey: String, value: Boolean) = apply {
if (eventDetails.containsKey(detailsKey)) {
eventValues.put(eventKey, value)
}
}
fun putEventTimeZone(eventKey: String, detailsKey: String) = apply {
eventValues.put(
eventKey,
if (eventDetails.containsKey(detailsKey)) {
eventDetails.getString(detailsKey)
} else {
TimeZone.getDefault().id
}
)
}
fun <OutputListItemType> putEventDetailsList(eventKey: String, detailsKey: String, mappingMethod: (Any?) -> OutputListItemType) = apply {
if (eventDetails.containsKey(eventKey)) {
val array = eventDetails.getList(eventKey)
val values = array.map {
mappingMethod(it)
}
eventValues.put(detailsKey, TextUtils.join(",", values))
}
}
private fun checkDetailsContainsRequiredKey(key: String) = apply {
if (!eventDetails.containsKey(key)) {
throw Exception("new calendars require $key")
}
}
fun build() = eventValues
}
| bsd-3-clause | 5ea324392d1bf4f7ad137621eec35661 | 27.131868 | 139 | 0.692969 | 3.775811 | false | false | false | false |
square/wire | wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/OptionElement.kt | 1 | 4065 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.schema.internal.parser
import com.squareup.wire.schema.internal.appendIndented
import com.squareup.wire.schema.internal.appendOptions
import com.squareup.wire.schema.internal.parser.OptionElement.Kind.BOOLEAN
import com.squareup.wire.schema.internal.parser.OptionElement.Kind.ENUM
import com.squareup.wire.schema.internal.parser.OptionElement.Kind.LIST
import com.squareup.wire.schema.internal.parser.OptionElement.Kind.MAP
import com.squareup.wire.schema.internal.parser.OptionElement.Kind.NUMBER
import com.squareup.wire.schema.internal.parser.OptionElement.Kind.OPTION
import com.squareup.wire.schema.internal.parser.OptionElement.Kind.STRING
import kotlin.jvm.JvmOverloads
data class OptionElement(
val name: String,
val kind: Kind,
val value: Any,
/** If true, this [OptionElement] is a custom option. */
val isParenthesized: Boolean
) {
enum class Kind {
STRING,
BOOLEAN,
NUMBER,
ENUM,
MAP,
LIST,
OPTION
}
/** An internal representation of the Option primitive types. */
data class OptionPrimitive(val kind: Kind, val value: Any)
private val formattedName = if (isParenthesized) "($name)" else name
fun toSchema(): String = buildString {
when (kind) {
STRING -> append("""$formattedName = "$value"""")
BOOLEAN,
NUMBER,
ENUM -> append("$formattedName = $value")
OPTION -> {
// Treat nested options as non-parenthesized always, prevents double parentheses.
val optionValue = (value as OptionElement).copy()
append("$formattedName.${optionValue.toSchema()}")
}
MAP -> {
append("$formattedName = {\n")
formatOptionMap(this, value as Map<String, *>)
append('}')
}
LIST -> {
append("$formattedName = ")
appendOptions(value as List<OptionElement>)
}
}
}
fun toSchemaDeclaration() = "option ${toSchema()};\n"
private fun formatOptionMap(
builder: StringBuilder,
valueMap: Map<String, *>
) {
val lastIndex = valueMap.size - 1
valueMap.entries.forEachIndexed { index, entry ->
val endl = if (index != lastIndex) "," else ""
builder.appendIndented("${entry.key}: ${formatOptionMapValue(entry.value!!)}$endl")
}
}
private fun formatOptionMapValue(value: Any): String = buildString {
when (value) {
is String -> {
append(""""$value"""")
}
is OptionPrimitive -> {
when (value.kind) {
BOOLEAN,
NUMBER,
ENUM -> {
append("${value.value}")
}
else -> append(formatOptionMapValue(value.value))
}
}
is Map<*, *> -> {
append("{\n")
formatOptionMap(this, value as Map<String, *>)
append('}')
}
is List<*> -> {
append("[\n")
val lastIndex = value.size - 1
value.forEachIndexed { index, item ->
val endl = if (index != lastIndex) "," else ""
appendIndented("${formatOptionMapValue(item!!)}$endl")
}
append("]")
}
else -> {
append(value)
}
}
}
companion object {
internal val PACKED_OPTION_ELEMENT =
OptionElement("packed", BOOLEAN, value = "true", isParenthesized = false)
@JvmOverloads
fun create(
name: String,
kind: Kind,
value: Any,
isParenthesized: Boolean = false
) = OptionElement(name, kind, value, isParenthesized)
}
}
| apache-2.0 | 288ee3056d48bec3de424fefbb430ce8 | 29.335821 | 89 | 0.640344 | 4.143731 | false | false | false | false |
Adventech/sabbath-school-android-2 | features/pdf/src/main/kotlin/app/ss/pdf/di/PdfModule.kt | 1 | 2163 | /*
* Copyright (c) 2021. 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 app.ss.pdf.di
import android.content.Context
import app.ss.pdf.PdfReader
import app.ss.pdf.PdfReaderImpl
import app.ss.pdf.PdfReaderPrefs
import app.ss.pdf.PdfReaderPrefsImpl
import com.cryart.sabbathschool.core.extensions.coroutines.DispatcherProvider
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object PdfModule {
@Provides
@Singleton
fun provideReaderPrefs(
@ApplicationContext context: Context
): PdfReaderPrefs = PdfReaderPrefsImpl(context)
@Provides
@Singleton
fun provideReader(
@ApplicationContext context: Context,
readerPrefs: PdfReaderPrefs,
dispatcherProvider: DispatcherProvider
): PdfReader = PdfReaderImpl(
context = context,
readerPrefs = readerPrefs,
dispatcherProvider = dispatcherProvider
)
}
| mit | c80d0640b343ce747a5cbd5bbd2ae126 | 35.661017 | 80 | 0.764679 | 4.525105 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/data/proto/TypeProtoDecoders.kt | 1 | 8449 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.data.proto
import arcs.core.data.CollectionType
import arcs.core.data.CountType
import arcs.core.data.EntityType
import arcs.core.data.FieldType
import arcs.core.data.PrimitiveType
import arcs.core.data.ReferenceType
import arcs.core.data.SchemaRegistry
import arcs.core.data.SingletonType
import arcs.core.data.TupleType
import arcs.core.data.TypeVariable
import arcs.core.type.Type
/** Converts a [PrimitiveTypeProto] protobuf instance into a Kotlin [FieldType] instance. */
fun PrimitiveTypeProto.decodeAsFieldType(): FieldType.Primitive {
return FieldType.Primitive(
when (this) {
PrimitiveTypeProto.TEXT -> PrimitiveType.Text
PrimitiveTypeProto.NUMBER -> PrimitiveType.Number
PrimitiveTypeProto.BOOLEAN -> PrimitiveType.Boolean
PrimitiveTypeProto.BIGINT -> PrimitiveType.BigInt
PrimitiveTypeProto.BYTE -> PrimitiveType.Byte
PrimitiveTypeProto.SHORT -> PrimitiveType.Short
PrimitiveTypeProto.INT -> PrimitiveType.Int
PrimitiveTypeProto.LONG -> PrimitiveType.Long
PrimitiveTypeProto.CHAR -> PrimitiveType.Char
PrimitiveTypeProto.FLOAT -> PrimitiveType.Float
PrimitiveTypeProto.DOUBLE -> PrimitiveType.Double
PrimitiveTypeProto.INSTANT -> PrimitiveType.Instant
PrimitiveTypeProto.DURATION -> PrimitiveType.Duration
PrimitiveTypeProto.UNRECOGNIZED ->
throw IllegalArgumentException("Unknown PrimitiveTypeProto value.")
}
)
}
/** Converts a [ReferenceTypeProto] protobuf instance into a Kotlin [FieldType] instance. */
fun ReferenceTypeProto.decodeAsFieldType(
annotationsList: List<AnnotationProto>
): FieldType.EntityRef {
val entitySchema = requireNotNull(decode().entitySchema) {
"Field that is a reference to an non-entity type is not possible."
}
return FieldType.EntityRef(entitySchema.hash, annotationsList.map { it.decode() })
}
/** Converts a [TupleTypeProto] protobuf instance into a Kotlin [FieldType] instance. */
fun TupleTypeProto.decodeAsFieldType(): FieldType.Tuple = FieldType.Tuple(
elementsList.map { it.decodeAsFieldType() }
)
/** Converts a [ListTypeProto] to a [FieldType.ListOf] instance. */
fun ListTypeProto.decodeAsFieldType(): FieldType.ListOf {
return FieldType.ListOf(elementType.decodeAsFieldType())
}
/** Converts a [NullableTypeProto] to a [FieldType.NullableOf] instance. */
fun NullableTypeProto.decodeAsFieldType(): FieldType {
return elementType.decodeAsFieldType().nullable()
}
/**
* Converts a [ListTypeProto] to a [FieldType.InlineEntity] instance. Only works for inline
* entities.
*/
fun EntityTypeProto.decodeAsFieldType(): FieldType.InlineEntity {
require(inline) { "Cannot decode non-inline entities to FieldType.InlineEntity" }
return FieldType.InlineEntity(schema.hash).also { SchemaRegistry.register(schema.decode()) }
}
/**
* Converts a [TypeProto] protobuf instance into a Kotlin [FieldType] instance.
*
* @throws [IllegalArgumentexception] if the type cannot be converted to [FieldType].
*/
fun TypeProto.decodeAsFieldType(
annotationsList: List<AnnotationProto> = emptyList()
): FieldType = when (dataCase) {
TypeProto.DataCase.PRIMITIVE -> primitive.decodeAsFieldType()
TypeProto.DataCase.REFERENCE -> reference.decodeAsFieldType(annotationsList)
TypeProto.DataCase.TUPLE -> tuple.decodeAsFieldType()
TypeProto.DataCase.LIST -> list.decodeAsFieldType()
TypeProto.DataCase.NULLABLE -> nullable.decodeAsFieldType()
TypeProto.DataCase.ENTITY -> entity.decodeAsFieldType()
TypeProto.DataCase.DATA_NOT_SET, null ->
throw IllegalArgumentException("Unknown data field in TypeProto.")
TypeProto.DataCase.VARIABLE,
TypeProto.DataCase.SINGLETON,
TypeProto.DataCase.COLLECTION,
TypeProto.DataCase.COUNT ->
throw IllegalArgumentException("Cannot decode non-field type $dataCase to FieldType.")
}
/**
* Converts a [EntityTypeProto] protobuf instance into a Kotlin [EntityType] instance. Does not work
* for inline entities.
*/
fun EntityTypeProto.decode(): EntityType {
require(!inline) { "Cannot decode inline entities to EntityType." }
return EntityType(schema.decode()).also { SchemaRegistry.register(it.entitySchema) }
}
/** Converts a [SingletonTypeProto] protobuf instance into a Kotlin [SingletonType] instance. */
fun SingletonTypeProto.decode() = SingletonType(singletonType.decode())
/** Converts a [CollectionTypeProto] protobuf instance into a Kotlin [CollectionType] instance. */
fun CollectionTypeProto.decode() = CollectionType(collectionType.decode())
/** Converts a [ReferenceTypeProto] protobuf instance into a Kotlin [ReferenceType] instance. */
fun ReferenceTypeProto.decode() = ReferenceType(referredType.decode())
/** Converts a [TupleTypeProto] protobuf instance into a Kotlin [TupleType] instance. */
fun TupleTypeProto.decode() = TupleType(elementsList.map { it.decode() })
/** Converts a [TypeVariableProto] protobuf instance into a Kotlin [TypeVariable] instance. */
fun TypeVariableProto.decode(): TypeVariable {
require(hasConstraint()) { "TypeVariableProto must have a constraint." }
return TypeVariable(
name,
if (constraint.hasConstraintType()) constraint.constraintType.decode() else null,
constraint.maxAccess
)
}
/** Converts a [TypeProto] protobuf instance into a Kotlin [Type] instance. */
// TODO(b/155812915): RefinementExpression.
fun TypeProto.decode(): Type = when (dataCase) {
TypeProto.DataCase.ENTITY -> entity.decode()
TypeProto.DataCase.SINGLETON -> singleton.decode()
TypeProto.DataCase.COLLECTION -> collection.decode()
TypeProto.DataCase.REFERENCE -> reference.decode()
TypeProto.DataCase.COUNT -> CountType()
TypeProto.DataCase.TUPLE -> tuple.decode()
TypeProto.DataCase.VARIABLE -> variable.decode()
TypeProto.DataCase.PRIMITIVE, TypeProto.DataCase.LIST, TypeProto.DataCase.NULLABLE ->
throw IllegalArgumentException("Cannot decode FieldType $dataCase to Type.")
TypeProto.DataCase.DATA_NOT_SET, null ->
throw IllegalArgumentException("Unknown data field in TypeProto.")
}
/** Encodes a [Type] as a [TypeProto]. */
fun Type.encode(): TypeProto = when (this) {
is TypeVariable -> {
val proto = TypeVariableProto.newBuilder().setName(name)
val infoBuilder = ConstraintInfo.newBuilder().setMaxAccess(maxAccess)
constraint?.let { infoBuilder.setConstraintType(it.encode()) }
proto.constraint = infoBuilder.build()
proto.build().asTypeProto()
}
is EntityType -> EntityTypeProto.newBuilder()
.setSchema(entitySchema.encode())
.build()
.asTypeProto()
is SingletonType<*> -> SingletonTypeProto.newBuilder()
.setSingletonType(containedType.encode())
.build()
.asTypeProto()
is CollectionType<*> -> CollectionTypeProto.newBuilder()
.setCollectionType(containedType.encode())
.build()
.asTypeProto()
is ReferenceType<*> -> ReferenceTypeProto.newBuilder()
.setReferredType(containedType.encode())
.build()
.asTypeProto()
is TupleType -> TupleTypeProto.newBuilder()
.addAllElements(elementTypes.map { it.encode() })
.build()
.asTypeProto()
is CountType -> CountTypeProto.getDefaultInstance().asTypeProto()
else -> throw UnsupportedOperationException("Unsupported Type: $this")
}
// Convenience methods for wrapping specific subtypes in a TypeProto.
fun SingletonTypeProto.asTypeProto() = TypeProto.newBuilder().setSingleton(this).build()
fun CollectionTypeProto.asTypeProto() = TypeProto.newBuilder().setCollection(this).build()
fun PrimitiveTypeProto.asTypeProto() = TypeProto.newBuilder().setPrimitive(this).build()
fun ReferenceTypeProto.asTypeProto() = TypeProto.newBuilder().setReference(this).build()
fun TupleTypeProto.asTypeProto() = TypeProto.newBuilder().setTuple(this).build()
fun ListTypeProto.asTypeProto() = TypeProto.newBuilder().setList(this).build()
fun NullableTypeProto.asTypeProto() = TypeProto.newBuilder().setNullable(this).build()
fun EntityTypeProto.asTypeProto() = TypeProto.newBuilder().setEntity(this).build()
fun TypeVariableProto.asTypeProto() = TypeProto.newBuilder().setVariable(this).build()
fun CountTypeProto.asTypeProto() = TypeProto.newBuilder().setCount(this).build()
| bsd-3-clause | 3596db6a222da7c1025fca04aca71b80 | 40.014563 | 100 | 0.761037 | 4.31953 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnnecessaryOptInAnnotationInspection.kt | 1 | 17673 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.getDirectlyOverriddenDeclarations
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.references.ReadWriteAccessChecker
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.SINCE_KOTLIN_FQ_NAME
import org.jetbrains.kotlin.resolve.checkers.OptInNames
import org.jetbrains.kotlin.resolve.checkers.OptInNames.OPT_IN_FQ_NAMES
import org.jetbrains.kotlin.resolve.constants.ArrayValue
import org.jetbrains.kotlin.resolve.constants.KClassValue
import org.jetbrains.kotlin.resolve.constants.StringValue
import org.jetbrains.kotlin.resolve.descriptorUtil.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
/**
* An inspection to detect unnecessary (obsolete) `@OptIn` annotations.
*
* The `@OptIn(SomeExperimentalMarker::class)` annotation is necessary for the code that
* uses experimental library API marked with `@SomeExperimentalMarker` but is not experimental by itself.
* When the library authors decide that the API is not experimental anymore, and they remove
* the experimental marker, the corresponding `@OptIn` annotation in the client code becomes unnecessary
* and may be removed so the people working with the code would not be misguided.
*
* For each `@OptIn` annotation, the inspection checks if in its scope there are names marked with
* the experimental marker mentioned in the `@OptIn`, and it reports the marker classes that don't match
* any names. For these redundant markers, the inspection proposes a quick fix to remove the marker
* or the entire unnecessary `@OptIn` annotation if it contains a single marker.
*/
class UnnecessaryOptInAnnotationInspection : AbstractKotlinInspection() {
/**
* Get the PSI element to which the given `@OptIn` annotation applies.
*
* @receiver the `@OptIn` annotation entry
* @return the annotated element, or null if no such element is found
*/
private fun KtAnnotationEntry.getOwner(): KtElement? = getStrictParentOfType<KtAnnotated>()
/**
* A temporary storage for expected experimental markers.
*
* @param expression a smart pointer to the argument expression to create a quick fix
* @param fqName the resolved fully qualified name
*/
private data class ResolvedMarker(
val expression: SmartPsiElementPointer<KtClassLiteralExpression>,
val fqName: FqName
)
// Short names for `kotlin.OptIn` and `kotlin.UseExperimental` for faster comparison without name resolution
private val OPT_IN_SHORT_NAMES = OPT_IN_FQ_NAMES.map { it.shortName().asString() }.toSet()
/**
* Main inspection visitor to traverse all annotation entries.
*/
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
val file = holder.file
val optInAliases = if (file is KtFile) KotlinPsiHeuristics.getImportAliases(file, OPT_IN_SHORT_NAMES) else emptySet()
return annotationEntryVisitor { annotationEntry ->
val annotationEntryArguments = annotationEntry.valueArguments.ifEmpty {
return@annotationEntryVisitor
}
// Fast check if the annotation may be `@OptIn`/`@UseExperimental` or any of their import aliases
val entryShortName = annotationEntry.shortName?.asString()
if (entryShortName != null && entryShortName !in OPT_IN_SHORT_NAMES && entryShortName !in optInAliases)
return@annotationEntryVisitor
// Resolve the candidate annotation entry. If it is an `@OptIn`/`@UseExperimental` annotation,
// resolve all expected experimental markers.
val resolutionFacade = annotationEntry.getResolutionFacade()
val annotationContext = annotationEntry.analyze(resolutionFacade)
val annotationFqName = annotationContext[BindingContext.ANNOTATION, annotationEntry]?.fqName
if (annotationFqName !in OPT_IN_FQ_NAMES) return@annotationEntryVisitor
val resolvedMarkers = mutableListOf<ResolvedMarker>()
for (arg in annotationEntryArguments) {
val argumentExpression = arg.getArgumentExpression()?.safeAs<KtClassLiteralExpression>() ?: continue
val markerFqName = annotationContext[
BindingContext.REFERENCE_TARGET,
argumentExpression.lhs?.safeAs<KtNameReferenceExpression>()
]?.fqNameSafe ?: continue
resolvedMarkers.add(ResolvedMarker(argumentExpression.createSmartPointer(), markerFqName))
}
// Find the scope of the `@OptIn` declaration and collect all its experimental markers.
val markerProcessor = MarkerCollector(resolutionFacade)
annotationEntry.getOwner()?.accept(OptInMarkerVisitor(), markerProcessor)
val unusedMarkers = resolvedMarkers.filter { markerProcessor.isUnused(it.fqName) }
if (annotationEntryArguments.size == unusedMarkers.size) {
// If all markers in the `@OptIn` annotation are useless, create a quick fix to remove
// the entire annotation.
holder.registerProblem(
annotationEntry,
KotlinBundle.message("inspection.unnecessary.opt_in.redundant.annotation"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
RemoveAnnotationEntry()
)
} else {
// Check each resolved marker whether it is actually used in the scope of the `@OptIn`.
// Create a quick fix to remove the unnecessary marker if no marked names have been found.
for (marker in unusedMarkers) {
val expression = marker.expression.element ?: continue
holder.registerProblem(
expression,
KotlinBundle.message(
"inspection.unnecessary.opt_in.redundant.marker",
marker.fqName.shortName().render()
),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
RemoveAnnotationArgumentOrEntireEntry()
)
}
}
}
}
}
/**
* A processor that collects experimental markers referred by names in the `@OptIn` annotation scope.
*/
private class MarkerCollector(private val resolutionFacade: ResolutionFacade) {
// Experimental markers found during a check for a specific annotation entry
private val foundMarkers = mutableSetOf<FqName>()
// A checker instance for setter call detection
private val readWriteAccessChecker = ReadWriteAccessChecker.getInstance(resolutionFacade.project)
/**
* Check if a specific experimental marker is not used in the scope of a specific `@OptIn` annotation.
*
* @param marker the fully qualified name of the experimental marker of interest
* @return true if no marked names was found during the check, false if there is at least one marked name
*/
fun isUnused(marker: FqName): Boolean = marker !in foundMarkers
/**
* Collect experimental markers for a declaration and add them to [foundMarkers].
*
* The `@OptIn` annotation is useful for declarations that override a marked declaration (e.g., overridden
* functions or properties in classes/objects). If the declaration overrides another name, we should
* collect experimental markers from the overridden declaration.
*
* @param declaration the declaration to process
*/
fun collectMarkers(declaration: KtDeclaration?) {
if (declaration == null) return
if (declaration !is KtFunction && declaration !is KtProperty && declaration !is KtParameter) return
if (declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
val descriptor = declaration.resolveToDescriptorIfAny(resolutionFacade)?.safeAs<CallableMemberDescriptor>() ?: return
descriptor.getDirectlyOverriddenDeclarations().forEach { it.collectMarkers(declaration.languageVersionSettings.apiVersion) }
}
}
/**
* Collect experimental markers for an expression and add them to [foundMarkers].
*
* @param expression the expression to process
*/
fun collectMarkers(expression: KtReferenceExpression?) {
if (expression == null) return
// Resolve the reference to descriptors, then analyze the annotations
// For each descriptor, we also check a corresponding importable descriptor
// if it is not equal to the descriptor itself. The goal is to correctly
// resolve class names. For example, the `Foo` reference in the code fragment
// `val x = Foo()` is resolved as a constructor, while the corresponding
// class descriptor can be found as the constructor's importable name.
// Both constructor and class may be annotated with an experimental API marker,
// so we should check both of them.
val descriptorList = expression
.resolveMainReferenceToDescriptors()
.flatMap { setOf(it, it.getImportableDescriptor()) }
val moduleApiVersion = expression.languageVersionSettings.apiVersion
for (descriptor in descriptorList) {
descriptor.collectMarkers(moduleApiVersion)
// A special case: a property has no experimental markers but its setter is experimental.
// We need to additionally collect markers from the setter if it is invoked in the expression.
if (descriptor is PropertyDescriptor) {
val setter = descriptor.setter
if (setter != null && expression.isSetterCall()) setter.collectMarkers(moduleApiVersion)
}
// The caller implicitly uses argument types and return types of a declaration,
// so we need to check whether these types have experimental markers
// regardless of the `@OptIn` annotation on the declaration itself.
if (descriptor is CallableDescriptor) {
descriptor.valueParameters.forEach { it.type.collectMarkers(moduleApiVersion)}
descriptor.returnType?.collectMarkers(moduleApiVersion)
}
}
}
/**
* Collect markers from a declaration descriptor corresponding to a Kotlin type.
*
* @receiver the type to collect markers
* @param moduleApiVersion the API version of the current module to check `@WasExperimental` annotations
*/
private fun KotlinType.collectMarkers(moduleApiVersion: ApiVersion) {
arguments.forEach { it.type.collectMarkers(moduleApiVersion) }
val descriptor = this.constructor.declarationDescriptor ?: return
descriptor.collectMarkers(moduleApiVersion)
}
/**
* Actually collect markers for a resolved descriptor and add them to [foundMarkers].
*
* @receiver the descriptor to collect markers
* @param moduleApiVersion the API version of the current module to check `@WasExperimental` annotations
*/
private fun DeclarationDescriptor.collectMarkers(moduleApiVersion: ApiVersion) {
for (ann in annotations) {
val annotationFqName = ann.fqName ?: continue
val annotationClass = ann.annotationClass ?: continue
// Add the annotation class as a marker if it has `@RequireOptIn` annotation.
if (annotationClass.annotations.hasAnnotation(OptInNames.REQUIRES_OPT_IN_FQ_NAME)
|| annotationClass.annotations.hasAnnotation(OptInNames.OLD_EXPERIMENTAL_FQ_NAME)) {
foundMarkers += annotationFqName
}
val wasExperimental = annotations.findAnnotation(OptInNames.WAS_EXPERIMENTAL_FQ_NAME) ?: continue
val sinceKotlin = annotations.findAnnotation(SINCE_KOTLIN_FQ_NAME) ?: continue
// If there are both `@SinceKotlin` and `@WasExperimental` annotations,
// and Kotlin API version of the module is less than the version specified by `@SinceKotlin`,
// then the `@OptIn` for `@WasExperimental` marker is necessary and should be added
// to the set of found markers.
//
// For example, consider a function
// ```
// @SinceKotlin("1.6")
// @WasExperimental(Marker::class)
// fun foo() { ... }
// ```
// This combination of annotations means that `foo` was experimental before Kotlin 1.6
// and required `@OptIn(Marker::class) or `@Marker` annotation. When the client code
// is compiled as Kotlin 1.6 code, there are no problems, and the `@OptIn(Marker::class)`
// annotation would not be necessary. At the same time, when the code is compiled with
// `apiVersion = 1.5`, the non-experimental declaration of `foo` will be hidden
// from the resolver, so `@OptIn` is necessary for the code to compile.
val sinceKotlinApiVersion = sinceKotlin.allValueArguments[VERSION_ARGUMENT]
?.safeAs<StringValue>()?.value?.let {
ApiVersion.parse(it)
}
if (sinceKotlinApiVersion != null && moduleApiVersion < sinceKotlinApiVersion) {
wasExperimental.allValueArguments[OptInNames.WAS_EXPERIMENTAL_ANNOTATION_CLASS]?.safeAs<ArrayValue>()?.value
?.mapNotNull { it.safeAs<KClassValue>()?.getArgumentType(module)?.fqName }
?.forEach { foundMarkers.add(it) }
}
}
}
/**
* Check if the reference expression is a part of a property setter invocation.
*
* @receiver the expression to check
*/
private fun KtReferenceExpression.isSetterCall(): Boolean =
readWriteAccessChecker.readWriteAccessWithFullExpression(this, true).first.isWrite
private val VERSION_ARGUMENT = Name.identifier("version")
}
/**
* The marker collecting visitor that navigates the PSI tree in the scope of the `@OptIn` declaration
* and collects experimental markers.
*/
private class OptInMarkerVisitor : KtTreeVisitor<MarkerCollector>() {
override fun visitNamedDeclaration(declaration: KtNamedDeclaration, markerCollector: MarkerCollector): Void? {
markerCollector.collectMarkers(declaration)
return super.visitNamedDeclaration(declaration, markerCollector)
}
override fun visitReferenceExpression(expression: KtReferenceExpression, markerCollector: MarkerCollector): Void? {
markerCollector.collectMarkers(expression)
return super.visitReferenceExpression(expression, markerCollector)
}
}
/**
* A quick fix that removes the argument from the value argument list of an annotation entry,
* or the entire entry if the argument was the only argument of the annotation.
*/
private class RemoveAnnotationArgumentOrEntireEntry : LocalQuickFix {
override fun getFamilyName(): String = KotlinBundle.message("inspection.unnecessary.opt_in.remove.marker.fix.family.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val valueArgument = descriptor.psiElement?.parentOfType<KtValueArgument>() ?: return
val annotationEntry = valueArgument.parentOfType<KtAnnotationEntry>() ?: return
if (annotationEntry.valueArguments.size == 1) {
annotationEntry.delete()
} else {
annotationEntry.valueArgumentList?.removeArgument(valueArgument)
}
}
}
/**
* A quick fix that removes the entire annotation entry.
*/
private class RemoveAnnotationEntry : LocalQuickFix {
override fun getFamilyName(): String = KotlinBundle.message("inspection.unnecessary.opt_in.remove.annotation.fix.family.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val annotationEntry = descriptor.psiElement?.safeAs<KtAnnotationEntry>() ?: return
annotationEntry.delete()
}
}
| apache-2.0 | 22072df46a27308b5d6944023d57ec2f | 50.524781 | 158 | 0.699768 | 5.326401 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/listener/ListenerSuppressor.kt | 1 | 2256 | /*
* 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.listener
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.diagnostic.vimLogger
import com.maddyhome.idea.vim.options.helpers.StrictMode
import java.io.Closeable
/**
* Base class for listener suppressors.
* Children of this class have an ability to suppress editor listeners
*
* E.g.
* ```
* CaretVimListenerSuppressor.lock()
* caret.moveToOffset(10) // vim's caret listener will not be executed
* CaretVimListenerSuppressor.unlock()
* ````
*
* Locks can be nested:
* ```
* CaretVimListenerSuppressor.lock()
* moveCaret(caret) // vim's caret listener will not be executed
* CaretVimListenerSuppressor.unlock()
*
* fun moveCaret(caret: Caret) {
* CaretVimListenerSuppressor.lock()
* caret.moveToOffset(10)
* CaretVimListenerSuppressor.unlock()
* }
* ```
*
* [Locked] implements [Closeable], so you can use try-with-resources block
*
* java
* ```
* try (VimListenerSuppressor.Locked ignored = SelectionVimListenerSuppressor.INSTANCE.lock()) {
* ....
* }
* ```
*
* Kotlin
* ```
* SelectionVimListenerSuppressor.lock().use { ... }
* ```
*/
sealed class VimListenerSuppressor {
private var caretListenerSuppressor = 0
fun lock(): Locked {
LOG.trace("Suppressor lock")
LOG.trace(injector.application.currentStackTrace())
caretListenerSuppressor++
return Locked()
}
// Please try not to use lock/unlock without scoping
// Prefer try-with-resources
fun unlock() {
LOG.trace("Suppressor unlock")
LOG.trace(injector.application.currentStackTrace())
caretListenerSuppressor--
}
fun reset() {
StrictMode.assert(caretListenerSuppressor == 0, "Listener is not zero")
caretListenerSuppressor = 0
}
val isNotLocked: Boolean
get() = caretListenerSuppressor == 0
inner class Locked : Closeable {
override fun close() = unlock()
}
companion object {
private val LOG = vimLogger<VimListenerSuppressor>()
}
}
object SelectionVimListenerSuppressor : VimListenerSuppressor()
| mit | 23a3af7e065c0e8783ab13931840453b | 24.348315 | 96 | 0.70523 | 4.10929 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/feedforward/batchnorm/BatchNormLayerParameters.kt | 1 | 1979 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.feedforward.batchnorm
import com.kotlinnlp.simplednn.core.arrays.ParamsArray
import com.kotlinnlp.simplednn.core.functionalities.initializers.GlorotInitializer
import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer
import com.kotlinnlp.simplednn.core.layers.LayerParameters
/**
* The parameters of the [BatchNormLayer].
*
* @property inputSize the input size (equal to the output size)
* @param weightsInitializer the initializer of the weights (zeros if null, default: Glorot)
* @param biasesInitializer the initializer of the biases (zeros if null, default: Glorot)
*/
class BatchNormLayerParameters(
inputSize: Int,
weightsInitializer: Initializer? = GlorotInitializer(),
biasesInitializer: Initializer? = GlorotInitializer()
) : LayerParameters(
inputSize = inputSize,
outputSize = inputSize,
weightsInitializer = weightsInitializer,
biasesInitializer = biasesInitializer
) {
companion object {
/**
* Private val used to serialize the class (needed by Serializable).
*/
@Suppress("unused")
private const val serialVersionUID: Long = 1L
}
/**
* The bias.
*/
val b = ParamsArray(this.outputSize)
/**
* The weights.
*/
val g = ParamsArray(this.outputSize)
/**
* The list of weights parameters.
*/
override val weightsList: List<ParamsArray> = listOf(
this.g
)
/**
* The list of biases parameters.
*/
override val biasesList: List<ParamsArray> = listOf(
this.b
)
/**
* Initialize all parameters values.
*/
init {
this.initialize()
}
}
| mpl-2.0 | 9e166b6de57d29d91086dbd360f0c36f | 26.486111 | 92 | 0.694795 | 4.447191 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/engagement/ListScenarioUtils.kt | 1 | 4179 | package org.wordpress.android.ui.engagement
import android.content.Context
import android.text.Spannable
import dagger.Reusable
import org.json.JSONArray
import org.json.JSONException
import org.wordpress.android.fluxc.tools.FormattableContent
import org.wordpress.android.models.Note
import org.wordpress.android.ui.engagement.ListScenarioType.LOAD_COMMENT_LIKES
import org.wordpress.android.ui.engagement.ListScenarioType.LOAD_POST_LIKES
import org.wordpress.android.ui.engagement.AuthorName.AuthorNameCharSequence
import org.wordpress.android.ui.notifications.blocks.HeaderNoteBlock
import org.wordpress.android.ui.notifications.blocks.NoteBlockClickableSpan
import org.wordpress.android.ui.notifications.utils.NotificationsUtilsWrapper
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T.NOTIFS
import org.wordpress.android.util.getMediaUrlOrEmpty
import org.wordpress.android.util.getRangeIdOrZero
import org.wordpress.android.util.getRangeSiteIdOrZero
import org.wordpress.android.util.getRangeUrlOrEmpty
import org.wordpress.android.util.getTextOrEmpty
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.util.image.ImageType.AVATAR_WITH_BACKGROUND
import java.util.ArrayList
import javax.inject.Inject
@Reusable
class ListScenarioUtils @Inject constructor(
val imageManager: ImageManager,
val notificationsUtilsWrapper: NotificationsUtilsWrapper
) {
fun mapLikeNoteToListScenario(note: Note, context: Context): ListScenario {
require(note.isLikeType) { "mapLikeNoteToListScenario > unexpected note type ${note.type}" }
val imageType = AVATAR_WITH_BACKGROUND
val headerNoteBlock = HeaderNoteBlock(
null,
transformToFormattableContentList(note.header),
imageType,
null,
null,
imageManager,
notificationsUtilsWrapper
)
headerNoteBlock.setIsComment(note.isCommentType)
val spannable: Spannable = notificationsUtilsWrapper.getSpannableContentForRanges(headerNoteBlock.getHeader(0))
val spans = spannable.getSpans(
0, spannable.length,
NoteBlockClickableSpan::class.java
)
for (span in spans) {
span.enableColors(context)
}
return ListScenario(
type = if (note.isPostLikeType) LOAD_POST_LIKES else LOAD_COMMENT_LIKES,
source = EngagementNavigationSource.LIKE_NOTIFICATION_LIST,
siteId = note.siteId.toLong(),
postOrCommentId = if (note.isPostLikeType) note.postId.toLong() else note.commentId,
commentPostId = if (note.isCommentLikeType) note.postId.toLong() else 0L,
commentSiteUrl = if (note.isCommentLikeType) note.url else "",
headerData = HeaderData(
authorName = AuthorNameCharSequence(spannable),
snippetText = headerNoteBlock.getHeader(1).getTextOrEmpty(),
authorAvatarUrl = headerNoteBlock.getHeader(0).getMediaUrlOrEmpty(0),
authorUserId = headerNoteBlock.getHeader(0).getRangeIdOrZero(0),
authorPreferredSiteId = headerNoteBlock.getHeader(0).getRangeSiteIdOrZero(0),
authorPreferredSiteUrl = headerNoteBlock.getHeader(0).getRangeUrlOrEmpty(0)
)
)
}
fun transformToFormattableContentList(headerArray: JSONArray?): List<FormattableContent> {
val headersList: MutableList<FormattableContent> = ArrayList()
if (headerArray != null) {
for (i in 0 until headerArray.length()) {
try {
headersList.add(
notificationsUtilsWrapper.mapJsonToFormattableContent(
headerArray.getJSONObject(i)
)
)
} catch (e: JSONException) {
AppLog.e(NOTIFS, "Header array has invalid format.")
}
}
}
return headersList
}
}
| gpl-2.0 | 5428afd85a152f12694403754365de89 | 44.423913 | 119 | 0.674324 | 4.882009 | false | false | false | false |
ingokegel/intellij-community | platform/platform-impl/src/com/intellij/formatting/visualLayer/VisualFormattingLayerService.kt | 1 | 3866 | // 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.formatting.visualLayer
import com.intellij.application.options.RegistryManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorCustomElementRenderer
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.util.Key
import com.intellij.psi.codeStyle.CodeStyleSettings
private const val REGISTRY_KEY = "editor.visual.formatting.layer.enabled"
val visualFormattingElementKey = Key.create<Boolean>("visual.formatting.element")
abstract class VisualFormattingLayerService {
private val EDITOR_VISUAL_FORMATTING_LAYER_CODE_STYLE_SETTINGS = Key.create<CodeStyleSettings>("visual.formatting.layer.info")
val Editor.visualFormattingLayerEnabled: Boolean
get() = visualFormattingLayerCodeStyleSettings != null
var Editor.visualFormattingLayerCodeStyleSettings: CodeStyleSettings?
get() = getUserData(EDITOR_VISUAL_FORMATTING_LAYER_CODE_STYLE_SETTINGS)
private set(value) = putUserData(EDITOR_VISUAL_FORMATTING_LAYER_CODE_STYLE_SETTINGS, value)
val enabledByRegistry: Boolean
get() = RegistryManager.getInstance().`is`(REGISTRY_KEY)
fun enabledForEditor(editor: Editor) = editor.visualFormattingLayerEnabled
fun enableForEditor(editor: Editor, codeStyleSettings: CodeStyleSettings) {
editor.visualFormattingLayerCodeStyleSettings = codeStyleSettings
}
fun disableForEditor(editor: Editor) {
editor.visualFormattingLayerCodeStyleSettings = null
}
abstract fun getVisualFormattingLayerElements(editor: Editor): List<VisualFormattingLayerElement>
companion object {
@JvmStatic
fun getInstance(): VisualFormattingLayerService =
ApplicationManager.getApplication().getService(VisualFormattingLayerService::class.java)
}
}
sealed class VisualFormattingLayerElement {
abstract fun applyToEditor(editor: Editor)
data class InlineInlay(val offset: Int, val length: Int) : VisualFormattingLayerElement() {
override fun applyToEditor(editor: Editor) {
editor.inlayModel
.addInlineElement(
offset,
false,
InlayPresentation(editor, length)
)
}
}
data class BlockInlay(val offset: Int, val lines: Int) : VisualFormattingLayerElement() {
override fun applyToEditor(editor: Editor) {
editor.inlayModel
.addBlockElement(
offset,
true,
true,
0,
InlayPresentation(editor, lines, vertical = true)
)
}
}
data class Folding(val offset: Int, val length: Int) : VisualFormattingLayerElement() {
override fun applyToEditor(editor: Editor) {
editor.foldingModel.runBatchFoldingOperation {
editor.foldingModel
.addFoldRegion(offset, offset + length, "")
?.apply {
isExpanded = false
shouldNeverExpand()
putUserData(visualFormattingElementKey, true)
}
}
}
}
}
data class InlayPresentation(val editor: Editor,
val fillerLength: Int,
val vertical: Boolean = false) : EditorCustomElementRenderer {
private val editorFontMetrics by lazy {
val editorFont = EditorColorsManager.getInstance().globalScheme.getFont(EditorFontType.PLAIN)
editor.contentComponent.getFontMetrics(editorFont)
}
override fun calcWidthInPixels(inlay: Inlay<*>) =
if (vertical) 0 else editorFontMetrics.stringWidth(" ".repeat(fillerLength))
override fun calcHeightInPixels(inlay: Inlay<*>) =
(if (vertical) fillerLength else 1) * editorFontMetrics.height
}
| apache-2.0 | 6cbc26b559d917e5ae72206460d503d4 | 35.130841 | 128 | 0.737713 | 4.802484 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/EliminateWhenSubjectIntention.kt | 1 | 2678 | // 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.branchedTransformations.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.toExpression
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.buildExpression
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class EliminateWhenSubjectIntention :
SelfTargetingIntention<KtWhenExpression>(KtWhenExpression::class.java, KotlinBundle.lazyMessage("inline.when.argument")),
LowPriorityAction {
override fun isApplicableTo(element: KtWhenExpression, caretOffset: Int): Boolean {
if (element.subjectExpression !is KtNameReferenceExpression) return false
val lBrace = element.openBrace ?: return false
if (caretOffset > lBrace.startOffset) return false
val lastEntry = element.entries.lastOrNull()
if (lastEntry?.isElse != true && element.isUsedAsExpression(element.analyze(BodyResolveMode.PARTIAL_WITH_CFA))) return false
return true
}
override fun applyTo(element: KtWhenExpression, editor: Editor?) {
val subject = element.subjectExpression ?: return
val commentSaver = CommentSaver(element, saveLineBreaks = true)
val whenExpression = KtPsiFactory(element).buildExpression {
appendFixedText("when {\n")
for (entry in element.entries) {
val branchExpression = entry.expression
if (entry.isElse) {
appendFixedText("else")
} else {
appendExpressions(entry.conditions.map { it.toExpression(subject) }, separator = "||")
}
appendFixedText("->")
appendExpression(branchExpression)
appendFixedText("\n")
}
appendFixedText("}")
}
val result = element.replace(whenExpression)
commentSaver.restore(result)
}
}
| apache-2.0 | 5df2820a4d979f7215c5465f240e5d9b | 43.633333 | 158 | 0.727409 | 5.2 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/hafilat/HafilatTransitData.kt | 1 | 6255 | /*
* HafilatMetrocardTransitData.kt
*
* Copyright 2015 Michael Farrell <[email protected]>
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.hafilat
import au.id.micolous.metrodroid.transit.*
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.desfire.DesfireCard
import au.id.micolous.metrodroid.card.desfire.DesfireCardTransitFactory
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.transit.en1545.En1545Parsed
import au.id.micolous.metrodroid.transit.en1545.En1545Parser
import au.id.micolous.metrodroid.transit.en1545.En1545TransitData
import au.id.micolous.metrodroid.transit.intercode.IntercodeTransitData
import au.id.micolous.metrodroid.ui.ListItem
import au.id.micolous.metrodroid.util.NumberUtils
import au.id.micolous.metrodroid.util.ImmutableByteArray
@Parcelize
class HafilatTransitData (
override val trips: List<TransactionTripAbstract>,
override val subscriptions: List<HafilatSubscription>?,
private val purse: HafilatSubscription?,
private val serial: Long,
private val parsed : En1545Parsed
): En1545TransitData(parsed) {
override val lookup: HafilatLookup
get() = HafilatLookup
override val serialNumber: String?
get() = formatSerial(serial)
override val cardName: String
get() = Localizer.localizeString(NAME)
override val info: List<ListItem>?
get() {
val items = mutableListOf<ListItem>()
if (purse != null) {
items.add(ListItem(R.string.ticket_type, purse.subscriptionName))
if (purse.machineId != null) {
items.add(ListItem(R.string.machine_id,
purse.machineId.toString()))
}
val purchaseTS = purse.purchaseTimestamp
if (purchaseTS != null) {
items.add(ListItem(R.string.issue_date, purchaseTS.format()))
}
val purseId = purse.id
if (purseId != null)
items.add(ListItem(R.string.purse_serial_number, purseId.toString(16)))
}
return super.info.orEmpty() + items
}
companion object {
private fun parse(card: DesfireCard): HafilatTransitData {
val app = card.getApplication(APP_ID)
// This is basically mapped from Intercode
// 0 = TICKETING_ENVIRONMENT
val parsed = En1545Parser.parse(app!!.getFile(0)!!.data,
IntercodeTransitData.TICKET_ENV_FIELDS)
// 1 is 0-record file on all cards we've seen so far
// 2 = TICKETING_CONTRACT_LIST, not really useful to use
val transactionList = mutableListOf<Transaction>()
// 3-6: TICKETING_LOG
// 8 is "ABU DHABI" and some indexing
// 9, 0xd: zero-filled
// a:???
for (fileId in intArrayOf(3, 4, 5, 6)) {
val data = app.getFile(fileId)?.data ?: continue
if (data.getBitsFromBuffer(0, 14) == 0)
continue
transactionList.add(HafilatTransaction(data))
}
// c-f: locked counters
val subs = mutableListOf<HafilatSubscription>()
var purse: HafilatSubscription? = null
// 10-13: contracts
for (fileId in intArrayOf(0x10, 0x11, 0x12, 0x13)) {
val data = app.getFile(fileId)?.data ?: continue
if (data.getBitsFromBuffer(0, 7) == 0)
continue
val sub = HafilatSubscription(data)
if (sub.isPurse)
purse = sub
else
subs.add(sub)
}
// 14-17: zero-filled
// 18: ??
// 19: zero-filled
// 1b-1c: locked
// 1d: empty record file
// 1e: const
return HafilatTransitData(purse = purse,
serial = getSerial(card.tagId),
subscriptions = if (subs.isNotEmpty()) subs else null,
trips = TransactionTrip.merge(transactionList),
parsed = parsed)
}
private const val APP_ID = 0x107f2
private val NAME = R.string.card_name_hafilat
private val CARD_INFO = CardInfo(
name = NAME,
locationId = R.string.location_abu_dhabi,
imageId = R.drawable.hafilat,
imageAlphaId = R.drawable.iso7810_id1_alpha,
cardType = CardType.MifareDesfire,
resourceExtraNote = R.string.card_note_adelaide,
region = TransitRegion.UAE,
preview = true)
val FACTORY: DesfireCardTransitFactory = object : DesfireCardTransitFactory {
override val allCards: List<CardInfo>
get() = listOf(CARD_INFO)
override fun parseTransitIdentity(card: DesfireCard) =
TransitIdentity(NAME, formatSerial(getSerial(card.tagId)))
override fun earlyCheck(appIds: IntArray) = APP_ID in appIds
override fun parseTransitData(card: DesfireCard) = parse(card)
}
private fun formatSerial(serial: Long) = "01-" + NumberUtils.zeroPad(serial, 15)
private fun getSerial(tagId: ImmutableByteArray) =
tagId.byteArrayToLongReversed(1, 6)
}
}
| gpl-3.0 | 7a64567ea82f4b0d27900902dcac771f | 37.611111 | 91 | 0.611351 | 4.392556 | false | false | false | false |
austinv11/D4JBot | src/main/kotlin/com/austinv11/d4j/bot/extensions/JVMExtensions.kt | 1 | 4817 | package com.austinv11.d4j.bot.extensions
import com.austinv11.d4j.bot.CLIENT
import com.austinv11.d4j.bot.command.Command
import sx.blah.discord.handle.obj.*
import java.util.concurrent.TimeUnit
import kotlin.reflect.KClass
fun String.coerceTo(`class`: KClass<*>, command: Command): Any? = when(`class`) {
Float::class, Float::class.javaPrimitiveType!! -> java.lang.Float.valueOf(this)
Double::class, Double::class.javaPrimitiveType!! -> java.lang.Double.valueOf(this)
Byte::class, Byte::class.javaPrimitiveType!! -> java.lang.Byte.valueOf(this)
Short::class, Short::class.javaPrimitiveType!! -> java.lang.Short.valueOf(this)
Int::class, Int::class.javaPrimitiveType!! -> java.lang.Integer.valueOf(this)
Long::class, Long::class.javaPrimitiveType!! -> if (this.startsWith("-")) java.lang.Long.valueOf(this) else java.lang.Long.parseUnsignedLong(this)
Boolean::class, Boolean::class.javaPrimitiveType!! -> if (java.lang.Boolean.valueOf(this)) true else if (!this.equals("false", true)) null else true
Char::class, Char::class.javaPrimitiveType!! -> if (this.length > 1) null else this.first()
String::class -> this
IMessage::class -> buffer {
try {
val id = java.lang.Long.parseUnsignedLong(this)
return@buffer command.channel.getMessageByID(id) ?: buffer { command.guild?.getMessageByID(id) ?: buffer { CLIENT.getMessageByID(id) } }
} catch (e: Throwable) {
return@buffer null
}
}
IVoiceChannel::class -> {
val idString: String
if (this.startsWith("<")) {
idString = this.removePrefix("<#").removeSuffix(">")
} else {
idString = this
}
try {
val id = java.lang.Long.parseUnsignedLong(idString)
command.guild?.getVoiceChannelByID(id) ?: CLIENT.getVoiceChannelByID(id)
} catch (e: Throwable) {
command.guild?.getVoiceChannelsByName(this)?.firstOrNull() ?: CLIENT.voiceChannels.find { it.name == this }
}
}
IChannel::class -> {
val idString: String
if (this.startsWith("<")) {
idString = this.removePrefix("<#").removeSuffix(">")
} else {
idString = this
}
try {
val id = java.lang.Long.parseUnsignedLong(idString)
command.guild?.getChannelByID(id) ?: CLIENT.getChannelByID(id)
} catch (e: Throwable) {
command.guild?.getChannelsByName(this)?.firstOrNull() ?: CLIENT.channels.find { it.name == this }
}
}
IGuild::class -> {
try {
val id = java.lang.Long.parseUnsignedLong(this)
CLIENT.getGuildByID(id)
} catch (e: Throwable) {
CLIENT.guilds.find { it.name == this }
}
}
IUser::class -> {
val idString: String
if (this.startsWith("<")) {
idString = this.removePrefix("<@").removeSuffix(">").removePrefix("!")
} else {
idString = this
}
try {
val id = java.lang.Long.parseUnsignedLong(idString)
command.guild?.getUserByID(id) ?: buffer { CLIENT.getUserByID(id) }
} catch (e: Throwable) {
command.guild?.getUsersByName(this)?.firstOrNull() ?: CLIENT.users.find { it.name == this }
}
}
IRole::class -> {
if (this == "@everyone")
command.guild?.everyoneRole
else {
val idString: String
if (this.startsWith("<")) {
idString = this.removePrefix("<&").removeSuffix(">")
} else {
idString = this
}
try {
val id = java.lang.Long.parseUnsignedLong(idString)
command.guild?.getRoleByID(id) ?: buffer { CLIENT.getRoleByID(id) }
} catch (e: Throwable) {
command.guild?.getRolesByName(this)?.firstOrNull() ?: CLIENT.roles.find { it.name == this }
}
}
}
StatusType::class -> StatusType.get(this)
Permissions::class -> try { Permissions.valueOf(this) } catch (e: Throwable) { null }
VerificationLevel::class -> VerificationLevel.valueOf(this)
else -> if (`class`.java.isEnum) `class`.java.enumConstants.firstOrNull { it.toString().equals(this, true) } else null
}
val Long.unsignedString: String
get() = java.lang.Long.toUnsignedString(this)
val String.unsignedLong: Long
get() = java.lang.Long.parseUnsignedLong(this)
val String.quote: String
get() = "\"$this\""
fun Long.msToTimestamp(): String {
val min = TimeUnit.MINUTES.convert(this, TimeUnit.MILLISECONDS)
val seconds = TimeUnit.SECONDS.convert(this - TimeUnit.MILLISECONDS.convert(min, TimeUnit.MINUTES), TimeUnit.MILLISECONDS).toString().padStart(2, '0')
return "$min:$seconds"
}
| gpl-3.0 | 2476bcd70e928ea4bd42bfcc8bd40859 | 41.254386 | 154 | 0.607432 | 4.099574 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/configuration/KotlinDataNodes.kt | 4 | 3063 | // 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.
@file:Suppress("DEPRECATION")
package org.jetbrains.kotlin.idea.gradle.configuration
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.Key
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.AbstractExternalEntityData
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.serialization.PropertyMapping
import org.jetbrains.kotlin.idea.gradleTooling.ArgsInfo
import org.jetbrains.kotlin.idea.gradleTooling.KotlinImportingDiagnostic
import org.jetbrains.kotlin.idea.gradleTooling.arguments.CachedExtractedArgsInfo
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.Serializable
interface ImplementedModulesAware : Serializable {
var implementedModuleNames: List<String>
}
class KotlinGradleProjectData : AbstractExternalEntityData(GradleConstants.SYSTEM_ID), ImplementedModulesAware {
var isResolved: Boolean = false
var kotlinTarget: String? = null
var hasKotlinPlugin: Boolean = false
var coroutines: String? = null
var isHmpp: Boolean = false
var kotlinImportingDiagnosticsContainer: Set<KotlinImportingDiagnostic>? = null
var platformPluginId: String? = null
lateinit var kotlinNativeHome: String
override var implementedModuleNames: List<String> = emptyList()
@Transient
val dependenciesCache: MutableMap<DataNode<ProjectData>, Collection<DataNode<out ModuleData>>> = mutableMapOf()
val pureKotlinSourceFolders: MutableCollection<String> = hashSetOf()
companion object {
val KEY = Key.create(KotlinGradleProjectData::class.java, ProjectKeys.MODULE.processingWeight + 1)
}
}
@IntellijInternalApi
val DataNode<KotlinGradleProjectData>.kotlinGradleSourceSetDataNodes: Collection<DataNode<KotlinGradleSourceSetData>>
get() = ExternalSystemApiUtil.findAll(this, KotlinGradleSourceSetData.KEY)
class KotlinGradleSourceSetData @PropertyMapping("sourceSetName") constructor(val sourceSetName: String?) :
AbstractExternalEntityData(GradleConstants.SYSTEM_ID), ImplementedModulesAware {
lateinit var cachedArgsInfo: CachedExtractedArgsInfo
var isProcessed: Boolean = false
var kotlinPluginVersion: String? = null
@Suppress("DEPRECATION")
@Deprecated("Use cachedArgsInfo instead", level = DeprecationLevel.ERROR)
lateinit var compilerArguments: ArgsInfo
lateinit var additionalVisibleSourceSets: Set<String>
override var implementedModuleNames: List<String> = emptyList()
companion object {
val KEY = Key.create(KotlinGradleSourceSetData::class.java, KotlinGradleProjectData.KEY.processingWeight + 1)
}
}
| apache-2.0 | 591641a377fe0d9762d53c1992527b98 | 44.716418 | 158 | 0.809664 | 5.130653 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/codeVision/CodeVisionPass.kt | 1 | 6724 | // 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.codeInsight.hints.codeVision
import com.intellij.codeHighlighting.EditorBoundHighlightingPass
import com.intellij.codeInsight.codeVision.CodeVisionHost
import com.intellij.codeInsight.codeVision.CodeVisionInitializer
import com.intellij.codeInsight.codeVision.CodeVisionProviderFactory
import com.intellij.codeInsight.codeVision.settings.CodeVisionSettings
import com.intellij.codeInsight.codeVision.ui.model.ProjectCodeVisionModel
import com.intellij.concurrency.JobLauncher
import com.intellij.diagnostic.telemetry.TraceManager
import com.intellij.diagnostic.telemetry.computeWithSpan
import com.intellij.diagnostic.telemetry.runWithSpan
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.rd.createLifetime
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.Processor
import com.jetbrains.rd.util.reactive.adviseUntil
import org.jetbrains.annotations.ApiStatus.Internal
import java.util.concurrent.ConcurrentHashMap
/**
* Prepares data for [com.intellij.codeInsight.codeVision.CodeVisionHost].
*
* Doesn't actually apply result to the editor - just caches the result and notifies CodeVisionHost that
* particular [com.intellij.codeInsight.codeVision.CodeVisionProvider] has to be invalidated.
* Host relaunches it and takes the result of this pass from cache.
*/
class CodeVisionPass(
rootElement: PsiElement,
private val editor: Editor
) : EditorBoundHighlightingPass(editor, rootElement.containingFile, true) {
companion object {
private val tracer by lazy { TraceManager.getTracer("CodeVision", true) }
@JvmStatic
@Internal
fun collectData(editor: Editor, file: PsiFile, providers: List<DaemonBoundCodeVisionProvider>): CodeVisionData {
val providerIdToLenses = ConcurrentHashMap<String, DaemonBoundCodeVisionCacheService.CodeVisionWithStamp>()
collect(EmptyProgressIndicator(), editor, file, providerIdToLenses, providers)
val allProviders = CodeVisionProviderFactory.createAllProviders(file.project)
val dataForAllProviders = HashMap<String, DaemonBoundCodeVisionCacheService.CodeVisionWithStamp>()
val modificationStamp = file.modificationStamp
for (provider in allProviders) {
if (provider !is CodeVisionProviderAdapter) continue
val providerId = provider.id
dataForAllProviders[providerId] = providerIdToLenses[providerId]
?: DaemonBoundCodeVisionCacheService.CodeVisionWithStamp(emptyList(), modificationStamp)
}
return CodeVisionData(dataForAllProviders)
}
private fun collect(progress: ProgressIndicator,
editor: Editor,
file: PsiFile,
providerIdToLenses: ConcurrentHashMap<String, DaemonBoundCodeVisionCacheService.CodeVisionWithStamp>,
providers: List<DaemonBoundCodeVisionProvider>) {
val modificationTracker = PsiModificationTracker.getInstance(editor.project)
runWithSpan(tracer, "codeVision") { span ->
span.setAttribute("file", file.name)
JobLauncher.getInstance().invokeConcurrentlyUnderProgress(providers, progress, Processor { provider ->
span.useWithScope {
computeWithSpan(tracer, provider.javaClass.simpleName) {
val results = provider.computeForEditor(editor, file)
providerIdToLenses[provider.id] = DaemonBoundCodeVisionCacheService.CodeVisionWithStamp(results,
modificationTracker.modificationCount)
}
}
true
})
}
}
internal fun updateProviders(project: Project,
editor: Editor,
providerIdToLenses: Map<String, DaemonBoundCodeVisionCacheService.CodeVisionWithStamp>) {
val codeVisionHost = CodeVisionInitializer.getInstance(project).getCodeVisionHost()
codeVisionHost.invalidateProviderSignal.fire(CodeVisionHost.LensInvalidateSignal(editor, providerIdToLenses.keys))
}
internal fun saveToCache(project: Project,
editor: Editor,
providerIdToLenses: Map<String, DaemonBoundCodeVisionCacheService.CodeVisionWithStamp>) {
val cacheService = DaemonBoundCodeVisionCacheService.getInstance(project)
for ((providerId, results) in providerIdToLenses) {
cacheService.storeVisionDataForEditor(editor, providerId, results)
}
}
}
private val providerIdToLenses: ConcurrentHashMap<String, DaemonBoundCodeVisionCacheService.CodeVisionWithStamp> = ConcurrentHashMap()
private val currentIndicator = ProgressManager.getGlobalProgressIndicator()
override fun doCollectInformation(progress: ProgressIndicator) {
val settings = CodeVisionSettings.instance()
val providers = DaemonBoundCodeVisionProvider.extensionPoint.extensionList
.filter { settings.isProviderEnabled(it.groupId) }
collect(progress, editor, myFile, providerIdToLenses, providers)
}
override fun doApplyInformationToEditor() {
saveToCache(myProject, editor, providerIdToLenses)
val lensPopupActive = ProjectCodeVisionModel.getInstance(editor.project!!).lensPopupActive
if (lensPopupActive.value.not()) {
updateProviders(myProject, editor, providerIdToLenses)
}
else {
lensPopupActive.adviseUntil(myProject.createLifetime()) {
if (it) return@adviseUntil false
if (currentIndicator == null || currentIndicator.isCanceled) return@adviseUntil true
updateProviders(myProject, editor, providerIdToLenses)
true
}
}
}
class CodeVisionData internal constructor(
private val providerIdToLenses: Map<String, DaemonBoundCodeVisionCacheService.CodeVisionWithStamp>
) {
fun applyTo(editor: Editor, project: Project) {
ApplicationManager.getApplication().assertIsDispatchThread()
saveToCache(project, editor, providerIdToLenses)
updateProviders(project, editor, providerIdToLenses)
}
override fun toString(): String {
return providerIdToLenses.toString()
}
}
} | apache-2.0 | 6b12fa48a08967fa1699c404d69a4f8d | 47.731884 | 140 | 0.744795 | 5.192278 | false | false | false | false |
GunoH/intellij-community | plugins/gitlab/src/org/jetbrains/plugins/gitlab/mergerequest/ui/filters/GitLabMergeRequestsFiltersViewModel.kt | 1 | 3965 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.mergerequest.ui.filters
import com.intellij.collaboration.ui.codereview.list.search.ReviewListSearchPanelViewModel
import com.intellij.collaboration.ui.codereview.list.search.ReviewListSearchPanelViewModelBase
import com.intellij.collaboration.ui.icon.IconsProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import org.jetbrains.plugins.gitlab.api.data.GitLabAccessLevel
import org.jetbrains.plugins.gitlab.api.dto.GitLabMemberDTO
import org.jetbrains.plugins.gitlab.api.dto.GitLabUserDTO
import org.jetbrains.plugins.gitlab.mergerequest.api.dto.GitLabLabelDTO
import org.jetbrains.plugins.gitlab.mergerequest.data.loaders.GitLabProjectDetailsLoader
import org.jetbrains.plugins.gitlab.mergerequest.ui.filters.GitLabMergeRequestsFiltersValue.MergeRequestStateFilterValue
import org.jetbrains.plugins.gitlab.mergerequest.ui.filters.GitLabMergeRequestsFiltersValue.MergeRequestsMemberFilterValue
internal interface GitLabMergeRequestsFiltersViewModel : ReviewListSearchPanelViewModel<GitLabMergeRequestsFiltersValue, GitLabMergeRequestsQuickFilter> {
val avatarIconsProvider: IconsProvider<GitLabUserDTO>
val stateFilterState: MutableStateFlow<MergeRequestStateFilterValue?>
val authorFilterState: MutableStateFlow<MergeRequestsMemberFilterValue?>
val assigneeFilterState: MutableStateFlow<MergeRequestsMemberFilterValue?>
val reviewerFilterState: MutableStateFlow<MergeRequestsMemberFilterValue?>
val labelFilterState: MutableStateFlow<GitLabMergeRequestsFiltersValue.LabelFilterValue?>
suspend fun getMergeRequestMembers(): List<GitLabMemberDTO>
suspend fun getLabels(): List<GitLabLabelDTO>
}
internal class GitLabMergeRequestsFiltersViewModelImpl(
scope: CoroutineScope,
historyModel: GitLabMergeRequestsFiltersHistoryModel,
override val avatarIconsProvider: IconsProvider<GitLabUserDTO>,
private val projectDetailsLoader: GitLabProjectDetailsLoader
) : GitLabMergeRequestsFiltersViewModel,
ReviewListSearchPanelViewModelBase<GitLabMergeRequestsFiltersValue, GitLabMergeRequestsQuickFilter>(
scope,
historyModel,
emptySearch = GitLabMergeRequestsFiltersValue.EMPTY,
defaultQuickFilter = GitLabMergeRequestsQuickFilter.Open()
) {
override fun GitLabMergeRequestsFiltersValue.withQuery(query: String?): GitLabMergeRequestsFiltersValue {
return copy(searchQuery = query)
}
override val quickFilters: List<GitLabMergeRequestsQuickFilter> = listOf(
GitLabMergeRequestsQuickFilter.Open()
)
override val stateFilterState = searchState.partialState(GitLabMergeRequestsFiltersValue::state) {
copy(state = it)
}
override val authorFilterState = searchState.partialState(GitLabMergeRequestsFiltersValue::author) {
copy(author = it)
}
override val assigneeFilterState = searchState.partialState(GitLabMergeRequestsFiltersValue::assignee) {
copy(assignee = it)
}
override val reviewerFilterState = searchState.partialState(GitLabMergeRequestsFiltersValue::reviewer) {
copy(reviewer = it)
}
override val labelFilterState = searchState.partialState(GitLabMergeRequestsFiltersValue::label) {
copy(label = it)
}
override suspend fun getLabels(): List<GitLabLabelDTO> = projectDetailsLoader.projectLabels()
override suspend fun getMergeRequestMembers(): List<GitLabMemberDTO> = projectDetailsLoader.projectMembers().filter { member ->
isValidMergeRequestAccessLevel(member.accessLevel)
}
companion object {
private fun isValidMergeRequestAccessLevel(accessLevel: GitLabAccessLevel): Boolean {
return accessLevel == GitLabAccessLevel.REPORTER ||
accessLevel == GitLabAccessLevel.DEVELOPER ||
accessLevel == GitLabAccessLevel.MAINTAINER ||
accessLevel == GitLabAccessLevel.OWNER
}
}
} | apache-2.0 | 778955b386ffe279843ca449b17bdc37 | 45.658824 | 154 | 0.823203 | 5.089859 | false | false | false | false |
fvasco/pinpoi | app/src/main/java/io/github/fvasco/pinpoi/importer/Ov2Importer.kt | 1 | 3848 | package io.github.fvasco.pinpoi.importer
import android.util.Log
import io.github.fvasco.pinpoi.model.Placemark
import io.github.fvasco.pinpoi.util.Coordinates
import java.io.DataInputStream
import java.io.IOException
import java.io.InputStream
/**
* Tomtom OV2 importer
* @author Francesco Vasco
*/
/* File format
1 byte: record type
4 bytes: length of this record in bytes (including the T and L fields)
4 bytes: longitude coordinate of the POI
4 bytes: latitude coordinate of the POI
length-14 bytes: ASCII string specifying the name of the POI
1 byte: null byte
*/
class Ov2Importer : AbstractImporter() {
private fun readIntLE(inputStream: InputStream): Int {
return inputStream.read() or (inputStream.read() shl 8) or (inputStream.read() shl 16) or (inputStream.read() shl 24)
}
@Throws(IOException::class)
override fun importImpl(inputStream: InputStream) {
val dataInputStream = DataInputStream(inputStream)
var nameBuffer = ByteArray(64)
var rectype = dataInputStream.read()
while (rectype >= 0) {
when (rectype) {
// it is a simple POI record
2, 3 -> {
val total = readIntLE(dataInputStream)
Log.d(Ov2Importer::class.java.simpleName, "Process record type $rectype total $total")
var nameLength = total - 14
// read lon, lat
// coordinate format: int*100000
val longitudeInt = readIntLE(dataInputStream)
val latitudeInt = readIntLE(dataInputStream)
if (longitudeInt < -18000000 || longitudeInt > 18000000
|| latitudeInt < -9000000 || latitudeInt > 9000000
) {
throw IOException("Wrong coordinates $longitudeInt,$latitudeInt")
}
// read name
if (nameLength > nameBuffer.size) {
//ensure buffer size
nameBuffer = ByteArray(nameLength)
}
dataInputStream.readFully(nameBuffer, 0, nameLength)
// skip null byte
if (dataInputStream.read() != 0) {
throw IOException("wrong string termination $rectype")
}
// if rectype=3 description contains two-zero terminated string
// select first, discard other
if (rectype == 3) {
var i = 0
while (i < nameLength) {
if (nameBuffer[i].toInt() == 0) {
// set name length
// then exit
nameLength = i
}
++i
}
}
val placemark = Placemark()
placemark.name = TextImporter.toString(nameBuffer, 0, nameLength)
placemark.coordinates = Coordinates(latitudeInt / 100000f, longitudeInt / 100000f)
importPlacemark(placemark)
}
// block header
1 -> {
Log.d(Ov2Importer::class.java.simpleName, "Skip record type $rectype")
dataInputStream.skipBytes(20)
}
else -> {
val total = readIntLE(dataInputStream)
Log.w(Ov2Importer::class.java.simpleName, "Skip record type $rectype total $total")
require(total > 4)
dataInputStream.skipBytes(total - 4)
}
}
rectype = dataInputStream.read()
}
}
}
| gpl-3.0 | 95327ceef7b76b2cdd57fba64e062876 | 38.670103 | 125 | 0.514033 | 5.256831 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/issues/comments.kt | 13 | 900 | // This is an end-of-line comment
/*
This is a block comment
*/
/*doc comment of class*/ //one line comment of class
//another one
/*another doc*/
internal class C {
// This is a class comment
/**
* This is a field doc comment.
*/
private val i = 0
/**
* This is a function doc comment.
*/
fun foo() {
/* This is a function comment */
}
//simple one line comment for function
fun f1() {}
//simple one line comment for field
var j = 0
//double c style
//comment before function
fun f2() {}
//double c style
//comment before field
var k = 0
//combination
/** of
*/
//
/**
* different
*/
//comments
fun f3() {}
//combination
/** of
*/
//
/**
* different
*/
//comments
var l = 0
/*two*/ /*comments*/ /*line*/
var z = 0
} | apache-2.0 | b29281866a081b5cf5efcfc8eda5a366 | 15.089286 | 52 | 0.503333 | 3.964758 | false | false | false | false |
ktorio/ktor | ktor-shared/ktor-resources/common/src/io/ktor/resources/serialization/Decoders.kt | 1 | 5093 | /*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.resources.serialization
import io.ktor.http.*
import io.ktor.resources.*
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.modules.*
@OptIn(ExperimentalSerializationApi::class)
internal class ParametersDecoder(
override val serializersModule: SerializersModule,
private val parameters: Parameters,
elementNames: Iterable<String>
) : AbstractDecoder() {
private val parameterNames = elementNames.iterator()
private lateinit var currentName: String
override fun decodeElementIndex(descriptor: SerialDescriptor): Int {
if (!parameterNames.hasNext()) {
return CompositeDecoder.DECODE_DONE
}
while (parameterNames.hasNext()) {
currentName = parameterNames.next()
val elementIndex = descriptor.getElementIndex(currentName)
val elementDescriptorKind = descriptor.getElementDescriptor(elementIndex).kind
val isPrimitive = elementDescriptorKind is PrimitiveKind
val isEnum = elementDescriptorKind is SerialKind.ENUM
if (!(isPrimitive || isEnum) || parameters.contains(currentName)) {
return elementIndex
}
}
return CompositeDecoder.DECODE_DONE
}
override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder {
if (descriptor.kind == StructureKind.LIST) {
return ListLikeDecoder(serializersModule, parameters, currentName)
}
return ParametersDecoder(serializersModule, parameters, descriptor.elementNames)
}
override fun decodeBoolean(): Boolean {
return decodeString().toBoolean()
}
override fun decodeByte(): Byte {
return decodeString().toByte()
}
override fun decodeChar(): Char {
return decodeString()[0]
}
override fun decodeDouble(): Double {
return decodeString().toDouble()
}
override fun decodeFloat(): Float {
return decodeString().toFloat()
}
override fun decodeInt(): Int {
return decodeString().toInt()
}
override fun decodeLong(): Long {
return decodeString().toLong()
}
override fun decodeShort(): Short {
return decodeString().toShort()
}
override fun decodeString(): String {
return parameters[currentName]!!
}
override fun decodeNotNullMark(): Boolean {
return parameters.contains(currentName)
}
override fun decodeNull(): Nothing? {
return null
}
override fun decodeEnum(enumDescriptor: SerialDescriptor): Int {
val enumName = decodeString()
val index = enumDescriptor.getElementIndex(enumName)
if (index == CompositeDecoder.UNKNOWN_NAME) {
throw ResourceSerializationException(
"${enumDescriptor.serialName} does not contain element with name '$enumName'"
)
}
return index
}
}
@OptIn(ExperimentalSerializationApi::class)
private class ListLikeDecoder(
override val serializersModule: SerializersModule,
private val parameters: Parameters,
private val parameterName: String
) : AbstractDecoder() {
private var currentIndex = -1
private val elementsCount = parameters.getAll(parameterName)?.size ?: 0
override fun decodeElementIndex(descriptor: SerialDescriptor): Int {
if (++currentIndex == elementsCount) {
return CompositeDecoder.DECODE_DONE
}
return currentIndex
}
override fun decodeBoolean(): Boolean {
return decodeString().toBoolean()
}
override fun decodeByte(): Byte {
return decodeString().toByte()
}
override fun decodeChar(): Char {
return decodeString()[0]
}
override fun decodeDouble(): Double {
return decodeString().toDouble()
}
override fun decodeFloat(): Float {
return decodeString().toFloat()
}
override fun decodeInt(): Int {
return decodeString().toInt()
}
override fun decodeLong(): Long {
return decodeString().toLong()
}
override fun decodeShort(): Short {
return decodeString().toShort()
}
override fun decodeString(): String {
return parameters.getAll(parameterName)!![currentIndex]
}
override fun decodeNotNullMark(): Boolean {
return parameters.contains(parameterName)
}
override fun decodeNull(): Nothing? {
return null
}
override fun decodeEnum(enumDescriptor: SerialDescriptor): Int {
val enumName = decodeString()
val index = enumDescriptor.getElementIndex(enumName)
if (index == CompositeDecoder.UNKNOWN_NAME) {
throw ResourceSerializationException(
"${enumDescriptor.serialName} does not contain element with name '$enumName'"
)
}
return index
}
}
| apache-2.0 | 0e7baafdfc62bb8ce1355866ff0d4232 | 27.9375 | 119 | 0.65914 | 5.63385 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/builders.kt | 1 | 6006 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.plugins.websocket
import io.ktor.client.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.websocket.*
import kotlinx.coroutines.*
/**
* Installs the [WebSockets] plugin using the [config] as configuration.
*/
public fun HttpClientConfig<*>.WebSockets(config: WebSockets.Config.() -> Unit) {
install(WebSockets) {
config()
}
}
/**
* Opens a [DefaultClientWebSocketSession].
*/
@OptIn(ExperimentalCoroutinesApi::class)
public suspend fun HttpClient.webSocketSession(
block: HttpRequestBuilder.() -> Unit
): DefaultClientWebSocketSession {
plugin(WebSockets)
val sessionDeferred = CompletableDeferred<DefaultClientWebSocketSession>()
val statement = prepareRequest {
url {
protocol = URLProtocol.WS
port = protocol.defaultPort
}
block()
}
@Suppress("SuspendFunctionOnCoroutineScope")
launch {
try {
statement.body<DefaultClientWebSocketSession, Unit> { session ->
val sessionCompleted = CompletableDeferred<Unit>()
sessionDeferred.complete(session)
session.outgoing.invokeOnClose {
if (it != null) sessionCompleted.completeExceptionally(it)
else sessionCompleted.complete(Unit)
}
sessionCompleted.await()
}
} catch (cause: Throwable) {
sessionDeferred.completeExceptionally(cause)
}
}
return sessionDeferred.await()
}
/**
* Opens a [DefaultClientWebSocketSession].
*/
public suspend fun HttpClient.webSocketSession(
method: HttpMethod = HttpMethod.Get,
host: String? = null,
port: Int? = null,
path: String? = null,
block: HttpRequestBuilder.() -> Unit = {}
): DefaultClientWebSocketSession = webSocketSession {
this.method = method
url("ws", host, port, path)
block()
}
/**
* Opens a [DefaultClientWebSocketSession].
*/
public suspend fun HttpClient.webSocketSession(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): DefaultClientWebSocketSession = webSocketSession {
url.takeFrom(urlString)
block()
}
/**
* Opens a [block] with [DefaultClientWebSocketSession].
*/
public suspend fun HttpClient.webSocket(
request: HttpRequestBuilder.() -> Unit,
block: suspend DefaultClientWebSocketSession.() -> Unit
) {
plugin(WebSockets)
val session = prepareRequest {
url {
protocol = URLProtocol.WS
}
request()
}
session.body<DefaultClientWebSocketSession, Unit> {
try {
block(it)
} finally {
it.close()
}
}
}
/**
* Opens a [block] with [DefaultClientWebSocketSession].
*/
public suspend fun HttpClient.webSocket(
method: HttpMethod = HttpMethod.Get,
host: String? = null,
port: Int? = null,
path: String? = null,
request: HttpRequestBuilder.() -> Unit = {},
block: suspend DefaultClientWebSocketSession.() -> Unit
) {
webSocket(
{
this.method = method
url("ws", host, port, path)
request()
},
block
)
}
/**
* Opens a [block] with [DefaultClientWebSocketSession].
*/
public suspend fun HttpClient.webSocket(
urlString: String,
request: HttpRequestBuilder.() -> Unit = {},
block: suspend DefaultClientWebSocketSession.() -> Unit
) {
webSocket(
HttpMethod.Get,
null,
null,
null,
{
url.protocol = URLProtocol.WS
url.port = port
url.takeFrom(urlString)
request()
},
block
)
}
/**
* Opens a [block] with [DefaultClientWebSocketSession].
*/
public suspend fun HttpClient.ws(
method: HttpMethod = HttpMethod.Get,
host: String? = null,
port: Int? = null,
path: String? = null,
request: HttpRequestBuilder.() -> Unit = {},
block: suspend DefaultClientWebSocketSession.() -> Unit
): Unit = webSocket(method, host, port, path, request, block)
/**
* Opens a [block] with [DefaultClientWebSocketSession].
*/
public suspend fun HttpClient.ws(
request: HttpRequestBuilder.() -> Unit,
block: suspend DefaultClientWebSocketSession.() -> Unit
): Unit = webSocket(request, block)
/**
* Opens a [block] with [DefaultClientWebSocketSession].
*/
public suspend fun HttpClient.ws(
urlString: String,
request: HttpRequestBuilder.() -> Unit = {},
block: suspend DefaultClientWebSocketSession.() -> Unit
): Unit = webSocket(urlString, request, block)
/**
* Opens a [block] with secure [DefaultClientWebSocketSession].
*/
public suspend fun HttpClient.wss(
request: HttpRequestBuilder.() -> Unit,
block: suspend DefaultClientWebSocketSession.() -> Unit
): Unit = webSocket(
{
url.protocol = URLProtocol.WSS
url.port = url.protocol.defaultPort
request()
},
block = block
)
/**
* Opens a [block] with secure [DefaultClientWebSocketSession].
*/
public suspend fun HttpClient.wss(
urlString: String,
request: HttpRequestBuilder.() -> Unit = {},
block: suspend DefaultClientWebSocketSession.() -> Unit
): Unit = wss(
{
url.takeFrom(urlString)
request()
},
block = block
)
/**
* Opens a [block] with secure [DefaultClientWebSocketSession].
*/
public suspend fun HttpClient.wss(
method: HttpMethod = HttpMethod.Get,
host: String? = null,
port: Int? = null,
path: String? = null,
request: HttpRequestBuilder.() -> Unit = {},
block: suspend DefaultClientWebSocketSession.() -> Unit
): Unit = webSocket(
method,
host,
port,
path,
request = {
url.protocol = URLProtocol.WSS
if (port != null) url.port = port
request()
},
block = block
)
| apache-2.0 | 09cfa68f65e292aa31ad208b025d667e | 24.666667 | 118 | 0.630203 | 4.442308 | false | false | false | false |
armcha/Ribble | app/src/main/kotlin/io/armcha/ribble/presentation/widget/MaterialDialog.kt | 1 | 3093 | package io.armcha.ribble.presentation.widget
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.Dialog
import android.content.Context
import android.view.View
import android.view.ViewPropertyAnimator
import android.widget.Button
import android.widget.TextView
import io.armcha.ribble.R
import io.armcha.ribble.presentation.utils.AnimationUtils
import io.armcha.ribble.presentation.utils.extensions.unSafeLazy
import io.armcha.ribble.presentation.utils.extensions.onClick
import io.armcha.ribble.presentation.utils.extensions.scale
import kotlinx.android.synthetic.main.dialog_item.*
/**
* Created by Chatikyan on 10.09.2017.
*/
class MaterialDialog(context: Context) : Dialog(context, R.style.MaterialDialogSheet) {
private val titleText by unSafeLazy {
findViewById<TextView>(R.id.title)
}
private val messageText by unSafeLazy {
findViewById<TextView>(R.id.message)
}
private val positiveButton by unSafeLazy {
findViewById<Button>(R.id.positiveButton)
}
init {
setContentView(R.layout.dialog_item)
setCancelable(true)
setCanceledOnTouchOutside(true)
dialogContainer.onClick { hide() }
}
override fun onDetachedFromWindow() {
super.dismiss()
super.onDetachedFromWindow()
}
infix fun title(title: String): MaterialDialog {
titleText.text = title
return this
}
infix fun message(message: String): MaterialDialog {
messageText.text = message
return this
}
fun addPositiveButton(text: String, action: MaterialDialog.() -> Unit): MaterialDialog {
positiveButton.text = text.toUpperCase()
positiveButton.onClick {
action()
}
return this
}
override fun show() {
super.show()
val view = findViewById<View>(io.armcha.ribble.R.id.container)
with(view) {
alpha = 0F
scale = .85F
animate()
.scale(1F)
.alpha(1F)
.setDuration(120)
.setInterpolator(AnimationUtils.FAST_OUT_LINEAR_IN_INTERPOLATOR)
.withLayer()
.start()
}
}
override fun hide() {
val view = findViewById<View>(io.armcha.ribble.R.id.container)
with(view) {
animate()
.scale(.85F)
.alpha(0F)
.setDuration(110)
.setInterpolator(AnimationUtils.FAST_OUT_LINEAR_IN_INTERPOLATOR)
.withLayer()
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
[email protected]()
}
})
.start()
}
}
private fun ViewPropertyAnimator.scale(scale: Float): ViewPropertyAnimator {
scaleX(scale)
scaleY(scale)
return this
}
} | apache-2.0 | e4a3f6ce12c17e871d3cce6735f54890 | 29.333333 | 92 | 0.607501 | 4.847962 | false | false | false | false |
javecs/text2expr | src/main/kotlin/xyz/javecs/tools/text2expr/rules/RuleBuilder.kt | 1 | 3379 | package xyz.javecs.tools.text2expr.rules
import com.atilika.kuromoji.ipadic.Tokenizer
import xyz.javecs.tools.expr.Calculator
import xyz.javecs.tools.text2expr.utils.normalize
private val BaseOffset = -1
private val NotFound = -2
private val Optional = -3
private val tokenizer = Tokenizer()
private fun coverage(matched: Int, total: Int) = matched.toDouble() / total.toDouble()
internal data class Evaluation(val value: Number = Double.NaN,
val expr: List<String> = ArrayList(),
val variables: Map<String, Double> = HashMap(),
val coverage: Double = 0.0,
val rule: String = "")
internal class RuleBuilder(source: String, val name: String = "") {
private val parser = RuleParser()
init {
parser.visit(parser(source).text2expr())
}
private fun indexOf(word: Word, tokens: List<SimpleToken>, start: Int, end: Int): Pair<Int, Boolean> {
for (i in start..end) {
val token = tokens[i]
var matched = 0
for ((key, value) in word.fields) {
when (key) {
"SF" -> if (value.contains(token.surface)) matched++
"P1" -> if (value.contains(token.partOfSpeechLevel1)) matched++
"P2" -> if (value.contains(token.partOfSpeechLevel2)) matched++
"P3" -> if (value.contains(token.partOfSpeechLevel3)) matched++
"P4" -> if (value.contains(token.partOfSpeechLevel4)) matched++
"BF" -> if (value.contains(token.baseForm)) matched++
"RD" -> if (value.contains(token.reading)) matched++
"PR" -> if (value.contains(token.pronunciation)) matched++
}
}
if (word.fields.size == matched) return Pair(i, false)
}
return if (word.isOptional()) Pair(Optional, true) else Pair(NotFound, false)
}
fun rule(): Array<Word> = parser.rule.toTypedArray()
fun expr(): Array<String> = parser.expr
.split(System.lineSeparator())
.filter { it.isNotEmpty() }
.toTypedArray()
fun matches(text: String, recognizedId: (id: Pair<String, String>) -> Unit = {}): Pair<Boolean, Double> {
val tokens = tokenizer.tokenize(text).toSimpleTokens()
var offset = BaseOffset
var remained = rule().size
rule().forEach {
val (index, optional) = indexOf(it, tokens, start = offset + 1, end = Math.min(tokens.size - remained, tokens.lastIndex))
if (index == NotFound) return Pair(false, 0.0)
if (it.id.isNotEmpty()) recognizedId(Pair(it.id, if (optional) it.optionalValue().toString() else tokens[index].surface))
if (!optional) offset = index
remained--
}
return Pair(true, coverage(rule().size, tokens.size))
}
fun eval(text: String): Evaluation {
val calc = Calculator()
val args = ArrayList<String>()
val (matched, coverage) = matches(normalize(text), { (key, value) -> args.add("$key = $value") })
return if (matched) {
args.forEach { calc.eval(it) }
expr().forEach { calc.eval(it) }
Evaluation(calc.value, expr().toList(), calc.variables(), coverage, name)
} else Evaluation(rule = name)
}
} | mit | ec1da4e9c2ce29e1aa2ce9ca221c2ef0 | 41.78481 | 133 | 0.579461 | 4.095758 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/core/src/templates/kotlin/core/windows/templates/User32.kt | 4 | 87633 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package core.windows.templates
import org.lwjgl.generator.*
import core.windows.*
val User32 = "User32".nativeClass(Module.CORE_WINDOWS, nativeSubPath = "windows", binding = simpleBinding(Module.CORE_WINDOWS, "user32")) {
nativeImport("WindowsLWJGL.h")
documentation = "Native bindings to WinUser.h and user32.dll."
IntConstant(
"Window Styles",
"WS_OVERLAPPED"..0x00000000,
"WS_POPUP"..0x80000000.i,
"WS_CHILD"..0x40000000,
"WS_MINIMIZE"..0x20000000,
"WS_VISIBLE"..0x10000000,
"WS_DISABLED"..0x08000000,
"WS_CLIPSIBLINGS"..0x04000000,
"WS_CLIPCHILDREN"..0x02000000,
"WS_MAXIMIZE"..0x01000000,
"WS_CAPTION"..0x00C00000, /* WS_BORDER | WS_DLGFRAME */
"WS_BORDER"..0x00800000,
"WS_DLGFRAME"..0x00400000,
"WS_VSCROLL"..0x00200000,
"WS_HSCROLL"..0x00100000,
"WS_SYSMENU"..0x00080000,
"WS_THICKFRAME"..0x00040000,
"WS_GROUP"..0x00020000,
"WS_TABSTOP"..0x00010000,
"WS_MINIMIZEBOX"..0x00020000,
"WS_MAXIMIZEBOX"..0x00010000,
// Common Window Styles
"WS_OVERLAPPEDWINDOW".."WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX",
"WS_POPUPWINDOW".."WS_POPUP | WS_BORDER | WS_SYSMENU",
"WS_CHILDWINDOW".."WS_CHILD",
"WS_TILED".."WS_OVERLAPPED",
"WS_ICONIC".."WS_MINIMIZE",
"WS_SIZEBOX".."WS_THICKFRAME",
"WS_TILEDWINDOW".."WS_OVERLAPPEDWINDOW"
)
IntConstant(
"Extended Window Styles",
"WS_EX_DLGMODALFRAME"..0x00000001,
"WS_EX_NOPARENTNOTIFY"..0x00000004,
"WS_EX_TOPMOST"..0x00000008,
"WS_EX_ACCEPTFILES"..0x00000010,
"WS_EX_TRANSPARENT"..0x00000020,
"WS_EX_MDICHILD"..0x00000040,
"WS_EX_TOOLWINDOW"..0x00000080,
"WS_EX_WINDOWEDGE"..0x00000100,
"WS_EX_CLIENTEDGE"..0x00000200,
"WS_EX_CONTEXTHELP"..0x00000400,
"WS_EX_RIGHT"..0x00001000,
"WS_EX_LEFT"..0x00000000,
"WS_EX_RTLREADING"..0x00002000,
"WS_EX_LTRREADING"..0x00000000,
"WS_EX_LEFTSCROLLBAR"..0x00004000,
"WS_EX_RIGHTSCROLLBAR"..0x00000000,
"WS_EX_CONTROLPARENT"..0x00010000,
"WS_EX_STATICEDGE"..0x00020000,
"WS_EX_APPWINDOW"..0x00040000,
"WS_EX_OVERLAPPEDWINDOW".."WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE",
"WS_EX_PALETTEWINDOW".."WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST",
"WS_EX_LAYERED"..0x00080000,
"WS_EX_NOINHERITLAYOUT"..0x00100000, // Disable inheritence of mirroring by children
"WS_EX_LAYOUTRTL"..0x00400000, // Right to left mirroring
"WS_EX_COMPOSITED"..0x02000000, // WIN32_WINNT >= 0x0501
"WS_EX_NOACTIVATE"..0x08000000
)
IntConstant(
"May be used in #CreateWindowEx() for the x, y, width, height parameters.",
"CW_USEDEFAULT"..0x80000000.i
)
IntConstant(
"Class styles",
"CS_VREDRAW"..0x0001,
"CS_HREDRAW"..0x0002,
"CS_DBLCLKS"..0x0008,
"CS_OWNDC"..0x0020,
"CS_CLASSDC"..0x0040,
"CS_PARENTDC"..0x0080,
"CS_NOCLOSE"..0x0200,
"CS_SAVEBITS"..0x0800,
"CS_BYTEALIGNCLIENT"..0x1000,
"CS_BYTEALIGNWINDOW"..0x2000,
"CS_GLOBALCLASS"..0x4000,
"CS_IME"..0x00010000,
"CS_DROPSHADOW"..0x00020000 // _WIN32_WINNT >="..0x0501,
)
IntConstant(
"Windows messages.",
"WM_NULL"..0x0000,
"WM_CREATE"..0x0001,
"WM_DESTROY"..0x0002,
"WM_MOVE"..0x0003,
"WM_SIZE"..0x0005,
"WM_ACTIVATE"..0x0006,
"WM_SETFOCUS"..0x0007,
"WM_KILLFOCUS"..0x0008,
"WM_ENABLE"..0x000A,
"WM_SETREDRAW"..0x000B,
"WM_SETTEXT"..0x000C,
"WM_GETTEXT"..0x000D,
"WM_GETTEXTLENGTH"..0x000E,
"WM_PAINT"..0x000F,
"WM_CLOSE"..0x0010,
"WM_QUERYENDSESSION"..0x0011,
"WM_QUERYOPEN"..0x0013,
"WM_ENDSESSION"..0x0016,
"WM_QUIT"..0x0012,
"WM_ERASEBKGND"..0x0014,
"WM_SYSCOLORCHANGE"..0x0015,
"WM_SHOWWINDOW"..0x0018,
"WM_WININICHANGE"..0x001A,
"WM_SETTINGCHANGE".."WM_WININICHANGE",
"WM_DEVMODECHANGE"..0x001B,
"WM_ACTIVATEAPP"..0x001C,
"WM_FONTCHANGE"..0x001D,
"WM_TIMECHANGE"..0x001E,
"WM_CANCELMODE"..0x001F,
"WM_SETCURSOR"..0x0020,
"WM_MOUSEACTIVATE"..0x0021,
"WM_CHILDACTIVATE"..0x0022,
"WM_QUEUESYNC"..0x0023,
"WM_GETMINMAXINFO"..0x0024,
"WM_PAINTICON"..0x0026,
"WM_ICONERASEBKGND"..0x0027,
"WM_NEXTDLGCTL"..0x0028,
"WM_SPOOLERSTATUS"..0x002A,
"WM_DRAWITEM"..0x002B,
"WM_MEASUREITEM"..0x002C,
"WM_DELETEITEM"..0x002D,
"WM_VKEYTOITEM"..0x002E,
"WM_CHARTOITEM"..0x002F,
"WM_SETFONT"..0x0030,
"WM_GETFONT"..0x0031,
"WM_SETHOTKEY"..0x0032,
"WM_GETHOTKEY"..0x0033,
"WM_QUERYDRAGICON"..0x0037,
"WM_COMPAREITEM"..0x0039,
"WM_GETOBJECT"..0x003D,
"WM_COMPACTING"..0x0041,
"WM_COMMNOTIFY"..0x0044,
"WM_WINDOWPOSCHANGING"..0x0046,
"WM_WINDOWPOSCHANGED"..0x0047,
"WM_POWER"..0x0048,
"WM_COPYDATA"..0x004A,
"WM_CANCELJOURNAL"..0x004B,
"WM_NOTIFY"..0x004E,
"WM_INPUTLANGCHANGEREQUEST"..0x0050,
"WM_INPUTLANGCHANGE"..0x0051,
"WM_TCARD"..0x0052,
"WM_HELP"..0x0053,
"WM_USERCHANGED"..0x0054,
"WM_NOTIFYFORMAT"..0x0055,
"WM_CONTEXTMENU"..0x007B,
"WM_STYLECHANGING"..0x007C,
"WM_STYLECHANGED"..0x007D,
"WM_DISPLAYCHANGE"..0x007E,
"WM_GETICON"..0x007F,
"WM_SETICON"..0x0080,
"WM_NCCREATE"..0x0081,
"WM_NCDESTROY"..0x0082,
"WM_NCCALCSIZE"..0x0083,
"WM_NCHITTEST"..0x0084,
"WM_NCPAINT"..0x0085,
"WM_NCACTIVATE"..0x0086,
"WM_GETDLGCODE"..0x0087,
"WM_SYNCPAINT"..0x0088,
"WM_NCMOUSEMOVE"..0x00A0,
"WM_NCLBUTTONDOWN"..0x00A1,
"WM_NCLBUTTONUP"..0x00A2,
"WM_NCLBUTTONDBLCLK"..0x00A3,
"WM_NCRBUTTONDOWN"..0x00A4,
"WM_NCRBUTTONUP"..0x00A5,
"WM_NCRBUTTONDBLCLK"..0x00A6,
"WM_NCMBUTTONDOWN"..0x00A7,
"WM_NCMBUTTONUP"..0x00A8,
"WM_NCMBUTTONDBLCLK"..0x00A9,
"WM_NCXBUTTONDOWN"..0x00AB,
"WM_NCXBUTTONUP"..0x00AC,
"WM_NCXBUTTONDBLCLK"..0x00AD,
// _WIN32_WINNT >= 0x0501
"WM_INPUT_DEVICE_CHANGE"..0x00FE,
"WM_INPUT"..0x00FF,
"WM_KEYFIRST"..0x0100,
"WM_KEYDOWN"..0x0100,
"WM_KEYUP"..0x0101,
"WM_CHAR"..0x0102,
"WM_DEADCHAR"..0x0103,
"WM_SYSKEYDOWN"..0x0104,
"WM_SYSKEYUP"..0x0105,
"WM_SYSCHAR"..0x0106,
"WM_SYSDEADCHAR"..0x0107,
// _WIN32_WINNT >= 0x0501
"WM_UNICHAR"..0x0109,
"UNICODE_NOCHAR"..0xFFFF,
"WM_IME_STARTCOMPOSITION"..0x010D,
"WM_IME_ENDCOMPOSITION"..0x010E,
"WM_IME_COMPOSITION"..0x010F,
"WM_IME_KEYLAST"..0x010F,
"WM_INITDIALOG"..0x0110,
"WM_COMMAND"..0x0111,
"WM_SYSCOMMAND"..0x0112,
"WM_TIMER"..0x0113,
"WM_HSCROLL"..0x0114,
"WM_VSCROLL"..0x0115,
"WM_INITMENU"..0x0116,
"WM_INITMENUPOPUP"..0x0117,
// WINVER >= 0x0601
"WM_GESTURE"..0x0119,
"WM_GESTURENOTIFY"..0x011A,
"WM_MENUSELECT"..0x011F,
"WM_MENUCHAR"..0x0120,
"WM_ENTERIDLE"..0x0121,
"WM_MENURBUTTONUP"..0x0122,
"WM_MENUDRAG"..0x0123,
"WM_MENUGETOBJECT"..0x0124,
"WM_UNINITMENUPOPUP"..0x0125,
"WM_MENUCOMMAND"..0x0126,
"WM_CHANGEUISTATE"..0x0127,
"WM_UPDATEUISTATE"..0x0128,
"WM_QUERYUISTATE"..0x0129,
"WM_CTLCOLORMSGBOX"..0x0132,
"WM_CTLCOLOREDIT"..0x0133,
"WM_CTLCOLORLISTBOX"..0x0134,
"WM_CTLCOLORBTN"..0x0135,
"WM_CTLCOLORDLG"..0x0136,
"WM_CTLCOLORSCROLLBAR"..0x0137,
"WM_CTLCOLORSTATIC"..0x0138,
"MN_GETHMENU"..0x01E1,
"WM_MOUSEFIRST"..0x0200,
"WM_MOUSEMOVE"..0x0200,
"WM_LBUTTONDOWN"..0x0201,
"WM_LBUTTONUP"..0x0202,
"WM_LBUTTONDBLCLK"..0x0203,
"WM_RBUTTONDOWN"..0x0204,
"WM_RBUTTONUP"..0x0205,
"WM_RBUTTONDBLCLK"..0x0206,
"WM_MBUTTONDOWN"..0x0207,
"WM_MBUTTONUP"..0x0208,
"WM_MBUTTONDBLCLK"..0x0209,
"WM_MOUSEWHEEL"..0x020A,
"WM_XBUTTONDOWN"..0x020B,
"WM_XBUTTONUP"..0x020C,
"WM_XBUTTONDBLCLK"..0x020D,
// _WIN32_WINNT >= 0x0600
"WM_MOUSEHWHEEL"..0x020E,
// TODO
/*
#if (_WIN32_WINNT >= 0x0600)
"WM_MOUSELAST"..0x020E,
#elif (_WIN32_WINNT >= 0x0500)
"WM_MOUSELAST"..0x020D,
#elif (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)
"WM_MOUSELAST"..0x020A,
#else
"WM_MOUSELAST"..0x0209,
#endif
*/
"WM_PARENTNOTIFY"..0x0210,
"WM_ENTERMENULOOP"..0x0211,
"WM_EXITMENULOOP"..0x0212,
"WM_NEXTMENU"..0x0213,
"WM_SIZING"..0x0214,
"WM_CAPTURECHANGED"..0x0215,
"WM_MOVING"..0x0216,
"WM_POWERBROADCAST"..0x0218,
"WM_DEVICECHANGE"..0x0219,
"WM_MDICREATE"..0x0220,
"WM_MDIDESTROY"..0x0221,
"WM_MDIACTIVATE"..0x0222,
"WM_MDIRESTORE"..0x0223,
"WM_MDINEXT"..0x0224,
"WM_MDIMAXIMIZE"..0x0225,
"WM_MDITILE"..0x0226,
"WM_MDICASCADE"..0x0227,
"WM_MDIICONARRANGE"..0x0228,
"WM_MDIGETACTIVE"..0x0229,
"WM_MDISETMENU"..0x0230,
"WM_ENTERSIZEMOVE"..0x0231,
"WM_EXITSIZEMOVE"..0x0232,
"WM_DROPFILES"..0x0233,
"WM_MDIREFRESHMENU"..0x0234,
// WINVER >= 0x0601
"WM_TOUCH"..0x0240,
"WM_IME_SETCONTEXT"..0x0281,
"WM_IME_NOTIFY"..0x0282,
"WM_IME_CONTROL"..0x0283,
"WM_IME_COMPOSITIONFULL"..0x0284,
"WM_IME_SELECT"..0x0285,
"WM_IME_CHAR"..0x0286,
"WM_IME_REQUEST"..0x0288,
"WM_IME_KEYDOWN"..0x0290,
"WM_IME_KEYUP"..0x0291,
"WM_MOUSEHOVER"..0x02A1,
"WM_MOUSELEAVE"..0x02A3,
"WM_NCMOUSEHOVER"..0x02A0,
"WM_NCMOUSELEAVE"..0x02A2,
// _WIN32_WINNT >= 0x0501
"WM_WTSSESSION_CHANGE"..0x02B1,
"WM_TABLET_FIRST"..0x02c0,
"WM_TABLET_LAST"..0x02df,
"WM_CUT"..0x0300,
"WM_COPY"..0x0301,
"WM_PASTE"..0x0302,
"WM_CLEAR"..0x0303,
"WM_UNDO"..0x0304,
"WM_RENDERFORMAT"..0x0305,
"WM_RENDERALLFORMATS"..0x0306,
"WM_DESTROYCLIPBOARD"..0x0307,
"WM_DRAWCLIPBOARD"..0x0308,
"WM_PAINTCLIPBOARD"..0x0309,
"WM_VSCROLLCLIPBOARD"..0x030A,
"WM_SIZECLIPBOARD"..0x030B,
"WM_ASKCBFORMATNAME"..0x030C,
"WM_CHANGECBCHAIN"..0x030D,
"WM_HSCROLLCLIPBOARD"..0x030E,
"WM_QUERYNEWPALETTE"..0x030F,
"WM_PALETTEISCHANGING"..0x0310,
"WM_PALETTECHANGED"..0x0311,
"WM_HOTKEY"..0x0312,
"WM_PRINT"..0x0317,
"WM_PRINTCLIENT"..0x0318,
"WM_APPCOMMAND"..0x0319,
// _WIN32_WINNT >= 0x0501
"WM_THEMECHANGED"..0x031A,
"WM_CLIPBOARDUPDATE"..0x031D,
// _WIN32_WINNT >= 0x0600
"WM_DWMCOMPOSITIONCHANGED"..0x031E,
"WM_DWMNCRENDERINGCHANGED"..0x031F,
"WM_DWMCOLORIZATIONCOLORCHANGED"..0x0320,
"WM_DWMWINDOWMAXIMIZEDCHANGE"..0x0321,
"WM_DWMSENDICONICTHUMBNAIL"..0x0323,
"WM_DWMSENDICONICLIVEPREVIEWBITMAP"..0x0326,
"WM_GETTITLEBARINFOEX"..0x033F,
"WM_HANDHELDFIRST"..0x0358,
"WM_HANDHELDLAST"..0x035F,
"WM_AFXFIRST"..0x0360,
"WM_AFXLAST"..0x037F,
"WM_PENWINFIRST"..0x0380,
"WM_PENWINLAST"..0x038F,
"WM_APP"..0x8000,
"WM_USER"..0x0400
)
IntConstant(
"#WM_ACTIVATE message {@code wParam} values.",
"WA_ACTIVE".."1",
"WA_CLICKACTIVE".."2",
"WA_INACTIVE".."0"
)
IntConstant(
"#WM_SIZE message {@code wParam} values.",
"SIZE_RESTORED".."0",
"SIZE_MINIMIZED".."1",
"SIZE_MAXIMIZED".."2",
"SIZE_MAXSHOW".."3",
"SIZE_MAXHIDE".."4"
)
IntConstant(
"#WM_DEVICECHANGE message {@code wParam} params.",
"DBT_APPYBEGIN"..0x0000,
"DBT_APPYEND"..0x0001,
"DBT_DEVNODES_CHANGED"..0x0007,
"DBT_QUERYCHANGECONFIG"..0x0017,
"DBT_CONFIGCHANGED"..0x0018,
"DBT_CONFIGCHANGECANCELED"..0x0019,
"DBT_MONITORCHANGE"..0x001B
)
IntConstant(
"System menu command values.",
"SC_SIZE"..0xF000,
"SC_MOVE"..0xF010,
"SC_MINIMIZE"..0xF020,
"SC_MAXIMIZE"..0xF030,
"SC_NEXTWINDOW"..0xF040,
"SC_PREVWINDOW"..0xF050,
"SC_CLOSE"..0xF060,
"SC_VSCROLL"..0xF070,
"SC_HSCROLL"..0xF080,
"SC_MOUSEMENU"..0xF090,
"SC_KEYMENU"..0xF100,
"SC_ARRANGE"..0xF110,
"SC_RESTORE"..0xF120,
"SC_TASKLIST"..0xF130,
"SC_SCREENSAVE"..0xF140,
"SC_HOTKEY"..0xF150,
"SC_DEFAULT"..0xF160,
"SC_MONITORPOWER"..0xF170,
"SC_CONTEXTHELP"..0xF180,
"SC_SEPARATOR"..0xF00F
)
IntConstant(
"Key state masks for mouse messages.",
"MK_LBUTTON"..0x0001,
"MK_RBUTTON"..0x0002,
"MK_SHIFT"..0x0004,
"MK_CONTROL"..0x0008,
"MK_MBUTTON"..0x0010,
"MK_XBUTTON1"..0x0020,
"MK_XBUTTON2"..0x0040
)
IntConstant(
"Mouse position codes.",
"HTERROR".."-2",
"HTTRANSPARENT".."-1",
"HTNOWHERE".."0",
"HTCLIENT".."1",
"HTCAPTION".."2",
"HTSYSMENU".."3",
"HTGROWBOX".."4",
"HTSIZE".."HTGROWBOX",
"HTMENU".."5",
"HTHSCROLL".."6",
"HTVSCROLL".."7",
"HTMINBUTTON".."8",
"HTMAXBUTTON".."9",
"HTLEFT".."10",
"HTRIGHT".."11",
"HTTOP".."12",
"HTTOPLEFT".."13",
"HTTOPRIGHT".."14",
"HTBOTTOM".."15",
"HTBOTTOMLEFT".."16",
"HTBOTTOMRIGHT".."17",
"HTBORDER".."18",
"HTREDUCE".."HTMINBUTTON",
"HTZOOM".."HTMAXBUTTON",
"HTSIZEFIRST".."HTLEFT",
"HTSIZELAST".."HTBOTTOMRIGHT",
"HTOBJECT".."19",
"HTCLOSE".."20",
"HTHELP".."21"
)
val WindowLongOffsets = IntConstant(
"Window field offsets for #GetWindowLongPtr().",
"GWL_WNDPROC".."-4",
"GWL_HINSTANCE".."-6",
"GWL_HWNDPARENT".."-8",
"GWL_STYLE".."-16",
"GWL_EXSTYLE".."-20",
"GWL_USERDATA".."-21",
"GWL_ID".."-12"
).javaDocLinks
val ShowWindowCommands = IntConstant(
"#ShowWindow() commands.",
"SW_HIDE".."0",
"SW_SHOWNORMAL".."1",
"SW_NORMAL".."1",
"SW_SHOWMINIMIZED".."2",
"SW_SHOWMAXIMIZED".."3",
"SW_MAXIMIZE".."3",
"SW_SHOWNOACTIVATE".."4",
"SW_SHOW".."5",
"SW_MINIMIZE".."6",
"SW_SHOWMINNOACTIVE".."7",
"SW_SHOWNA".."8",
"SW_RESTORE".."9",
"SW_SHOWDEFAULT".."10",
"SW_FORCEMINIMIZE".."11",
"SW_MAX".."11"
).javaDocLinks
val VirtualWindowHandles = LongConstant(
"Virtual window handles used by the #SetWindowPos() insertAfter argument.",
"HWND_TOP"..0L,
"HWND_BOTTOM"..1L,
"HWND_TOPMOST"..-1L,
"HWND_NOTOPMOST"..-2L
).javaDocLinks
LongConstant(
"""
Virtual window handle used by #PostMessage() that matches all top-level windows in the system, including disabled or invisible unowned windows,
overlapped windows, and pop-up windows.
""",
"HWND_BROADCAST"..0xFFFFL
)
val SizePosFlags = IntConstant(
"Window sizing and positiong flags used by the #SetWindowPos() flags argument.",
"SWP_NOSIZE"..0x0001,
"SWP_NOMOVE"..0x0002,
"SWP_NOZORDER"..0x0004,
"SWP_NOREDRAW"..0x0008,
"SWP_NOACTIVATE"..0x0010,
"SWP_FRAMECHANGED"..0x0020, // The frame changed: send WM_NCCALCSIZE
"SWP_SHOWWINDOW"..0x0040,
"SWP_HIDEWINDOW"..0x0080,
"SWP_NOCOPYBITS"..0x0100,
"SWP_NOOWNERZORDER"..0x0200, // Don't do owner Z ordering
"SWP_NOSENDCHANGING"..0x0400, // Don't send WM_WINDOWPOSCHANGING
"SWP_DRAWFRAME".."SWP_FRAMECHANGED",
"SWP_NOREPOSITION".."SWP_NOOWNERZORDER",
"SWP_DEFERERASE"..0x2000,
"SWP_ASYNCWINDOWPOS"..0x4000
).javaDocLinks
val StandardIcons = IntConstant(
"Standard Icon IDs. Use with #LoadIcon().",
"IDI_APPLICATION".."32512",
"IDI_HAND".."32513",
"IDI_QUESTION".."32514",
"IDI_EXCLAMATION".."32515",
"IDI_ASTERISK".."32516",
"IDI_WINLOGO".."32517",
"IDI_SHIELD".."32518", // WINVER >= 0x0600
"IDI_WARNING".."IDI_EXCLAMATION",
"IDI_ERROR".."IDI_HAND",
"IDI_INFORMATION".."IDI_ASTERISK"
).javaDocLinks
val StandardCursors = IntConstant(
"Standard Cursor IDs. Use with #LoadCursor().",
"IDC_ARROW".."32512",
"IDC_IBEAM".."32513",
"IDC_WAIT".."32514",
"IDC_CROSS".."32515",
"IDC_UPARROW".."32516",
"IDC_SIZE".."32640",
"IDC_ICON".."32641",
"IDC_SIZENWSE".."32642",
"IDC_SIZENESW".."32643",
"IDC_SIZEWE".."32644",
"IDC_SIZENS".."32645",
"IDC_SIZEALL".."32646",
"IDC_NO".."32648",
"IDC_HAND".."32649",
"IDC_APPSTARTING".."32650",
"IDC_HELP".."32651"
).javaDocLinks
val ClassLongOffsets = IntConstant(
"Class field offsets for #GetClassLongPtr().",
"GCL_MENUNAME".."-8",
"GCL_HBRBACKGROUND".."-10",
"GCL_HCURSOR".."-12",
"GCL_HICON".."-14",
"GCL_HMODULE".."-16",
"GCL_CBWNDEXTRA".."-18",
"GCL_CBCLSEXTRA".."-20",
"GCL_WNDPROC".."-24",
"GCL_STYLE".."-26",
"GCW_ATOM".."-32",
"GCL_HICONSM".."-34"
).javaDocLinks
IntConstant(
"Queue status flags for {@code GetQueueStatus} and {@code MsgWaitForMultipleObjects}",
"QS_KEY"..0x0001,
"QS_MOUSEMOVE"..0x0002,
"QS_MOUSEBUTTON"..0x0004,
"QS_POSTMESSAGE"..0x0008,
"QS_TIMER"..0x0010,
"QS_PAINT"..0x0020,
"QS_SENDMESSAGE"..0x0040,
"QS_HOTKEY"..0x0080,
"QS_ALLPOSTMESSAGE"..0x0100,
"QS_RAWINPUT"..0x0400, // _WIN32_WINNT >= 0x0501
"QS_MOUSE".."QS_MOUSEMOVE | QS_MOUSEBUTTON",
"QS_INPUT".."QS_MOUSE | QS_KEY", // TODO: Add | QS_RAWINPUT if _WIN32_WINNT >= 0x0501
"QS_ALLEVENTS".."QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY",
"QS_ALLINPUT".."QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY | QS_SENDMESSAGE"
)
IntConstant(
"Remove message flags for #PeekMessage().",
"PM_NOREMOVE"..0x0000,
"PM_REMOVE"..0x0001,
"PM_NOYIELD"..0x0002,
"PM_QS_INPUT".."QS_INPUT << 16",
"PM_QS_POSTMESSAGE".."(QS_POSTMESSAGE | QS_HOTKEY | QS_TIMER) << 16",
"PM_QS_PAINT".."QS_PAINT << 16",
"PM_QS_SENDMESSAGE".."QS_SENDMESSAGE << 16"
)
IntConstant(
"Virtual Keys.",
"VK_LBUTTON"..0x01,
"VK_RBUTTON"..0x02,
"VK_CANCEL"..0x03,
"VK_MBUTTON"..0x04,
"VK_XBUTTON1"..0x05,
"VK_XBUTTON2"..0x06,
"VK_BACK"..0x08,
"VK_TAB"..0x09,
"VK_CLEAR"..0x0C,
"VK_RETURN"..0x0D,
"VK_SHIFT"..0x10,
"VK_CONTROL"..0x11,
"VK_MENU"..0x12,
"VK_PAUSE"..0x13,
"VK_CAPITAL"..0x14,
"VK_KANA"..0x15,
"VK_HANGEUL"..0x15,
"VK_HANGUL"..0x15,
"VK_JUNJA"..0x17,
"VK_FINAL"..0x18,
"VK_HANJA"..0x19,
"VK_KANJI"..0x19,
"VK_ESCAPE"..0x1B,
"VK_CONVERT"..0x1C,
"VK_NONCONVERT"..0x1D,
"VK_ACCEPT"..0x1E,
"VK_MODECHANGE"..0x1F,
"VK_SPACE"..0x20,
"VK_PRIOR"..0x21,
"VK_NEXT"..0x22,
"VK_END"..0x23,
"VK_HOME"..0x24,
"VK_LEFT"..0x25,
"VK_UP"..0x26,
"VK_RIGHT"..0x27,
"VK_DOWN"..0x28,
"VK_SELECT"..0x29,
"VK_PRINT"..0x2A,
"VK_EXECUTE"..0x2B,
"VK_SNAPSHOT"..0x2C,
"VK_INSERT"..0x2D,
"VK_DELETE"..0x2E,
"VK_HELP"..0x2F,
"VK_LWIN"..0x5B,
"VK_RWIN"..0x5C,
"VK_APPS"..0x5D,
"VK_SLEEP"..0x5F,
"VK_NUMPAD0"..0x60,
"VK_NUMPAD1"..0x61,
"VK_NUMPAD2"..0x62,
"VK_NUMPAD3"..0x63,
"VK_NUMPAD4"..0x64,
"VK_NUMPAD5"..0x65,
"VK_NUMPAD6"..0x66,
"VK_NUMPAD7"..0x67,
"VK_NUMPAD8"..0x68,
"VK_NUMPAD9"..0x69,
"VK_MULTIPLY"..0x6A,
"VK_ADD"..0x6B,
"VK_SEPARATOR"..0x6C,
"VK_SUBTRACT"..0x6D,
"VK_DECIMAL"..0x6E,
"VK_DIVIDE"..0x6F,
"VK_F1"..0x70,
"VK_F2"..0x71,
"VK_F3"..0x72,
"VK_F4"..0x73,
"VK_F5"..0x74,
"VK_F6"..0x75,
"VK_F7"..0x76,
"VK_F8"..0x77,
"VK_F9"..0x78,
"VK_F10"..0x79,
"VK_F11"..0x7A,
"VK_F12"..0x7B,
"VK_F13"..0x7C,
"VK_F14"..0x7D,
"VK_F15"..0x7E,
"VK_F16"..0x7F,
"VK_F17"..0x80,
"VK_F18"..0x81,
"VK_F19"..0x82,
"VK_F20"..0x83,
"VK_F21"..0x84,
"VK_F22"..0x85,
"VK_F23"..0x86,
"VK_F24"..0x87,
"VK_NUMLOCK"..0x90,
"VK_SCROLL"..0x91,
"VK_OEM_NEC_EQUAL"..0x92,
"VK_OEM_FJ_JISHO"..0x92,
"VK_OEM_FJ_MASSHOU"..0x93,
"VK_OEM_FJ_TOUROKU"..0x94,
"VK_OEM_FJ_LOYA"..0x95,
"VK_OEM_FJ_ROYA"..0x96,
"VK_LSHIFT"..0xA0,
"VK_RSHIFT"..0xA1,
"VK_LCONTROL"..0xA2,
"VK_RCONTROL"..0xA3,
"VK_LMENU"..0xA4,
"VK_RMENU"..0xA5,
"VK_BROWSER_BACK"..0xA6,
"VK_BROWSER_FORWARD"..0xA7,
"VK_BROWSER_REFRESH"..0xA8,
"VK_BROWSER_STOP"..0xA9,
"VK_BROWSER_SEARCH"..0xAA,
"VK_BROWSER_FAVORITES"..0xAB,
"VK_BROWSER_HOME"..0xAC,
"VK_VOLUME_MUTE"..0xAD,
"VK_VOLUME_DOWN"..0xAE,
"VK_VOLUME_UP"..0xAF,
"VK_MEDIA_NEXT_TRACK"..0xB0,
"VK_MEDIA_PREV_TRACK"..0xB1,
"VK_MEDIA_STOP"..0xB2,
"VK_MEDIA_PLAY_PAUSE"..0xB3,
"VK_LAUNCH_MAIL"..0xB4,
"VK_LAUNCH_MEDIA_SELECT"..0xB5,
"VK_LAUNCH_APP1"..0xB6,
"VK_LAUNCH_APP2"..0xB7,
"VK_OEM_1"..0xBA,
"VK_OEM_PLUS"..0xBB,
"VK_OEM_COMMA"..0xBC,
"VK_OEM_MINUS"..0xBD,
"VK_OEM_PERIOD"..0xBE,
"VK_OEM_2"..0xBF,
"VK_OEM_3"..0xC0,
"VK_OEM_4"..0xDB,
"VK_OEM_5"..0xDC,
"VK_OEM_6"..0xDD,
"VK_OEM_7"..0xDE,
"VK_OEM_8"..0xDF,
"VK_OEM_AX"..0xE1,
"VK_OEM_102"..0xE2,
"VK_ICO_HELP"..0xE3,
"VK_ICO_00"..0xE4,
"VK_PROCESSKEY"..0xE5,
"VK_ICO_CLEAR"..0xE6,
"VK_PACKET"..0xE7,
"VK_OEM_RESET"..0xE9,
"VK_OEM_JUMP"..0xEA,
"VK_OEM_PA1"..0xEB,
"VK_OEM_PA2"..0xEC,
"VK_OEM_PA3"..0xED,
"VK_OEM_WSCTRL"..0xEE,
"VK_OEM_CUSEL"..0xEF,
"VK_OEM_ATTN"..0xF0,
"VK_OEM_FINISH"..0xF1,
"VK_OEM_COPY"..0xF2,
"VK_OEM_AUTO"..0xF3,
"VK_OEM_ENLW"..0xF4,
"VK_OEM_BACKTAB"..0xF5,
"VK_ATTN"..0xF6,
"VK_CRSEL"..0xF7,
"VK_EXSEL"..0xF8,
"VK_EREOF"..0xF9,
"VK_PLAY"..0xFA,
"VK_ZOOM"..0xFB,
"VK_NONAME"..0xFC,
"VK_PA1"..0xFD,
"VK_OEM_CLEAR"..0xFE
)
IntConstant(
"XButton values.",
"XBUTTON1"..0x0001,
"XBUTTON2"..0x0002
)
IntConstant(
"Value for rolling one detent.",
"WHEEL_DELTA".."120"
)
EnumConstant(
"Identifies the dots per inch (dpi) setting for a thread, process, or window. ({@code DPI_AWARENESS})",
"DPI_AWARENESS_INVALID".enum(
"""
Invalid DPI awareness.
This is an invalid DPI awareness value.
""",
"-1"
),
"DPI_AWARENESS_UNAWARE".enum(
"""
DPI unaware.
This process does not scale for DPI changes and is always assumed to have a scale factor of 100% (96 DPI). It will be automatically scaled by the
system on any other DPI setting.
""",
"0"
),
"DPI_AWARENESS_SYSTEM_AWARE".enum(
"""
System DPI aware.
This process does not scale for DPI changes. It will query for the DPI once and use that value for the lifetime of the process. If the DPI changes,
the process will not adjust to the new DPI value. It will be automatically scaled up or down by the system when the DPI changes from the system
value.
""",
"1"
),
"DPI_AWARENESS_PER_MONITOR_AWARE".enum(
"""
Per monitor DPI aware.
This process checks for the DPI when it is created and adjusts the scale factor whenever the DPI changes. These processes are not automatically
scaled by the system.
""",
"2"
)
)
LongConstant(
"""
DPI unaware.
This window does not scale for DPI changes and is always assumed to have a scale factor of 100% (96 DPI). It will be automatically scaled by the system
on any other DPI setting.
""",
"DPI_AWARENESS_CONTEXT_UNAWARE".."-1L"
)
LongConstant(
"""
System DPI aware.
This window does not scale for DPI changes. It will query for the DPI once and use that value for the lifetime of the process. If the DPI changes, the
process will not adjust to the new DPI value. It will be automatically scaled up or down by the system when the DPI changes from the system value.
""",
"DPI_AWARENESS_CONTEXT_SYSTEM_AWARE".."-2L"
)
LongConstant(
"""
Per monitor DPI aware.
This window checks for the DPI when it is created and adjusts the scale factor whenever the DPI changes. These processes are not automatically scaled
by the system.
""",
"DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE".."-3L"
)
LongConstant(
"""
Also known as Per Monitor v2.
An advancement over the original per-monitor DPI awareness mode, which enables applications to access new DPI-related scaling behaviors on a per
top-level window basis.
Per Monitor v2 was made available in the Creators Update of Windows 10, and is not available on earlier versions of the operating system.
The additional behaviors introduced are as follows:
${ul(
"Child window DPI change notifications - In Per Monitor v2 contexts, the entire window tree is notified of any DPI changes that occur.",
"""
Scaling of non-client area - All windows will automatically have their non-client area drawn in a DPI sensitive fashion. Calls to
{@code EnableNonClientDpiScaling} are unnecessary.
""",
"Scaling of Win32 menus - All {@code NTUSER} menus created in Per Monitor v2 contexts will be scaling in a per-monitor fashion.",
"Dialog Scaling - Win32 dialogs created in Per Monitor v2 contexts will automatically respond to DPI changes.",
"Improved scaling of {@code comctl32} controls - Various {@code comctl32} controls have improved DPI scaling behavior in Per Monitor v2 contexts.",
"""
Improved theming behavior - {@code UxTheme} handles opened in the context of a Per Monitor v2 window will operate in terms of the DPI associated
with that window.
"""
)}
""",
"DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2".."-4L"
)
NativeName("RegisterClassExW")..SaveLastError..ATOM(
"RegisterClassEx",
"Registers a window class for subsequent use in calls to the #CreateWindowEx() function.",
WNDCLASSEX.const.p(
"lpwcx",
"a ##WNDCLASSEX structure. You must fill the structure with the appropriate class attributes before passing it to the function."
)
)
NativeName("UnregisterClassW")..SaveLastError..BOOL(
"UnregisterClass",
"Unregisters a window class, freeing the memory required for the class.",
LPCTSTR(
"lpClassName",
"""
a null-terminated string or a class atom. If {@code lpClassName} is a string, it specifies the window class name. This class name must have been
registered by a previous call to the #RegisterClassEx() function. System classes, such as dialog box controls, cannot be unregistered. If this
parameter is an atom, it must be a class atom created by a previous call to the #RegisterClassEx() function. The atom must be in the low-order
word of {@code lpClassName}; the high-order word must be zero.
"""
),
nullable..HINSTANCE("hInstance", "a handle to the instance of the module that created the class")
)
NativeName("CreateWindowExW")..SaveLastError..HWND(
"CreateWindowEx",
"Creates an overlapped, pop-up, or child window with an extended window style; otherwise, this function is identical to the CreateWindow function.",
DWORD("dwExStyle", "the extended window style of the window being created"),
nullable..LPCTSTR(
"lpClassName",
"a null-terminated string or a class atom created by a previous call to the #RegisterClassEx(WNDCLASSEX) function."
),
nullable..LPCTSTR(
"lpWindowName",
"the window name. If the window style specifies a title bar, the window title pointed to by {@code lpWindowName} is displayed in the title bar."
),
DWORD("dwStyle", "the style of the window being created"),
int("x", "the initial horizontal position of the window"),
int("y", "the initial vertical position of the window"),
int("nWidth", "the width, in device units, of the window"),
int("nHeight", "the height, in device units, of the window"),
nullable..HWND(
"hWndParent",
"a handle to the parent or owner window of the window being created. To create a child window or an owned window, supply a valid window handle."
),
nullable..HMENU("hMenu", "a handle to a menu, or specifies a child-window identifier, depending on the window style"),
nullable..HINSTANCE("hInstance", "a handle to the instance of the module to be associated with the window"),
nullable..LPVOID(
"lpParam",
"""
a value to be passed to the window through the {@code CREATESTRUCT} structure ({@code createParams} member) pointed to by the {@code lParam} param
of the #WM_CREATE message.
"""
)
)
SaveLastError..BOOL(
"DestroyWindow",
"""
Destroys the specified window. The function sends #WM_DESTROY and #WM_NCDESTROY messages to the window to deactivate it and remove the keyboard focus
from it. The function also destroys the window's menu, flushes the thread message queue, destroys timers, removes clipboard ownership, and breaks the
clipboard viewer chain (if the window is at the top of the viewer chain).
If the specified window is a parent or owner window, DestroyWindow automatically destroys the associated child or owned windows when it destroys the
parent or owner window. The function first destroys child or owned windows, and then it destroys the parent or owner window.
""",
HWND("hWnd", "a handle to the window to be destroyed")
)
NativeName("DefWindowProcW")..LRESULT(
"DefWindowProc",
"""
Calls the default window procedure to provide default processing for any window messages that an application does not process. This function ensures
that every message is processed. DefWindowProc is called with the same parameters received by the window procedure.
""",
HWND("hWnd", "a handle to the window that received the message"),
UINT("Msg", "the message"),
WPARAM("wParam", "additional message information. The content of this parameter depends on the value of the {@code Msg} parameter."),
LPARAM("lParam", "additional message information. The content of this parameter depends on the value of the {@code Msg} parameter.")
)
NativeName("CallWindowProcW")..LRESULT(
"CallWindowProc",
"Passes message information to the specified window procedure.",
WNDPROC(
"lpPrevWndFunc",
"""
the previous window procedure.
If this value is obtained by calling the #GetWindowLongPtr() function with the {@code nIndex} parameter set to #GWL_WNDPROC or {@code DWL_DLGPROC},
it is actually either the address of a window or dialog box procedure, or a special internal value meaningful only to {@code CallWindowProc}.
"""
),
HWND("hWnd", "a handle to the window procedure to receive the message"),
UINT("Msg", "the message"),
WPARAM("wParam", "additional message information. The content of this parameter depends on the value of the {@code Msg} parameter."),
LPARAM("lParam", "additional message information. The content of this parameter depends on the value of the {@code Msg} parameter.")
)
BOOL(
"ShowWindow",
"Sets the specified window's show state.",
HWND("hWnd", "a handle to the window"),
int(
"nCmdShow",
"""
controls how the window is to be shown. This parameter is ignored the first time an application calls {@code ShowWindow}, if the program that
launched the application provides a {@code STARTUPINFO} structure. Otherwise, the first time {@code ShowWindow} is called, the value should be the
value obtained by the {@code WinMain} function in its {@code nCmdShow} parameter. In subsequent calls, this parameter can be
""",
ShowWindowCommands, LinkMode.SINGLE_CNT
)
)
BOOL(
"UpdateWindow",
"""
Updates the client area of the specified window by sending a #WM_PAINT message to the window if the window's update region is not empty. The function
sends a #WM_PAINT message directly to the window procedure of the specified window, bypassing the application queue. If the update region is empty, no
message is sent.
""",
HWND("hWnd", "handle to the window to be updated")
)
SaveLastError..BOOL(
"SetWindowPos",
"""
Changes the size, position, and Z order of a child, pop-up, or top-level window. These windows are ordered according to their appearance on the screen.
The topmost window receives the highest rank and is the first window in the Z order.
""",
HWND("hWnd", "a handle to the window"),
nullable..HWND(
"hWndInsertAfter",
"a handle to the window to precede the positioned window in the Z order. This parameter must be a window handle or",
VirtualWindowHandles, LinkMode.SINGLE_CNT
),
int("X", "the new position of the left side of the window, in client coordinates"),
int("Y", "the new position of the top of the window, in client coordinates"),
int("cx", "the new width of the window, in pixels"),
int("cy", "the new height of the window, in pixels"),
UINT("uFlags", "the window sizing and positioning flags", SizePosFlags, LinkMode.BITFIELD)
)
NativeName("SetWindowTextW")..SaveLastError..BOOL(
"SetWindowText",
"""
Changes the text of the specified window's title bar (if it has one). If the specified window is a control, the text of the control is changed.
However, {@code SetWindowText} cannot change the text of a control in another application.
""",
HWND("hWnd", "a handle to the window or control whose text is to be changed"),
LPCTSTR("lpString", "the new title or control text")
)
val GetMessage = NativeName("GetMessageW")..SaveLastError..BOOL(
"GetMessage",
"""
Retrieves a message from the calling thread's message queue. The function dispatches incoming sent messages until a posted message is available for
retrieval. Unlike GetMessage, the #PeekMessage() function does not wait for a message to be posted before returning.
""",
LPMSG("lpMsg", "a pointer to an ##MSG structure that receives message information from the thread's message queue"),
nullable..HWND(
"hWnd",
"""
a handle to the window whose messages are to be retrieved. The window must belong to the current thread.
If {@code hWnd} is #NULL, {@code GetMessage} retrieves messages for any window that belongs to the current thread, and any messages on the current
thread's message queue whose {@code hwnd} value is #NULL (see the ##MSG structure). Therefore if {@code hWnd} is #NULL, both window messages and
thread messages are processed.
If {@code hWnd} is -1, {@code GetMessage} retrieves only messages on the current thread's message queue whose {@code hwnd} value is #NULL, that is,
thread messages as posted by #PostMessage() (when the {@code hWnd} parameter is #NULL) or {@code PostThreadMessage}.
"""
),
UINT("wMsgFilterMin", "the integer value of the lowest message value to be retrieved"),
UINT("wMsgFilterMax", "the integer value of the highest message value to be retrieved")
)
NativeName("PeekMessageW")..BOOL(
"PeekMessage",
"Dispatches incoming sent messages, checks the thread message queue for a posted message, and retrieves the message (if any exist).",
LPMSG("lpMsg", "a pointer to an ##MSG structure that receives message information"),
GetMessage["hWnd"],
GetMessage["wMsgFilterMin"],
GetMessage["wMsgFilterMax"],
UINT("wRemoveMsg", "specifies how messages are to be handled.", "#PM_NOREMOVE #PM_REMOVE #PM_NOYIELD")
)
BOOL(
"TranslateMessage",
"""
Translates virtual-key messages into character messages. The character messages are posted to the calling thread's message queue, to be read the next
time the thread calls the #GetMessage() or #PeekMessage() function.
""",
MSG.const.p(
"lpMsg",
"""
an ##MSG structure that contains message information retrieved from the calling thread's message queue by using the #GetMessage() or #PeekMessage()
function.
"""
)
)
SaveLastError..BOOL(
"WaitMessage",
"""
Yields control to other threads when a thread has no other messages in its message queue. The WaitMessage function suspends the thread and does not
return until a new message is placed in the thread's message queue.
""",
void()
)
NativeName("DispatchMessageW")..LRESULT(
"DispatchMessage",
"Dispatches a message to a window procedure. It is typically used to dispatch a message retrieved by the #GetMessage() function.",
MSG.const.p("lpmsg", "a pointer to a structure that contains the message.")
)
NativeName("PostMessageW")..SaveLastError..BOOL(
"PostMessage",
"""
Places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread
to process the message.
""",
nullable..HWND(
"hWnd",
"""
a handle to the window whose window procedure is to receive the message. The following values have special meanings:
${ul(
"""
#HWND_BROADCAST - The message is posted to all top-level windows in the system, including disabled or invisible unowned windows, overlapped
windows, and pop-up windows. The message is not posted to child windows.
""",
"#NULL - The function behaves like a call to PostThreadMessage with the dwThreadId parameter set to the identifier of the current thread."
)}
"""
),
UINT("Msg", "the message to be posted"),
WPARAM("wParam", "additional message-specific information"),
LPARAM("lParam", "additional message-specific information")
)
NativeName("SendMessageW")..SaveLastError..BOOL(
"SendMessage",
"""
Sends the specified message to a window or windows. The {@code SendMessage} function calls the window procedure for the specified window and does not
return until the window procedure has processed the message.
""",
HWND(
"hWnd",
"""
a handle to the window whose window procedure will receive the message. If this parameter is #HWND_BROADCAST, the message is sent to all top-level
windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows; but the message is not sent to
child windows.
Message sending is subject to UIPI. The thread of a process can send messages only to message queues of threads in processes of lesser or equal
integrity level.
"""
),
UINT("Msg", "the message to be sent"),
WPARAM("wParam", "additional message-specific information"),
LPARAM("lParam", "additional message-specific information")
)
SaveLastError..BOOL(
"AdjustWindowRectEx",
"""
Calculates the required size of the window rectangle, based on the desired size of the client rectangle. The window rectangle can then be passed to the
#CreateWindowEx() function to create a window whose client area is the desired size.
""",
LPRECT(
"lpRect",
"""
a pointer to a ##RECT structure that contains the coordinates of the top-left and bottom-right corners of the desired client area. When the
function returns, the structure contains the coordinates of the top-left and bottom-right corners of the window to accommodate the desired client
area.
"""
),
DWORD("dwStyle", "the window style of the window whose required size is to be calculated. Note that you cannot specify the #WS_OVERLAPPED style."),
BOOL("bMenu", "indicates whether the window has a menu"),
DWORD("dwExStyle", "the extended window style of the window whose required size is to be calculated")
)
SaveLastError..BOOL(
"GetWindowRect",
"""
Retrieves the dimensions of the bounding rectangle of the specified window. The dimensions are given in screen coordinates that are relative to the
upper-left corner of the screen.
""",
HWND("hWnd", "a handle to the window"),
LPRECT("lpRect", "a pointer to a ##RECT structure that receives the screen coordinates of the upper-left and lower-right corners of the window")
)
SaveLastError..BOOL(
"MoveWindow",
"""
Changes the position and dimensions of the specified window. For a top-level window, the position and dimensions are relative to the upper-left corner
of the screen. For a child window, they are relative to the upper-left corner of the parent window's client area.
""",
HWND("hWnd", "a handle to the window"),
int("X", "the new position of the left side of the window"),
int("Y", "the new position of the top of the window"),
int("nWidth", "the new width of the window"),
int("nHeight", "the new height of the window"),
BOOL(
"bRepaint",
"""
indicates whether the window is to be repainted. If this parameter is TRUE, the window receives a message. If the parameter is FALSE, no repainting
of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent
window uncovered as a result of moving a child window.
"""
)
)
IntConstant(
"##WINDOWPLACEMENT flags.",
"WPF_SETMINPOSITION"..0x0001,
"WPF_RESTORETOMAXIMIZED"..0x0002,
"WPF_ASYNCWINDOWPLACEMENT"..0x0004
)
SaveLastError..BOOL(
"GetWindowPlacement",
"Retrieves the show state and the restored, minimized, and maximized positions of the specified window.",
HWND("hWnd", "a handle to the window"),
Input..WINDOWPLACEMENT.p(
"lpwndpl",
"""
a pointer to the ##WINDOWPLACEMENT structure that receives the show state and position information.
Before calling {@code GetWindowPlacement}, set the length member to WINDOWPLACEMENT#SIZEOF. {@code GetWindowPlacement} fails if
{@code lpwndpl->length} is not set correctly.
"""
)
)
SaveLastError..BOOL(
"SetWindowPlacement",
"Sets the show state and the restored, minimized, and maximized positions of the specified window.",
HWND("hWnd", "a handle to the window"),
WINDOWPLACEMENT.const.p(
"lpwndpl",
"""
a pointer to the ##WINDOWPLACEMENT structure that specifies the new show state and window positions.
Before calling {@code SetWindowPlacement}, set the {@code length} member of the {@code WINDOWPLACEMENT} structure to WINDOWPLACEMENT#SIZEOF.
{@code SetWindowPlacement} fails if the length member is not set correctly.
"""
)
)
BOOL(
"IsWindowVisible",
"Determines the visibility state of the specified window.",
HWND("hWnd", "a handle to the window to be tested")
)
BOOL(
"IsIconic",
"Determines whether the specified window is minimized (iconic).",
HWND("hWnd", "a handle to the window to be tested")
)
BOOL(
"IsZoomed",
"Determines whether a window is maximized.",
HWND("hWnd", "a handle to the window to be tested")
)
BOOL(
"BringWindowToTop",
"""
Brings the specified window to the top of the Z order. If the window is a top-level window, it is activated. If the window is a child window, the
top-level parent window associated with the child window is activated.
""",
HWND("hWnd", "a handle to the window to bring to the top of the Z order")
)
NativeName("Pointer.BITS64 ? \"SetWindowLongPtrW\" : \"SetWindowLongW\"")..SaveLastError..LONG_PTR(
"SetWindowLongPtr",
"Changes an attribute of the specified window. The function also sets a value at the specified offset in the extra window memory.",
HWND("hWnd", "a handle to the window and, indirectly, the class to which the window belongs"),
int(
"nIndex",
"""
the zero-based offset to the value to be set. Valid values are in the range zero through the number of bytes of extra window memory, minus the size
of an integer. To set any other value, specify
""",
WindowLongOffsets, LinkMode.SINGLE_CNT
),
LONG_PTR("dwNewLong", "the replacement value"),
returnDoc = "the previous value at the given {@code index}"
)
NativeName("Pointer.BITS64 ? \"GetWindowLongPtrW\" : \"GetWindowLongW\"")..SaveLastError..LONG_PTR(
"GetWindowLongPtr",
"Retrieves information about the specified window. The function also retrieves the value at a specified offset into the extra window memory.",
HWND("hWnd", "a handle to the window and, indirectly, the class to which the window belongs"),
int(
"nIndex",
"""
the zero-based offset to the value to be set. Valid values are in the range zero through the number of bytes of extra window memory, minus the size
of an integer. To set any other value, specify
""",
WindowLongOffsets, LinkMode.SINGLE_CNT
)
)
NativeName("Pointer.BITS64 ? \"SetClassLongPtrW\" : \"SetClassLongW\"")..SaveLastError..LONG_PTR(
"SetClassLongPtr",
"""
Replaces the specified value at the specified offset in the extra class memory or the ##WNDCLASSEX structure for the class to which the specified
window belongs.
""",
HWND("hWnd", "a handle to the window and, indirectly, the class to which the window belongs"),
int(
"nIndex",
"""
the value to be replaced. To set a value in the extra class memory, specify the positive, zero-based byte offset of the value to be set. Valid
values are in the range zero through the number of bytes of extra class memory, minus eight; for example, if you specified 24 or more bytes of
extra class memory, a value of 16 would be an index to the third integer. To set a value other than the ##WNDCLASSEX structure, specify
""",
ClassLongOffsets, LinkMode.SINGLE_CNT
),
LONG_PTR("dwNewLong", "the replacement value"),
returnDoc =
"""
if the function succeeds, the return value is the previous value of the specified offset. If this was not previously set, the return value is zero.
If the function fails, the return value is zero. To get extended error information, call #getLastError().
"""
)
NativeName("Pointer.BITS64 ? \"GetClassLongPtrW\" : \"GetClassLongW\"")..SaveLastError..LONG_PTR(
"GetClassLongPtr",
"Retrieves the specified value from the ##WNDCLASSEX structure associated with the specified window.",
HWND("hWnd", "a handle to the window and, indirectly, the class to which the window belongs"),
int(
"nIndex",
"""
the value to be retrieved. To retrieve a value from the extra class memory, specify the positive, zero-based byte offset of the value to be
retrieved. Valid values are in the range zero through the number of bytes of extra class memory, minus eight; for example, if you specified 24 or
more bytes of extra class memory, a value of 16 would be an index to the third integer. To retrieve any other value from the ##WNDCLASSEX
structure, specify
""",
ClassLongOffsets, LinkMode.SINGLE_CNT
)
)
IntConstant(
"Actions for #SetLayeredWindowAttributes().",
"LWA_COLORKEY"..0x00000001,
"LWA_ALPHA"..0x00000002
)
SaveLastError..BOOL(
"SetLayeredWindowAttributes",
"",
HWND(
"hwnd",
"""
a handle to the layered window. A layered window is created by specifying #WS_EX_LAYERED when creating the window with the #CreateWindowEx()
function or by setting #WS_EX_LAYERED via #SetWindowLongPtr() after the window has been created.
"""
),
COLORREF(
"crKey",
"""
the transparency color key (0x00bbggrr) to be used when composing the layered window. All pixels painted by the window in this color will be
transparent.
"""
),
BYTE(
"bAlpha",
"""
the alpha value used to describe the opacity of the layered window. When {@code bAlpha} is 0, the window is completely transparent. When
{@code bAlpha} is 255, the window is opaque.
"""
),
DWORD("dwFlags", "an action to be taken", "#LWA_COLORKEY #LWA_ALPHA", LinkMode.BITFIELD)
)
NativeName("LoadIconW")..SaveLastError..HICON(
"LoadIcon",
"Loads the specified icon resource from the executable (.exe) file associated with an application instance.",
nullable..HINSTANCE(
"instance",
"""
a handle to an instance of the module whose executable file contains the icon to be loaded. This parameter must be #NULL when a standard icon is
being loaded.
"""
),
LPCTSTR("iconName", "the name of the icon resource to be loaded or", StandardIcons, LinkMode.SINGLE_CNT)
)
NativeName("LoadCursorW")..SaveLastError..HCURSOR(
"LoadCursor",
"Loads the specified cursor resource from the executable (.EXE) file associated with an application instance.",
nullable..HINSTANCE("instance", "a handle to an instance of the module whose executable file contains the cursor to be loaded."),
LPCTSTR("cursorName", "the name of the cursor resource to be loaded or", StandardCursors, LinkMode.SINGLE_CNT)
)
HDC(
"GetDC",
"""
Retrieves a handle to a device context (DC) for the client area of a specified window or for the entire screen. You can use the returned handle in
subsequent GDI functions to draw in the DC. The device context is an opaque data structure, whose values are used internally by GDI.
""",
nullable..HWND("hWnd", "a handle to the window whose DC is to be retrieved. If this value is #NULL, GetDC retrieves the DC for the entire screen.")
)
BOOL(
"ReleaseDC",
"""
Releases a device context (DC), freeing it for use by other applications. The effect of the ReleaseDC function depends on the type of DC. It frees only
common and window DCs. It has no effect on class or private DCs.
""",
HWND("hWnd", "a handle to the window whose DC is to be released"),
HDC("hDC", "a handle to the DC to be released")
)
val SystemMetrics = IntConstant(
"#GetSystemMetrics() codes.",
"SM_CXSCREEN".."0",
"SM_CYSCREEN".."1",
"SM_CXVSCROLL".."2",
"SM_CYHSCROLL".."3",
"SM_CYCAPTION".."4",
"SM_CXBORDER".."5",
"SM_CYBORDER".."6",
"SM_CXDLGFRAME".."7",
"SM_CYDLGFRAME".."8",
"SM_CYVTHUMB".."9",
"SM_CXHTHUMB".."10",
"SM_CXICON".."11",
"SM_CYICON".."12",
"SM_CXCURSOR".."13",
"SM_CYCURSOR".."14",
"SM_CYMENU".."15",
"SM_CXFULLSCREEN".."16",
"SM_CYFULLSCREEN".."17",
"SM_CYKANJIWINDOW".."18",
"SM_MOUSEPRESENT".."19",
"SM_CYVSCROLL".."20",
"SM_CXHSCROLL".."21",
"SM_DEBUG".."22",
"SM_SWAPBUTTON".."23",
"SM_RESERVED1".."24",
"SM_RESERVED2".."25",
"SM_RESERVED3".."26",
"SM_RESERVED4".."27",
"SM_CXMIN".."28",
"SM_CYMIN".."29",
"SM_CXSIZE".."30",
"SM_CYSIZE".."31",
"SM_CXFRAME".."32",
"SM_CYFRAME".."33",
"SM_CXMINTRACK".."34",
"SM_CYMINTRACK".."35",
"SM_CXDOUBLECLK".."36",
"SM_CYDOUBLECLK".."37",
"SM_CXICONSPACING".."38",
"SM_CYICONSPACING".."39",
"SM_MENUDROPALIGNMENT".."40",
"SM_PENWINDOWS".."41",
"SM_DBCSENABLED".."42",
"SM_CMOUSEBUTTONS".."43",
"SM_CXFIXEDFRAME".."SM_CXDLGFRAME",
"SM_CYFIXEDFRAME".."SM_CYDLGFRAME",
"SM_CXSIZEFRAME".."SM_CXFRAME",
"SM_CYSIZEFRAME".."SM_CYFRAME",
"SM_SECURE".."44",
"SM_CXEDGE".."45",
"SM_CYEDGE".."46",
"SM_CXMINSPACING".."47",
"SM_CYMINSPACING".."48",
"SM_CXSMICON".."49",
"SM_CYSMICON".."50",
"SM_CYSMCAPTION".."51",
"SM_CXSMSIZE".."52",
"SM_CYSMSIZE".."53",
"SM_CXMENUSIZE".."54",
"SM_CYMENUSIZE".."55",
"SM_ARRANGE".."56",
"SM_CXMINIMIZED".."57",
"SM_CYMINIMIZED".."58",
"SM_CXMAXTRACK".."59",
"SM_CYMAXTRACK".."60",
"SM_CXMAXIMIZED".."61",
"SM_CYMAXIMIZED".."62",
"SM_NETWORK".."63",
"SM_CLEANBOOT".."67",
"SM_CXDRAG".."68",
"SM_CYDRAG".."69",
"SM_SHOWSOUNDS".."70",
"SM_CXMENUCHECK".."71",
"SM_CYMENUCHECK".."72",
"SM_SLOWMACHINE".."73",
"SM_MIDEASTENABLED".."74",
"SM_MOUSEWHEELPRESENT".."75",
"SM_XVIRTUALSCREEN".."76",
"SM_YVIRTUALSCREEN".."77",
"SM_CXVIRTUALSCREEN".."78",
"SM_CYVIRTUALSCREEN".."79",
"SM_CMONITORS".."80",
"SM_SAMEDISPLAYFORMAT".."81",
"SM_IMMENABLED".."82",
"SM_REMOTESESSION"..0x1000,
// _WIN32_WINNT >= 0x0501
"SM_SHUTTINGDOWN"..0x2000,
"SM_REMOTECONTROL"..0x2001,
"SM_CARETBLINKINGENABLED"..0x2002,
"SM_CXFOCUSBORDER".."83",
"SM_CYFOCUSBORDER".."84",
"SM_TABLETPC".."86",
"SM_MEDIACENTER".."87",
"SM_STARTER".."88",
"SM_SERVERR2".."89",
// _WIN32_WINNT >= 0x0600
"SM_MOUSEHORIZONTALWHEELPRESENT".."91",
"SM_CXPADDEDBORDER".."92",
// WINVER >= 0x0601
"SM_DIGITIZER".."94",
"SM_MAXIMUMTOUCHES".."95"
).javaDocLinks
int(
"GetSystemMetrics",
"Retrieves the specified system metric or system configuration setting.",
int("index", "the system metric or configuration setting to be retrieved", SystemMetrics)
)
val TouchFlags = IntConstant(
"#RegisterTouchWindow() flags.",
"TWF_FINETOUCH"..0x00000001,
"TWF_WANTPALM"..0x00000002
).javaDocLinks
IntConstant(
"Touch input flag values (TOUCHINPUT#dwFlags()).",
"TOUCHEVENTF_MOVE"..0x0001,
"TOUCHEVENTF_DOWN"..0x0002,
"TOUCHEVENTF_UP"..0x0004,
"TOUCHEVENTF_INRANGE"..0x0008,
"TOUCHEVENTF_PRIMARY"..0x0010,
"TOUCHEVENTF_NOCOALESCE"..0x0020,
"TOUCHEVENTF_PEN"..0x0040,
"TOUCHEVENTF_PALM"..0x0080
)
IntConstant(
"Touch input mask values (TOUCHINPUT#dwMask()).",
"TOUCHINPUTMASKF_TIMEFROMSYSTEM"..0x0001,
"TOUCHINPUTMASKF_EXTRAINFO"..0x0002,
"TOUCHINPUTMASKF_CONTACTAREA"..0x0004
)
IgnoreMissing..SaveLastError..BOOL(
"RegisterTouchWindow",
"""
Registers a window as being touch-capable.
{@code RegisterTouchWindow} must be called on every window that will be used for touch input. This means that if you have an application that has
multiple windows within it, {@code RegisterTouchWindow} must be called on every window in that application that uses touch features. Also, an
application can call {@code RegisterTouchWindow} any number of times for the same window if it desires to change the modifier flags. A window can be
marked as no longer requiring touch input using the #UnregisterTouchWindow() function.
""",
HWND(
"hWnd",
"""
the handle of the window being registered. The function fails with {@code ERROR_ACCESS_DENIED} if the calling thread does not own the specified
window.
"""
),
ULONG(
"ulFlags",
"a set of bit flags that specify optional modifications. This field may contain 0 or",
TouchFlags, LinkMode.BITFIELD_CNT
),
since = "Windows 7 (desktop apps only)"
)
IgnoreMissing..SaveLastError..BOOL(
"UnregisterTouchWindow",
"Registers a window as no longer being touch-capable.",
HWND(
"hWnd",
"the handle of the window. The function fails with {@code ERROR_ACCESS_DENIED} if the calling thread does not own the specified window."
),
since = "Windows 7 (desktop apps only)"
)
IgnoreMissing..BOOL(
"IsTouchWindow",
"Checks whether a specified window is touch-capable and, optionally, retrieves the modifier flags set for the window's touch capability.",
HWND(
"hWnd",
"""
the handle of the window. The function fails with {@code ERROR_ACCESS_DENIED} if the calling thread is not on the same desktop as the specified
window.
"""
),
Check(1)..nullable..PULONG(
"pulFlags",
"an optional address of the {@code ULONG} variable to receive the modifier flags for the specified window's touch capability."
),
since = "Windows 7 (desktop apps only)"
)
IgnoreMissing..SaveLastError..BOOL(
"GetTouchInputInfo",
"Retrieves detailed information about touch inputs associated with a particular touch input handle.",
HTOUCHINPUT(
"hTouchInput",
"""
the touch input handle received in the {@code LPARAM} of a touch message. The function fails with {@code ERROR_INVALID_HANDLE} if this handle is
not valid. Note that the handle is not valid after it has been used in a successful call to #CloseTouchInputHandle() or after it has been passed to
#DefWindowProc(), #PostMessage(), #SendMessage() or one of their variants.
"""
),
AutoSize("pInputs")..UINT(
"cInputs",
"""
The number of structures in the {@code pInputs} array. This should ideally be at least equal to the number of touch points associated with the
message as indicated in the message {@code WPARAM}. If {@code cInputs} is less than the number of touch points, the function will still succeed and
populate the {@code pInputs} buffer with information about {@code cInputs} touch points.
"""
),
PTOUCHINPUT(
"pInputs",
"a pointer to an array of ##TOUCHINPUT structures to receive information about the touch points associated with the specified touch input handle"
),
int(
"cbSize",
"""
the size, in bytes, of a single ##TOUCHINPUT structure. If {@code cbSize} is not the size of a single {@code TOUCHINPUT} structure, the function
fails with {@code ERROR_INVALID_PARAMETER}.
"""
),
since = "Windows 7 (desktop apps only)"
)
IgnoreMissing..SaveLastError..BOOL(
"CloseTouchInputHandle",
"Closes a touch input handle, frees process memory associated with it, and invalidates the handle.",
HTOUCHINPUT(
"hTouchInput",
"""
the touch input handle received in the {@code LPARAM} of a touch message. The function fails with {@code ERROR_INVALID_HANDLE} if this handle is
not valid. Note that the handle is not valid after it has been used in a successful call to #CloseTouchInputHandle() or after it has been passed to
#DefWindowProc(), #PostMessage(), #SendMessage() or one of their variants.
"""
),
since = "Windows 7 (desktop apps only)"
)
val MonitorFromWindowFlags = IntConstant(
"#MonitorFromWindow() flags.",
"MONITOR_DEFAULTTONULL"..0x00000000,
"MONITOR_DEFAULTTOPRIMARY"..0x00000001,
"MONITOR_DEFAULTTONEAREST"..0x00000002
).javaDocLinks
HMONITOR(
"MonitorFromWindow",
"Retrieves a handle to the display monitor that has the largest area of intersection with the bounding rectangle of a specified window.",
HWND("hWnd", "a handle to the window of interest"),
DWORD("dwFlags", "determines the function's return value if the window does not intersect any display monitor", MonitorFromWindowFlags)
)
IntConstant(
"##MONITORINFOEX flags.",
"MONITORINFOF_PRIMARY"..0x00000001
)
NativeName("GetMonitorInfoW")..BOOL(
"GetMonitorInfo",
"Retrieves information about a display monitor.",
HMONITOR("hMonitor", "a handle to the display monitor of interest"),
LPMONITORINFOEX(
"lpmi",
"""
a pointer to a ##MONITORINFOEX structure that receives information about the specified display monitor.
You must set the {@code cbSize} member of the structure to MONITORINFOEX#SIZEOF before calling the {@code GetMonitorInfo} function. Doing so lets
the function determine the type of structure you are passing to it.
"""
)
)
IntConstant(
"Flag for #EnumDisplayDevices().",
"EDD_GET_DEVICE_INTERFACE_NAME"..0x00000001
)
val EnumDisplaySettingsMode = IntConstant(
"#EnumDisplaySettingsEx() mode.",
"ENUM_CURRENT_SETTINGS".."-1",
"ENUM_REGISTRY_SETTINGS".."-2"
).javaDocLinks
val EnumDisplaySettingsFlags = IntConstant(
"Flags for #EnumDisplaySettingsEx().",
"EDS_RAWMODE"..0x00000002,
"EDS_ROTATEDMODE"..0x00000004
).javaDocLinks
val ChangeDisplaySettingsFlags = IntConstant(
"Flags for #ChangeDisplaySettingsEx().",
"CDS_UPDATEREGISTRY"..0x00000001,
"CDS_TEST"..0x00000002,
"CDS_FULLSCREEN"..0x00000004,
"CDS_GLOBAL"..0x00000008,
"CDS_SET_PRIMARY"..0x00000010,
"CDS_VIDEOPARAMETERS"..0x00000020,
"CDS_ENABLE_UNSAFE_MODES"..0x00000100, // WINVER >= 0x0600
"CDS_DISABLE_UNSAFE_MODES"..0x00000200, // WINVER >= 0x0600
"CDS_RESET"..0x40000000,
"CDS_RESET_EX"..0x20000000,
"CDS_NORESET"..0x10000000
).javaDocLinks
val ChangeDisplaySettingsResults = IntConstant(
"Return values for #ChangeDisplaySettingsEx().",
"DISP_CHANGE_SUCCESSFUL".."0",
"DISP_CHANGE_RESTART".."1",
"DISP_CHANGE_FAILED".."-1",
"DISP_CHANGE_BADMODE".."-2",
"DISP_CHANGE_NOTUPDATED".."-3",
"DISP_CHANGE_BADFLAGS".."-4",
"DISP_CHANGE_BADPARAM".."-5",
"DISP_CHANGE_BADDUALVIEW".."-6" // _WIN32_WINNT >= 0x0501
).javaDocLinks
NativeName("EnumDisplayDevicesW")..BOOL(
"EnumDisplayDevices",
"Obtains information about the display devices in the current session.",
nullable..LPCTSTR(
"lpDevice",
"the device name. If #NULL, function returns information for the display adapter(s) on the machine, based on {@code devNum}."
),
DWORD(
"iDevNum",
"""
an index value that specifies the display device of interest.
The operating system identifies each display device in the current session with an index value. The index values are consecutive integers, starting
at 0. If the current session has three display devices, for example, they are specified by the index values 0, 1, and 2.
"""
),
PDISPLAY_DEVICE(
"lpDisplayDevice",
"""
a pointer to a ##DISPLAY_DEVICE structure that receives information about the display device specified by {@code iDevNum}.
Before calling {@code EnumDisplayDevices}, you must initialize the {@code cb} member of {@code DISPLAY_DEVICE} to the size, in bytes, of
{@code DISPLAY_DEVICE}.
"""
),
DWORD(
"dwFlags",
"""
set this flag to #EDD_GET_DEVICE_INTERFACE_NAME to retrieve the device interface name for {@code GUID_DEVINTERFACE_MONITOR}, which is registered by
the operating system on a per monitor basis. The value is placed in the {@code DeviceID} member of the ##DISPLAY_DEVICE structure returned in
{@code lpDisplayDevice}. The resulting device interface name can be used with SetupAPI functions and serves as a link between GDI monitor devices
and SetupAPI monitor devices.
"""
)
)
NativeName("EnumDisplaySettingsExW")..BOOL(
"EnumDisplaySettingsEx",
"""
Retrieves information about one of the graphics modes for a display device. To retrieve information for all the graphics modes for a display device,
make a series of calls to this function.
""",
nullable..LPCTSTR(
"lpszDeviceName",
"""
a pointer to a null-terminated string that specifies the display device about which graphics mode the function will obtain information.
This parameter is either #NULL or a DISPLAY_DEVICE#DeviceName() returned from #EnumDisplayDevices(). A #NULL value specifies the current display
device on the computer that the calling thread is running on.
"""
),
DWORD(
"iModeNum",
"""
indicates the type of information to be retrieved.
Graphics mode indexes start at zero. To obtain information for all of a display device's graphics modes, make a series of calls to
{@code EnumDisplaySettingsEx}, as follows: Set {@code iModeNum} to zero for the first call, and increment {@code iModeNum} by one for each
subsequent call. Continue calling the function until the return value is zero.
When you call {@code EnumDisplaySettingsEx} with {@code iModeNum} set to zero, the operating system initializes and caches information about the
display device. When you call {@code EnumDisplaySettingsEx} with {@code iModeNum} set to a nonzero value, the function returns the information that
was cached the last time the function was called with {@code iModeNum} set to zero.
This value can be a graphics mode index or
""",
EnumDisplaySettingsMode,
LinkMode.SINGLE_CNT
),
DEVMODE.p(
"lpDevMode",
"""
a pointer to a ##DEVMODE structure into which the function stores information about the specified graphics mode. Before calling
{@code EnumDisplaySettingsEx}, set the {@code dmSize} member to DEVMODE#SIZEOF, and set the {@code dmDriverExtra} member to indicate the size, in
bytes, of the additional space available to receive private driver data.
The {@code EnumDisplaySettingsEx} function will populate the {@code dmFields} member of the {@code lpDevMode} and one or more other members of the
{@code DEVMODE} structure. To determine which members were set by the call to {@code EnumDisplaySettingsEx}, inspect the {@code dmFields} bitmask.
"""
),
DWORD("dwFlags", "this parameter can be", EnumDisplaySettingsFlags, LinkMode.SINGLE_CNT)
)
NativeName("ChangeDisplaySettingsExW")..LONG(
"ChangeDisplaySettingsEx",
"Changes the settings of the specified display device to the specified graphics mode.",
nullable..LPCTSTR(
"lpszDeviceName",
"""
a pointer to a null-terminated string that specifies the display device whose graphics mode will change. Only display device names as returned by
#EnumDisplayDevices() are valid.
The {@code lpszDeviceName} parameter can be #NULL. A #NULL value specifies the default display device. The default device can be determined by
calling {@code EnumDisplayDevices} and checking for the #DISPLAY_DEVICE_PRIMARY_DEVICE flag.
"""
),
nullable..DEVMODE.p(
"lpDevMode",
"""
a pointer to a ##DEVMODE structure that describes the new graphics mode. If {@code lpDevMode} is #NULL, all the values currently in the registry
will be used for the display setting. Passing #NULL for the {@code lpDevMode} parameter and 0 for the {@code dwFlags} parameter is the easiest way
to return to the default mode after a dynamic mode change.
The {@code dmSize} member must be initialized to the size, in bytes, of the {@code DEVMODE} structure. The {@code dmDriverExtra} member must be
initialized to indicate the number of bytes of private driver data following the {@code DEVMODE} structure.
"""
),
nullable..HWND("hwnd", "reserved; must be #NULL"),
DWORD("dwflags", "indicates how the graphics mode should be changed", ChangeDisplaySettingsFlags),
nullable..LPVOID(
"lParam",
"""
if {@code flags} is #CDS_VIDEOPARAMETERS, {@code lParam} is a pointer to a {@code VIDEOPARAMETERS} structure. Otherwise {@code lParam} must be #NULL.
"""
),
returnDoc = "one of the following values: $ChangeDisplaySettingsResults"
)
BOOL(
"GetCursorPos",
"Retrieves the position of the mouse cursor, in screen coordinates.",
LPPOINT("point", "a pointer to a {@link POINT} structure that receives the screen coordinates of the cursor")
)
BOOL(
"SetCursorPos",
"""
Moves the cursor to the specified screen coordinates. If the new coordinates are not within the screen rectangle set by the most recent #ClipCursor()
function call, the system automatically adjusts the coordinates so that the cursor stays within the rectangle.
""",
int("X", "the new x-coordinate of the cursor, in screen coordinates."),
int("Y", "the new y-coordinate of the cursor, in screen coordinates.")
)
BOOL(
"ClipCursor",
"""
Confines the cursor to a rectangular area on the screen. If a subsequent cursor position (set by the #SetCursorPos() function or the mouse) lies
outside the rectangle, the system automatically adjusts the position to keep the cursor inside the rectangular area.
""",
nullable..RECT.const.p(
"rect",
"""
a pointer to the structure that contains the screen coordinates of the upper-left and lower-right corners of the confining rectangle. If this
parameter is #NULL, the cursor is free to move anywhere on the screen.
"""
)
)
int(
"ShowCursor",
"""
Displays or hides the cursor.
This function sets an internal display counter that determines whether the cursor should be displayed. The cursor is displayed only if the display
count is greater than or equal to 0. If a mouse is installed, the initial display count is 0. If no mouse is installed, the display count is –1.
""",
BOOL(
"show",
"If {@code show} is #TRUE, the display count is incremented by one. If {@code show} is #FALSE, the display count is decremented by one."
),
returnDoc = "the new display counter"
)
HCURSOR(
"SetCursor",
"""
Sets the cursor shape.
The cursor is set only if the new cursor is different from the previous cursor; otherwise, the function returns immediately.
The cursor is a shared resource. A window should set the cursor shape only when the cursor is in its client area or when the window is capturing mouse
input. In systems without a mouse, the window should restore the previous cursor before the cursor leaves the client area or before it relinquishes
control to another window.
If your application must set the cursor while it is in a window, make sure the class cursor for the specified window's class is set to #NULL. If the
class cursor is not #NULL, the system restores the class cursor each time the mouse is moved.
The cursor is not shown on the screen if the internal cursor display count is less than zero. This occurs if the application uses the #ShowCursor()
function to hide the cursor more times than to show the cursor.
""",
nullable..HCURSOR(
"hCursor",
"""
a handle to the cursor. The cursor must have been created by the {@code CreateCursor} function or loaded by the #LoadCursor() or {@code LoadImage}
function. If this parameter is #NULL, the cursor is removed from the screen.
"""
),
returnDoc = "the handle to the previous cursor, if there was one"
)
BOOL(
"ClientToScreen",
"""
Converts the client-area coordinates of a specified point to screen coordinates.
The {@code ClientToScreen} function replaces the client-area coordinates in the ##POINT structure with the screen coordinates. The screen coordinates
are relative to the upper-left corner of the screen. Note, a screen-coordinate point that is above the window's client area has a negative
y-coordinate. Similarly, a screen coordinate to the left of a client area has a negative x-coordinate.
All coordinates are device coordinates.
""",
HWND("hWnd", "a handle to the window whose client area is used for the conversion"),
LPPOINT(
"lpPoint",
"""
a pointer to a {@code POINT} structure that contains the client coordinates to be converted. The new screen coordinates are copied into this
structure if the function succeeds.
"""
)
)
SHORT(
"GetAsyncKeyState",
"""
Determines whether a key is up or down at the time the function is called, and whether the key was pressed after a previous call to
{@code GetAsyncKeyState}.
The {@code GetAsyncKeyState} function works with mouse buttons. However, it checks on the state of the physical mouse buttons, not on the logical mouse
buttons that the physical buttons are mapped to. For example, the call {@code GetAsyncKeyState(VK_LBUTTON)} always returns the state of the left
physical mouse button, regardless of whether it is mapped to the left or right logical mouse button. You can determine the system's current mapping of
physical mouse buttons to logical mouse buttons by calling {@code GetSystemMetrics(SM_SWAPBUTTON)} which returns #TRUE if the mouse buttons have been
swapped.
Although the least significant bit of the return value indicates whether the key has been pressed since the last query, due to the pre-emptive
multitasking nature of Windows, another application can call {@code GetAsyncKeyState} and receive the "recently pressed" bit instead of your
application. The behavior of the least significant bit of the return value is retained strictly for compatibility with 16-bit Windows applications
(which are non-preemptive) and should not be relied upon.
You can use the virtual-key code constants #VK_SHIFT, #VK_CONTROL, and #VK_MENU as values for the {@code vKey} parameter. This gives the state of the
SHIFT, CTRL, or ALT keys without distinguishing between left and right.
""",
int("vKey", "the virtual-key code. You can use left- and right-distinguishing constants to specify certain keys."),
returnDoc =
"""
if the function succeeds, the return value specifies whether the key was pressed since the last call to {@code GetAsyncKeyState}, and whether the key
is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the
previous call to {@code GetAsyncKeyState}. However, you should not rely on this last behavior; for more information, see the Remarks.
The return value is zero for the following cases:
${ul(
"The current desktop is not the active desktop",
"The foreground thread belongs to another process and the desktop does not allow the hook or the journal record."
)}
"""
)
IntConstant(
"The type of input event.",
"INPUT_MOUSE".."0",
"INPUT_KEYBOARD".."1",
"INPUT_HARDWARE".."2"
)
IntConstant(
"##MOUSEINPUT flags.",
"MOUSEEVENTF_ABSOLUTE"..0x8000,
"MOUSEEVENTF_HWHEEL"..0x01000,
"MOUSEEVENTF_MOVE"..0x0001,
"MOUSEEVENTF_MOVE_NOCOALESCE"..0x2000,
"MOUSEEVENTF_LEFTDOWN"..0x0002,
"MOUSEEVENTF_LEFTUP"..0x0004,
"MOUSEEVENTF_RIGHTDOWN"..0x0008,
"MOUSEEVENTF_RIGHTUP"..0x0010,
"MOUSEEVENTF_MIDDLEDOWN"..0x0020,
"MOUSEEVENTF_MIDDLEUP"..0x0040,
"MOUSEEVENTF_VIRTUALDESK"..0x4000,
"MOUSEEVENTF_WHEEL"..0x0800,
"MOUSEEVENTF_XDOWN"..0x0080,
"MOUSEEVENTF_XUP"..0x0100
)
IntConstant(
"##KEYBDINPUT flags.",
"KEYEVENTF_EXTENDEDKEY"..0x0001,
"KEYEVENTF_KEYUP"..0x0002,
"KEYEVENTF_SCANCODE"..0x0008,
"KEYEVENTF_UNICODE"..0x0004
)
LPARAM(
"GetMessageExtraInfo",
"""
Retrieves the extra message information for the current thread.
Extra message information is an application- or driver-defined value associated with the current thread's message queue.
""",
returnDoc = "the extra information. The meaning of the extra information is device specific."
)
UINT(
"SendInput",
"""
Synthesizes keystrokes, mouse motions, and button clicks.
This function is subject to UIPI. Applications are permitted to inject input only into applications that are at an equal or lesser integrity level.
The {@code SendInput} function inserts the events in the ##INPUT structures serially into the keyboard or mouse input stream. These events are not
interspersed with other keyboard or mouse input events inserted either by the user (with the keyboard or mouse) or by calls to {@code keybd_event},
{@code mouse_event}, or other calls to {@code SendInput}.
This function does not reset the keyboard's current state. Any keys that are already pressed when the function is called might interfere with the
events that this function generates. To avoid this problem, check the keyboard's state with the #GetAsyncKeyState() function and correct as necessary.
Because the touch keyboard uses the surrogate macros defined in {@code winnls.h} to send input to the system, a listener on the keyboard event hook
must decode input originating from the touch keyboard.
An accessibility application can use {@code SendInput} to inject keystrokes corresponding to application launch shortcut keys that are handled by the
shell. This functionality is not guaranteed to work for other types of applications.
""",
AutoSize("pInputs")..UINT("cInputs", "the number of structures in the {@code pInputs} array"),
LPINPUT("pInputs", "an array of {@code INPUT} structures. Each structure represents an event to be inserted into the keyboard or mouse input stream."),
int(
"cbSize",
"the size, in bytes, of an {@code INPUT} structure. If {@code cbSiz}e is not the size of an {@code INPUT} structure, the function fails."
),
returnDoc =
"""
the number of events that it successfully inserted into the keyboard or mouse input stream. If the function returns zero, the input was already blocked
by another thread. To get extended error information, call #GetLastError().
This function fails when it is blocked by UIPI. Note that neither GetLastError nor the return value will indicate the failure was caused by UIPI
blocking.
"""
)
IgnoreMissing..UINT(
"GetDpiForSystem",
"""
Returns the system DPI.
The return value will be dependent based upon the calling context. If the current thread has a {@code DPI_AWARENESS} value of #DPI_AWARENESS_UNAWARE,
the return value will be 96. That is because the current context always assumes a DPI of 96. For any other {@code DPI_AWARENESS} value, the return
value will be the actual system DPI.
You should not cache the system DPI, but should use {@code GetDpiForSystem} whenever you need the system DPI value.
""",
returnDoc = "the system DPI value",
since = "Windows 10"
)
IgnoreMissing..UINT(
"GetDpiForWindow",
"Returns the dots per inch (dpi) value for the associated window.",
HWND("hwnd", "the window you want to get information about"),
returnDoc =
"the DPI for the window which depends on the {@code DPI_AWARENESS} of the window. An invalid {@code hwnd} value will result in a return value of 0.",
since = "Windows 10"
)
IgnoreMissing.."DPI_AWARENESS".enumType(
"GetAwarenessFromDpiAwarenessContext",
"Retrieves the {@code DPI_AWARENESS} value from a {@code DPI_AWARENESS_CONTEXT}.",
DPI_AWARENESS_CONTEXT("value", "the {@code DPI_AWARENESS_CONTEXT} you want to examine"),
returnDoc = "the {@code DPI_AWARENESS}. If the provided value is null or invalid, this method will return #DPI_AWARENESS_INVALID.",
since = "Windows 10"
)
IgnoreMissing..DPI_AWARENESS_CONTEXT(
"GetThreadDpiAwarenessContext",
"""
Gets the {@code DPI_AWARENESS_CONTEXT} for the current thread.
If #SetThreadDpiAwarenessContext() was never called for this thread, then the return value will equal the default {@code DPI_AWARENESS_CONTEXT} for the
process.
""",
returnDoc = "the current {@code DPI_AWARENESS_CONTEXT} for the thread.",
since = "Windows 10"
)
IgnoreMissing..DPI_AWARENESS_CONTEXT(
"GetWindowDpiAwarenessContext",
"Returns the {@code DPI_AWARENESS_CONTEXT} associated with a window.",
HWND("hwnd", "the window to query"),
returnDoc = "the {@code DPI_AWARENESS_CONTEXT} for the provided window. If the window is not valid, the return value is #NULL.",
since = "Windows 10"
)
IgnoreMissing..BOOL(
"IsValidDpiAwarenessContext",
"Determines if a specified {@code DPI_AWARENESS_CONTEXT} is valid and supported by the current system.",
nullable..DPI_AWARENESS_CONTEXT("value", "the context that you want to determine if it is supported"),
returnDoc = "#TRUE if the provided context is supported, otherwise #FALSE",
since = "Windows 10"
)
IgnoreMissing..DPI_AWARENESS_CONTEXT(
"SetThreadDpiAwarenessContext",
"Set the DPI awareness for the current thread to the provided value.",
DPI_AWARENESS_CONTEXT("dpiContext", "the DPI awareness value to set"),
returnDoc =
"""
The old {@code DPI_AWARENESS_CONTEXT} for the thread. If the {@code dpiContext} is invalid, the thread will not be updated and the return value will be
#NULL. You can use this value to restore the old {@code DPI_AWARENESS_CONTEXT} after overriding it with a predefined value.
""",
since = "Windows 10"
)
} | bsd-3-clause | 67da8da84158fa30c1ace31275508dde | 37.740937 | 161 | 0.605254 | 3.920675 | false | false | false | false |
Frederikam/FredBoat | FredBoat/src/main/java/fredboat/sentinel/guildCache.kt | 1 | 5788 | package fredboat.sentinel
import com.fredboat.sentinel.SentinelExchanges
import com.fredboat.sentinel.entities.GuildSubscribeRequest
import com.google.common.cache.CacheBuilder
import fredboat.audio.lavalink.SentinelLavalink
import fredboat.config.property.AppConfig
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.reactive.awaitFirstOrNull
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import java.time.Duration
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
@Service
class GuildCache(private val sentinel: Sentinel,
private val appConfig: AppConfig,
private val lavalink: SentinelLavalink) {
init {
@Suppress("LeakingThis")
INSTANCE = this
}
companion object {
lateinit var INSTANCE: GuildCache
private val log: Logger = LoggerFactory.getLogger(GuildCache::class.java)
}
@Autowired
/* Cyclic dependency */
lateinit var rabbitConsumer: RabbitConsumer
val cache = ConcurrentHashMap<Long, InternalGuild>()
/** Non-finished requests. Acts as a debounce */
private val requestCache = CacheBuilder.newBuilder()
.expireAfterWrite(1, TimeUnit.MINUTES) // Just as a precaution
.build<Long, Mono<Guild?>>()!!
/**
* @param id the ID of the guild
* @param textChannelInvoked optionally the ID of the text channel used,
* in case we need to warn the user of long loading times
* @param skipCache if we should skip the cache and potentially resubscribe
*/
fun get(
id: Long,
textChannelInvoked: Long? = null,
skipCache: Boolean = false
): Mono<Guild?> {
if (!skipCache) {
cache[id]?.let { return Mono.just(it) }
// If a request is already created and not finished, return that instead
requestCache.getIfPresent(id)?.let { return it }
}
val startTime = System.currentTimeMillis()
val mono = sentinel.genericMonoSendAndReceive<RawGuild?, Guild?>(
SentinelExchanges.REQUESTS,
sentinel.tracker.getKey(calculateShardId(id)),
GuildSubscribeRequest(id, channelInvoked = textChannelInvoked),
mayBeEmpty = true,
transform = {
transform(startTime, it)
})
.timeout(Duration.ofSeconds(30), Mono.error(TimeoutException("Timed out while subscribing to $id")))
.doFinally {
requestCache.invalidate(id)
}
requestCache.put(id, mono)
return mono
}
private fun transform(startTime: Long, it: RawGuild?): InternalGuild? {
if (it == null) return null
val timeTakenReceive = System.currentTimeMillis() - startTime
val g = InternalGuild(it)
cache[g.id] = g
val timeTakenParse = System.currentTimeMillis() - startTime - timeTakenReceive
val timeTaken = timeTakenReceive + timeTakenParse
log.info("Subscribing to {} took {}ms including {}ms parsing time.\nMembers: {}\nChannels: {}\nRoles: {}\n",
g,
timeTaken,
timeTakenParse,
g.members.size,
g.textChannels.size + g.voiceChannels.size,
g.roles.size
)
// Asynchronously handle existing VSU from an older FredBoat session, if it exists
it.voiceServerUpdate?.let { vsu ->
GlobalScope.launch {
val channelId = g.selfMember.voiceChannel?.idString
val link = lavalink.getLink(g)
if (channelId == null) {
log.warn("Received voice server update during guild subscribe, but we are not in a channel." +
"This should not happen. Disconnecting...")
link.queueAudioDisconnect()
return@launch
}
link.setChannel(channelId)
rabbitConsumer.receive(vsu)
/*
// This code is an excellent way to test expired voice server updates
val json = JSONObject(vsu.raw)
json.put("token", "asd")
rabbitConsumer.receive(VoiceServerUpdate(vsu.sessionId, json.toString()))
*/
}
}
return g
}
fun getIfCached(id: Long): Guild? = cache[id]
private fun calculateShardId(guildId: Long): Int = ((guildId shr 22) % appConfig.shardCount.toLong()).toInt()
}
/**
* @param id the ID of the guild
* @param textChannelInvoked optionally the ID of the text channel used,
* in case we need to warn the user of long loading times
*/
suspend fun getGuild(id: Long, textChannelInvoked: Long? = null) = GuildCache.INSTANCE.get(id, textChannelInvoked)
.awaitFirstOrNull()
/**
* @param id the ID of the guild
* @param textChannelInvoked optionally the ID of the text channel used,
* in case we need to warn the user of long loading times
*/
fun getGuildMono(id: Long, textChannelInvoked: Long? = null) = GuildCache.INSTANCE.get(id, textChannelInvoked)
/**
* @param id the ID of the guild
* @param textChannelInvoked optionally the ID of the text channel used,
* in case we need to warn the user of long loading times
*/
fun getGuild(id: Long, textChannelInvoked: Long? = null, callback: (Guild) -> Unit) {
GuildCache.INSTANCE.get(id, textChannelInvoked).subscribe { callback(it!!) }
}
| mit | aac53f290ec5c0e8db40411b437464d2 | 36.341935 | 116 | 0.635971 | 4.671509 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToSafeAccessInspection.kt | 2 | 6789 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.branchedTransformations
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.*
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.refactoring.rename.KotlinVariableInplaceRenameHandler
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getType
class IfThenToSafeAccessInspection @JvmOverloads constructor(private val inlineWithPrompt: Boolean = true) :
AbstractApplicabilityBasedInspection<KtIfExpression>(KtIfExpression::class.java) {
override fun isApplicable(element: KtIfExpression): Boolean = isApplicableTo(element, expressionShouldBeStable = true)
override fun inspectionHighlightRangeInElement(element: KtIfExpression) = element.fromIfKeywordToRightParenthesisTextRangeInThis()
override fun inspectionText(element: KtIfExpression) = KotlinBundle.message("foldable.if.then")
override fun inspectionHighlightType(element: KtIfExpression): ProblemHighlightType =
if (element.shouldBeTransformed()) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION
override val defaultFixText get() = KotlinBundle.message("simplify.foldable.if.then")
override fun fixText(element: KtIfExpression): String = fixTextFor(element)
override val startFixInWriteAction = false
override fun applyTo(element: KtIfExpression, project: Project, editor: Editor?) {
convert(element, editor, inlineWithPrompt)
}
companion object {
@Nls
fun fixTextFor(element: KtIfExpression): String {
val ifThenToSelectData = element.buildSelectTransformationData()
return if (ifThenToSelectData?.baseClauseEvaluatesToReceiver() == true) {
if (ifThenToSelectData.condition is KtIsExpression) {
KotlinBundle.message("replace.if.expression.with.safe.cast.expression")
} else {
KotlinBundle.message("remove.redundant.if.expression")
}
} else {
KotlinBundle.message("replace.if.expression.with.safe.access.expression")
}
}
fun convert(ifExpression: KtIfExpression, editor: Editor?, inlineWithPrompt: Boolean) {
val ifThenToSelectData = ifExpression.buildSelectTransformationData() ?: return
val factory = KtPsiFactory(ifExpression)
val resultExpr = runWriteAction {
val replacedBaseClause = ifThenToSelectData.replacedBaseClause(factory)
val newExpr = ifExpression.replaced(replacedBaseClause)
KtPsiUtil.deparenthesize(newExpr)
}
if (editor != null && resultExpr is KtSafeQualifiedExpression) {
resultExpr.inlineReceiverIfApplicable(editor, inlineWithPrompt)
resultExpr.renameLetParameter(editor)
}
}
fun isApplicableTo(element: KtIfExpression, expressionShouldBeStable: Boolean): Boolean {
val ifThenToSelectData = element.buildSelectTransformationData() ?: return false
if (expressionShouldBeStable &&
!ifThenToSelectData.receiverExpression.isStableSimpleExpression(ifThenToSelectData.context)
) return false
return ifThenToSelectData.clausesReplaceableBySafeCall()
}
internal fun KtSafeQualifiedExpression.renameLetParameter(editor: Editor) {
val callExpression = selectorExpression as? KtCallExpression ?: return
if (callExpression.calleeExpression?.text != "let") return
val parameter = callExpression.lambdaArguments.singleOrNull()?.getLambdaExpression()?.valueParameters?.singleOrNull() ?: return
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document)
editor.caretModel.moveToOffset(parameter.startOffset)
KotlinVariableInplaceRenameHandler().doRename(parameter, editor, null)
}
}
}
private fun IfThenToSelectData.clausesReplaceableBySafeCall(): Boolean = when {
baseClause == null -> false
negatedClause == null && baseClause.isUsedAsExpression(context) -> false
negatedClause != null && !negatedClause.isNullExpression() -> false
context.diagnostics.forElement(condition)
.any { it.factory == Errors.SENSELESS_COMPARISON || it.factory == Errors.USELESS_IS_CHECK } -> false
baseClause.evaluatesTo(receiverExpression) -> true
(baseClause as? KtCallExpression)?.calleeExpression?.evaluatesTo(receiverExpression) == true
&& baseClause.isCallingInvokeFunction(context) -> true
baseClause.hasFirstReceiverOf(receiverExpression) -> withoutResultInCallChain(baseClause, context)
baseClause.anyArgumentEvaluatesTo(receiverExpression) -> true
receiverExpression is KtThisExpression -> getImplicitReceiver()?.let { it.type == receiverExpression.getType(context) } == true
else -> false
}
private fun withoutResultInCallChain(expression: KtExpression, context: BindingContext): Boolean {
if (expression !is KtDotQualifiedExpression || expression.receiverExpression !is KtDotQualifiedExpression) return true
return !hasResultInCallExpression(expression, context)
}
private fun hasResultInCallExpression(expression: KtExpression, context: BindingContext): Boolean =
if (expression is KtDotQualifiedExpression)
returnTypeIsResult(expression.callExpression, context) || hasResultInCallExpression(expression.receiverExpression, context)
else
false
private fun returnTypeIsResult(call: KtCallExpression?, context: BindingContext) = call
?.getType(context)
?.constructor
?.declarationDescriptor
?.importableFqName == RESULT_FQNAME
private val RESULT_FQNAME = FqName("kotlin.Result")
| apache-2.0 | 1adcea0b93668e8b1376f983cb82a707 | 50.824427 | 158 | 0.751657 | 5.316366 | false | false | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/component/ItemDecoration.kt | 1 | 2381 | package org.secfirst.umbrella.component
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
class ItemDecoration @JvmOverloads constructor(private val spacing: Int, private var displayMode: Int = -1) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildViewHolder(view).adapterPosition
val itemCount = state.itemCount
val layoutManager = parent.layoutManager!!
setSpacingForDirection(outRect, layoutManager, position, itemCount)
}
private fun setSpacingForDirection(outRect: Rect,
layoutManager: RecyclerView.LayoutManager,
position: Int,
itemCount: Int) {
// Resolve display mode automatically
if (displayMode == -1) {
displayMode = resolveDisplayMode(layoutManager)
}
when (displayMode) {
HORIZONTAL -> {
outRect.left = spacing
outRect.right = if (position == itemCount - 1) spacing else 0
outRect.top = spacing
outRect.bottom = spacing
}
VERTICAL -> {
outRect.left = spacing
outRect.right = spacing
outRect.top = spacing
outRect.bottom = if (position == itemCount - 1) spacing else 0
}
GRID -> if (layoutManager is GridLayoutManager) {
val cols = layoutManager.spanCount
val rows = itemCount / cols
outRect.left = spacing
outRect.right = if (position % cols == cols - 1) spacing else 0
outRect.top = spacing
outRect.bottom = if (position / cols == rows - 1) spacing else 0
}
}
}
private fun resolveDisplayMode(layoutManager: RecyclerView.LayoutManager): Int {
if (layoutManager is GridLayoutManager) return GRID
return if (layoutManager.canScrollHorizontally()) HORIZONTAL else VERTICAL
}
companion object {
const val HORIZONTAL = 0
const val VERTICAL = 1
const val GRID = 2
}
} | gpl-3.0 | 1246194b7fa771c072524bd14ee65184 | 37.419355 | 141 | 0.595128 | 5.669048 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/elasticbeanstalk/src/main/kotlin/com/aws/example/DescribeEnvironment.kt | 1 | 1862 | // snippet-sourcedescription:[DescribeEnvironment.kt demonstrates how to describe an AWS Elastic Beanstalk environment.]
// snippet-keyword:[SDK for Kotlin]
// snippet-service:[AWS Elastic Beanstalk]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.aws.example
// snippet-start:[eb.kotlin.describe_env.import]
import aws.sdk.kotlin.services.elasticbeanstalk.ElasticBeanstalkClient
import aws.sdk.kotlin.services.elasticbeanstalk.model.DescribeEnvironmentsRequest
import kotlin.system.exitProcess
// snippet-end:[eb.kotlin.describe_env.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<appName>
Where:
appName - The name of the AWS Elastic Beanstalk application.
"""
if (args.size != 1) {
println(usage)
exitProcess(1)
}
val appName = args[0]
describeEnv(appName)
}
// snippet-start:[eb.kotlin.describe_env.main]
suspend fun describeEnv(appName: String) {
val request = DescribeEnvironmentsRequest {
environmentNames = listOf(appName)
}
ElasticBeanstalkClient { region = "us-east-1" }.use { beanstalkClient ->
val res = beanstalkClient.describeEnvironments(request)
res.environments?.forEach { env ->
System.out.println("The environment name is ${env.environmentName}")
System.out.println("The environment ARN is ${env.environmentArn}")
}
}
}
// snippet-end:[eb.kotlin.describe_env.main]
| apache-2.0 | 385aa46e50a221d82d70b3956aa9e6e6 | 30.103448 | 120 | 0.684748 | 4.012931 | false | false | false | false |
Madrapps/Pikolo | pikolo/src/main/java/com/madrapps/pikolo/components/rgb/BlueComponent.kt | 1 | 737 | package com.madrapps.pikolo.components.rgb
import android.graphics.Color
import com.madrapps.pikolo.Metrics
import com.madrapps.pikolo.Paints
import com.madrapps.pikolo.components.ArcComponent
internal class BlueComponent(metrics: Metrics, paints: Paints, arcLength: Float, arcStartAngle: Float) : ArcComponent(metrics, paints, arcLength, arcStartAngle) {
override val componentIndex: Int = 2
override val range: Float = 255f
override val noOfColors = 2
override val colors = IntArray(noOfColors)
override val colorPosition = FloatArray(noOfColors)
override fun getColorArray(color: FloatArray): IntArray {
colors[0] = Color.BLACK
colors[1] = Color.rgb(0, 0, 255)
return colors
}
} | apache-2.0 | de806db0073c76a7f52489c8384401c5 | 34.142857 | 162 | 0.744912 | 3.741117 | false | false | false | false |
cbeust/klaxon | klaxon/src/main/kotlin/com/beust/klaxon/World.kt | 1 | 2615 | package com.beust.klaxon
import java.util.*
class World(var status : Status, val pathMatchers: List<PathMatcher> = emptyList()) {
private val statusStack = LinkedList<Status>()
private val valueStack = LinkedList<Any>()
var result : Any? = null
var parent = JsonObject()
/**
* The path of the current JSON element.
* See https://github.com/json-path/JsonPath
*/
val path: String get() {
val result = arrayListOf("$")
valueStack.reversed().forEach { value ->
when(value) {
is JsonObject -> {
if (value.any()) {
result.add("." + value.keys.last().toString())
}
}
is JsonArray<*> -> {
result.add("[" + (value.size - 1) + "]")
}
else -> {
result.add("." + value)
}
}
}
return result.joinToString("")
}
fun pushAndSet(status: Status, value: Any) : World {
pushStatus(status)
pushValue(value)
this.status = status
return this
}
private fun pushStatus(status: Status) : World {
statusStack.addFirst(status)
return this
}
private fun pushValue(value: Any) : World {
valueStack.addFirst(value)
return this
}
/**
* The index of the character we are currently on.
*/
var index: Int = 0
/**
* The current line.
*/
var line: Int = 0
fun popValue() : Any {
return valueStack.removeFirst()
}
fun popStatus() : Status {
return statusStack.removeFirst()
}
fun getFirstObject() : JsonObject {
return valueStack.first as JsonObject
}
@Suppress("UNCHECKED_CAST")
fun getFirstArray() : JsonArray<Any?> {
return valueStack.first as JsonArray<Any?>
}
fun peekStatus() : Status {
return statusStack[0]
}
fun isNestedStatus() : Boolean {
return statusStack.size > 1
}
fun hasValues() : Boolean {
return valueStack.size > 1
}
internal fun foundValue() {
val first = valueStack.peekFirst()
if (first is JsonObject && first.isNotEmpty()) {
val value = first.values.last()
if (value != null && value !is JsonArray<*> && value !is JsonObject) {
pathMatchers.filter {
it.pathMatches(path)
}.forEach {
it.onMatch(path, value)
}
}
}
}
} | apache-2.0 | fd1e99136f73bc0faa0caff42ed5372f | 23.914286 | 85 | 0.510516 | 4.628319 | false | false | false | false |
BreakOutEvent/breakout-backend | src/main/java/backend/view/InvitationView.kt | 1 | 357 | package backend.view
import backend.model.event.Invitation
class InvitationView() {
var team: Long? = null
var name: String? = null
var email: String = ""
constructor(invitation: Invitation) : this() {
this.team = invitation.team?.id
this.name = invitation.team?.name
this.email = invitation.invitee.value
}
}
| agpl-3.0 | 73a5d787cb3bf3afd5dc93783a97b52d | 22.8 | 50 | 0.64986 | 3.966667 | false | false | false | false |
paramsen/noise | sample/src/main/java/com/paramsen/noise/sample/view/AudioView.kt | 1 | 1956 | package com.paramsen.noise.sample.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import java.util.*
/**
* @author Pär Amsen 06/2017
*/
class AudioView(context: Context, attrs: AttributeSet?) : SimpleSurface(context, attrs) {
val sec = 10
val hz = 44100
val merge = 512
val history = hz * sec / merge
val audio: ArrayDeque<Float> = ArrayDeque()
val paintAudio: Paint = Paint()
val paintLines: Paint = Paint()
val paintText: Paint = textPaint()
val path: Path = Path()
val bg = Color.parseColor("#39424F")
init {
paintAudio.color = Color.parseColor("#23E830")
paintAudio.strokeWidth = 0f
paintAudio.style = Paint.Style.STROKE
}
fun drawAudio(canvas: Canvas): Canvas {
path.reset()
synchronized(audio) {
for ((i, sample) in audio.withIndex()) {
if (i == 0) path.moveTo(width.toFloat(), sample)
path.lineTo(width - width * i / history.toFloat(), Math.min(sample * 0.175f + height / 2f, height.toFloat()))
}
if (audio.size in 1..(history - 1)) path.lineTo(0f, height / 2f)
}
canvas.drawColor(bg)
canvas.drawPath(path, paintAudio)
canvas.drawText("AUDIO", 16f.px, 24f.px, paintText)
return canvas
}
fun onWindow(window: FloatArray) {
synchronized(audio) {
var accum = 0f
for ((i, sample) in window.withIndex()) {
if (i > 0 && i % merge != 0) {
accum += sample
} else {
audio.addFirst(accum / merge)
accum = 0f
}
}
while (audio.size > history)
audio.removeLast()
}
drawSurface(this::drawAudio)
}
} | apache-2.0 | fcd5fa92e5e8abbfd8ef08f384421b58 | 26.549296 | 125 | 0.566752 | 4.064449 | false | false | false | false |
paplorinc/intellij-community | java/idea-ui/testSrc/com/intellij/facet/ImportedFacetsSerializationTest.kt | 3 | 4595 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.facet
import com.intellij.facet.mock.MockFacetConfiguration
import com.intellij.openapi.roots.ProjectModelExternalSource
import org.jetbrains.jps.model.serialization.facet.FacetState
/**
* @author nik
*/
class ImportedFacetsSerializationTest : FacetTestCase() {
override fun getProjectDirOrFile() = getProjectDirOrFile(true)
override fun isCreateProjectFileExplicitly() = false
fun `test regular facet`() {
addFacet()
assertEmpty(getExternalFacetStates())
val state = assertOneElement(facetManager.state.facets)
assertEquals("name", state.name)
assertNull(state.externalSystemId)
assertNull(FacetFromExternalSourcesStorage.getInstance(module).externalSource)
}
fun `test imported facet`() {
addFacet(createFacet("name"), MOCK_EXTERNAL_SOURCE)
assertEmpty(facetManager.state.facets)
val state = assertOneElement(getExternalFacetStates())
assertEquals("name", state.name)
assertNotNull(state.configuration)
assertEquals("mock", state.externalSystemId)
assertEquals("mock", FacetFromExternalSourcesStorage.getInstance(module).externalSource?.id)
}
fun `test regular facet and sub-facet`() {
createFacetAndSubFacet(null, null)
assertEmpty(getExternalFacetStates())
val state = assertOneElement(facetManager.state.facets)
checkFacetAndSubFacetState(state, true, true)
reloadStateAndCheckFacetAndSubFacet(null, null)
}
fun `test imported facet and sub-facet`() {
createFacetAndSubFacet(MOCK_EXTERNAL_SOURCE, MOCK_EXTERNAL_SOURCE)
assertEmpty(facetManager.state.facets)
val state = assertOneElement(getExternalFacetStates())
checkFacetAndSubFacetState(state, true, true)
reloadStateAndCheckFacetAndSubFacet(MOCK_EXTERNAL_SOURCE, MOCK_EXTERNAL_SOURCE)
}
fun `test imported facet and regular sub-facet`() {
createFacetAndSubFacet(MOCK_EXTERNAL_SOURCE, null)
val state = assertOneElement(facetManager.state.facets)
checkFacetAndSubFacetState(state, false, true)
val externalState = assertOneElement(getExternalFacetStates())
checkFacetAndSubFacetState(externalState, true, false)
reloadStateAndCheckFacetAndSubFacet(MOCK_EXTERNAL_SOURCE, null)
}
fun `test regular facet and imported sub-facet`() {
createFacetAndSubFacet(null, MOCK_EXTERNAL_SOURCE)
val state = assertOneElement(facetManager.state.facets)
checkFacetAndSubFacetState(state, true, false)
val externalState = assertOneElement(getExternalFacetStates())
checkFacetAndSubFacetState(externalState, false, true)
reloadStateAndCheckFacetAndSubFacet(null, MOCK_EXTERNAL_SOURCE)
}
private fun createFacetAndSubFacet(facetSource: ProjectModelExternalSource?, subFacetSource: ProjectModelExternalSource?) {
val facet = addFacet(createFacet("name"), facetSource)
facet.configuration.data = "1"
val subFacet = addSubFacet(facet, "sub", subFacetSource)
subFacet.configuration.data = "2"
}
private fun reloadStateAndCheckFacetAndSubFacet(facetSource: ProjectModelExternalSource?, subFacetSource: ProjectModelExternalSource?) {
facetManager.loadState(facetManager.state)
val facets = facetManager.sortedFacets
assertEquals(2, facets.size)
val (facet, subFacet) = facets
assertEquals("name", facet.name)
assertEquals(facetSource?.id, facet.externalSource?.id)
assertEquals("1", (facet.configuration as MockFacetConfiguration).data)
assertEquals(facet, subFacet.underlyingFacet)
assertEquals("sub", subFacet.name)
assertEquals(subFacetSource?.id, subFacet.externalSource?.id)
assertEquals("2", (subFacet.configuration as MockFacetConfiguration).data)
}
private fun checkFacetAndSubFacetState(state: FacetState, hasConfiguration: Boolean, hasConfigurationOfSubFacet: Boolean) {
assertEquals("name", state.name)
if (hasConfiguration) {
assertNotNull(state.configuration)
}
else {
assertNull(state.configuration)
}
if (hasConfigurationOfSubFacet) {
val subState = assertOneElement(state.subFacets)
assertEquals("sub", subState.name)
assertNotNull(subState.configuration)
}
else {
assertEmpty(state.subFacets)
}
}
private fun getExternalFacetStates() = FacetFromExternalSourcesStorage.getInstance(module).state.facets
}
private val MOCK_EXTERNAL_SOURCE = object: ProjectModelExternalSource {
override fun getDisplayName() = "mock"
override fun getId() = "mock"
} | apache-2.0 | fff4b3d0155afd9a2620161a2d2ed9a2 | 37.621849 | 140 | 0.764962 | 4.581256 | false | true | false | false |
JetBrains/intellij-community | plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/configuration/cachedCompilerArgumentsRestoring.kt | 1 | 13303 | // 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.gradle.configuration
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.PathUtil
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.K2MetadataCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments
import org.jetbrains.kotlin.idea.gradle.configuration.CachedCompilerArgumentsRestoringManager.restoreCompilerArgument
import org.jetbrains.kotlin.idea.gradleTooling.arguments.*
import org.jetbrains.kotlin.idea.projectModel.ArgsInfo
import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheAware
import org.jetbrains.kotlin.idea.projectModel.KotlinCachedCompilerArgument
import org.jetbrains.kotlin.idea.projectModel.KotlinRawCompilerArgument
import org.jetbrains.kotlin.platform.impl.FakeK2NativeCompilerArguments
import java.io.File
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.KProperty1
import kotlin.reflect.full.memberProperties
sealed interface EntityArgsInfo : ArgsInfo<CommonCompilerArguments, String>
data class EntityArgsInfoImpl(
override val currentCompilerArguments: CommonCompilerArguments,
override val defaultCompilerArguments: CommonCompilerArguments,
override val dependencyClasspath: Collection<String>
) : EntityArgsInfo
class EmptyEntityArgsInfo : EntityArgsInfo {
override val currentCompilerArguments: CommonCompilerArguments = CommonCompilerArguments.DummyImpl()
override val defaultCompilerArguments: CommonCompilerArguments = CommonCompilerArguments.DummyImpl()
override val dependencyClasspath: Collection<String> = emptyList()
}
sealed interface FlatSerializedArgsInfo : ArgsInfo<List<String>, String>
data class FlatSerializedArgsInfoImpl(
override val currentCompilerArguments: List<String>,
override val defaultCompilerArguments: List<String>,
override val dependencyClasspath: Collection<String>
) : FlatSerializedArgsInfo
class EmptyFlatArgsInfo : FlatSerializedArgsInfo {
override val currentCompilerArguments: List<String> = emptyList()
override val defaultCompilerArguments: List<String> = emptyList()
override val dependencyClasspath: Collection<String> = emptyList()
}
object CachedArgumentsRestoring {
private val LOGGER = Logger.getInstance(CachedArgumentsRestoring.javaClass)
private const val STUB_K_2_NATIVE_COMPILER_ARGUMENTS_CLASS = "org.jetbrains.kotlin.gradle.tasks.StubK2NativeCompilerArguments"
fun restoreSerializedArgsInfo(
cachedSerializedArgsInfo: CachedSerializedArgsInfo,
compilerArgumentsCacheHolder: CompilerArgumentsCacheHolder
): FlatSerializedArgsInfo {
val cacheAware = compilerArgumentsCacheHolder.getCacheAware(cachedSerializedArgsInfo.cacheOriginIdentifier)
?: return EmptyFlatArgsInfo().also {
LOGGER.error("CompilerArgumentsCacheAware with UUID '${cachedSerializedArgsInfo.cacheOriginIdentifier}' was not found!")
}
val currentCompilerArguments =
cachedSerializedArgsInfo.currentCompilerArguments.mapNotNull { it.restoreArgumentAsString(cacheAware) }
val defaultCompilerArguments =
cachedSerializedArgsInfo.defaultCompilerArguments.mapNotNull { it.restoreArgumentAsString(cacheAware) }
val dependencyClasspath = cachedSerializedArgsInfo.dependencyClasspath.mapNotNull { it.restoreArgumentAsString(cacheAware) }
return FlatSerializedArgsInfoImpl(currentCompilerArguments, defaultCompilerArguments, dependencyClasspath)
}
fun restoreExtractedArgs(
cachedExtractedArgsInfo: CachedExtractedArgsInfo,
compilerArgumentsCacheHolder: CompilerArgumentsCacheHolder
): EntityArgsInfo {
val cacheAware = compilerArgumentsCacheHolder.getCacheAware(cachedExtractedArgsInfo.cacheOriginIdentifier)
?: return EmptyEntityArgsInfo().also {
LOGGER.error("CompilerArgumentsCacheAware with UUID '${cachedExtractedArgsInfo.cacheOriginIdentifier}' was not found!")
}
val currentCompilerArguments = restoreCachedCompilerArguments(cachedExtractedArgsInfo.currentCompilerArguments, cacheAware)
val defaultCompilerArgumentsBucket = restoreCachedCompilerArguments(cachedExtractedArgsInfo.defaultCompilerArguments, cacheAware)
val dependencyClasspath = cachedExtractedArgsInfo.dependencyClasspath
.mapNotNull { it.restoreArgumentAsString(cacheAware) }
.map { PathUtil.toSystemIndependentName(it) }
return EntityArgsInfoImpl(currentCompilerArguments, defaultCompilerArgumentsBucket, dependencyClasspath)
}
private fun Map.Entry<KotlinCachedRegularCompilerArgument, KotlinCachedCompilerArgument<*>?>.obtainPropertyWithCachedValue(
propertiesByName: Map<String, KProperty1<out CommonCompilerArguments, *>>,
cacheAware: CompilerArgumentsCacheAware
): Pair<KProperty1<out CommonCompilerArguments, *>, KotlinRawCompilerArgument<*>>? {
val (key, value) = restoreEntry(this, cacheAware) ?: return null
val restoredKey = (key as? KotlinRawRegularCompilerArgument)?.data ?: return null
return (propertiesByName[restoredKey] ?: return null) to value
}
@Suppress("UNCHECKED_CAST")
private fun restoreCachedCompilerArguments(
cachedBucket: CachedCompilerArgumentsBucket,
cacheAware: CompilerArgumentsCacheAware
): CommonCompilerArguments {
fun KProperty1<*, *>.prepareLogMessage(): String =
"Failed to restore value for $returnType compiler argument '$name'. Default value will be used!"
val compilerArgumentsClassName = cachedBucket.compilerArgumentsClassName.data.let {
cacheAware.getCached(it) ?: return CommonCompilerArguments.DummyImpl().also { _ ->
LOGGER.error("Failed to restore name of compiler arguments class from id $it! 'CommonCompilerArguments' instance was created instead")
}
}
//TODO: Fixup. Remove it once actual K2NativeCompilerArguments will be available without 'kotlin.native.enabled = true' flag
val compilerArgumentsClass = if (compilerArgumentsClassName == STUB_K_2_NATIVE_COMPILER_ARGUMENTS_CLASS)
FakeK2NativeCompilerArguments::class.java
else
Class.forName(compilerArgumentsClassName) as Class<out CommonCompilerArguments>
val newCompilerArgumentsBean = compilerArgumentsClass.getConstructor().newInstance()
val propertiesByName = compilerArgumentsClass.kotlin.memberProperties.associateBy { it.name }
cachedBucket.singleArguments.entries.mapNotNull {
val (property, value) = it.obtainPropertyWithCachedValue(propertiesByName, cacheAware) ?: return@mapNotNull null
val newValue = if (value is KotlinRawRegularCompilerArgument) {
value.data
} else {
LOGGER.error(property.prepareLogMessage())
return@mapNotNull null
}
property to newValue
}.forEach { (prop, newVal) ->
(prop as KMutableProperty1<CommonCompilerArguments, String?>).set(newCompilerArgumentsBean, newVal)
}
cachedBucket.flagArguments.entries.mapNotNull {
val (property, value) = it.obtainPropertyWithCachedValue(propertiesByName, cacheAware) ?: return@mapNotNull null
val restoredValue = (value as? KotlinRawBooleanCompilerArgument)?.data ?: run {
LOGGER.error(property.prepareLogMessage())
return@mapNotNull null
}
property to restoredValue
}.forEach { (prop, newVal) ->
(prop as KMutableProperty1<CommonCompilerArguments, Boolean>).set(newCompilerArgumentsBean, newVal)
}
cachedBucket.multipleArguments.entries.mapNotNull {
val (property, value) = it.obtainPropertyWithCachedValue(propertiesByName, cacheAware) ?: return@mapNotNull null
val restoredValue = if (value is KotlinRawMultipleCompilerArgument) {
value.data.toTypedArray()
} else {
LOGGER.error(property.prepareLogMessage())
return@mapNotNull null
}
property to restoredValue
}.forEach { (prop, newVal) ->
(prop as KMutableProperty1<CommonCompilerArguments, Array<String>?>).set(newCompilerArgumentsBean, newVal)
}
val classpathValue = (restoreCompilerArgument(cachedBucket.classpathParts, cacheAware) as KotlinRawMultipleCompilerArgument?)
?.data
?.joinToString(File.pathSeparator)
when (newCompilerArgumentsBean) {
is K2JVMCompilerArguments -> newCompilerArgumentsBean.classpath = classpathValue
is K2MetadataCompilerArguments -> newCompilerArgumentsBean.classpath = classpathValue
}
val freeArgs = cachedBucket.freeArgs.mapNotNull { it.restoreArgumentAsString(cacheAware) }
val internalArgs = cachedBucket.internalArguments.mapNotNull { it.restoreArgumentAsString(cacheAware) }
parseCommandLineArguments(freeArgs + internalArgs, newCompilerArgumentsBean)
return newCompilerArgumentsBean
}
private fun KotlinCachedCompilerArgument<*>.restoreArgumentAsString(cacheAware: CompilerArgumentsCacheAware): String? =
when (val arg = restoreCompilerArgument(this, cacheAware)) {
is KotlinRawBooleanCompilerArgument -> arg.data.toString()
is KotlinRawRegularCompilerArgument -> arg.data
is KotlinRawMultipleCompilerArgument -> arg.data.joinToString(File.separator)
else -> {
LOGGER.error("Unknown argument received" + arg?.let { ": ${it::class.qualifiedName}" }.orEmpty())
null
}
}
private fun restoreEntry(
entry: Map.Entry<KotlinCachedCompilerArgument<*>, KotlinCachedCompilerArgument<*>?>,
cacheAware: CompilerArgumentsCacheAware
): Pair<KotlinRawCompilerArgument<*>, KotlinRawCompilerArgument<*>>? {
val key = restoreCompilerArgument(entry.key, cacheAware) ?: return null
val value = restoreCompilerArgument(entry.value, cacheAware) ?: return null
return key to value
}
}
object CachedCompilerArgumentsRestoringManager {
private val LOGGER = Logger.getInstance(CachedCompilerArgumentsRestoringManager.javaClass)
fun <TCache> restoreCompilerArgument(
argument: TCache,
cacheAware: CompilerArgumentsCacheAware
): KotlinRawCompilerArgument<*>? =
when (argument) {
null -> null
is KotlinCachedBooleanCompilerArgument -> BOOLEAN_ARGUMENT_RESTORING_STRATEGY.restoreArgument(argument, cacheAware)
is KotlinCachedRegularCompilerArgument -> REGULAR_ARGUMENT_RESTORING_STRATEGY.restoreArgument(argument, cacheAware)
is KotlinCachedMultipleCompilerArgument -> MULTIPLE_ARGUMENT_RESTORING_STRATEGY.restoreArgument(argument, cacheAware)
else -> {
LOGGER.error("Unknown argument received" + argument?.let { ": ${it::class.java.name}" })
null
}
}
private interface CompilerArgumentRestoringStrategy<TCache, TArg> {
fun restoreArgument(cachedArgument: TCache, cacheAware: CompilerArgumentsCacheAware): KotlinRawCompilerArgument<TArg>?
}
private val BOOLEAN_ARGUMENT_RESTORING_STRATEGY =
object : CompilerArgumentRestoringStrategy<KotlinCachedBooleanCompilerArgument, Boolean> {
override fun restoreArgument(
cachedArgument: KotlinCachedBooleanCompilerArgument,
cacheAware: CompilerArgumentsCacheAware
): KotlinRawBooleanCompilerArgument =
KotlinRawBooleanCompilerArgument(java.lang.Boolean.valueOf(cachedArgument.data))
}
private val REGULAR_ARGUMENT_RESTORING_STRATEGY =
object : CompilerArgumentRestoringStrategy<KotlinCachedRegularCompilerArgument, String> {
override fun restoreArgument(
cachedArgument: KotlinCachedRegularCompilerArgument,
cacheAware: CompilerArgumentsCacheAware
): KotlinRawRegularCompilerArgument? =
cacheAware.getCached(cachedArgument.data)?.let { KotlinRawRegularCompilerArgument(it) } ?: run {
LOGGER.error("Cannot find string argument value for key '${cachedArgument.data}'")
null
}
}
private val MULTIPLE_ARGUMENT_RESTORING_STRATEGY =
object : CompilerArgumentRestoringStrategy<KotlinCachedMultipleCompilerArgument, List<String>> {
override fun restoreArgument(
cachedArgument: KotlinCachedMultipleCompilerArgument,
cacheAware: CompilerArgumentsCacheAware
): KotlinRawMultipleCompilerArgument {
val cachedArguments = cachedArgument.data.mapNotNull { restoreCompilerArgument(it, cacheAware)?.data?.toString() }
return KotlinRawMultipleCompilerArgument(cachedArguments)
}
}
} | apache-2.0 | ed17db8ced5a97dd8cd0a3a8542709b2 | 54.89916 | 150 | 0.73427 | 5.829535 | false | false | false | false |
Masterzach32/SwagBot | src/main/kotlin/commands/Queue.kt | 1 | 6519 | package xyz.swagbot.commands
import com.mojang.brigadier.arguments.*
import com.sedmelluq.discord.lavaplayer.track.*
import discord4j.core.`object`.entity.*
import discord4j.core.`object`.reaction.*
import discord4j.core.event.domain.message.*
import io.facet.chatcommands.*
import io.facet.common.*
import io.facet.common.dsl.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.*
import xyz.swagbot.extensions.*
import xyz.swagbot.features.music.*
import xyz.swagbot.util.*
object Queue : ChatCommand(
name = "View Queue",
aliases = setOf("queue"),
scope = Scope.GUILD,
category = "music",
description = "",
usage = commandUsage {
default("")
}
) {
private val endLeft = ReactionEmoji.unicode("⏮️")
private val nextLeft = ReactionEmoji.unicode("◀️")
private val nextRight = ReactionEmoji.unicode("▶️")
private val endRight = ReactionEmoji.unicode("⏭️")
private val pageLeft = listOf(endLeft, nextLeft)
private val pageRight = listOf(nextRight, endRight)
private val allReactions = pageLeft + pageRight
override fun DSLCommandNode<ChatCommandSource>.register() {
runs {
val scheduler = getGuild().trackScheduler
val currentTrack: AudioTrack? = scheduler.player.playingTrack
val queue = scheduler.queue
.map { it to client.getMemberById(guildId!!, it.context.requesterId).awaitNullable() }
if (currentTrack == null || queue.isEmpty()) {
message.reply(
"The queue is empty! Go add a video or song with the `${prefixUsed}play` or " +
"`${prefixUsed}search` commands!"
)
return@runs
}
val queueMessage = message.reply(
queueEmbed(
currentTrack,
queue,
0,
scheduler.shouldAutoplay,
scheduler.shouldLoop,
scheduler.player.isPaused,
scheduler.queueTimeLeft
)
)
allReactions.forEach { queueMessage.addReaction(it).await() }
val pagesActor = actor<ReactionAddEvent> {
var currentPage = 0
for (event in channel) {
val queue = scheduler.queue
.map { it to client.getMemberById(guildId!!, it.context.requesterId).awaitNullable() }
val maxPage = queue.size / 10
when (event.emoji) {
endLeft -> currentPage = 0
nextLeft -> currentPage--
nextRight -> currentPage++
endRight -> currentPage = maxPage
}
if (currentPage in 0..maxPage) {
queueMessage.edit()
.withEmbeds(
queueEmbed(
scheduler.player.playingTrack,
queue,
currentPage,
scheduler.shouldAutoplay,
scheduler.shouldLoop,
scheduler.player.isPaused,
scheduler.queueTimeLeft
)
)
.await()
} else {
when {
currentPage > maxPage -> currentPage = maxPage
currentPage < 0 -> currentPage = 0
}
}
queueMessage.removeReaction(event.emoji, event.userId).await()
}
queueMessage.removeAllReactions().await()
}
val reactionEvents = client.flowOf<ReactionAddEvent>()
.filter { it.messageId == queueMessage.id }
val pagesJob = reactionEvents
.filter { it.userId == member.id && it.emoji in allReactions }
.onEach { pagesActor.send(it) }
.launchIn(this)
val cleanupJob = reactionEvents
.filter { it.userId != client.selfId && (it.userId != member.id || it.emoji !in allReactions) }
.onEach { queueMessage.removeReaction(it.emoji, it.userId).await() }
.launchIn(this)
launch {
delay(60_000 * 60)
pagesJob.cancel()
cleanupJob.cancel()
pagesActor.close()
}
}
argument("any", StringArgumentType.greedyString()) {
runs { context ->
message.reply(
"`${prefixUsed}${context.aliasUsed}` is used to view queued tracks. Use `${prefixUsed}play` or " +
"`${prefixUsed}search` to add music to the queue."
)
}
}
}
private fun queueEmbed(
currentTrack: AudioTrack,
tracks: List<Pair<AudioTrack, Member?>>,
page: Int,
autoplay: Boolean,
loop: Boolean,
paused: Boolean,
queueLength: Long,
) = baseTemplate.and {
title = ":musical_note: | Track Queue"
val startIndex = page * 10
description = tracks
.subList(startIndex, (startIndex + 10).coerceAtMost(tracks.size))
.mapIndexed { i, (track, member) ->
"${startIndex + i + 1}. ${track.info.boldFormattedTitleWithLink} - " +
"**${track.formattedLength}** (**${member?.displayName ?: "Unknown"}**)"
}
.joinToString("\n") + "\n"
field {
name = ":musical_note: Currently Playing"
value = "${currentTrack.info.boldFormattedTitleWithLink} - " +
"**${currentTrack.formattedPosition}** / **${currentTrack.formattedLength}**"
}
field("Autoplay", if (autoplay) ":white_check_mark:" else ":x:", true)
field("Loop", if (loop) ":white_check_mark:" else ":x:", true)
field("Paused", if (paused) ":white_check_mark:" else ":x:", true)
field("In Queue", "${tracks.size}", true)
field("Queue Length", getFormattedTime(queueLength / 1000), true)
field("Page", "${page + 1} / ${tracks.size / 10 + 1}", true)
}
}
| gpl-2.0 | 2f04296dacbf748e23e4747a4e5e7946 | 37.94012 | 118 | 0.508227 | 5.025502 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.