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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CruGlobal/android-gto-support | gto-support-androidx-lifecycle/src/main/kotlin/org/ccci/gto/android/common/androidx/lifecycle/Lifecycle.kt | 2 | 1860 | package org.ccci.gto.android.common.androidx.lifecycle
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
fun Lifecycle.onStart(block: (owner: LifecycleOwner) -> Unit): LifecycleObserver =
LambdaLifecycleObserver(onStart = block).also { addObserver(it) }
fun Lifecycle.onResume(block: (owner: LifecycleOwner) -> Unit): LifecycleObserver =
LambdaLifecycleObserver(onResume = block).also { addObserver(it) }
fun Lifecycle.onPause(block: (owner: LifecycleOwner) -> Unit): LifecycleObserver =
LambdaLifecycleObserver(onPause = block).also { addObserver(it) }
fun Lifecycle.onStop(block: (owner: LifecycleOwner) -> Unit): LifecycleObserver =
LambdaLifecycleObserver(onStop = block).also { addObserver(it) }
fun Lifecycle.onDestroy(block: (owner: LifecycleOwner) -> Unit): LifecycleObserver =
LambdaLifecycleObserver(onDestroy = block).also { addObserver(it) }
internal class LambdaLifecycleObserver(
private val onStart: ((owner: LifecycleOwner) -> Unit)? = null,
private val onResume: ((owner: LifecycleOwner) -> Unit)? = null,
private val onPause: ((owner: LifecycleOwner) -> Unit)? = null,
private val onStop: ((owner: LifecycleOwner) -> Unit)? = null,
private val onDestroy: ((owner: LifecycleOwner) -> Unit)? = null
) : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
onStart?.invoke(owner)
}
override fun onResume(owner: LifecycleOwner) {
onResume?.invoke(owner)
}
override fun onPause(owner: LifecycleOwner) {
onPause?.invoke(owner)
}
override fun onStop(owner: LifecycleOwner) {
onStop?.invoke(owner)
}
override fun onDestroy(owner: LifecycleOwner) {
onDestroy?.invoke(owner)
}
}
| mit | 370a9e73be980f489d6d348871c1339e | 36.959184 | 84 | 0.724731 | 4.69697 | false | false | false | false |
JetBrains-Research/big | src/main/kotlin/org/jetbrains/bio/big/BigFile.kt | 2 | 29611 | package org.jetbrains.bio.big
import com.google.common.collect.Iterators
import gnu.trove.TCollections
import gnu.trove.map.TIntObjectMap
import gnu.trove.map.hash.TIntObjectHashMap
import org.apache.commons.math3.util.Precision
import org.jetbrains.annotations.TestOnly
import org.jetbrains.bio.*
import org.slf4j.LoggerFactory
import java.io.Closeable
import java.io.IOException
import java.nio.ByteOrder
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.atomic.AtomicLong
import kotlin.LazyThreadSafetyMode.NONE
typealias RomBufferFactoryProvider = (String, ByteOrder) -> RomBufferFactory
/**
* A common superclass for Big files.
*
* Supported format versions
*
* 3 full support
* 4 partial support, specifically, extra indices aren't supported
* 5 custom version, requires Snappy instead of DEFLATE for
* compressed data blocks
*/
abstract class BigFile<out T> internal constructor(
val source: String,
internal val buffFactory: RomBufferFactory,
magic: Int,
prefetch: Int,
cancelledChecker: (() -> Unit)?
) : Closeable {
internal lateinit var header: Header
internal lateinit var zoomLevels: List<ZoomLevel>
internal lateinit var bPlusTree: BPlusTree
internal lateinit var rTree: RTreeIndex
// Kotlin doesn't allow do this val and init in constructor
private var prefetechedTotalSummary: BigSummary? = null
/** Whole-file summary. */
val totalSummary: BigSummary by lazy(NONE) {
prefetechedTotalSummary ?: buffFactory.create().use {
BigSummary.read(it, header.totalSummaryOffset)
}
}
private var prefetchedChromosomes: TIntObjectMap<String>? = null
/**
* An in-memory mapping of chromosome IDs to chromosome names.
*
* Because sometimes (always) you don't need a B+ tree for that.
*/
val chromosomes: TIntObjectMap<String> by lazy(NONE) {
prefetchedChromosomes ?: with(bPlusTree) {
val res = TIntObjectHashMap<String>(header.itemCount)
// returns sequence, but process here => resource could be closed
buffFactory.create().use {
for ((key, id) in traverse(it)) {
res.put(id, key)
}
}
TCollections.unmodifiableMap(res)
}
}
internal var prefetchedLevel2RTreeIndex: Map<ZoomLevel, RTreeIndex>? = null
internal var prefetchedChr2Leaf: Map<String, BPlusLeaf?>? = null
init {
try {
buffFactory.create().use { input ->
cancelledChecker?.invoke()
header = Header.read(input, magic)
zoomLevels = (0 until header.zoomLevelCount).map { ZoomLevel.read(input) }
bPlusTree = BPlusTree.read(input, header.chromTreeOffset)
// if do prefetch input and file not empty:
if (prefetch >= BigFile.PREFETCH_LEVEL_FAST) {
// stored in the beginning of file near header
cancelledChecker?.invoke()
prefetechedTotalSummary = BigSummary.read(input, header.totalSummaryOffset)
// stored in the beginning of file near header
cancelledChecker?.invoke()
prefetchedChromosomes = with(bPlusTree) {
val res = TIntObjectHashMap<String>(this.header.itemCount)
// returns sequence, but process here => resource could be closed
for ((key, id) in traverse(input)) {
res.put(id, key)
}
TCollections.unmodifiableMap(res)
}
// stored in the beginning of file near header
cancelledChecker?.invoke()
prefetchedChr2Leaf = prefetchedChromosomes!!.valueCollection().map {
it to bPlusTree.find(input, it)
}.toMap()
// stored not in the beginning of file
prefetchedLevel2RTreeIndex = zoomLevels.mapNotNull {
if (it.reduction == 0) {
null
} else {
require(it.indexOffset != 0L) {
"Zoom index offset expected to be not zero."
}
require(it.dataOffset != 0L) {
"Zoom data offset expected to be not zero."
}
val zRTree = RTreeIndex.read(input, it.indexOffset)
zRTree.prefetchBlocksIndex(
input, true, false, header.uncompressBufSize,
cancelledChecker
)
it to zRTree
}
}.toMap()
}
// this point not to the beginning of file => read it here using new buffer
// in buffered stream
cancelledChecker?.invoke()
rTree = RTreeIndex.read(input, header.unzoomedIndexOffset)
if (prefetch >= BigFile.PREFETCH_LEVEL_DETAILED) {
rTree.prefetchBlocksIndex(
input, false, true, header.uncompressBufSize, cancelledChecker
)
}
}
} catch (e: Exception) {
buffFactory.close()
throw e
}
}
/**
* File compression type.
*
* @since 0.2.6
*/
val compression: CompressionType get() = with(header) {
when {
// Compression was introduced in version 3 of the format. See
// bbiFile.h in UCSC sources.
version < 3 || uncompressBufSize == 0 -> CompressionType.NO_COMPRESSION
version <= 4 -> CompressionType.DEFLATE
version == 5 -> CompressionType.SNAPPY
else -> error("unsupported version: $version")
}
}
/**
* Internal caching Statistics: Counter for case when cached decompressed block
* differs from desired
*/
private val blockCacheMisses = AtomicLong()
/**
* Internal caching Statistics: Counter for case when cached decompressed block
* matches desired
*/
private val blockCacheIns = AtomicLong()
/**
* Splits the interval `[startOffset, endOffset)` into `numBins`
* non-intersecting sub-intervals (aka bins) and computes a summary
* of the data values for each bin.
*
* @param name human-readable chromosome name, e.g. `"chr9"`.
* @param startOffset 0-based start offset (inclusive).
* @param endOffset 0-based end offset (exclusive), if 0 than the whole
* chromosome is used.
* @param numBins number of summaries to compute. Defaults to `1`.
* @param index if `true` pre-computed is index is used if possible.
* @param cancelledChecker Throw cancelled exception to abort operation
* @return a list of summaries.
*/
@Throws(IOException::class)
fun summarize(name: String, startOffset: Int = 0, endOffset: Int = 0,
numBins: Int = 1, index: Boolean = true,
cancelledChecker: (() -> Unit)? = null): List<BigSummary> {
var list: List<BigSummary> = emptyList()
buffFactory.create().use { input ->
val chromosome = when {
prefetchedChr2Leaf != null -> prefetchedChr2Leaf!![name]
else -> bPlusTree.find(input, name)
} ?: throw NoSuchElementException(name)
val properEndOffset = if (endOffset == 0) chromosome.size else endOffset
val query = Interval(chromosome.id, startOffset, properEndOffset)
require(numBins <= query.length()) {
"number of bins must not exceed interval length, got " +
"$numBins > ${query.length()}, source $source"
}
// The 2-factor guarantees that we get at least two data points
// per bin. Otherwise we might not be able to estimate SD.
val zoomLevel = zoomLevels.pick(query.length() / (2 * numBins))
val sparseSummaries = if (zoomLevel == null || !index) {
LOG.trace("Summarizing $query from raw data")
summarizeInternal(input, query, numBins, cancelledChecker)
} else {
LOG.trace("Summarizing $query from ${zoomLevel.reduction}x zoom")
summarizeFromZoom(input, query, zoomLevel, numBins, cancelledChecker)
}
val emptySummary = BigSummary()
val summaries = Array(numBins) { emptySummary }
for ((i, summary) in sparseSummaries) {
summaries[i] = summary
}
list = summaries.asList()
}
return list
}
@Throws(IOException::class)
internal abstract fun summarizeInternal(
input: RomBuffer,
query: ChromosomeInterval,
numBins: Int,
cancelledChecker: (() -> Unit)?
): Sequence<IndexedValue<BigSummary>>
private fun summarizeFromZoom(input: RomBuffer,
query: ChromosomeInterval, zoomLevel: ZoomLevel,
numBins: Int,
cancelledChecker: (() -> Unit)?): Sequence<IndexedValue<BigSummary>> {
val zRTree = when {
prefetchedLevel2RTreeIndex != null -> prefetchedLevel2RTreeIndex!![zoomLevel]!!
else -> RTreeIndex.read(input, zoomLevel.indexOffset)
}
val zoomData = zRTree.findOverlappingBlocks(input, query, header.uncompressBufSize, cancelledChecker)
.flatMap { (_ /* interval */, offset, size) ->
assert(!compression.absent || size % ZoomData.SIZE == 0L)
val chrom = chromosomes[query.chromIx]
with(decompressAndCacheBlock(input, chrom, offset, size)) {
val res = ArrayList<ZoomData>()
do {
val zoomData = ZoomData.read(this)
if (zoomData.interval intersects query) {
res.add(zoomData)
}
} while (hasRemaining())
res.asSequence()
}
// XXX we can avoid explicit '#toList' call here, but the
// worst-case space complexity will still be O(n).
}.toList()
var edge = 0 // yay! map with a side effect.
return query.slice(numBins).mapIndexed { i, bin ->
val summary = BigSummary()
for (j in edge until zoomData.size) {
val interval = zoomData[j].interval
if (interval.endOffset <= bin.startOffset) {
edge = j + 1
continue
} else if (interval.startOffset > bin.endOffset) {
break
}
if (interval intersects bin) {
summary.update(zoomData[j],
interval.intersectionLength(bin),
interval.length())
}
}
if (summary.isEmpty()) null else IndexedValue(i, summary)
}.filterNotNull()
}
/**
* Queries an R+-tree.
*
* @param name human-readable chromosome name, e.g. `"chr9"`.
* @param startOffset 0-based start offset (inclusive).
* @param endOffset 0-based end offset (exclusive), if 0 than the whole
* chromosome is used.
* @param overlaps if `false` the resulting list contains only the
* items completely contained within the query,
* otherwise it also includes the items overlapping
* the query.
* @param cancelledChecker Throw cancelled exception to abort operation
* @return a list of items.
* @throws IOException if the underlying [RomBuffer] does so.
*/
@Throws(IOException::class)
@JvmOverloads fun query(name: String, startOffset: Int = 0, endOffset: Int = 0,
overlaps: Boolean = false,
cancelledChecker: (() -> Unit)? = null): List<T> {
buffFactory.create().use { input ->
val res = when {
prefetchedChr2Leaf != null -> prefetchedChr2Leaf!![name]
else -> bPlusTree.find(input, name)
}
return if (res == null) {
emptyList()
} else {
val (_/* key */, chromIx, size) = res
val properEndOffset = if (endOffset == 0) size else endOffset
query(input, Interval(chromIx, startOffset, properEndOffset), overlaps, cancelledChecker).toList()
}
}
}
internal fun query(
input: RomBuffer,
query: ChromosomeInterval,
overlaps: Boolean,
cancelledChecker: (() -> Unit)?
): Sequence<T> {
val chrom = chromosomes[query.chromIx]
return rTree.findOverlappingBlocks(input, query, header.uncompressBufSize, cancelledChecker)
.flatMap { (_, dataOffset, dataSize) ->
cancelledChecker?.invoke()
decompressAndCacheBlock(input, chrom, dataOffset, dataSize).use { decompressedInput ->
queryInternal(decompressedInput, query, overlaps)
}
}
}
internal fun decompressAndCacheBlock(input: RomBuffer,
chrom: String,
dataOffset: Long, dataSize: Long): RomBuffer {
var stateAndBlock = lastCachedBlockInfo.get()
// LOG.trace("Decompress $chrom $dataOffset, size=$dataSize")
val newState = RomBufferState(buffFactory, dataOffset, dataSize, chrom)
val decompressedBlock: RomBuffer
if (stateAndBlock.first != newState) {
val newDecompressedInput = input.decompress(dataOffset, dataSize, compression, header.uncompressBufSize)
stateAndBlock = newState to newDecompressedInput
// We cannot cache block if it is resource which is supposed to be closed
decompressedBlock = when (newDecompressedInput) {
is BBRomBuffer, is MMBRomBuffer -> {
lastCachedBlockInfo.set(stateAndBlock)
blockCacheMisses.incrementAndGet()
// we will reuse block, so let's path duplicate to reader
// in order not to affect buffer state
newDecompressedInput.duplicate(newDecompressedInput.position, newDecompressedInput.limit)
}
else -> newDecompressedInput // no buffer re-use => pass as is
}
} else {
// if decompressed input was supposed to be close => it hasn't been cached => won't be here
blockCacheIns.incrementAndGet()
// we reuse block, so let's path duplicate to reader
// in order not to affect buffer state
val block = stateAndBlock.second!!
decompressedBlock = block.duplicate(block.position, block.limit)
}
return decompressedBlock
}
@Throws(IOException::class)
internal abstract fun queryInternal(decompressedBlock: RomBuffer,
query: ChromosomeInterval,
overlaps: Boolean): Sequence<T>
override fun close() {
lastCachedBlockInfo.remove()
val m = blockCacheMisses.get()
val n = m + blockCacheIns.get()
LOG.trace("BigFile closed: Cache misses ${Precision.round(100.0 * m / n, 1)}% ($m of $n), " +
"source: : $source ")
buffFactory.close()
}
internal data class Header(
val order: ByteOrder,
val magic: Int,
val version: Int = 5,
val zoomLevelCount: Int = 0,
val chromTreeOffset: Long,
val unzoomedDataOffset: Long,
val unzoomedIndexOffset: Long,
val fieldCount: Int,
val definedFieldCount: Int,
val asOffset: Long = 0,
val totalSummaryOffset: Long = 0,
val uncompressBufSize: Int,
val extendedHeaderOffset: Long = 0
) {
internal fun write(output: OrderedDataOutput) = with(output) {
check(output.tell() == 0L) // a header is always first.
writeInt(magic)
writeShort(version)
writeShort(zoomLevelCount)
writeLong(chromTreeOffset)
writeLong(unzoomedDataOffset)
writeLong(unzoomedIndexOffset)
writeShort(fieldCount)
writeShort(definedFieldCount)
writeLong(asOffset)
writeLong(totalSummaryOffset)
writeInt(uncompressBufSize)
writeLong(extendedHeaderOffset)
}
companion object {
/** Number of bytes used for this header. */
internal const val BYTES = 64
internal fun read(input: RomBuffer, magic: Int) = with(input) {
checkHeader(magic)
val version = readUnsignedShort()
val zoomLevelCount = readUnsignedShort()
val chromTreeOffset = readLong()
val unzoomedDataOffset = readLong()
val unzoomedIndexOffset = readLong()
val fieldCount = readUnsignedShort()
val definedFieldCount = readUnsignedShort()
val asOffset = readLong()
val totalSummaryOffset = readLong()
val uncompressBufSize = readInt()
val extendedHeaderOffset = readLong()
when {
// asOffset > 0 -> LOG.trace("AutoSQL queries are unsupported")
extendedHeaderOffset > 0 -> LOG.debug("Header extensions are unsupported")
}
Header(order, magic, version, zoomLevelCount, chromTreeOffset,
unzoomedDataOffset, unzoomedIndexOffset,
fieldCount, definedFieldCount, asOffset,
totalSummaryOffset, uncompressBufSize,
extendedHeaderOffset)
}
}
}
internal data class RomBufferState(private val buffFactory: RomBufferFactory?,
val offset: Long, val size: Long,
val chrom: String)
companion object {
private val LOG = LoggerFactory.getLogger(BigFile::class.java)
const val PREFETCH_LEVEL_OFF = 0
const val PREFETCH_LEVEL_FAST = 1
const val PREFETCH_LEVEL_DETAILED = 2
private val lastCachedBlockInfo: ThreadLocal<Pair<RomBufferState, RomBuffer?>> = ThreadLocal.withInitial {
RomBufferState(null, 0L, 0L, "") to null
}
@TestOnly
internal fun lastCachedBlockInfoValue() = lastCachedBlockInfo.get()
/**
* Magic specifies file format and bytes order. Let's read magic as little endian.
*/
private fun readLEMagic(buffFactory: RomBufferFactory) =
buffFactory.create().use {
it.readInt()
}
/**
* Determines byte order using expected magic field value
*/
internal fun getByteOrder(path: String, magic: Int, bufferFactory: RomBufferFactory): ByteOrder {
val leMagic = readLEMagic(bufferFactory)
val (valid, byteOrder) = guess(magic, leMagic)
check(valid) {
val bigMagic = java.lang.Integer.reverseBytes(magic)
"Unexpected header leMagic: Actual $leMagic doesn't match expected LE=$magic and BE=$bigMagic}," +
" file: $path"
}
return byteOrder
}
private fun guess(expectedMagic: Int, littleEndianMagic: Int): Pair<Boolean, ByteOrder> {
if (littleEndianMagic != expectedMagic) {
val bigEndianMagic = java.lang.Integer.reverseBytes(littleEndianMagic)
if (bigEndianMagic != expectedMagic) {
return false to ByteOrder.BIG_ENDIAN
}
return (true to ByteOrder.BIG_ENDIAN)
}
return true to ByteOrder.LITTLE_ENDIAN
}
/**
* @since 0.7.0
*/
fun defaultFactory(): RomBufferFactoryProvider = { p, byteOrder ->
EndianSynchronizedBufferFactory.create(p, byteOrder)
}
@Throws(IOException::class)
@JvmStatic
fun read(path: Path, cancelledChecker: (() -> Unit)? = null): BigFile<Comparable<*>> = read(path.toString(), cancelledChecker = cancelledChecker)
@Throws(IOException::class)
@JvmStatic
fun read(src: String, prefetch: Int = BigFile.PREFETCH_LEVEL_DETAILED,
cancelledChecker: (() -> Unit)? = null,
factoryProvider: RomBufferFactoryProvider = defaultFactory()
): BigFile<Comparable<*>> = factoryProvider(src, ByteOrder.LITTLE_ENDIAN).use { factory ->
val magic = readLEMagic(factory)
when (guessFileType(magic)) {
Type.BIGBED -> BigBedFile.read(src, prefetch, cancelledChecker, factoryProvider)
Type.BIGWIG -> BigWigFile.read(src, prefetch, cancelledChecker, factoryProvider)
else -> throw IllegalStateException("Unsupported file header magic: $magic")
}
}
/**
* Determines file type by reading first byte
*
* @since 0.8.0
*/
fun determineFileType(
src: String,
factoryProvider: RomBufferFactoryProvider = defaultFactory()
) = factoryProvider(src, ByteOrder.LITTLE_ENDIAN).use { factory ->
guessFileType(readLEMagic(factory))
}
private fun guessFileType(magic: Int) = when {
guess(BigBedFile.MAGIC, magic).first -> BigFile.Type.BIGBED
guess(BigWigFile.MAGIC, magic).first -> BigFile.Type.BIGWIG
else -> null
}
}
/** Ad hoc post-processing for [BigFile]. */
protected object Post {
private val LOG = LoggerFactory.getLogger(javaClass)
private inline fun <T> modify(
path: Path, offset: Long = 0L,
block: (BigFile<*>, OrderedDataOutput) -> T): T = read(path).use { bf ->
OrderedDataOutput(path, bf.header.order, offset, create = false).use {
block(bf, it)
}
}
/**
* Fills in zoom levels for a [BigFile] located at [path].
*
* Note that the number of zoom levels to compute must be
* specified in the file [Header]. Additionally the file must
* contain `ZoomData.BYTES * header.zoomLevelCount` zero
* bytes right after the header.
*
* @param path to [BigFile].
* @param itemsPerSlot number of summaries to aggregate prior to
* building an R+ tree. Lower values allow
* for better granularity when loading zoom
* levels, but may degrade the performance
* of [BigFile.summarizeFromZoom]. See
* [RTreeIndex] for details
* @param initial initial reduction.
* @param step reduction step to use, i.e. the first zoom level
* will be `initial`, next `initial * step` etc.
*/
internal fun zoom(
path: Path,
itemsPerSlot: Int = 512,
initial: Int = 8,
step: Int = 4,
cancelledChecker: (() -> Unit)?
) {
LOG.time("Computing zoom levels with step $step for $path") {
val zoomLevels = ArrayList<ZoomLevel>()
modify(path, offset = Files.size(path)) { bf, output ->
var reduction = initial
for (level in bf.zoomLevels.indices) {
val zoomLevel = reduction.zoomAt(
bf, output, itemsPerSlot,
reduction / step,
cancelledChecker
)
if (zoomLevel == null) {
LOG.trace("${reduction}x reduction rejected")
break
} else {
LOG.trace("${reduction}x reduction accepted")
zoomLevels.add(zoomLevel)
}
reduction *= step
if (reduction < 0) {
LOG.trace("Reduction overflow ($reduction) at level $level, next levels ignored")
break
}
}
}
modify(path, offset = Header.BYTES.toLong()) { _/* bf */, output ->
for (zoomLevel in zoomLevels) {
val zoomHeaderOffset = output.tell()
zoomLevel.write(output)
assert((output.tell() - zoomHeaderOffset).toInt() == ZoomLevel.BYTES)
}
}
}
}
private fun Int.zoomAt(
bf: BigFile<*>,
output: OrderedDataOutput,
itemsPerSlot: Int,
prevLevelReduction: Int,
cancelledChecker: (() -> Unit)?
): ZoomLevel? {
val reduction = this
val zoomedDataOffset = output.tell()
val leaves = ArrayList<RTreeIndexLeaf>()
bf.buffFactory.create().use { input ->
for ((_/* name */, chromIx, size) in bf.bPlusTree.traverse(input)) {
val query = Interval(chromIx, 0, size)
if (prevLevelReduction > size) {
// chromosome already covered by 1 bin at prev level
continue
}
// We can re-use pre-computed zooms, but preliminary
// results suggest this doesn't give a noticeable speedup.
val summaries = bf.summarizeInternal(
input, query,
numBins = size divCeiling reduction,
cancelledChecker = cancelledChecker
)
for (slot in Iterators.partition(summaries.iterator(), itemsPerSlot)) {
val dataOffset = output.tell()
output.with(bf.compression) {
for ((i, summary) in slot) {
val startOffset = i * reduction
val endOffset = (i + 1) * reduction
val (count, minValue, maxValue, sum, sumSquares) = summary
ZoomData(chromIx, startOffset, endOffset,
count.toInt(),
minValue.toFloat(), maxValue.toFloat(),
sum.toFloat(), sumSquares.toFloat()).write(this)
}
}
// Compute the bounding interval.
val interval = Interval(chromIx, slot.first().index * reduction,
(slot.last().index + 1) * reduction)
leaves.add(RTreeIndexLeaf(interval, dataOffset, output.tell() - dataOffset))
}
}
}
return if (leaves.size > 1) {
val zoomedIndexOffset = output.tell()
RTreeIndex.write(output, leaves, itemsPerSlot = itemsPerSlot)
ZoomLevel(reduction, zoomedDataOffset, zoomedIndexOffset)
} else {
null // no need for trivial zoom levels.
}
}
/**
* Fills in whole-file [BigSummary] for a [BigFile] located at [path].
*
* The file must contain `BigSummary.BYTES` zero bytes right after
* the zoom levels block.
*/
internal fun totalSummary(path: Path) {
val totalSummaryOffset = BigFile.read(path).use {
it.header.totalSummaryOffset
}
LOG.time("Computing total summary block for $path") {
modify(path, offset = totalSummaryOffset) { bf, output ->
bf.chromosomes.valueCollection()
.flatMap { bf.summarize(it, 0, 0, numBins = 1) }
.fold(BigSummary(), BigSummary::plus)
.write(output)
assert((output.tell() - totalSummaryOffset).toInt() == BigSummary.BYTES)
}
}
}
}
enum class Type {
BIGWIG, BIGBED
}
}
| mit | 4fcb3e65e5acdbd0544ebb6083dd3fad | 40.240947 | 153 | 0.533856 | 5.433211 | false | false | false | false |
czyzby/ktx | tiled/src/main/kotlin/ktx/tiled/mapObjects.kt | 2 | 4798 | package ktx.tiled
import com.badlogic.gdx.maps.MapObject
import com.badlogic.gdx.maps.MapObjects
import com.badlogic.gdx.maps.MapProperties
import com.badlogic.gdx.maps.objects.CircleMapObject
import com.badlogic.gdx.maps.objects.EllipseMapObject
import com.badlogic.gdx.maps.objects.PolygonMapObject
import com.badlogic.gdx.maps.objects.PolylineMapObject
import com.badlogic.gdx.maps.objects.RectangleMapObject
import com.badlogic.gdx.maps.objects.TextureMapObject
import com.badlogic.gdx.math.Circle
import com.badlogic.gdx.math.Ellipse
import com.badlogic.gdx.math.Polygon
import com.badlogic.gdx.math.Polyline
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Shape2D
/**
* Extension method to directly access the [MapProperties] of a [MapObject]. If the property
* is not defined then this method throws a [MissingPropertyException].
* @param key property name.
* @return value of the property.
* @throws MissingPropertyException If the property is not defined.
*/
inline fun <reified T> MapObject.property(key: String): T = properties[key, T::class.java]
?: throw MissingPropertyException("Property $key does not exist for object $name")
/**
* Extension method to directly access the [MapProperties] of a [MapObject]. The type is automatically
* derived from the type of the given default value. If the property is not defined the [defaultValue]
* will be returned.
* @param key property name.
* @param defaultValue default value in case the property is missing.
* @return value of the property or defaultValue if property is missing.
*/
inline fun <reified T> MapObject.property(key: String, defaultValue: T): T = properties[key, defaultValue, T::class.java]
/**
* Extension method to directly access the [MapProperties] of a [MapObject]. If the property
* is not defined then this method returns null.
* @param key property name.
* @return value of the property or null if the property is missing.
*/
inline fun <reified T> MapObject.propertyOrNull(key: String): T? = properties[key, T::class.java]
/**
* Extension method to directly access the [MapProperties] of a [MapObject] and its
* [containsKey][MapProperties.containsKey] method.
* @param key property name.
* @return true if the property exists. Otherwise false.
*/
fun MapObject.containsProperty(key: String) = properties.containsKey(key)
/**
* Extension property to retrieve the x-coordinate of the [MapObject].
* @throws MissingPropertyException if property x does not exist.
*/
val MapObject.x: Float
get() = property("x")
/**
* Extension property to retrieve the y-coordinate of the [MapObject].
* @throws MissingPropertyException if property y does not exist.
*/
val MapObject.y: Float
get() = property("y")
/**
* Extension property to retrieve the width of the [MapObject].
* @throws MissingPropertyException if property width does not exist.
*/
val MapObject.width: Float
get() = property("width")
/**
* Extension property to retrieve the height of the [MapObject].
* @throws MissingPropertyException if property height does not exist.
*/
val MapObject.height: Float
get() = property("height")
/**
* Extension property to retrieve the unique ID of the [MapObject].
* @throws MissingPropertyException if property id does not exist.
*/
val MapObject.id: Int
get() = property("id")
/**
* Extension property to retrieve the rotation of the [MapObject]. Null if the property is unset.
*/
val MapObject.rotation: Float?
get() = propertyOrNull("rotation")
/**
* Extension property to retrieve the type of the [MapObject]. Null if the property is unset.
*/
val MapObject.type: String?
get() = propertyOrNull("type")
/**
* Extension method to retrieve the [Shape2D] instance of a [MapObject].
* Depending on the type of the object a different shape will be returned:
*
* - [CircleMapObject] -> [Circle]
* - [EllipseMapObject] -> [Ellipse]
* - [PolylineMapObject] -> [Polyline]
* - [PolygonMapObject] -> [Polygon]
* - [RectangleMapObject] -> [Rectangle]
*
* Note that objects that do not have any shape like [TextureMapObject] will throw a [MissingShapeException]
* @throws MissingShapeException If the object does not have any shape
*/
val MapObject.shape: Shape2D
get() = when (this) {
is CircleMapObject -> circle
is EllipseMapObject -> ellipse
is PolylineMapObject -> polyline
is PolygonMapObject -> polygon
is RectangleMapObject -> rectangle
else -> throw MissingShapeException("MapObject of type ${this::class.java} does not have a shape.")
}
/**
* Returns **true** if and only if the [MapObjects] collection is empty.
*/
fun MapObjects.isEmpty() = this.count <= 0
/**
* Returns **true** if and only if the [MapObjects] collection is not empty.
*/
fun MapObjects.isNotEmpty() = this.count > 0
| cc0-1.0 | 3e72b0ef890fc9594b20dbd4b123f83a | 35.075188 | 121 | 0.74281 | 4.048945 | false | false | false | false |
jeffgbutler/mybatis-dynamic-sql | src/test/kotlin/examples/kotlin/mybatis3/column/comparison/ColumnComparisonDynamicSqlSupport.kt | 1 | 1280 | /*
* Copyright 2016-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 examples.kotlin.mybatis3.column.comparison
import org.mybatis.dynamic.sql.SqlTable
import org.mybatis.dynamic.sql.util.kotlin.elements.column
import java.sql.JDBCType
object ColumnComparisonDynamicSqlSupport {
val columnComparison = ColumnComparison()
val number1 = columnComparison.number1
val number2 = columnComparison.number2
val columnList = listOf(number1, number2)
class ColumnComparison : SqlTable("ColumnComparison") {
val number1 = column<Int>(name = "number1", jdbcType = JDBCType.INTEGER)
val number2 = column<Int>(name = "number2", jdbcType = JDBCType.INTEGER)
}
}
| apache-2.0 | 6be143d521081b5033481ca1cf6b6aa7 | 37.787879 | 80 | 0.729688 | 4.102564 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/social/InvitationsView.kt | 1 | 1508 | package com.habitrpg.android.habitica.ui.views.social
import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import com.habitrpg.android.habitica.databinding.ViewInvitationBinding
import com.habitrpg.common.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.models.invitations.GenericInvitation
class InvitationsView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
var acceptCall: ((String) -> Unit)? = null
var rejectCall: ((String) -> Unit)? = null
var setLeader: ((String) -> Unit)? = null
var leaderID: String? = null
var groupName: String? = null
init {
orientation = VERTICAL
}
fun setInvitations(invitations: List<GenericInvitation>) {
removeAllViews()
for (invitation in invitations) {
leaderID = invitation.inviter
groupName = invitation.name
val binding = ViewInvitationBinding.inflate(context.layoutInflater, this, true)
leaderID?.let {
setLeader?.invoke(it)
invalidate()
}
binding.acceptButton.setOnClickListener {
invitation.id?.let { it1 -> acceptCall?.invoke(it1) }
}
binding.rejectButton.setOnClickListener {
invitation.id?.let { it1 -> rejectCall?.invoke(it1) }
}
}
}
}
| gpl-3.0 | 3bbc2bcfd5d1f80af8e84ecb7be0e408 | 31.782609 | 91 | 0.65252 | 4.7125 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/user_reviews/ui/adapter/delegate/UserReviewsPotentialAdapterDelegate.kt | 2 | 3029 | package org.stepik.android.view.user_reviews.ui.adapter.delegate
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.item_user_review_potential.*
import org.stepic.droid.R
import org.stepik.android.domain.user_reviews.model.UserCourseReviewItem
import org.stepik.android.model.Course
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
class UserReviewsPotentialAdapterDelegate(
private val onCourseTitleClicked: (Course) -> Unit,
private val onWriteReviewClicked: (Long, String, Float) -> Unit
) : AdapterDelegate<UserCourseReviewItem, DelegateViewHolder<UserCourseReviewItem>>() {
companion object {
private const val RATING_RESET_DELAY_MS = 750L
}
override fun isForViewType(position: Int, data: UserCourseReviewItem): Boolean =
data is UserCourseReviewItem.PotentialReviewItem
override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<UserCourseReviewItem> =
ViewHolder(createView(parent, R.layout.item_user_review_potential))
private inner class ViewHolder(override val containerView: View) : DelegateViewHolder<UserCourseReviewItem>(containerView), LayoutContainer {
init {
userReviewIcon.setOnClickListener { (itemData as? UserCourseReviewItem.PotentialReviewItem)?.course?.let(onCourseTitleClicked) }
userReviewCourseTitle.setOnClickListener { (itemData as? UserCourseReviewItem.PotentialReviewItem)?.course?.let(onCourseTitleClicked) }
userReviewRating.setOnRatingBarChangeListener { ratingBar, rating, fromUser ->
val potentialReview = (itemData as? UserCourseReviewItem.PotentialReviewItem) ?: return@setOnRatingBarChangeListener
if (fromUser) {
onWriteReviewClicked(potentialReview.course.id, potentialReview.course.title.toString(), rating)
// TODO .postDelayed is not safe, it would be a good idea to replace this
ratingBar.postDelayed({ ratingBar.rating = 0f }, RATING_RESET_DELAY_MS)
}
}
userReviewWriteAction.setOnClickListener {
val potentialReview = (itemData as? UserCourseReviewItem.PotentialReviewItem) ?: return@setOnClickListener
onWriteReviewClicked(potentialReview.course.id, potentialReview.course.title.toString(), -1f)
}
}
override fun onBind(data: UserCourseReviewItem) {
data as UserCourseReviewItem.PotentialReviewItem
userReviewCourseTitle.text = data.course.title
Glide
.with(context)
.asBitmap()
.load(data.course.cover)
.placeholder(R.drawable.general_placeholder)
.fitCenter()
.into(userReviewIcon)
userReviewRating.max = 5
}
}
} | apache-2.0 | 9f55139a2280d1c899cf6baaf19ce484 | 47.095238 | 147 | 0.709145 | 5.399287 | false | false | false | false |
rabsouza/bgscore | app/src/androidTest/java/br/com/battista/bgscore/robot/BaseRobot.kt | 1 | 2876 | package br.com.battista.bgscore.robot
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.*
import android.support.v7.widget.Toolbar
import android.widget.TextView
import br.com.battista.bgscore.R
import br.com.battista.bgscore.helper.CustomViewMatcher.withBottomBarItemCheckedStatus
import org.hamcrest.Matchers.allOf
abstract class BaseRobot {
protected fun doWait(millis: Long) {
try {
Thread.sleep(millis)
} catch (var4: InterruptedException) {
throw RuntimeException("Could not sleep.", var4)
}
}
fun navigationToHome() = apply {
onView(withId(R.id.action_home))
.perform(click())
onView(allOf(isAssignableFrom(TextView::class.java), withParent(isAssignableFrom(Toolbar::class.java))))
.check(matches(withText(R.string.title_home)))
}
fun navigationToMatches() = apply {
onView(withId(R.id.action_matches))
.perform(click())
onView(allOf(isAssignableFrom(TextView::class.java), withParent(isAssignableFrom(Toolbar::class.java))))
.check(matches(withText(R.string.title_matches)))
}
fun navigationToGames() = apply {
onView(withId(R.id.action_games))
.perform(click())
onView(allOf(isAssignableFrom(TextView::class.java), withParent(isAssignableFrom(Toolbar::class.java))))
.check(matches(withText(R.string.title_games)))
}
fun navigationToAccount() = apply {
onView(withId(R.id.action_more))
.perform(click())
onView(allOf(isAssignableFrom(TextView::class.java), withParent(isAssignableFrom(Toolbar::class.java))))
.check(matches(withText(R.string.title_account)))
}
fun checkBottomBarHomeChecked() = apply {
onView(withId(R.id.action_home))
.check(matches(withBottomBarItemCheckedStatus(true)))
}
fun checkBottomBarMatchesChecked() = apply {
onView(withId(R.id.action_matches))
.check(matches(withBottomBarItemCheckedStatus(true)))
}
fun checkBottomBarGamesChecked() = apply {
onView(withId(R.id.action_games))
.check(matches(withBottomBarItemCheckedStatus(true)))
}
fun checkBottomBarAccountChecked() = apply {
onView(withId(R.id.action_more))
.check(matches(withBottomBarItemCheckedStatus(true)))
}
fun closeWelcomeDialog() = apply {
try {
onView(withText(R.string.btn_ok))
.perform(click())
} catch (e: Exception) {
}
}
companion object {
val DO_WAIT_MILLIS = 500
}
}
| gpl-3.0 | 9f6753d51c9f1df02fb22f443538fb28 | 31.314607 | 112 | 0.650904 | 4.364188 | false | false | false | false |
MarcBob/SmartRecyclerViewAdapter | smartrecyclerviewadapter/src/main/kotlin/bobzien/com/smartrecyclerviewadapter/SmartRecyclerViewAdapter.kt | 1 | 8888 | package bobzien.com.smartrecyclerviewadapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.RecyclerView.Adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import bobzien.com.smartrecyclerviewadapter.SmartRecyclerViewAdapter.ViewHolder
import java.util.*
open class SmartRecyclerViewAdapter @Throws(DuplicateItemViewTypeException::class)
constructor(viewHolders: Array<ViewHolder<Any>>) : Adapter<ViewHolder<Any>>() {
private val viewHolders = HashMap<Class<Any>, ViewHolder<Any>>()
private val itemViewTypeToViewHolders = HashMap<Int, ViewHolder<Any>>()
private var items: MutableList<Any> = ArrayList()
private val typeViewHolders = ArrayList<TypeViewHolder<Any>>()
var selectedPosition: Int = 0
set(selectedPosition: Int) {
val oldSelectedPosition = this.selectedPosition
field = selectedPosition
notifyItemChanged(oldSelectedPosition)
notifyItemChanged(selectedPosition)
}
init {
for (viewHolder in viewHolders) {
addViewHolder(viewHolder)
}
}
constructor(viewHolder: ViewHolder<Any>) : this(arrayOf(viewHolder)) {
}
fun addViewHolders(vararg viewHolders: ViewHolder<Any>) {
for (viewHolder in viewHolders) {
addViewHolder(viewHolder)
}
}
fun addViewHolder(viewHolder: ViewHolder<Any>) {
if (itemViewTypeToViewHolders.containsKey(viewHolder.genericItemViewType)) {
throw (DuplicateItemViewTypeException((itemViewTypeToViewHolders[viewHolder.genericItemViewType] as Any).javaClass.simpleName
+ " has same ItemViewType as " + viewHolder.javaClass.simpleName
+ ". Overwrite getGenericItemViewType() in one of the two classes and assign a new type. Consider using an android id."))
}
itemViewTypeToViewHolders.put(viewHolder.genericItemViewType, viewHolder)
if (viewHolder is TypeViewHolder<Any>) {
typeViewHolders.add(viewHolder)
}
this.viewHolders.put(viewHolder.getHandledClass() as Class<Any>, viewHolder)
}
fun setItems(items: List<Any>) {
this.items = ArrayList(items)
wrapItems()
notifyDataSetChanged()
}
fun addItems(position: Int, vararg newItems: Any) {
var index = position
val insertionPosition = position
for (item in newItems) {
items.add(index++, wrapItem(item))
}
notifyItemRangeInserted(insertionPosition, newItems.size)
}
fun addItems(position: Int, newItems: List<Any>) {
var index = position
val insertionPosition = position
for (item in newItems) {
items.add(index++, wrapItem(item))
}
wrapItems()
notifyItemRangeInserted(insertionPosition, newItems.size)
}
fun removeItemAt(position: Int) {
items.removeAt(position)
notifyItemRemoved(position)
}
fun removeItem(item: Any) {
val index = items.indexOf(item)
items.removeAt(index)
notifyItemRemoved(index)
}
fun removeItemRange(startPosition: Int, itemCount: Int) {
for (i in 0..itemCount - 1) {
items.removeAt(startPosition)
}
notifyItemRangeRemoved(startPosition, itemCount)
}
fun getItem(position: Int): Any? {
if (position >= itemCount || position < 0) {
return null
}
val item = items[position]
if (item is Wrapper) {
return item.item
}
return item
}
fun indexOf(item: Any?): Int {
return items.indexOf(item)
}
private fun wrapItems() {
if (typeViewHolders.size > 0) {
var i = 0
for (item in items) {
items[i] = wrapItem(item)
i++
}
}
}
private fun wrapItem(item: Any): Any {
for (typeViewHolder in typeViewHolders) {
if (typeViewHolder.internalCanHandle(item)) {
val wrappedObject = typeViewHolder.getWrappedObject(item)
return wrappedObject
}
}
return item
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<Any> {
val viewHolder = itemViewTypeToViewHolders[viewType]
val instance = viewHolder!!.getInstance(parent)
instance.adapter = this
return instance
}
override fun onBindViewHolder(holder: ViewHolder<Any>?, position: Int) {
var item = items[position]
if (holder is TypeViewHolder<*>) {
item = (item as Wrapper).item
}
(holder as ViewHolder<Any>).bindViewHolder(item, position == selectedPosition)
}
override fun getItemCount(): Int {
return items.size
}
override fun getItemViewType(position: Int): Int {
val viewHolder = getViewHolder(position)
return viewHolder.genericItemViewType
}
private fun getViewHolder(position: Int): ViewHolder<Any> {
val item = items[position]
val itemClass = item.javaClass
var viewHolder: ViewHolder<Any>? = viewHolders[itemClass]
if (viewHolder == null) {
viewHolder = tryToFindSuperClass(itemClass)
if (viewHolder != null) {
return viewHolder
}
throw (MissingViewHolderException("There is no Viewholder for " + itemClass.simpleName + " or one of its superClasses."))
}
return viewHolder
}
private fun tryToFindSuperClass(itemClass: Class<*>): ViewHolder<Any>? {
var viewHolder: ViewHolder<Any>?
var superclass: Class<*>? = itemClass.superclass
while (superclass != null) {
viewHolder = viewHolders[superclass]
if (viewHolder != null) {
viewHolders.put(superclass as Class<Any>, viewHolder)
return viewHolder
}
superclass = superclass.superclass
}
return null
}
abstract class ViewHolder<T>
/**
* This constructor is just used to create a factory that can produce the
* ViewHolder that contains the actual itemView using the getInstance(View parent) method.
* @param context
* *
* @param handledClass
*/
(val context: Context, handledClass: Class<*>, itemView: View? = null) : RecyclerView.ViewHolder(itemView ?: View(context)) {
var adapter: SmartRecyclerViewAdapter? = null
private var _handledClass: Class<*>
open fun getHandledClass(): Class<*> {
return _handledClass
}
init {
_handledClass = handledClass
}
fun getInstance(parent: ViewGroup): ViewHolder<Any> {
val view = LayoutInflater.from(context).inflate(layoutResourceId, parent, false)
return getInstance(view)
}
/**
* This has to create a new instance which was created using a constructor which calls super(itemView).
* @param itemView
* *
* @return the new ViewHolder
*/
abstract fun getInstance(itemView: View): ViewHolder<Any>
/**
* Gets the LayoutResourceId of the layout this ViewHolder uses
* @return
*/
abstract val layoutResourceId: Int
/**
* Override this if itemViewTypes are colliding. Consider using an android Id.
* @return itemViewType
*/
open val genericItemViewType: Int
get() = layoutResourceId
/**
* Bind the ViewHolder and return it.
* @param item
* *
* @param selected
* *
* @return ViewHolder
*/
abstract fun bindViewHolder(item: T, selected: Boolean)
}
abstract class TypeViewHolder<T>(context: Context, clazz: Class<Any>, itemView: View? = null) : ViewHolder<T>(context, clazz, itemView) {
private lateinit var _handledClass: Class<*>
init {
_handledClass = getWrappedObject(null).javaClass
}
fun internalCanHandle(item: Any): Boolean {
if (item.javaClass == super.getHandledClass()) {
return canHandle(item as T)
}
return false
}
protected abstract fun canHandle(item: T): Boolean
abstract fun getWrappedObject(item: T?): Wrapper
override fun getHandledClass(): Class<*> {
return _handledClass
}
}
interface Wrapper {
val item: Any
}
class DuplicateItemViewTypeException(detailMessage: String) : RuntimeException(detailMessage)
class MissingViewHolderException(detailMessage: String) : RuntimeException(detailMessage)
}
| apache-2.0 | 13aeb87196803225d01636556df4ecd9 | 30.40636 | 141 | 0.619037 | 5.119816 | false | false | false | false |
square/wire | wire-library/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcResponse.kt | 1 | 1514 | /*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("GrpcResponseCloseable")
package com.squareup.wire
import com.squareup.wire.internal.addSuppressed
import okio.IOException
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
expect class GrpcResponse {
@get:JvmName("body") val body: GrpcResponseBody?
@JvmOverloads fun header(name: String, defaultValue: String? = null): String?
@Throws(IOException::class)
fun trailers(): GrpcHeaders
fun close()
}
internal inline fun <T : GrpcResponse?, R> T.use(block: (T) -> R): R {
var exception: Throwable? = null
try {
return block(this)
} catch (e: Throwable) {
exception = e
throw e
} finally {
closeFinally(exception)
}
}
private fun GrpcResponse?.closeFinally(cause: Throwable?) = when {
this == null -> {
}
cause == null -> close()
else ->
try {
close()
} catch (closeException: Throwable) {
cause.addSuppressed(closeException)
}
}
| apache-2.0 | b190fb7058d0a8b47351370b8541fb95 | 25.103448 | 79 | 0.704095 | 3.963351 | false | false | false | false |
DiUS/pact-jvm | core/model/src/test/kotlin/au/com/dius/pact/core/model/OptionalBodyTest.kt | 1 | 2958 | package au.com.dius.pact.core.model
import io.kotlintest.shouldBe
import io.kotlintest.specs.StringSpec
import java.nio.charset.Charset
class OptionalBodyTest : StringSpec() {
val nullBodyVar: OptionalBody? = null
val missingBody = OptionalBody.missing()
val nullBody = OptionalBody.nullBody()
val emptyBody = OptionalBody.empty()
val presentBody = OptionalBody.body("present".toByteArray())
init {
"a null body variable is missing" {
nullBodyVar.isMissing() shouldBe true
}
"a missing body is missing" {
missingBody.isMissing() shouldBe true
}
"a body that contains a null is not missing" {
nullBody.isMissing() shouldBe false
}
"an empty body is not missing" {
emptyBody.isMissing() shouldBe false
}
"a present body is not missing" {
presentBody.isMissing() shouldBe false
}
"a null body variable is null" {
nullBodyVar.isNull() shouldBe true
}
"a missing body is not null" {
missingBody.isNull() shouldBe false
}
"a body that contains a null is null" {
nullBody.isNull() shouldBe true
}
"an empty body is not null" {
emptyBody.isNull() shouldBe false
}
"a present body is not null" {
presentBody.isNull() shouldBe false
}
"a null body variable is not empty" {
nullBodyVar.isEmpty() shouldBe false
}
"a missing body is not empty" {
missingBody.isEmpty() shouldBe false
}
"a body that contains a null is not empty" {
nullBody.isEmpty() shouldBe false
}
"an empty body is empty" {
emptyBody.isEmpty() shouldBe true
}
"a present body is not empty" {
presentBody.isEmpty() shouldBe false
}
"a null body variable is not present" {
nullBodyVar.isPresent() shouldBe false
}
"a missing body is not present" {
missingBody.isPresent() shouldBe false
}
"a body that contains a null is not present" {
nullBody.isPresent() shouldBe false
}
"an empty body is not present" {
emptyBody.isPresent() shouldBe false
}
"a present body is present" {
presentBody.isPresent() shouldBe true
}
"a null body or else returns the else" {
nullBodyVar.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldBe "else"
}
"a missing body or else returns the else" {
missingBody.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldBe "else"
}
"a body that contains a null or else returns the else" {
nullBody.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldBe "else"
}
"an empty body or else returns empty" {
emptyBody.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldBe ""
}
"a present body or else returns the body" {
presentBody.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldBe "present"
}
}
}
| apache-2.0 | d7cba95355519efea669a6fdc4aeb7a8 | 24.282051 | 100 | 0.657877 | 4.516031 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/core/layers/recurrent/deltarnn/DeltaLayersWindow.kt | 1 | 3216 | /* 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 core.layers.recurrent.deltarnn
import com.kotlinnlp.simplednn.core.functionalities.activations.Tanh
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.models.recurrent.RecurrentLayerUnit
import com.kotlinnlp.simplednn.core.layers.models.recurrent.LayersWindow
import com.kotlinnlp.simplednn.core.layers.models.recurrent.deltarnn.DeltaRNNLayerParameters
import com.kotlinnlp.simplednn.core.layers.models.recurrent.deltarnn.DeltaRNNLayer
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
/**
*
*/
internal sealed class DeltaLayersWindow: LayersWindow {
/**
*
*/
object Empty : DeltaLayersWindow() {
override fun getPrevState(): Nothing? = null
override fun getNextState(): Nothing? = null
}
/**
*
*/
object Back : DeltaLayersWindow() {
override fun getPrevState(): DeltaRNNLayer<DenseNDArray> = buildPrevStateLayer()
override fun getNextState(): Nothing? = null
}
/**
*
*/
object Front : DeltaLayersWindow() {
override fun getPrevState(): Nothing? = null
override fun getNextState(): DeltaRNNLayer<DenseNDArray> = buildNextStateLayer()
}
/**
*
*/
object Bilateral : DeltaLayersWindow() {
override fun getPrevState(): DeltaRNNLayer<DenseNDArray> = buildPrevStateLayer()
override fun getNextState(): DeltaRNNLayer<DenseNDArray> = buildNextStateLayer()
}
}
/**
*
*/
private fun buildPrevStateLayer(): DeltaRNNLayer<DenseNDArray> = DeltaRNNLayer(
inputArray = AugmentedArray(size = 4),
inputType = LayerType.Input.Dense,
outputArray = RecurrentLayerUnit<DenseNDArray>(5).apply {
assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.2, 0.2, -0.3, -0.9, -0.8)))
setActivation(Tanh)
activate()
},
params = DeltaRNNLayerParameters(inputSize = 4, outputSize = 5),
activationFunction = Tanh,
layersWindow = DeltaLayersWindow.Empty,
dropout = 0.0
)
/**
*
*/
private fun buildNextStateLayer(): DeltaRNNLayer<DenseNDArray> = DeltaRNNLayer(
inputArray = AugmentedArray<DenseNDArray>(size = 4),
inputType = LayerType.Input.Dense,
outputArray = RecurrentLayerUnit<DenseNDArray>(5).apply {
assignErrors(errors = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.1, -0.5, 0.7, 0.2)))
},
params = DeltaRNNLayerParameters(inputSize = 4, outputSize = 5),
activationFunction = Tanh,
layersWindow = DeltaLayersWindow.Empty,
dropout = 0.0
).apply {
wx.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.7, -0.7, -0.2, 0.8, -0.6)))
partition.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.2, -0.1, 0.6, -0.8, 0.5)))
candidate.assignErrors(DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.4, 0.6, -0.1, 0.3, 0.0)))
}
| mpl-2.0 | 793c038beee6e2c024ba55669e426157 | 31.16 | 96 | 0.722637 | 4.176623 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/main/jetpack/migration/JetpackMigrationFragment.kt | 1 | 4573 | package org.wordpress.android.ui.main.jetpack.migration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewmodel.compose.viewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.ui.ActivityLauncher
import org.wordpress.android.ui.accounts.HelpActivity.Origin.JETPACK_MIGRATION_HELP
import org.wordpress.android.ui.compose.theme.AppTheme
import org.wordpress.android.ui.main.jetpack.migration.JetpackMigrationViewModel.JetpackMigrationActionEvent
import org.wordpress.android.ui.main.jetpack.migration.JetpackMigrationViewModel.JetpackMigrationActionEvent.CompleteFlow
import org.wordpress.android.ui.main.jetpack.migration.JetpackMigrationViewModel.JetpackMigrationActionEvent.ShowHelp
import org.wordpress.android.ui.main.jetpack.migration.JetpackMigrationViewModel.UiState.Content
import org.wordpress.android.ui.main.jetpack.migration.JetpackMigrationViewModel.UiState.Error
import org.wordpress.android.ui.main.jetpack.migration.JetpackMigrationViewModel.UiState.Loading
import org.wordpress.android.ui.main.jetpack.migration.compose.state.DeleteStep
import org.wordpress.android.ui.main.jetpack.migration.compose.state.DoneStep
import org.wordpress.android.ui.main.jetpack.migration.compose.state.ErrorStep
import org.wordpress.android.ui.main.jetpack.migration.compose.state.LoadingState
import org.wordpress.android.ui.main.jetpack.migration.compose.state.NotificationsStep
import org.wordpress.android.ui.main.jetpack.migration.compose.state.WelcomeStep
import javax.inject.Inject
@AndroidEntryPoint
class JetpackMigrationFragment : Fragment() {
@Inject lateinit var dispatcher: Dispatcher
private val viewModel: JetpackMigrationViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = ComposeView(requireContext()).apply {
setContent {
AppTheme {
JetpackMigrationScreen()
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
observeViewModelEvents()
val showDeleteWpState = arguments?.getBoolean(KEY_SHOW_DELETE_WP_STATE, false) ?: false
viewModel.start(showDeleteWpState)
}
private fun observeViewModelEvents() {
viewModel.actionEvents.onEach(this::handleActionEvents).launchIn(viewLifecycleOwner.lifecycleScope)
}
private fun handleActionEvents(actionEvent: JetpackMigrationActionEvent) {
when (actionEvent) {
is CompleteFlow -> ActivityLauncher.showMainActivity(requireContext())
is ShowHelp -> launchHelpScreen()
}
}
private fun launchHelpScreen() {
ActivityLauncher.viewHelpAndSupport(
requireContext(),
JETPACK_MIGRATION_HELP,
null,
null
)
}
companion object {
private const val KEY_SHOW_DELETE_WP_STATE = "KEY_SHOW_DELETE_WP_STATE"
fun newInstance(showDeleteWpState: Boolean = false): JetpackMigrationFragment =
JetpackMigrationFragment().apply {
arguments = Bundle().apply {
putBoolean(KEY_SHOW_DELETE_WP_STATE, showDeleteWpState)
}
}
}
}
@Composable
private fun JetpackMigrationScreen(viewModel: JetpackMigrationViewModel = viewModel()) {
Box {
val uiState by viewModel.uiState.collectAsState(Loading)
Crossfade(targetState = uiState) { state ->
when (state) {
is Content.Welcome -> WelcomeStep(state)
is Content.Notifications -> NotificationsStep(state)
is Content.Done -> DoneStep(state)
is Content.Delete -> DeleteStep(state)
is Error -> ErrorStep(state)
is Loading -> LoadingState()
}
}
}
}
| gpl-2.0 | 91cf4362d6b38dddf59dfe9469a51e73 | 40.572727 | 121 | 0.736059 | 4.875267 | false | false | false | false |
michaelkourlas/voipms-sms-client | voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/database/entities/Sms.kt | 1 | 2232 | /*
* VoIP.ms SMS
* Copyright (C) 2021 Michael Kourlas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kourlas.voipms_sms.database.entities
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import net.kourlas.voipms_sms.sms.Message
import java.util.*
@Entity(tableName = Sms.TABLE_NAME)
data class Sms(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = COLUMN_DATABASE_ID) val databaseId: Long = 0,
@ColumnInfo(name = COLUMN_VOIP_ID) val voipId: Long? = null,
@ColumnInfo(name = COLUMN_DATE) val date: Long = Date().time / 1000L,
@ColumnInfo(name = COLUMN_INCOMING) val incoming: Long = 0,
@ColumnInfo(name = COLUMN_DID) val did: String = "",
@ColumnInfo(name = COLUMN_CONTACT) val contact: String = "",
@ColumnInfo(name = COLUMN_TEXT) val text: String = "",
@ColumnInfo(name = COLUMN_UNREAD) val unread: Long = 0,
@ColumnInfo(name = COLUMN_DELIVERED) val delivered: Long = 0,
@ColumnInfo(name = COLUMN_DELIVERY_IN_PROGRESS)
val deliveryInProgress: Long = 0
) {
fun toMessage(): Message = Message(this)
fun toMessage(databaseId: Long): Message = Message(this, databaseId)
companion object {
const val TABLE_NAME = "sms"
const val COLUMN_DATABASE_ID = "DatabaseId"
const val COLUMN_VOIP_ID = "VoipId"
const val COLUMN_DATE = "Date"
const val COLUMN_INCOMING = "Type"
const val COLUMN_DID = "Did"
const val COLUMN_CONTACT = "Contact"
const val COLUMN_TEXT = "Text"
const val COLUMN_UNREAD = "Unread"
const val COLUMN_DELIVERED = "Delivered"
const val COLUMN_DELIVERY_IN_PROGRESS = "DeliveryInProgress"
}
} | apache-2.0 | 6c8514b612d28b9951c7d853ddfbaa62 | 36.847458 | 75 | 0.69086 | 3.854922 | false | false | false | false |
bkmioa/NexusRss | app/src/main/java/io/github/bkmioa/nexusrss/download/ui/DownloadNodeListFragment.kt | 1 | 4859 | package io.github.bkmioa.nexusrss.download.ui
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.PopupMenu
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.airbnb.epoxy.EpoxyController
import com.google.android.material.snackbar.Snackbar
import io.github.bkmioa.nexusrss.R
import io.github.bkmioa.nexusrss.base.BaseFragment
import io.github.bkmioa.nexusrss.model.DownloadNodeModel
import io.github.bkmioa.nexusrss.ui.TabListActivity
import kotlinx.android.synthetic.main.activity_tab_list.*
class DownloadNodeListFragment : BaseFragment() {
companion object {
const val REQUEST_CODE_ADD = 0x1
const val REQUEST_CODE_EDIT = 0x2
}
private val listViewModel: DownloadNodeListViewModel by viewModels()
private val listController = ListController()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_download_node_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView.layoutManager = LinearLayoutManager(requireContext())
recyclerView.adapter = listController.adapter
listViewModel.getAllLiveData().observe(viewLifecycleOwner, {
it ?: throw IllegalStateException()
listController.update(it)
})
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.add("Add")
.setIcon(R.drawable.ic_menu_add)
.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS)
.setOnMenuItemClickListener {
val intent = DownloadEditActivity.createIntent(requireContext())
startActivityForResult(intent, REQUEST_CODE_ADD)
true
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
TabListActivity.REQUEST_CODE_ADD -> {
val downloadNode: DownloadNodeModel = data?.getParcelableExtra(DownloadEditActivity.KEY_DOWNLOAD_NODE)
?: throw IllegalStateException()
listViewModel.addDownloadNode(downloadNode)
}
TabListActivity.REQUEST_CODE_EDIT -> {
val downloadNode: DownloadNodeModel = data?.getParcelableExtra(DownloadEditActivity.KEY_DOWNLOAD_NODE)
?: throw IllegalStateException()
listViewModel.addDownloadNode(downloadNode)
}
}
}
}
private fun onItemClicked(model: DownloadNodeModel) {
val intent = DownloadEditActivity.createIntent(requireContext(), model)
startActivityForResult(intent, REQUEST_CODE_EDIT)
}
private fun onMoreClicked(clickedView: View, model: DownloadNodeModel) {
val popupMenu = PopupMenu(requireContext(), clickedView)
popupMenu.menu
.add(R.string.action_duplicate).setOnMenuItemClickListener {
listViewModel.addDownloadNode(model.copy(id = null))
true
}
popupMenu.menu
.add(R.string.action_delete).setOnMenuItemClickListener {
deleteNode(model)
true
}
popupMenu.show()
}
private fun deleteNode(model: DownloadNodeModel) {
listViewModel.delete(model)
Snackbar.make(requireView(), R.string.deleted, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.undo_action) {
listViewModel.addDownloadNode(model)
}
.show()
}
inner class ListController : EpoxyController() {
private var nodeList: List<DownloadNodeModel> = emptyList()
override fun buildModels() {
nodeList.forEach { item ->
DownloadNodeItemViewModel_(item)
.onClickListener(View.OnClickListener { onItemClicked(item) })
.onMoreClickListener(View.OnClickListener { onMoreClicked(it, item) })
.addTo(this)
}
}
fun update(list: List<DownloadNodeModel>) {
nodeList = list
requestModelBuild()
}
}
} | apache-2.0 | 075c6d0d8a2c17a8c98da3405edbc318 | 36.674419 | 122 | 0.66063 | 5.2473 | false | false | false | false |
efficios/jabberwocky | jabberwockd/src/main/kotlin/com/efficios/jabberwocky/jabberwockd/HttpConstants.kt | 2 | 885 | /*
* 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 com.efficios.jabberwocky.jabberwockd
object HttpConstants {
object Methods {
const val GET = "GET"
const val PUT = "PUT"
const val DELETE = "DELETE"
}
object ReturnCodes {
/** Success */
const val R_200 = 200
/** Success, resulted in resource creation */
const val R_201 = 201
/** Requested resource not found */
const val R_404 = 404
/** Operation not allowed (i.e. deleting a read-only resource) */
const val R_405 = 405
}
} | epl-1.0 | 5e3a81149b1782acf423c87cba96808d | 26.6875 | 84 | 0.639548 | 4.23445 | false | false | false | false |
NordicSemiconductor/Android-DFU-Library | profile_dfu/src/main/java/no/nordicsemi/android/dfu/profile/settings/viewmodel/SettingsViewModel.kt | 1 | 7194 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.dfu.profile.settings.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import no.nordicsemi.android.dfu.analytics.*
import no.nordicsemi.android.common.navigation.NavigationManager
import no.nordicsemi.android.dfu.profile.DfuWelcomeScreen
import no.nordicsemi.android.dfu.profile.settings.domain.DFUSettings
import no.nordicsemi.android.dfu.profile.settings.repository.SettingsRepository
import no.nordicsemi.android.dfu.profile.settings.view.*
import javax.inject.Inject
private const val INFOCENTER_LINK = "https://infocenter.nordicsemi.com/topic/sdk_nrf5_v17.1.0/examples_bootloader.html"
@HiltViewModel
class SettingsViewModel @Inject constructor(
private val repository: SettingsRepository,
private val navigationManager: NavigationManager,
private val analytics: DfuAnalytics
) : ViewModel() {
val state = repository.settings.stateIn(viewModelScope, SharingStarted.Eagerly, DFUSettings())
fun onEvent(event: SettingsScreenViewEvent) {
when (event) {
NavigateUp -> navigationManager.navigateUp()
OnResetButtonClick -> restoreDefaultSettings()
OnAboutAppClick -> navigationManager.navigateTo(DfuWelcomeScreen)
OnAboutDfuClick -> navigationManager.openLink(INFOCENTER_LINK)
OnExternalMcuDfuSwitchClick -> onExternalMcuDfuSwitchClick()
OnKeepBondInformationSwitchClick -> onKeepBondSwitchClick()
OnPacketsReceiptNotificationSwitchClick -> onPacketsReceiptNotificationSwitchClick()
OnDisableResumeSwitchClick -> onDisableResumeSwitchClick()
OnForceScanningAddressesSwitchClick -> onForceScanningAddressesSwitchClick()
is OnNumberOfPocketsChange -> onNumberOfPocketsChange(event.numberOfPockets)
is OnPrepareDataObjectDelayChange -> onPrepareDataObjectDelayChange(event.delay)
is OnRebootTimeChange -> onRebootTimeChange(event.time)
is OnScanTimeoutChange -> onScanTimeoutChange(event.timeout)
}
}
private fun restoreDefaultSettings() {
viewModelScope.launch {
repository.storeSettings(DFUSettings().copy(showWelcomeScreen = false))
}
analytics.logEvent(ResetSettingsEvent)
}
private fun onExternalMcuDfuSwitchClick() {
val currentValue = state.value.externalMcuDfu
val newSettings = state.value.copy(externalMcuDfu = !currentValue)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(ExternalMCUSettingsEvent(newSettings.externalMcuDfu))
}
private fun onKeepBondSwitchClick() {
val currentValue = state.value.keepBondInformation
val newSettings = state.value.copy(keepBondInformation = !currentValue)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(KeepBondSettingsEvent(newSettings.keepBondInformation))
}
private fun onPacketsReceiptNotificationSwitchClick() {
val currentValue = state.value.packetsReceiptNotification
val newSettings = state.value.copy(packetsReceiptNotification = !currentValue)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(PacketsReceiptNotificationSettingsEvent(newSettings.packetsReceiptNotification))
}
private fun onDisableResumeSwitchClick() {
val currentValue = state.value.disableResume
val newSettings = state.value.copy(disableResume = !currentValue)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(DisableResumeSettingsEvent(newSettings.disableResume))
}
private fun onForceScanningAddressesSwitchClick() {
val currentValue = state.value.forceScanningInLegacyDfu
val newSettings = state.value.copy(forceScanningInLegacyDfu = !currentValue)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(ForceScanningSettingsEvent(newSettings.forceScanningInLegacyDfu))
}
private fun onNumberOfPocketsChange(numberOfPockets: Int) {
val newSettings = state.value.copy(numberOfPackets = numberOfPockets)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(NumberOfPacketsSettingsEvent(newSettings.numberOfPackets))
}
private fun onPrepareDataObjectDelayChange(delay: Int) {
val newSettings = state.value.copy(prepareDataObjectDelay = delay)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(PrepareDataObjectDelaySettingsEvent(newSettings.prepareDataObjectDelay))
}
private fun onRebootTimeChange(rebootTime: Int) {
val newSettings = state.value.copy(rebootTime = rebootTime)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(RebootTimeSettingsEvent(newSettings.rebootTime))
}
private fun onScanTimeoutChange(scanTimeout: Int) {
val newSettings = state.value.copy(scanTimeout = scanTimeout)
viewModelScope.launch {
repository.storeSettings(newSettings)
}
analytics.logEvent(ScanTimeoutSettingsEvent(newSettings.scanTimeout))
}
}
| bsd-3-clause | ded63797fadc5aae2a9075c2b545ec3f | 43.407407 | 119 | 0.745482 | 5.216824 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/stories/viewer/StoryViewerActivity.kt | 1 | 2012 | package org.thoughtcrime.securesms.stories.viewer
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatDelegate
import org.thoughtcrime.securesms.PassphraseRequiredActivity
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.voice.VoiceNoteMediaController
import org.thoughtcrime.securesms.components.voice.VoiceNoteMediaControllerOwner
import org.thoughtcrime.securesms.stories.StoryViewerArgs
class StoryViewerActivity : PassphraseRequiredActivity(), VoiceNoteMediaControllerOwner {
override lateinit var voiceNoteMediaController: VoiceNoteMediaController
override fun attachBaseContext(newBase: Context) {
delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES
super.attachBaseContext(newBase)
}
override fun onCreate(savedInstanceState: Bundle?, ready: Boolean) {
supportPostponeEnterTransition()
super.onCreate(savedInstanceState, ready)
setContentView(R.layout.fragment_container)
voiceNoteMediaController = VoiceNoteMediaController(this)
if (savedInstanceState == null) {
replaceStoryViewerFragment()
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
setIntent(intent)
replaceStoryViewerFragment()
}
override fun onEnterAnimationComplete() {
if (Build.VERSION.SDK_INT >= 21) {
window.transitionBackgroundFadeDuration = 100
}
}
private fun replaceStoryViewerFragment() {
supportFragmentManager.beginTransaction()
.replace(
R.id.fragment_container,
StoryViewerFragment.create(intent.getParcelableExtra(ARGS)!!)
)
.commit()
}
companion object {
private const val ARGS = "story.viewer.args"
@JvmStatic
fun createIntent(
context: Context,
storyViewerArgs: StoryViewerArgs
): Intent {
return Intent(context, StoryViewerActivity::class.java).putExtra(ARGS, storyViewerArgs)
}
}
}
| gpl-3.0 | a01bb6803576e7c4947889cb51f9dcd1 | 28.588235 | 93 | 0.767396 | 4.943489 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/badges/gifts/viewgift/received/ViewReceivedGiftBottomSheet.kt | 1 | 10501 | package org.thoughtcrime.securesms.badges.gifts.viewgift.received
import android.content.DialogInterface
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.kotlin.subscribeBy
import org.signal.core.util.DimensionUnit
import org.signal.core.util.logging.Log
import org.signal.libsignal.zkgroup.InvalidInputException
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.badges.BadgeRepository
import org.thoughtcrime.securesms.badges.gifts.ExpiredGiftSheetConfiguration.forExpiredGiftBadge
import org.thoughtcrime.securesms.badges.gifts.viewgift.ViewGiftRepository
import org.thoughtcrime.securesms.badges.models.Badge
import org.thoughtcrime.securesms.badges.models.BadgeDisplay112
import org.thoughtcrime.securesms.badges.models.BadgeDisplay160
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter
import org.thoughtcrime.securesms.components.settings.DSLSettingsBottomSheetFragment
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.app.AppSettingsActivity
import org.thoughtcrime.securesms.components.settings.app.subscription.errors.DonationError
import org.thoughtcrime.securesms.components.settings.app.subscription.errors.DonationErrorDialogs
import org.thoughtcrime.securesms.components.settings.app.subscription.errors.DonationErrorSource
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.components.settings.models.IndeterminateLoadingCircle
import org.thoughtcrime.securesms.components.settings.models.OutlinedSwitch
import org.thoughtcrime.securesms.database.model.MmsMessageRecord
import org.thoughtcrime.securesms.database.model.databaseprotos.GiftBadge
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.BottomSheetUtil
import org.thoughtcrime.securesms.util.LifecycleDisposable
import java.util.concurrent.TimeUnit
/**
* Handles all interactions for received gift badges.
*/
class ViewReceivedGiftBottomSheet : DSLSettingsBottomSheetFragment() {
companion object {
private val TAG = Log.tag(ViewReceivedGiftBottomSheet::class.java)
private const val ARG_GIFT_BADGE = "arg.gift.badge"
private const val ARG_SENT_FROM = "arg.sent.from"
private const val ARG_MESSAGE_ID = "arg.message.id"
@JvmField
val REQUEST_KEY: String = TAG
const val RESULT_NOT_NOW = "result.not.now"
@JvmStatic
fun show(fragmentManager: FragmentManager, messageRecord: MmsMessageRecord) {
ViewReceivedGiftBottomSheet().apply {
arguments = Bundle().apply {
putParcelable(ARG_SENT_FROM, messageRecord.recipient.id)
putByteArray(ARG_GIFT_BADGE, messageRecord.giftBadge!!.toByteArray())
putLong(ARG_MESSAGE_ID, messageRecord.id)
}
show(fragmentManager, BottomSheetUtil.STANDARD_BOTTOM_SHEET_FRAGMENT_TAG)
}
}
}
private val lifecycleDisposable = LifecycleDisposable()
private val sentFrom: RecipientId
get() = requireArguments().getParcelable(ARG_SENT_FROM)!!
private val messageId: Long
get() = requireArguments().getLong(ARG_MESSAGE_ID)
private val viewModel: ViewReceivedGiftViewModel by viewModels(
factoryProducer = { ViewReceivedGiftViewModel.Factory(sentFrom, messageId, ViewGiftRepository(), BadgeRepository(requireContext())) }
)
private var errorDialog: DialogInterface? = null
private lateinit var progressDialog: AlertDialog
override fun bindAdapter(adapter: DSLSettingsAdapter) {
BadgeDisplay112.register(adapter)
OutlinedSwitch.register(adapter)
BadgeDisplay160.register(adapter)
IndeterminateLoadingCircle.register(adapter)
progressDialog = MaterialAlertDialogBuilder(requireContext())
.setView(R.layout.redeeming_gift_dialog)
.setCancelable(false)
.create()
lifecycleDisposable.bindTo(viewLifecycleOwner)
lifecycleDisposable += DonationError
.getErrorsForSource(DonationErrorSource.GIFT_REDEMPTION)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { donationError ->
onRedemptionError(donationError)
}
lifecycleDisposable += viewModel.state.observeOn(AndroidSchedulers.mainThread()).subscribe { state ->
adapter.submitList(getConfiguration(state).toMappingModelList())
}
}
override fun onDestroy() {
super.onDestroy()
progressDialog.hide()
}
private fun onRedemptionError(throwable: Throwable?) {
Log.w(TAG, "onRedemptionError", throwable, true)
if (errorDialog != null) {
Log.i(TAG, "Already displaying an error dialog. Skipping.")
return
}
errorDialog = DonationErrorDialogs.show(
requireContext(), throwable,
object : DonationErrorDialogs.DialogCallback() {
override fun onDialogDismissed() {
findNavController().popBackStack()
}
}
)
}
private fun getConfiguration(state: ViewReceivedGiftState): DSLConfiguration {
return configure {
if (state.giftBadge == null) {
customPref(IndeterminateLoadingCircle)
} else if (isGiftBadgeExpired(state.giftBadge)) {
forExpiredGiftBadge(
giftBadge = state.giftBadge,
onMakeAMonthlyDonation = {
requireActivity().startActivity(AppSettingsActivity.subscriptions(requireContext()))
requireActivity().finish()
},
onNotNow = {
dismissAllowingStateLoss()
}
)
} else {
if (state.giftBadge.redemptionState == GiftBadge.RedemptionState.STARTED) {
progressDialog.show()
} else {
progressDialog.hide()
}
if (state.recipient != null && !isGiftBadgeRedeemed(state.giftBadge)) {
noPadTextPref(
title = DSLSettingsText.from(
charSequence = requireContext().getString(R.string.ViewReceivedGiftBottomSheet__s_sent_you_a_gift, state.recipient.getShortDisplayName(requireContext())),
DSLSettingsText.CenterModifier, DSLSettingsText.Title2BoldModifier
)
)
space(DimensionUnit.DP.toPixels(12f).toInt())
presentSubheading(state.recipient)
space(DimensionUnit.DP.toPixels(37f).toInt())
}
if (state.badge != null && state.controlState != null) {
presentForUnexpiredGiftBadge(state, state.giftBadge, state.controlState, state.badge)
space(DimensionUnit.DP.toPixels(16f).toInt())
}
}
}
}
private fun DSLConfiguration.presentSubheading(recipient: Recipient) {
noPadTextPref(
title = DSLSettingsText.from(
charSequence = requireContext().getString(R.string.ViewReceivedGiftBottomSheet__youve_received_a_gift_badge, recipient.getDisplayName(requireContext())),
DSLSettingsText.CenterModifier
)
)
}
private fun DSLConfiguration.presentForUnexpiredGiftBadge(
state: ViewReceivedGiftState,
giftBadge: GiftBadge,
controlState: ViewReceivedGiftState.ControlState,
badge: Badge
) {
when (giftBadge.redemptionState) {
GiftBadge.RedemptionState.REDEEMED -> {
customPref(
BadgeDisplay160.Model(
badge = badge
)
)
state.recipient?.run {
presentSubheading(this)
}
}
else -> {
customPref(
BadgeDisplay112.Model(
badge = badge
)
)
customPref(
OutlinedSwitch.Model(
text = DSLSettingsText.from(
when (controlState) {
ViewReceivedGiftState.ControlState.DISPLAY -> R.string.SubscribeThanksForYourSupportBottomSheetDialogFragment__display_on_profile
ViewReceivedGiftState.ControlState.FEATURE -> R.string.SubscribeThanksForYourSupportBottomSheetDialogFragment__make_featured_badge
}
),
isEnabled = giftBadge.redemptionState != GiftBadge.RedemptionState.STARTED,
isChecked = state.getControlChecked(),
onClick = {
viewModel.setChecked(!it.isChecked)
}
)
)
if (state.hasOtherBadges && state.displayingOtherBadges) {
noPadTextPref(DSLSettingsText.from(R.string.ThanksForYourSupportBottomSheetFragment__when_you_have_more))
}
space(DimensionUnit.DP.toPixels(36f).toInt())
primaryButton(
text = DSLSettingsText.from(R.string.ViewReceivedGiftSheet__redeem),
isEnabled = giftBadge.redemptionState != GiftBadge.RedemptionState.STARTED,
onClick = {
lifecycleDisposable += viewModel.redeem().subscribeBy(
onComplete = {
dismissAllowingStateLoss()
},
onError = {
onRedemptionError(it)
}
)
}
)
secondaryButtonNoOutline(
text = DSLSettingsText.from(R.string.ViewReceivedGiftSheet__not_now),
isEnabled = giftBadge.redemptionState != GiftBadge.RedemptionState.STARTED,
onClick = {
setFragmentResult(
REQUEST_KEY,
Bundle().apply {
putBoolean(RESULT_NOT_NOW, true)
}
)
dismissAllowingStateLoss()
}
)
}
}
}
private fun isGiftBadgeRedeemed(giftBadge: GiftBadge): Boolean {
return giftBadge.redemptionState == GiftBadge.RedemptionState.REDEEMED
}
private fun isGiftBadgeExpired(giftBadge: GiftBadge): Boolean {
return try {
val receiptCredentialPresentation = ReceiptCredentialPresentation(giftBadge.redemptionToken.toByteArray())
receiptCredentialPresentation.receiptExpirationTime <= TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())
} catch (e: InvalidInputException) {
Log.w(TAG, "Failed to check expiration of given badge.", e)
true
}
}
}
| gpl-3.0 | e6c77f0c6a99adc0a5242ea4471db66d | 36.370107 | 168 | 0.712694 | 5.124939 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/stories/viewer/reply/direct/StoryDirectReplyViewModel.kt | 2 | 2000 | package org.thoughtcrime.securesms.stories.viewer.reply.direct
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.livedata.Store
class StoryDirectReplyViewModel(
private val storyId: Long,
private val groupDirectReplyRecipientId: RecipientId?,
private val repository: StoryDirectReplyRepository
) : ViewModel() {
private val store = Store(StoryDirectReplyState())
private val disposables = CompositeDisposable()
val state: LiveData<StoryDirectReplyState> = store.stateLiveData
init {
if (groupDirectReplyRecipientId != null) {
store.update(Recipient.live(groupDirectReplyRecipientId).liveDataResolved) { recipient, state ->
state.copy(groupDirectReplyRecipient = recipient)
}
}
disposables += repository.getStoryPost(storyId).subscribe { record ->
store.update { it.copy(storyRecord = record) }
}
}
fun sendReply(charSequence: CharSequence): Completable {
return repository.send(storyId, groupDirectReplyRecipientId, charSequence, false)
}
fun sendReaction(emoji: CharSequence): Completable {
return repository.send(storyId, groupDirectReplyRecipientId, emoji, true)
}
override fun onCleared() {
super.onCleared()
disposables.clear()
}
class Factory(
private val storyId: Long,
private val groupDirectReplyRecipientId: RecipientId?,
private val repository: StoryDirectReplyRepository
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return modelClass.cast(
StoryDirectReplyViewModel(storyId, groupDirectReplyRecipientId, repository)
) as T
}
}
}
| gpl-3.0 | a1e02965729a9f75379c6fb1a19820e8 | 32.333333 | 102 | 0.7695 | 4.950495 | false | false | false | false |
evanchooly/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/JavaInfo.kt | 1 | 1063 | package com.beust.kobalt
import java.io.File
abstract public class JavaInfo {
public var javaExecutable: File? = null
get() = findExecutable("java")
public var javacExecutable: File? = null
get() = findExecutable("javac")
public var javadocExecutable: File? = null
get() = findExecutable("javadoc")
abstract public var javaHome: File?
abstract public var runtimeJar: File?
abstract public var toolsJar: File?
abstract public fun findExecutable(command: String) : File
companion object {
fun create(javaBase: File?): Jvm {
val vendor = System.getProperty("java.vm.vendor")
if (vendor.toLowerCase().startsWith("apple inc.")) {
return AppleJvm(OperatingSystem.Companion.current(), javaBase!!)
}
if (vendor.toLowerCase().startsWith("ibm corporation")) {
return IbmJvm(OperatingSystem.Companion.current(), javaBase!!)
}
return Jvm(OperatingSystem.Companion.current(), javaBase)
}
}
}
| apache-2.0 | 6f501090eb15ddd3611866f13224e59c | 34.433333 | 80 | 0.634055 | 4.682819 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/cio/NettyHttpResponsePipeline.kt | 1 | 13028 | /*
* 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.server.netty.cio
import io.ktor.http.*
import io.ktor.server.netty.*
import io.ktor.server.netty.http1.*
import io.ktor.util.*
import io.ktor.util.cio.*
import io.ktor.utils.io.*
import io.netty.channel.*
import io.netty.handler.codec.http.*
import io.netty.handler.codec.http2.*
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import java.io.*
import kotlin.coroutines.*
private const val UNFLUSHED_LIMIT = 65536
/**
* Contains methods for handling http request with Netty
*/
internal class NettyHttpResponsePipeline constructor(
private val context: ChannelHandlerContext,
private val httpHandlerState: NettyHttpHandlerState,
override val coroutineContext: CoroutineContext
) : CoroutineScope {
/**
* True if there is unflushed written data in channel
*/
private val isDataNotFlushed: AtomicBoolean = atomic(false)
/**
* Represents promise which is marked as success when the last read request is handled.
* Marked as fail when last read request is failed.
* Default value is success on purpose to start first request handle
*/
private var previousCallHandled: ChannelPromise = context.newPromise().also {
it.setSuccess()
}
/** Flush if all is true:
* - there is some unflushed data
* - nothing to read from the channel
* - there are no active requests
*/
internal fun flushIfNeeded() {
if (
isDataNotFlushed.value &&
httpHandlerState.isChannelReadCompleted.value &&
httpHandlerState.activeRequests.value == 0L
) {
context.flush()
isDataNotFlushed.compareAndSet(expect = true, update = false)
}
}
internal fun processResponse(call: NettyApplicationCall) {
call.previousCallFinished = previousCallHandled
call.finishedEvent = context.newPromise()
previousCallHandled = call.finishedEvent
processElement(call)
}
private fun processElement(call: NettyApplicationCall) = setOnResponseReadyHandler(call) {
try {
handleRequestMessage(call)
} catch (actualException: Throwable) {
respondWithFailure(call, actualException)
} finally {
call.responseWriteJob.cancel()
}
}
/**
* Process [call] with [block] when the response is ready and previous call is successfully processed.
* [call] won't be processed with [block] if previous call is failed.
*/
private fun setOnResponseReadyHandler(call: NettyApplicationCall, block: () -> Unit) {
call.response.responseReady.addListener responseFlag@{ responseFlagResult ->
call.previousCallFinished.addListener waitPreviousCall@{ previousCallResult ->
if (!previousCallResult.isSuccess) {
respondWithFailure(call, previousCallResult.cause())
return@waitPreviousCall
}
if (!responseFlagResult.isSuccess) {
respondWithFailure(call, responseFlagResult.cause())
return@waitPreviousCall
}
block.invoke()
}
}
}
private fun respondWithFailure(call: NettyApplicationCall, actualException: Throwable) {
val t = when {
actualException is IOException && actualException !is ChannelIOException ->
ChannelWriteException(exception = actualException)
else -> actualException
}
call.response.responseChannel.cancel(t)
call.responseWriteJob.cancel()
call.response.cancel()
call.dispose()
call.finishedEvent.setFailure(t)
}
private fun respondWithUpgrade(call: NettyApplicationCall, responseMessage: Any): ChannelFuture {
val future = context.write(responseMessage)
call.upgrade(context)
call.isByteBufferContent = true
context.flush()
isDataNotFlushed.compareAndSet(expect = true, update = false)
return future
}
/**
* Writes the [lastMessage] to the channel, schedules flush and close the channel if needed
*/
private fun handleLastResponseMessage(
call: NettyApplicationCall,
lastMessage: Any?,
lastFuture: ChannelFuture
) {
val prepareForClose = call.isContextCloseRequired() &&
(!call.request.keepAlive || call.response.isUpgradeResponse())
val lastMessageFuture = if (lastMessage != null) {
val future = context.write(lastMessage)
isDataNotFlushed.compareAndSet(expect = false, update = true)
future
} else {
null
}
httpHandlerState.onLastResponseMessage(context)
call.finishedEvent.setSuccess()
lastMessageFuture?.addListener {
if (prepareForClose) {
close(lastFuture)
return@addListener
}
}
if (prepareForClose) {
close(lastFuture)
return
}
scheduleFlush()
}
fun close(lastFuture: ChannelFuture) {
context.flush()
isDataNotFlushed.compareAndSet(expect = true, update = false)
lastFuture.addListener {
context.close()
}
}
private fun scheduleFlush() {
context.executor().execute {
flushIfNeeded()
}
}
/**
* Gets the request message and decides how it should be handled
*/
private fun handleRequestMessage(call: NettyApplicationCall) {
val responseMessage = call.response.responseMessage
val response = call.response
val requestMessageFuture = if (response.isUpgradeResponse()) {
respondWithUpgrade(call, responseMessage)
} else {
respondWithHeader(responseMessage)
}
if (responseMessage is FullHttpResponse) {
return handleLastResponseMessage(call, null, requestMessageFuture)
} else if (responseMessage is Http2HeadersFrame && responseMessage.isEndStream) {
return handleLastResponseMessage(call, null, requestMessageFuture)
}
val responseChannel = response.responseChannel
val bodySize = when {
responseChannel === ByteReadChannel.Empty -> 0
responseMessage is HttpResponse -> responseMessage.headers().getInt("Content-Length", -1)
responseMessage is Http2HeadersFrame -> responseMessage.headers().getInt("content-length", -1)
else -> -1
}
launch(context.executor().asCoroutineDispatcher(), start = CoroutineStart.UNDISPATCHED) {
respondWithBodyAndTrailerMessage(
call,
response,
bodySize,
requestMessageFuture
)
}
}
/**
* Writes response header to the channel and makes a flush
* if client is waiting for the response header
*/
private fun respondWithHeader(responseMessage: Any): ChannelFuture {
return if (isHeaderFlushNeeded()) {
val future = context.writeAndFlush(responseMessage)
isDataNotFlushed.compareAndSet(expect = true, update = false)
future
} else {
val future = context.write(responseMessage)
isDataNotFlushed.compareAndSet(expect = false, update = true)
future
}
}
/**
* True if client is waiting for response header, false otherwise
*/
private fun isHeaderFlushNeeded(): Boolean {
val activeRequestsValue = httpHandlerState.activeRequests.value
return httpHandlerState.isChannelReadCompleted.value &&
!httpHandlerState.isCurrentRequestFullyRead.value &&
activeRequestsValue == 1L
}
/**
* Writes response body of size [bodySize] and trailer message to the channel and makes flush if needed
*/
private suspend fun respondWithBodyAndTrailerMessage(
call: NettyApplicationCall,
response: NettyApplicationResponse,
bodySize: Int,
requestMessageFuture: ChannelFuture
) {
try {
when (bodySize) {
0 -> respondWithEmptyBody(call, requestMessageFuture)
in 1..65536 -> respondWithSmallBody(call, response, bodySize)
-1 -> respondBodyWithFlushOnLimitOrEmptyChannel(call, response, requestMessageFuture)
else -> respondBodyWithFlushOnLimit(call, response, requestMessageFuture)
}
} catch (actualException: Throwable) {
respondWithFailure(call, actualException)
}
}
/**
* Writes trailer message to the channel and makes flush if needed when response body is empty.
*/
private fun respondWithEmptyBody(call: NettyApplicationCall, lastFuture: ChannelFuture) {
return handleLastResponseMessage(call, call.prepareEndOfStreamMessage(false), lastFuture)
}
/**
* Writes body and trailer message to the channel if response body size is up to 65536 bytes.
* Makes flush if needed.
*/
private suspend fun respondWithSmallBody(
call: NettyApplicationCall,
response: NettyApplicationResponse,
size: Int
) {
val buffer = context.alloc().buffer(size)
val channel = response.responseChannel
val start = buffer.writerIndex()
channel.readFully(buffer.nioBuffer(start, buffer.writableBytes()))
buffer.writerIndex(start + size)
val future = context.write(call.prepareMessage(buffer, true))
isDataNotFlushed.compareAndSet(expect = false, update = true)
val lastMessage = response.prepareTrailerMessage() ?: call.prepareEndOfStreamMessage(true)
handleLastResponseMessage(call, lastMessage, future)
}
/**
* Writes body and trailer message to the channel if body size is more than 65536 bytes.
* Makes flush only when limit of written bytes is reached.
*/
private suspend fun respondBodyWithFlushOnLimit(
call: NettyApplicationCall,
response: NettyApplicationResponse,
requestMessageFuture: ChannelFuture
) = respondWithBigBody(call, response, requestMessageFuture) { _, unflushedBytes ->
unflushedBytes >= UNFLUSHED_LIMIT
}
/**
* Writes body and trailer message to the channel if body size is unknown.
* Makes flush when there is nothing to read from the response channel or
* limit of written bytes is reached.
*/
private suspend fun respondBodyWithFlushOnLimitOrEmptyChannel(
call: NettyApplicationCall,
response: NettyApplicationResponse,
requestMessageFuture: ChannelFuture
) = respondWithBigBody(call, response, requestMessageFuture) { channel, unflushedBytes ->
unflushedBytes >= UNFLUSHED_LIMIT || channel.availableForRead == 0
}
private suspend fun respondWithBigBody(
call: NettyApplicationCall,
response: NettyApplicationResponse,
requestMessageFuture: ChannelFuture,
shouldFlush: (channel: ByteReadChannel, unflushedBytes: Int) -> Boolean
) {
val channel = response.responseChannel
var unflushedBytes = 0
var lastFuture: ChannelFuture = requestMessageFuture
@Suppress("DEPRECATION")
channel.lookAheadSuspend {
while (true) {
val buffer = request(0, 1)
if (buffer == null) {
if (!awaitAtLeast(1)) break
continue
}
val rc = buffer.remaining()
val buf = context.alloc().buffer(rc)
val idx = buf.writerIndex()
buf.setBytes(idx, buffer)
buf.writerIndex(idx + rc)
consumed(rc)
unflushedBytes += rc
val message = call.prepareMessage(buf, false)
if (shouldFlush.invoke(channel, unflushedBytes)) {
context.read()
val future = context.writeAndFlush(message)
isDataNotFlushed.compareAndSet(expect = true, update = false)
lastFuture = future
future.suspendAwait()
unflushedBytes = 0
} else {
lastFuture = context.write(message)
isDataNotFlushed.compareAndSet(expect = false, update = true)
}
}
}
val lastMessage = response.prepareTrailerMessage() ?: call.prepareEndOfStreamMessage(false)
handleLastResponseMessage(call, lastMessage, lastFuture)
}
}
private fun NettyApplicationResponse.isUpgradeResponse() =
status()?.value == HttpStatusCode.SwitchingProtocols.value
public class NettyResponsePipelineException(message: String) : Exception(message)
| apache-2.0 | e384d96afcfaea1defa3029b2dcbb64a | 34.693151 | 118 | 0.637243 | 5.444212 | false | false | false | false |
cfieber/orca | orca-pipelinetemplate/src/main/java/com/netflix/spinnaker/orca/pipelinetemplate/v1schema/handler/V1TemplateLoaderHandler.kt | 1 | 4410 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.pipelinetemplate.v1schema.handler
import com.fasterxml.jackson.databind.ObjectMapper
import com.netflix.spinnaker.orca.pipelinetemplate.handler.Handler
import com.netflix.spinnaker.orca.pipelinetemplate.handler.HandlerChain
import com.netflix.spinnaker.orca.pipelinetemplate.handler.PipelineTemplateContext
import com.netflix.spinnaker.orca.pipelinetemplate.loader.TemplateLoader
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.TemplateMerge
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.model.PipelineTemplate
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.model.TemplateConfiguration
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.DefaultRenderContext
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.RenderContext
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.RenderUtil
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.Renderer
import java.util.stream.Collectors
class V1TemplateLoaderHandler(
private val templateLoader: TemplateLoader,
private val renderer: Renderer,
private val objectMapper: ObjectMapper
) : Handler {
override fun handle(chain: HandlerChain, context: PipelineTemplateContext) {
val config = objectMapper.convertValue(context.getRequest().config, TemplateConfiguration::class.java)
// Allow template inlining to perform plans without publishing the template
if (context.getRequest().plan && context.getRequest().template != null) {
val template = objectMapper.convertValue(context.getRequest().template, PipelineTemplate::class.java)
val templates = templateLoader.load(template)
context.setSchemaContext(V1PipelineTemplateContext(config, TemplateMerge.merge(templates)))
return
}
val trigger = context.getRequest().trigger as MutableMap<String, Any>?
setTemplateSourceWithJinja(config, trigger)
// If a template source isn't provided by the configuration, we're assuming that the configuration is fully-formed.
val template: PipelineTemplate
if (config.pipeline.template == null) {
template = PipelineTemplate().apply {
variables = config.pipeline.variables.entries.stream()
.map { PipelineTemplate.Variable().apply {
name = it.key
defaultValue = it.value
}}
.collect(Collectors.toList())
}
} else {
val templates = templateLoader.load(config.pipeline.template)
template = TemplateMerge.merge(templates)
}
// ensure that any expressions contained with template variables are rendered
val renderContext = RenderUtil.createDefaultRenderContext(template, config, trigger)
renderTemplateVariables(renderContext, template)
context.setSchemaContext(V1PipelineTemplateContext(
config,
template
))
}
private fun renderTemplateVariables(renderContext: RenderContext, pipelineTemplate: PipelineTemplate) {
if (pipelineTemplate.variables == null) {
return
}
pipelineTemplate.variables.forEach { v ->
val value = v.defaultValue
if (v.isNullable() && value == null) {
renderContext.variables.putIfAbsent(v.name, v.defaultValue)
} else if (value != null && value is String) {
v.defaultValue = renderer.renderGraph(value.toString(), renderContext)
renderContext.variables.putIfAbsent(v.name, v.defaultValue)
}
}
}
private fun setTemplateSourceWithJinja(tc: TemplateConfiguration, trigger: MutableMap<String, Any>?) {
if (trigger == null || tc.pipeline.template == null) {
return
}
val context = DefaultRenderContext(tc.pipeline.application, null, trigger)
tc.pipeline.template.source = renderer.render(tc.pipeline.template.source, context)
}
}
| apache-2.0 | 216346de34ef453c427ac2e70ff50e34 | 42.235294 | 119 | 0.756009 | 4.555785 | false | true | false | false |
MichaelRocks/grip | library/src/main/java/io/michaelrocks/grip/mirrors/FieldMirror.kt | 1 | 2649 | /*
* Copyright 2021 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.grip.mirrors
import io.michaelrocks.grip.commons.LazyList
import io.michaelrocks.grip.mirrors.signature.EmptyFieldSignatureMirror
import io.michaelrocks.grip.mirrors.signature.FieldSignatureMirror
import io.michaelrocks.grip.mirrors.signature.GenericDeclaration
import io.michaelrocks.grip.mirrors.signature.LazyFieldSignatureMirror
interface FieldMirror : Element<Type>, Annotated {
val signature: FieldSignatureMirror
val value: Any?
class Builder(
private val asmApi: Int,
private val enclosingGenericDeclaration: GenericDeclaration
) {
private var access = 0
private var name: String? = null
private var type: Type? = null
private var signature: String? = null
private var value: Any? = null
private val annotations = LazyList<AnnotationMirror>()
fun access(access: Int) = apply {
this.access = access
}
fun name(name: String) = apply {
this.name = name
this.type = getTypeByInternalName(name)
}
fun type(type: Type) = apply {
this.type = type
}
fun signature(signature: String?) = apply {
this.signature = signature
}
fun value(value: Any?) = apply {
this.value = value
}
fun addAnnotation(mirror: AnnotationMirror) = apply {
this.annotations += mirror
}
fun build(): FieldMirror = ImmutableFieldMirror(this)
private fun buildSignature(): FieldSignatureMirror =
signature?.let { LazyFieldSignatureMirror(asmApi, enclosingGenericDeclaration, it) }
?: EmptyFieldSignatureMirror(type!!)
private class ImmutableFieldMirror(builder: Builder) : FieldMirror {
override val access = builder.access
override val name = builder.name!!
override val type = builder.type!!
override val signature = builder.buildSignature()
override val value = builder.value
override val annotations = ImmutableAnnotationCollection(builder.annotations)
override fun toString() = "FieldMirror{name = $name, type = $type}"
}
}
}
| apache-2.0 | 45d668a17cd02f52a4e928f8fb5997a7 | 30.915663 | 90 | 0.715364 | 4.606957 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/uhabits/intents/PendingIntentFactory.kt | 1 | 7229 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.intents
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.app.PendingIntent.FLAG_MUTABLE
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.app.PendingIntent.getActivity
import android.app.PendingIntent.getBroadcast
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import org.isoron.uhabits.activities.habits.list.ListHabitsActivity
import org.isoron.uhabits.activities.habits.show.ShowHabitActivity
import org.isoron.uhabits.core.AppScope
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.Timestamp
import org.isoron.uhabits.inject.AppContext
import org.isoron.uhabits.receivers.ReminderReceiver
import org.isoron.uhabits.receivers.WidgetReceiver
import javax.inject.Inject
@AppScope
class PendingIntentFactory
@Inject constructor(
@AppContext private val context: Context,
private val intentFactory: IntentFactory
) {
fun addCheckmark(habit: Habit, timestamp: Timestamp?): PendingIntent =
getBroadcast(
context,
1,
Intent(context, WidgetReceiver::class.java).apply {
data = Uri.parse(habit.uriString)
action = WidgetReceiver.ACTION_ADD_REPETITION
if (timestamp != null) putExtra("timestamp", timestamp.unixTime)
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun dismissNotification(habit: Habit): PendingIntent =
getBroadcast(
context,
0,
Intent(context, ReminderReceiver::class.java).apply {
action = WidgetReceiver.ACTION_DISMISS_REMINDER
data = Uri.parse(habit.uriString)
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun removeRepetition(habit: Habit, timestamp: Timestamp?): PendingIntent =
getBroadcast(
context,
3,
Intent(context, WidgetReceiver::class.java).apply {
action = WidgetReceiver.ACTION_REMOVE_REPETITION
data = Uri.parse(habit.uriString)
if (timestamp != null) putExtra("timestamp", timestamp.unixTime)
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun showHabit(habit: Habit): PendingIntent =
androidx.core.app.TaskStackBuilder
.create(context)
.addNextIntentWithParentStack(
intentFactory.startShowHabitActivity(
context,
habit
)
)
.getPendingIntent(0, FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT)!!
fun showHabitTemplate(): PendingIntent {
return getActivity(
context,
0,
Intent(context, ShowHabitActivity::class.java),
getIntentTemplateFlags()
)
}
fun showHabitFillIn(habit: Habit) =
Intent().apply {
data = Uri.parse(habit.uriString)
}
fun showReminder(
habit: Habit,
reminderTime: Long?,
timestamp: Long
): PendingIntent =
getBroadcast(
context,
(habit.id!! % Integer.MAX_VALUE).toInt() + 1,
Intent(context, ReminderReceiver::class.java).apply {
action = ReminderReceiver.ACTION_SHOW_REMINDER
data = Uri.parse(habit.uriString)
putExtra("timestamp", timestamp)
putExtra("reminderTime", reminderTime)
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun snoozeNotification(habit: Habit): PendingIntent =
getBroadcast(
context,
0,
Intent(context, ReminderReceiver::class.java).apply {
data = Uri.parse(habit.uriString)
action = ReminderReceiver.ACTION_SNOOZE_REMINDER
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun toggleCheckmark(habit: Habit, timestamp: Long?): PendingIntent =
getBroadcast(
context,
2,
Intent(context, WidgetReceiver::class.java).apply {
data = Uri.parse(habit.uriString)
action = WidgetReceiver.ACTION_TOGGLE_REPETITION
if (timestamp != null) putExtra("timestamp", timestamp)
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun updateWidgets(): PendingIntent =
getBroadcast(
context,
0,
Intent(context, WidgetReceiver::class.java).apply {
action = WidgetReceiver.ACTION_UPDATE_WIDGETS_VALUE
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
fun showNumberPicker(habit: Habit, timestamp: Timestamp): PendingIntent? {
return getActivity(
context,
(habit.id!! % Integer.MAX_VALUE).toInt() + 1,
Intent(context, ListHabitsActivity::class.java).apply {
action = ListHabitsActivity.ACTION_EDIT
putExtra("habit", habit.id)
putExtra("timestamp", timestamp.unixTime)
},
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
)
}
fun showNumberPickerTemplate(): PendingIntent {
return getActivity(
context,
1,
Intent(context, ListHabitsActivity::class.java).apply {
action = ListHabitsActivity.ACTION_EDIT
},
getIntentTemplateFlags()
)
}
fun showNumberPickerFillIn(habit: Habit, timestamp: Timestamp) = Intent().apply {
putExtra("habit", habit.id)
putExtra("timestamp", timestamp.unixTime)
}
private fun getIntentTemplateFlags(): Int {
var flags = 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
flags = flags or FLAG_MUTABLE
}
return flags
}
fun toggleCheckmarkTemplate(): PendingIntent =
getBroadcast(
context,
2,
Intent(context, WidgetReceiver::class.java).apply {
action = WidgetReceiver.ACTION_TOGGLE_REPETITION
},
getIntentTemplateFlags()
)
fun toggleCheckmarkFillIn(habit: Habit, timestamp: Timestamp) = Intent().apply {
data = Uri.parse(habit.uriString)
putExtra("timestamp", timestamp.unixTime)
}
}
| gpl-3.0 | f3618649813d19da999a9ca282502235 | 33.419048 | 85 | 0.61912 | 4.984828 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/parser/internal/expression/function/FunctionIf.kt | 1 | 3335 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.parser.internal.expression.function
import org.hisp.dhis.android.core.parser.internal.expression.CommonExpressionVisitor
import org.hisp.dhis.android.core.parser.internal.expression.ExpressionItem
import org.hisp.dhis.antlr.AntlrParserUtils
import org.hisp.dhis.parser.expression.antlr.ExpressionParser.ExprContext
/**
* Function if
* <pre>
*
* In-memory Logic:
*
* arg0 returns
* ---- -------
* true arg1
* false arg2
* null null
*
* SQL logic (CASE WHEN arg0 THEN arg1 ELSE arg2 END):
*
* arg0 returns
* ---- -------
* true arg1
* false arg2
* null arg2
</pre> *
*
* @author Jim Grace
*/
internal class FunctionIf : ExpressionItem {
override fun evaluate(ctx: ExprContext, visitor: CommonExpressionVisitor): Any? {
val arg0 = visitor.castBooleanVisit(ctx.expr(0))
return when {
arg0 == null -> null
arg0 -> visitor.visit(ctx.expr(1))
else -> visitor.visit(ctx.expr(2))
}
}
override fun evaluateAllPaths(ctx: ExprContext, visitor: CommonExpressionVisitor): Any {
val arg0 = visitor.castBooleanVisit(ctx.expr(0))
val arg1 = visitor.visit(ctx.expr(1))
val arg2 = visitor.visit(ctx.expr(2))
if (arg1 != null) {
AntlrParserUtils.castClass(arg1.javaClass, arg2)
}
return when {
arg0 != null && arg0 -> arg1
else -> arg2
}
}
override fun getSql(ctx: ExprContext, visitor: CommonExpressionVisitor): Any {
return "CASE WHEN ${visitor.castStringVisit(ctx.expr(0))} " +
"THEN ${visitor.castStringVisit(ctx.expr(1))} " +
"ELSE ${visitor.castStringVisit(ctx.expr(2))} END"
}
}
| bsd-3-clause | 406b14da14f1f32e3e53b7b52996b9de | 36.055556 | 92 | 0.693853 | 4.057178 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/common/DateFilterPeriodHelper.kt | 1 | 5327 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.common
import dagger.Reusable
import java.util.*
import javax.inject.Inject
import org.hisp.dhis.android.core.event.EventDataFilter
import org.hisp.dhis.android.core.period.Period
import org.hisp.dhis.android.core.period.internal.CalendarProvider
import org.hisp.dhis.android.core.period.internal.ParentPeriodGenerator
@Reusable
internal class DateFilterPeriodHelper @Inject constructor(
private val calendarProvider: CalendarProvider,
private val parentPeriodGenerator: ParentPeriodGenerator
) {
companion object {
@JvmStatic
fun mergeDateFilterPeriods(baseFilter: DateFilterPeriod?, newFilter: DateFilterPeriod?): DateFilterPeriod? {
return when {
newFilter == null -> baseFilter
baseFilter == null -> newFilter
newFilter.period() != null -> newFilter
newFilter.startBuffer() != null || newFilter.endBuffer() != null -> {
val builder = baseFilter.toBuilder()
builder.period(null)
builder.startDate(null)
builder.endDate(null)
builder.type(DatePeriodType.RELATIVE)
newFilter.startBuffer()?.let { builder.startBuffer(it) }
newFilter.endBuffer()?.let { builder.endBuffer(it) }
builder.build()
}
newFilter.startDate() != null || newFilter.endDate() != null -> {
val builder = baseFilter.toBuilder()
builder.period(null)
builder.startBuffer(null)
builder.endBuffer(null)
builder.type(DatePeriodType.ABSOLUTE)
newFilter.startDate()?.let { builder.startDate(it) }
newFilter.endDate()?.let { builder.endDate(it) }
builder.build()
}
else -> null
}
}
@JvmStatic
fun mergeEventDataFilters(list: List<EventDataFilter>, item: EventDataFilter): List<EventDataFilter> {
return list + item
}
}
fun getStartDate(filter: DateFilterPeriod): Date? {
return when (filter.type()) {
DatePeriodType.RELATIVE ->
when {
filter.period() != null -> getPeriod(filter.period()!!)?.startDate()
filter.startBuffer() != null -> addDaysToCurrentDate(filter.startBuffer()!!)
else -> null
}
DatePeriodType.ABSOLUTE -> filter.startDate()
else -> null
}
}
fun getEndDate(filter: DateFilterPeriod): Date? {
return when (filter.type()) {
DatePeriodType.RELATIVE ->
when {
filter.period() != null -> getPeriod(filter.period()!!)?.endDate()
filter.endBuffer() != null -> addDaysToCurrentDate(filter.endBuffer()!!)
else -> null
}
DatePeriodType.ABSOLUTE -> filter.endDate()
else -> null
}
}
private fun getPeriod(period: RelativePeriod): Period? {
val periods = parentPeriodGenerator.generateRelativePeriods(period)
return if (periods.isNotEmpty()) {
Period.builder()
.startDate(periods.first().startDate())
.endDate(periods.last().endDate())
.build()
} else {
null
}
}
private fun addDaysToCurrentDate(days: Int): Date {
val calendar = calendarProvider.calendar.clone() as Calendar
calendar.add(Calendar.DATE, days)
return calendar.time
}
}
| bsd-3-clause | 42844d94b5495347555006144ef4d6c8 | 39.356061 | 116 | 0.622301 | 5.08787 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-api/src/com/intellij/openapi/ui/UiSwitcher.kt | 3 | 1854 | // 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.openapi.ui
import com.intellij.openapi.util.Key
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus
import java.awt.Component
import javax.swing.JComponent
/**
* Defines switcher component which can change visibility state of component
* in UI view, for example collapsible groups in Kotlin UI DSL.
* Use [UiSwitcher.append] to add a switcher to a component. At the same time component can belong to several UiSwitcher
*
* @see UIUtil#showComponent(Component)
*/
@ApiStatus.Experimental
interface UiSwitcher {
/**
* Returns false if the component assigned to this UiSwitcher cannot be shown
*/
fun show(): Boolean
companion object {
private val UI_SWITCHER = Key.create<UiSwitcher>("com.intellij.openapi.ui.UI_SWITCHER")
@JvmStatic
fun append(component: JComponent, uiSwitcher: UiSwitcher) {
val existingSwitcher = component.getUserData(UI_SWITCHER)
component.putUserData(UI_SWITCHER, if (existingSwitcher == null) uiSwitcher
else UnionUiSwitcher(
listOf(existingSwitcher, uiSwitcher)))
}
/**
* Tries to show the component in UI hierarchy:
* * Expands collapsable groups if the component is inside such groups
*/
@JvmStatic
fun show(component: Component) {
var c = component
while (!c.isShowing) {
if (c is JComponent) {
val uiSwitcher = c.getUserData(UI_SWITCHER)
if (uiSwitcher?.show() == false) {
return
}
}
c = c.parent
}
}
}
}
private class UnionUiSwitcher(private val uiSwitchers: List<UiSwitcher>) : UiSwitcher {
override fun show(): Boolean {
return uiSwitchers.all { it.show() }
}
}
| apache-2.0 | a7ea245a8399dd5b14e0997a6f20482c | 28.903226 | 120 | 0.692017 | 4.262069 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/fir-fe10-binding/src/org/jetbrains/kotlin/idea/fir/fe10/binding/ToDescriptorBindingContextValueProviders.kt | 2 | 4927 | // 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.fir.fe10.binding
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.fir.fe10.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class ToDescriptorBindingContextValueProviders(bindingContext: KtSymbolBasedBindingContext) {
private val context = bindingContext.context
private val declarationToDescriptorGetters = mutableListOf<(PsiElement) -> DeclarationDescriptor?>()
private inline fun <reified K : PsiElement, V : DeclarationDescriptor> KtSymbolBasedBindingContext.registerDeclarationToDescriptorByKey(
slice: ReadOnlySlice<K, V>,
crossinline getter: (K) -> V?
) {
declarationToDescriptorGetters.add {
if (it is K) getter(it) else null
}
registerGetterByKey(slice, { getter(it) })
}
init {
bindingContext.registerDeclarationToDescriptorByKey(BindingContext.CLASS, this::getClass)
bindingContext.registerDeclarationToDescriptorByKey(BindingContext.TYPE_PARAMETER, this::getTypeParameter)
bindingContext.registerDeclarationToDescriptorByKey(BindingContext.FUNCTION, this::getFunction)
bindingContext.registerDeclarationToDescriptorByKey(BindingContext.CONSTRUCTOR, this::getConstructor)
bindingContext.registerDeclarationToDescriptorByKey(BindingContext.VARIABLE, this::getVariable)
bindingContext.registerDeclarationToDescriptorByKey(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, this::getPrimaryConstructorParameter)
bindingContext.registerGetterByKey(BindingContext.DECLARATION_TO_DESCRIPTOR, this::getDeclarationToDescriptor)
}
private inline fun <reified T : Any> PsiElement.getKtSymbolOfTypeOrNull(): T? =
this@ToDescriptorBindingContextValueProviders.context.withAnalysisSession {
[email protected]<KtDeclaration>()?.getSymbol().safeAs<T>()
}
private fun getClass(key: PsiElement): ClassDescriptor? {
val ktClassSymbol = key.getKtSymbolOfTypeOrNull<KtNamedClassOrObjectSymbol>() ?: return null
return KtSymbolBasedClassDescriptor(ktClassSymbol, context)
}
private fun getTypeParameter(key: KtTypeParameter): TypeParameterDescriptor {
val ktTypeParameterSymbol = context.withAnalysisSession { key.getTypeParameterSymbol() }
return KtSymbolBasedTypeParameterDescriptor(ktTypeParameterSymbol, context)
}
private fun getFunction(key: PsiElement): SimpleFunctionDescriptor? {
val ktFunctionLikeSymbol = key.getKtSymbolOfTypeOrNull<KtFunctionLikeSymbol>() ?: return null
return ktFunctionLikeSymbol.toDeclarationDescriptor(context) as? SimpleFunctionDescriptor
}
private fun getConstructor(key: PsiElement): ConstructorDescriptor? {
val ktConstructorSymbol = key.getKtSymbolOfTypeOrNull<KtConstructorSymbol>() ?: return null
val containerClass = context.withAnalysisSession { ktConstructorSymbol.getContainingSymbol() }
check(containerClass is KtNamedClassOrObjectSymbol) {
"Unexpected contained for Constructor symbol: $containerClass, ktConstructorSymbol = $ktConstructorSymbol"
}
return KtSymbolBasedConstructorDescriptor(ktConstructorSymbol, KtSymbolBasedClassDescriptor(containerClass, context))
}
private fun getVariable(key: PsiElement): VariableDescriptor? {
if (key !is KtVariableDeclaration) return null
if (key is KtProperty) {
val symbol = context.withAnalysisSession { key.getVariableSymbol() }
if (symbol !is KtPropertySymbol) context.implementationPlanned("Local property not supported: $symbol")
return KtSymbolBasedPropertyDescriptor(symbol, context)
} else {
context.implementationPostponed("Destruction declaration is not supported yet: $key")
}
}
private fun getPrimaryConstructorParameter(key: PsiElement): PropertyDescriptor? {
val parameter = key.safeAs<KtParameter>() ?: return null
val parameterSymbol = context.withAnalysisSession { parameter.getParameterSymbol() }
val propertySymbol = parameterSymbol.safeAs<KtValueParameterSymbol>()?.generatedPrimaryConstructorProperty ?: return null
return KtSymbolBasedPropertyDescriptor(propertySymbol, context)
}
private fun getDeclarationToDescriptor(key: PsiElement): DeclarationDescriptor? {
for (getter in declarationToDescriptorGetters) {
getter(key)?.let { return it }
}
return null
}
}
| apache-2.0 | df0b0039cb74f4556556c71f789d521a | 50.322917 | 158 | 0.758474 | 6.045399 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/expectactual/AddActualFix.kt | 2 | 4405 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.expectactual
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.quickfix.TypeAccessibilityChecker
import org.jetbrains.kotlin.idea.refactoring.getExpressionShortText
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class AddActualFix(
actualClassOrObject: KtClassOrObject,
missedDeclarations: List<KtDeclaration>
) : KotlinQuickFixAction<KtClassOrObject>(actualClassOrObject) {
private val missedDeclarationPointers = missedDeclarations.map { it.createSmartPointer() }
override fun getFamilyName() = text
override fun getText() = KotlinBundle.message("fix.create.missing.actual.members")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val factory = KtPsiFactory(element)
val codeStyleManager = CodeStyleManager.getInstance(project)
fun PsiElement.clean() {
ShortenReferences.DEFAULT.process(codeStyleManager.reformat(this) as KtElement)
}
val module = element.module ?: return
val checker = TypeAccessibilityChecker.create(project, module)
val errors = linkedMapOf<KtDeclaration, KotlinTypeInaccessibleException>()
for (missedDeclaration in missedDeclarationPointers.mapNotNull { it.element }) {
val actualDeclaration = try {
when (missedDeclaration) {
is KtClassOrObject -> factory.generateClassOrObject(project, false, missedDeclaration, checker)
is KtFunction, is KtProperty -> missedDeclaration.toDescriptor()?.safeAs<CallableMemberDescriptor>()?.let {
generateCallable(project, false, missedDeclaration, it, element, checker = checker)
}
else -> null
} ?: continue
} catch (e: KotlinTypeInaccessibleException) {
errors += missedDeclaration to e
continue
}
if (actualDeclaration is KtPrimaryConstructor) {
if (element.primaryConstructor == null)
element.addAfter(actualDeclaration, element.nameIdentifier).clean()
} else {
element.addDeclaration(actualDeclaration).clean()
}
}
if (errors.isNotEmpty()) {
val message = errors.entries.joinToString(
separator = "\n",
prefix = KotlinBundle.message("fix.create.declaration.error.some.types.inaccessible") + "\n"
) { (declaration, error) ->
getExpressionShortText(declaration) + " -> " + error.message
}
showInaccessibleDeclarationError(element, message, editor)
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val missedDeclarations = DiagnosticFactory.cast(diagnostic, Errors.NO_ACTUAL_CLASS_MEMBER_FOR_EXPECTED_CLASS).b.mapNotNull {
DescriptorToSourceUtils.descriptorToDeclaration(it.first) as? KtDeclaration
}.ifEmpty { return null }
return (diagnostic.psiElement as? KtClassOrObject)?.let {
AddActualFix(it, missedDeclarations)
}
}
}
} | apache-2.0 | 1552d35bd3a5ec1efda712f6cb3f6f04 | 45.87234 | 158 | 0.704427 | 5.339394 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/models/db/Signature.kt | 1 | 2001 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.shared.models.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import android.graphics.Bitmap
import android.os.Parcel
import android.os.Parcelable
import de.dreier.mytargets.shared.utils.readBitmap
import de.dreier.mytargets.shared.utils.writeBitmap
@Entity
data class Signature(
@PrimaryKey(autoGenerate = true)
var id: Long = 0,
var name: String = "",
/** A bitmap of the signature or null if no signature has been set. */
@ColumnInfo(typeAffinity = ColumnInfo.BLOB)
var bitmap: Bitmap? = null
) : Parcelable {
val isSigned: Boolean
get() = bitmap != null
fun getName(defaultName: String): String {
return if (name.isEmpty()) defaultName else name
}
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(id)
dest.writeString(name)
dest.writeBitmap(bitmap)
}
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<Signature> {
override fun createFromParcel(source: Parcel): Signature {
val id = source.readLong()
val name = source.readString()!!
val bitmap = source.readBitmap()
return Signature(id, name, bitmap)
}
override fun newArray(size: Int) = arrayOfNulls<Signature>(size)
}
}
}
| gpl-2.0 | 742eabf7f251d2fabed5db66d6d16c3d | 28.865672 | 78 | 0.668166 | 4.506757 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/service/cache/CacheBook.kt | 1 | 2256 | package top.zbeboy.isy.service.cache
/**
* 缓存相关key 与 有效期配置
*
* @author zbeboy
* @version 1.1
* @since 1.0
*/
open class CacheBook {
companion object {
/*
配置通用到期时间
*/
@JvmField
val EXPIRES_SECONDS: Long = 1800
@JvmField
val EXPIRES_MINUTES: Long = 30
@JvmField
val EXPIRES_HOURS: Long = 4
@JvmField
val EXPIRES_DAYS: Long = 1
@JvmField
val EXPIRES_YEAR: Long = 365
/*
特殊到期时间
*/
@JvmField
val EXPIRES_APPLICATION_ID_DAYS: Long = 2
@JvmField
val EXPIRES_GRADUATION_DESIGN_TEACHER_STUDENT_DAYS: Long = 30
@JvmField
val EXPIRES_SCHOOL_INFO_DAYS: Long = 300
/*
配置 KEY
*/
const val QUERY_USER_TYPE_BY_NAME = "QUERY_USER_TYPE_BY_NAME"
const val QUERY_USER_TYPE_BY_ID = "QUERY_USER_TYPE_BY_ID"
const val QUERY_SYSTEM_ALERT_TYPE_BY_NAME = "QUERY_SYSTEM_ALERT_TYPE_BY_NAME"
const val MENU_HTML = "MENU_HTML_"
const val SCHOOL_INFO_PATH = "SCHOOL_INFO_PATH_"
const val USER_APPLICATION_ID = "USER_APPLICATION_ID_"
const val URL_MAPPING = "URL_MAPPING_"
const val USER_ROLE_ID = "USER_ROLE_ID_"
const val USER_ROLE = "USER_ROLE_"
const val USER_KEY = "USER_KEY_"
const val USER_COLLEGE_ID = "USER_COLLEGE_ID_"
const val USER_DEPARTMENT_ID = "USER_DEPARTMENT_ID_"
const val USER_ORGANIZE_INFO = "USER_ORGANIZE_INFO_"
const val INTERNSHIP_BASE_CONDITION = "INTERNSHIP_BASE_CONDITION_"
const val GRADUATION_DESIGN_BASE_CONDITION = "GRADUATION_DESIGN_BASE_CONDITION_"
const val GRADUATION_DESIGN_TEACHER_STUDENT_COUNT = "GRADUATION_DESIGN_TEACHER_STUDENT_COUNT_"
const val GRADUATION_DESIGN_TEACHER_STUDENT = "GRADUATION_DESIGN_TEACHER_STUDENT_"
const val GRADUATION_DESIGN_PHARMTECH_STUDENT = "GRADUATION_DESIGN_PHARMTECH_STUDENT_"
const val GRADUATION_DESIGN_PHARMTECH_STUDENT_LIST = "GRADUATION_DESIGN_PHARMTECH_STUDENT_LIST_"
const val GRADUATION_DESIGN_ADJUSTECH_SYNC_TIME = "GRADUATION_DESIGN_ADJUSTECH_SYNC_TIME_"
}
} | mit | c370d82d684beb3eba544eaaf20677a8 | 27.269231 | 104 | 0.620236 | 3.754685 | false | false | false | false |
vladmm/intellij-community | plugins/settings-repository/src/keychain/CredentialsStore.kt | 5 | 1520 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.keychain
import com.intellij.openapi.diagnostic.Logger
val LOG: Logger = Logger.getInstance(CredentialsStore::class.java)
public class Credentials(id: String?, token: String?) {
public val id: String? = if (id.isNullOrEmpty()) null else id
public val token: String? = if (token.isNullOrEmpty()) null else token
override fun equals(other: Any?): Boolean {
if (other !is Credentials) return false
return id == other.id && token == other.token
}
override fun hashCode(): Int {
return (id?.hashCode() ?: 0) * 37 + (token?.hashCode() ?: 0)
}
}
public fun Credentials?.isFulfilled(): Boolean = this != null && id != null && token != null
public interface CredentialsStore {
public fun get(host: String?, sshKeyFile: String? = null): Credentials?
public fun save(host: String?, credentials: Credentials, sshKeyFile: String? = null)
public fun reset(host: String)
}
| apache-2.0 | a25dc00f03fe606dbfcf3b1fac8e5b63 | 33.545455 | 92 | 0.714474 | 4.03183 | false | false | false | false |
vladmm/intellij-community | platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/connection/VmConnection.kt | 1 | 3931 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger.connection
import com.intellij.ide.browsers.WebBrowser
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import com.intellij.util.EventDispatcher
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.socketConnection.ConnectionState
import com.intellij.util.io.socketConnection.ConnectionStatus
import com.intellij.util.io.socketConnection.SocketConnectionListener
import org.jetbrains.annotations.TestOnly
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.isPending
import org.jetbrains.concurrency.resolvedPromise
import org.jetbrains.debugger.DebugEventListener
import org.jetbrains.debugger.Vm
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import javax.swing.event.HyperlinkListener
abstract class VmConnection<T : Vm> : Disposable {
open val browser: WebBrowser? = null
private val stateRef = AtomicReference(ConnectionState(ConnectionStatus.NOT_CONNECTED))
private val dispatcher = EventDispatcher.create(DebugEventListener::class.java)
private val connectionDispatcher = ContainerUtil.createLockFreeCopyOnWriteList<(ConnectionState) -> Unit>()
@Volatile var vm: T? = null
protected set
private val opened = AsyncPromise<Any?>()
private val closed = AtomicBoolean()
val state: ConnectionState
get() = stateRef.get()
fun addDebugListener(listener: DebugEventListener) {
dispatcher.addListener(listener)
}
@TestOnly
fun opened(): Promise<*> = opened
fun executeOnStart(runnable: Runnable) {
opened.done { runnable.run() }
}
protected fun setState(status: ConnectionStatus, message: String? = null, messageLinkListener: HyperlinkListener? = null) {
val newState = ConnectionState(status, message, messageLinkListener)
val oldState = stateRef.getAndSet(newState)
if (oldState == null || oldState.status != status) {
if (status == ConnectionStatus.CONNECTION_FAILED) {
opened.setError(newState.message)
}
for (listener in connectionDispatcher) {
listener(newState)
}
}
}
fun stateChanged(listener: (ConnectionState) -> Unit) {
connectionDispatcher.add(listener)
}
// backward compatibility, go debugger
fun addListener(listener: SocketConnectionListener) {
stateChanged { listener.statusChanged(it.status) }
}
protected val debugEventListener: DebugEventListener
get() = dispatcher.multicaster
protected open fun startProcessing() {
opened.setResult(null)
}
fun close(message: String?, status: ConnectionStatus) {
if (!closed.compareAndSet(false, true)) {
return
}
if (opened.isPending) {
opened.setError("closed")
}
setState(status, message)
Disposer.dispose(this, false)
}
override fun dispose() {
vm = null
}
open fun detachAndClose(): Promise<*> {
if (opened.isPending) {
opened.setError("detached and closed")
}
val currentVm = vm
val callback: Promise<*>
if (currentVm == null) {
callback = resolvedPromise()
}
else {
vm = null
callback = currentVm.attachStateManager.detach()
}
close(null, ConnectionStatus.DISCONNECTED)
return callback
}
} | apache-2.0 | 4e72eebad62e59d104936c7e49cb2608 | 29.96063 | 125 | 0.741033 | 4.597661 | false | false | false | false |
AfzalivE/AwakeDebug | app/src/main/java/com/afzaln/awakedebug/ui/ToggleViewModel.kt | 1 | 2743 | package com.afzaln.awakedebug.ui
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.afzaln.awakedebug.DebuggingType
import com.afzaln.awakedebug.Injector
import com.afzaln.awakedebug.ToggleController
import com.afzaln.awakedebug.data.Prefs
import com.afzaln.awakedebug.data.SystemSettings
/**
* Responsible for handling logic related to
* enabling and disabling the Awake for Debug
* setting. Also, for publishing the UI state
* to liveData observers.
*/
class ToggleViewModel(
private val systemSettings: SystemSettings = Injector.systemSettings,
private val prefs: Prefs = Injector.prefs,
private val shortcuts: Shortcuts = Injector.shortcuts,
private val toggleController: ToggleController = Injector.toggleController
) : ViewModel() {
private val settingsLiveData = MutableLiveData(SettingsUiState())
val uiStateLiveData = MediatorLiveData<SettingsUiState>().apply {
addSource(settingsLiveData) { emit () }
addSource(toggleController.visibleDebugNotifications) { emit() }
addSource(systemSettings.screenTimeoutLiveData) { emit() }
}
private fun MediatorLiveData<*>.emit() {
val settings = settingsLiveData.value ?: return
val activeNotification = toggleController.visibleDebugNotifications.value ?: return
val screenTimeout = systemSettings.screenTimeoutLiveData.value ?: return
value = settings.copy(
screenTimeout = screenTimeout,
debuggingStatus = activeNotification
)
}
init {
val settingsUiState = SettingsUiState(prefs.awakeDebug, prefs.usbDebugging, prefs.wifiDebugging)
settingsLiveData.value = settingsUiState
}
fun setDebugAwake(shouldEnable: Boolean) {
toggleController.toggle(shouldEnable)
shortcuts.updateShortcuts()
settingsLiveData.value = SettingsUiState(
debugAwake = prefs.awakeDebug,
usbDebugging = prefs.usbDebugging,
wifiDebugging = prefs.wifiDebugging,
screenTimeout = systemSettings.screenTimeoutLiveData.value ?: 0
)
}
fun toggleUsbDebugging(shouldEnable: Boolean) {
prefs.usbDebugging = shouldEnable
setDebugAwake(prefs.awakeDebug)
}
fun toggleWifiDebugging(shouldEnable: Boolean) {
prefs.wifiDebugging = shouldEnable
setDebugAwake(prefs.awakeDebug)
}
data class SettingsUiState(
val debugAwake: Boolean = false,
val usbDebugging: Boolean = true,
val wifiDebugging: Boolean = true,
val screenTimeout: Int = 0,
val debuggingStatus: List<DebuggingType> = listOf(DebuggingType.NONE)
)
}
| apache-2.0 | c8754016e85767f1eba15ac9bac0a5e0 | 34.166667 | 104 | 0.718556 | 5.042279 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/core/RoDialog.kt | 2 | 5167 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.ui.core
import io.kvision.core.CssSize
import io.kvision.core.UNIT
import io.kvision.core.Widget
import io.kvision.form.FormPanel
import io.kvision.html.Button
import io.kvision.html.ButtonStyle
import io.kvision.panel.HPanel
import io.kvision.panel.vPanel
import org.apache.causeway.client.kroviz.to.ValueType
import org.apache.causeway.client.kroviz.ui.dialog.Controller
import org.apache.causeway.client.kroviz.ui.dialog.DiagramDialog
import org.apache.causeway.client.kroviz.ui.kv.override.RoWindow
import org.apache.causeway.client.kroviz.utils.Direction
import org.apache.causeway.client.kroviz.utils.IconManager
import org.apache.causeway.client.kroviz.utils.Point
import io.kvision.html.Link as KvisionHtmlLink
class RoDialog(
caption: String,
val items: List<FormItem> = mutableListOf(),
val controller: Controller,
defaultAction: String = "OK",
widthPerc: Int = 30,
heightPerc: Int = 50,
menu: List<KvisionHtmlLink>? = null,
customButtons: List<FormItem> = emptyList()
) :
Displayable, RoWindow(caption = caption, closeButton = true, menu = menu) {
private val okButton = Button(
text = defaultAction,
icon = IconManager.find(defaultAction),
style = ButtonStyle.SUCCESS
)
.onClick {
execute()
}
private val cancelButton = Button(
"Cancel",
"fas fa-times",
ButtonStyle.OUTLINEINFO
)
.onClick {
close()
}
@Deprecated("remove once leaflet/svg is fully operational")
private val scaleUpButton = Button(
"",
"fas fa-plus",
ButtonStyle.OUTLINEINFO
)
.onClick {
(controller as DiagramDialog).scale(Direction.UP)
}
@Deprecated("remove once leaflet/svg is fully operational")
private val scaleDownButton = Button(
"",
"fas fa-minus",
ButtonStyle.OUTLINEINFO
)
.onClick {
(controller as DiagramDialog).scale(Direction.DOWN)
}
var formPanel: FormPanel<String>? = null
init {
icon = IconManager.find(caption)
isDraggable = true
isResizable = true
closeButton = true
contentWidth = CssSize(widthPerc, UNIT.perc)
contentHeight = CssSize(heightPerc, UNIT.perc)
vPanel() {
height = CssSize(heightPerc, UNIT.vh)
this.addCssClass("dialog")
formPanel = FormPanelFactory(items).panel
formPanel!!.addCssClass("dialog-content")
add(formPanel!!)
val buttonBar = buildButtonBar(customButtons)
buttonBar.addCssClass("button-bar")
add(buttonBar)
}
}
private fun buildButtonBar(customButtons: List<FormItem>): HPanel {
val buttonBar = HPanel(spacing = 10)
buttonBar.add(okButton)
customButtons.forEach {
val b = createButton(it)
buttonBar.add(b)
}
buttonBar.add(cancelButton)
if (items.isNotEmpty() && hasScalableContent()) {
buttonBar.add(scaleUpButton)
buttonBar.add(scaleDownButton)
}
return buttonBar
}
private fun execute() {
controller.execute()
close()
}
fun open(at: Point = Point(x = 100, y = 100)): Widget {
ViewManager.openDialog(this, at)
super.show()
okButton.focus()
return this
}
override fun close() {
hide()
super.remove(this)
clearParent()
dispose()
}
@Deprecated("remove once leaflet/svg is fully operational")
private fun hasScalableContent(): Boolean {
val scalable = items.firstOrNull { it.type == ValueType.IMAGE }
return scalable != null
}
override fun toggleMaximize() {
execute()
}
/**
* Minimize or restore the window size.
*/
override fun toggleMinimize() {
//TODO put Dialog to lower right message box
}
private fun createButton(fi: FormItem): Button {
val item = Button(text = fi.label, icon = IconManager.find(fi.label))
val obj = fi.callBack!! as Controller
val action = fi.callBackAction
item.onClick {
obj.execute(action)
}
return item
}
}
| apache-2.0 | 070775bd669e1920433e749880171cdc | 28.867052 | 79 | 0.641378 | 4.342017 | false | false | false | false |
Masterzach32/SwagBot | src/main/kotlin/commands/Play.kt | 1 | 4184 | package xyz.swagbot.commands
import com.sedmelluq.discord.lavaplayer.track.*
import io.facet.commands.*
import io.facet.common.*
import io.facet.common.dsl.*
import io.facet.core.*
import xyz.swagbot.extensions.*
import xyz.swagbot.features.music.*
import xyz.swagbot.util.*
import java.util.*
object Play : GlobalGuildApplicationCommand {
override val request = applicationCommandRequest("play", "Queue up music and/or videos to be played by the bot.") {
string(
"query",
"The name of the song/video, or url to the YouTube/Soundcloud/Audio file.",
true
)
}
override suspend fun GuildSlashCommandContext.execute() {
val guild = getGuild()
if (!guild.isPremium())
return event.reply("Music is a premium feature of SwagBot").withEphemeral(true).await()
if (member.voiceState.awaitNullable()?.channelId?.unwrap() == null)
return event.reply("You must be in a voice channel to add music to the queue!").withEphemeral(true).await()
acknowledge()
val musicFeature = client.feature(Music)
val query: String by options
val item: AudioItem? = try {
if ("http://" in query || "https://" in query)
musicFeature.searchItem(query)
else
musicFeature.searchItem("ytsearch:$query")
} catch (e: Throwable) {
event.interactionResponse.createFollowupMessage("I couldn't find anything for *\"$query\"*.").await()
return
}
val scheduler = guild.trackScheduler
when (item) {
is AudioTrack -> {
item.setTrackContext(member, getChannel())
scheduler.queue(item)
interactionResponse.sendFollowupMessage(
trackRequestedTemplate(
member.displayName,
item,
scheduler.queueTimeLeft
)
)
if (getGuild().getConnectedVoiceChannel() == null)
member.getConnectedVoiceChannel()?.join()
}
is AudioPlaylist -> {
if (item.isSearchResult) {
val track = item.tracks.maxByOrNull { track ->
track.info.title.lowercase(Locale.getDefault()).let { "audio" in it || "lyrics" in it }
}
if (track != null) {
track.setTrackContext(member, getChannel())
scheduler.queue(track)
event.interactionResponse.sendFollowupMessage(
trackRequestedTemplate(
member.displayName,
track,
scheduler.queueTimeLeft
)
)
if (getGuild().getConnectedVoiceChannel() == null)
member.getConnectedVoiceChannel()?.join()
} else
event.interactionResponse.createFollowupMessage("I couldn't find anything for *\"$query\"*.")
} else {
item.tracks.forEach { track ->
track.setTrackContext(member, getChannel())
scheduler.queue(track)
}
event.interactionResponse.sendFollowupMessage(
baseTemplate.and {
title = ":musical_note: | Playlist requested by ${member.displayName}"
description = """
**${item.name}**
${item.tracks.size} Tracks
""".trimIndent().trim()
}
)
if (getGuild().getConnectedVoiceChannel() == null)
member.getConnectedVoiceChannel()?.join()
}
}
else -> event.interactionResponse.createFollowupMessage("I couldn't find anything for *\"$query\"*.")
}
}
}
| gpl-2.0 | cdcf7297dc58edc9e399d15c730bb5b7 | 38.471698 | 119 | 0.505736 | 5.786999 | false | false | false | false |
youdonghai/intellij-community | platform/configuration-store-impl/src/ProjectStoreImpl.kt | 1 | 17507 | /*
* 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.ide.highlighter.ProjectFileType
import com.intellij.ide.highlighter.WorkspaceFileType
import com.intellij.notification.Notifications
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.diagnostic.catchAndLog
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectCoreUtil
import com.intellij.openapi.project.impl.ProjectImpl
import com.intellij.openapi.project.impl.ProjectManagerImpl.UnableToSaveProjectNotification
import com.intellij.openapi.project.impl.ProjectStoreClassProvider
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.ReadonlyStatusHandler
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import com.intellij.util.attribute
import com.intellij.util.containers.forEachGuaranteed
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.io.*
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.text.nullize
import org.jdom.Element
import java.io.File
import java.io.IOException
import java.nio.file.Path
import java.nio.file.Paths
const val PROJECT_FILE = "\$PROJECT_FILE$"
const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$"
val IProjectStore.nameFile: Path
get() = Paths.get(directoryStorePath, ProjectImpl.NAME_FILE)
internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false)
internal val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true)
abstract class ProjectStoreBase(override final val project: ProjectImpl) : ComponentStoreImpl(), IProjectStore {
// protected setter used in upsource
// Zelix KlassMaster - ERROR: Could not find method 'getScheme()'
var scheme = StorageScheme.DEFAULT
override final var loadPolicy = StateLoadPolicy.LOAD
override final fun isOptimiseTestLoadSpeed() = loadPolicy != StateLoadPolicy.LOAD
override final fun getStorageScheme() = scheme
override abstract val storageManager: StateStorageManagerImpl
protected val isDirectoryBased: Boolean
get() = scheme == StorageScheme.DIRECTORY_BASED
override final fun setOptimiseTestLoadSpeed(value: Boolean) {
// we don't load default state in tests as app store does because
// 1) we should not do it
// 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations)
loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD
}
override fun getProjectFilePath() = storageManager.expandMacro(PROJECT_FILE)
override final fun getWorkspaceFilePath() = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE)
override final fun clearStorages() {
storageManager.clearStorages()
}
override final fun loadProjectFromTemplate(defaultProject: Project) {
defaultProject.save()
val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return
LOG.catchAndLog {
removeWorkspaceComponentConfiguration(defaultProject, element)
}
if (isDirectoryBased) {
LOG.catchAndLog {
for (component in element.getChildren("component")) {
when (component.getAttributeValue("name")) {
"InspectionProjectProfileManager" -> convertProfiles(component.getChildren("profile").iterator(), true)
"CopyrightManager" -> convertProfiles(component.getChildren("copyright").iterator(), false)
}
}
}
}
(storageManager.getOrCreateStorage(PROJECT_FILE) as XmlElementStorage).setDefaultState(element)
}
fun convertProfiles(profileIterator: MutableIterator<Element>, isInspection: Boolean) {
for (profile in profileIterator) {
val schemeName = profile.getChildren("option").find { it.getAttributeValue("name") == "myName" }?.getAttributeValue(
"value") ?: continue
profileIterator.remove()
val wrapper = Element("component").attribute("name", if (isInspection) "InspectionProjectProfileManager" else "CopyrightManager")
wrapper.addContent(profile)
val path = Paths.get(storageManager.expandMacro(PROJECT_CONFIG_DIR), if (isInspection) "inspectionProfiles" else "copyright",
"${FileUtil.sanitizeFileName(schemeName, true)}.xml")
JDOMUtil.writeParent(wrapper, path.outputStream(), "\n")
}
}
override final fun getProjectBasePath(): String {
if (isDirectoryBased) {
val path = PathUtilRt.getParentPath(storageManager.expandMacro(PROJECT_CONFIG_DIR))
if (Registry.`is`("store.basedir.parent.detection", true) && PathUtilRt.getFileName(path).startsWith("${Project.DIRECTORY_STORE_FOLDER}.")) {
return PathUtilRt.getParentPath(PathUtilRt.getParentPath(path))
}
return path
}
else {
return PathUtilRt.getParentPath(projectFilePath)
}
}
// used in upsource
protected fun setPath(filePath: String, refreshVfs: Boolean, useOldWorkspaceContentIfExists: Boolean) {
val storageManager = storageManager
val fs = LocalFileSystem.getInstance()
if (FileUtilRt.extensionEquals(filePath, ProjectFileType.DEFAULT_EXTENSION)) {
scheme = StorageScheme.DEFAULT
storageManager.addMacro(PROJECT_FILE, filePath)
val workspacePath = composeWsPath(filePath)
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, workspacePath)
if (refreshVfs) {
invokeAndWaitIfNeed {
VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath))
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !File(filePath).exists()
}
}
else {
scheme = StorageScheme.DIRECTORY_BASED
// if useOldWorkspaceContentIfExists false, so, file path is expected to be correct (we must avoid file io operations)
val isDir = !useOldWorkspaceContentIfExists || Paths.get(filePath).isDirectory()
val configDir = "${(if (isDir) filePath else PathUtilRt.getParentPath(filePath))}/${Project.DIRECTORY_STORE_FOLDER}"
storageManager.addMacro(PROJECT_CONFIG_DIR, configDir)
storageManager.addMacro(PROJECT_FILE, "$configDir/misc.xml")
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, "$configDir/workspace.xml")
if (!isDir) {
val workspace = File(workspaceFilePath)
if (!workspace.exists()) {
useOldWorkspaceContent(filePath, workspace)
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !Paths.get(filePath).exists()
}
if (refreshVfs) {
invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir)) }
}
}
}
override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): Array<out Storage> {
val storages = stateSpec.storages
if (storages.isEmpty()) {
return arrayOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
if (isDirectoryBased) {
var result: MutableList<Storage>? = null
for (storage in storages) {
@Suppress("DEPRECATION")
if (storage.path != PROJECT_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
}
}
if (result.isNullOrEmpty()) {
return arrayOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
result!!.sortWith(deprecatedComparator)
// if we create project from default, component state written not to own storage file, but to project file,
// we don't have time to fix it properly, so, ancient hack restored
result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION)
return result.toTypedArray()
}
}
else {
var result: MutableList<Storage>? = null
// FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry
var hasOnlyDeprecatedStorages = true
for (storage in storages) {
@Suppress("DEPRECATION")
if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
if (!storage.deprecated) {
hasOnlyDeprecatedStorages = false
}
}
}
if (result.isNullOrEmpty()) {
return arrayOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
if (hasOnlyDeprecatedStorages) {
result!!.add(PROJECT_FILE_STORAGE_ANNOTATION)
}
result!!.sortWith(deprecatedComparator)
return result.toTypedArray()
}
}
}
override fun isProjectFile(file: VirtualFile): Boolean {
if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file, file.fileType)) {
return false
}
val filePath = file.path
if (!isDirectoryBased) {
return filePath == projectFilePath || filePath == workspaceFilePath
}
return FileUtil.isAncestor(PathUtilRt.getParentPath(projectFilePath), filePath, false)
}
override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean) = if (!ignoreProjectStorageScheme && !isDirectoryBased) null else PathUtilRt.getParentPath(projectFilePath).nullize()
override fun getDirectoryStoreFile() = directoryStorePath?.let { LocalFileSystem.getInstance().findFileByPath(it) }
override fun getDirectoryStorePathOrBase() = PathUtilRt.getParentPath(projectFilePath)
}
private open class ProjectStoreImpl(project: ProjectImpl, private val pathMacroManager: PathMacroManager) : ProjectStoreBase(project) {
private var lastSavedProjectName: String? = null
init {
assert(!project.isDefault)
}
override final fun getPathMacroManagerForDefaults() = pathMacroManager
override val storageManager = ProjectStateStorageManager(pathMacroManager.createTrackingSubstitutor(), project)
override fun setPath(filePath: String) {
setPath(filePath, true, true)
}
override fun getProjectName(): String {
if (isDirectoryBased) {
val baseDir = projectBasePath
val nameFile = nameFile
if (nameFile.exists()) {
try {
nameFile.inputStream().reader().useLines { it.firstOrNull { !it.isEmpty() }?.trim() }?.let {
lastSavedProjectName = it
return it
}
}
catch (ignored: IOException) {
}
}
return PathUtilRt.getFileName(baseDir).replace(":", "")
}
else {
return PathUtilRt.getFileName(projectFilePath).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)
}
}
private fun saveProjectName() {
if (!isDirectoryBased) {
return
}
val currentProjectName = project.name
if (lastSavedProjectName == currentProjectName) {
return
}
lastSavedProjectName = currentProjectName
val basePath = projectBasePath
if (currentProjectName == PathUtilRt.getFileName(basePath)) {
// name equals to base path name - just remove name
nameFile.delete()
}
else {
if (Paths.get(basePath).isDirectory()) {
nameFile.write(currentProjectName.toByteArray())
}
}
}
override fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<Pair<SaveSession, VirtualFile>>, prevErrors: MutableList<Throwable>?): MutableList<Throwable>? {
try {
saveProjectName()
}
catch (e: Throwable) {
LOG.error("Unable to store project name", e)
}
var errors = prevErrors
beforeSave(readonlyFiles)
errors = super.doSave(saveSessions, readonlyFiles, errors)
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (readonlyFiles.isEmpty()) {
for (notification in notifications) {
notification.expire()
}
return errors
}
if (!notifications.isEmpty()) {
throw IComponentStore.SaveCancelledException()
}
val status = runReadAction { ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(*getFilesList(readonlyFiles)) }
if (status.hasReadonlyFiles()) {
dropUnableToSaveProjectNotification(project, status.readonlyFiles)
throw IComponentStore.SaveCancelledException()
}
val oldList = readonlyFiles.toTypedArray()
readonlyFiles.clear()
for (entry in oldList) {
errors = executeSave(entry.first, readonlyFiles, errors)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
if (!readonlyFiles.isEmpty()) {
dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles))
throw IComponentStore.SaveCancelledException()
}
return errors
}
protected open fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) {
}
}
private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: Array<VirtualFile>) {
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (notifications.isEmpty()) {
Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project)
}
else {
notifications[0].myFiles = readOnlyFiles
}
}
private fun getFilesList(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) = Array(readonlyFiles.size) { readonlyFiles[it].second }
private class ProjectWithModulesStoreImpl(project: ProjectImpl, pathMacroManager: PathMacroManager) : ProjectStoreImpl(project, pathMacroManager) {
override fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) {
super.beforeSave(readonlyFiles)
for (module in (ModuleManager.getInstance(project)?.modules ?: Module.EMPTY_ARRAY)) {
module.stateStore.save(readonlyFiles)
}
}
}
// used in upsource
class PlatformLangProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectWithModulesStoreImpl::class.java
}
}
private class PlatformProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectStoreImpl::class.java
}
}
private fun composeWsPath(filePath: String) = "${FileUtilRt.getNameWithoutExtension(filePath)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}"
private fun useOldWorkspaceContent(filePath: String, ws: File) {
val oldWs = File(composeWsPath(filePath))
if (!oldWs.exists()) {
return
}
try {
FileUtil.copyContent(oldWs, ws)
}
catch (e: IOException) {
LOG.error(e)
}
}
// public only to test
fun removeWorkspaceComponentConfiguration(defaultProject: Project, element: Element) {
val componentElements = element.getChildren("component")
if (componentElements.isEmpty()) {
return
}
@Suppress("DEPRECATION")
val projectComponents = defaultProject.getComponents(PersistentStateComponent::class.java)
projectComponents.forEachGuaranteed {
val stateAnnotation = StoreUtil.getStateSpec(it.javaClass)
if (stateAnnotation == null || stateAnnotation.name.isNullOrEmpty()) {
return@forEachGuaranteed
}
val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return@forEachGuaranteed
if (storage.path != StoragePathMacros.WORKSPACE_FILE) {
return@forEachGuaranteed
}
val iterator = componentElements.iterator()
for (componentElement in iterator) {
if (componentElement.getAttributeValue("name") == stateAnnotation.name) {
iterator.remove()
break
}
}
}
return
} | apache-2.0 | 32b317e7de9cd63221c459655419b389 | 36.33049 | 191 | 0.732393 | 5.178054 | false | false | false | false |
allotria/intellij-community | plugins/git4idea/src/git4idea/rebase/interactive/dialog/AnActionOptionButton.kt | 3 | 2827 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.rebase.interactive.dialog
import com.intellij.ide.DataManager
import com.intellij.ide.ui.laf.darcula.ui.DarculaButtonPainter
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAwareWithCallbacks
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.project.DumbAware
import com.intellij.ui.AnActionButton
import com.intellij.ui.components.JBOptionButton
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import java.awt.Component
import java.awt.Dimension
import java.awt.Insets
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.JButton
import javax.swing.JComponent
internal fun JButton.adjustForToolbar() {
val buttonHeight = JBUI.scale(28)
preferredSize = Dimension(preferredSize.width, buttonHeight)
border = object : DarculaButtonPainter() {
override fun getBorderInsets(c: Component?): Insets {
return JBUI.emptyInsets()
}
}
isFocusable = false
}
internal fun JButton.withLeftToolbarBorder() = BorderLayoutPanel().addToCenter(this).apply {
border = JBUI.Borders.emptyLeft(6)
}
internal class AnActionOptionButton(
val action: AnAction,
val options: List<AnAction>
) : AnActionButton(), CustomComponentAction, DumbAware {
private val optionButton = JBOptionButton(null, null).apply {
action = AnActionWrapper([email protected], this)
setOptions([email protected])
adjustForToolbar()
mnemonic = [email protected]().toInt()
}
private val optionButtonPanel = optionButton.withLeftToolbarBorder()
override fun actionPerformed(e: AnActionEvent) {
throw UnsupportedOperationException()
}
override fun createCustomComponent(presentation: Presentation, place: String) = optionButtonPanel
override fun updateButton(e: AnActionEvent) {
action.update(e)
UIUtil.setEnabled(optionButton, e.presentation.isEnabled, true)
}
private class AnActionWrapper(
private val action: AnAction,
private val component: JComponent
) : AbstractAction(action.templatePresentation.text) {
override fun actionPerformed(e: ActionEvent?) {
val context = DataManager.getInstance().getDataContext(component)
val event = AnActionEvent.createFromAnAction(action, null, GitInteractiveRebaseDialog.PLACE, context)
performActionDumbAwareWithCallbacks(action, event)
}
}
} | apache-2.0 | 13e8bc1de0a5574a019694119dca53c4 | 37.216216 | 140 | 0.797312 | 4.642036 | false | false | false | false |
allotria/intellij-community | uast/uast-common/src/org/jetbrains/uast/declarations/UClassInitializer.kt | 2 | 1544 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast
import com.intellij.psi.PsiClassInitializer
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* A class initializer wrapper to be used in [UastVisitor].
*/
interface UClassInitializer : UDeclaration, PsiClassInitializer {
@Suppress("OverridingDeprecatedMember")
@Deprecated("see the base property description", ReplaceWith("javaPsi"))
override val psi: PsiClassInitializer
/**
* Returns the body of this class initializer.
*/
val uastBody: UExpression
@Suppress("DEPRECATION")
private val javaPsiInternal
get() = (this as? UClassInitializerEx)?.javaPsi ?: psi
override fun accept(visitor: UastVisitor) {
if (visitor.visitInitializer(this)) return
uAnnotations.acceptList(visitor)
uastBody.accept(visitor)
visitor.afterVisitInitializer(this)
}
override fun asRenderString(): String = buildString {
append(modifierList)
appendln(uastBody.asRenderString().withMargin)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R =
visitor.visitClassInitializer(this, data)
override fun asLogString(): String = log("isStatic = $isStatic")
}
interface UClassInitializerEx : UClassInitializer, UDeclarationEx {
override val javaPsi: PsiClassInitializer
} | apache-2.0 | 2d3aa00af130723b7a37d88cee11850e | 30.530612 | 140 | 0.76101 | 4.650602 | false | false | false | false |
allotria/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/GroovyInferenceSessionBuilder.kt | 3 | 9682 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors.inference
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.PsiType
import com.intellij.psi.PsiTypeParameter
import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.TypeConversionUtil
import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrClassInitializer
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrClassTypeElement
import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter.Position.*
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.skipParentheses
import org.jetbrains.plugins.groovy.lang.resolve.MethodResolveResult
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyMethodCandidate
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.getContainingCall
open class GroovyInferenceSessionBuilder constructor(
private val context: PsiElement,
private val candidate: GroovyMethodCandidate,
private val contextSubstitutor: PsiSubstitutor
) {
protected var expressionFilters = mutableSetOf<ExpressionPredicate>()
protected var skipClosureBlock = true
fun resolveMode(skipClosureBlock: Boolean): GroovyInferenceSessionBuilder {
//TODO:add explicit typed closure constraints
this.skipClosureBlock = skipClosureBlock
return this
}
fun ignoreArguments(arguments: Collection<Argument>): GroovyInferenceSessionBuilder {
expressionFilters.add {
ExpressionArgument(it) !in arguments
}
return this
}
fun skipClosureIn(call: GrCall): GroovyInferenceSessionBuilder {
expressionFilters.add {
it !is GrFunctionalExpression || call != getContainingCall(it)
}
return this
}
protected fun collectExpressionFilters() {
if (skipClosureBlock) expressionFilters.add(ignoreFunctionalExpressions)
}
open fun build(): GroovyInferenceSession {
collectExpressionFilters()
val session = GroovyInferenceSession(candidate.method.typeParameters, contextSubstitutor, context, skipClosureBlock, expressionFilters)
return doBuild(session)
}
protected fun doBuild(basicSession: GroovyInferenceSession): GroovyInferenceSession {
basicSession.initArgumentConstraints(candidate.argumentMapping)
return basicSession
}
}
fun buildTopLevelSession(place: PsiElement): GroovyInferenceSession =
GroovyInferenceSession(PsiTypeParameter.EMPTY_ARRAY, PsiSubstitutor.EMPTY, place, false).apply { addExpression(place) }
fun InferenceSession.addExpression(place : PsiElement) {
val expression = findExpression(place) ?: return
val startConstraint = if (expression is GrBinaryExpression || expression is GrAssignmentExpression && expression.isOperatorAssignment) {
OperatorExpressionConstraint(expression as GrOperatorExpression)
}
else if (expression is GrSafeCastExpression && expression.operand !is GrFunctionalExpression) {
val result = expression.reference.advancedResolve() as? GroovyMethodResult ?: return
MethodCallConstraint(null, result, expression)
}
else {
val mostTopLevelExpression = getMostTopLevelExpression(expression)
val typeAndPosition = getExpectedTypeAndPosition(mostTopLevelExpression)
ExpressionConstraint(typeAndPosition, mostTopLevelExpression)
}
addConstraint(startConstraint)
}
fun findExpression(place: PsiElement): GrExpression? {
val parent = place.parent
return when {
parent is GrAssignmentExpression && parent.lValue === place -> parent
place is GrIndexProperty -> place
parent is GrMethodCall -> parent
parent is GrNewExpression -> parent
parent is GrClassTypeElement -> parent.parent as? GrSafeCastExpression
place is GrExpression -> place
else -> null
}
}
fun getMostTopLevelExpression(start: GrExpression): GrExpression {
var current: GrExpression = start
while (true) {
val parent = current.parent
current = if (parent is GrArgumentList) {
val grandParent = parent.parent
if (grandParent is GrCallExpression && grandParent.advancedResolve() is MethodResolveResult) {
grandParent
}
else {
return current
}
}
else {
return current
}
}
}
fun getExpectedType(expression: GrExpression): PsiType? {
return getExpectedTypeAndPosition(expression)?.type
}
private fun getExpectedTypeAndPosition(expression: GrExpression): ExpectedType? {
return getAssignmentOrReturnExpectedTypeAndPosition(expression)
?: getArgumentExpectedType(expression)
}
private fun getAssignmentOrReturnExpectedTypeAndPosition(expression: GrExpression): ExpectedType? {
return getAssignmentExpectedType(expression)?.let { ExpectedType(it, ASSIGNMENT) }
?: getReturnExpectedType(expression)?.let { ExpectedType(it, RETURN_VALUE) }
}
fun getAssignmentOrReturnExpectedType(expression: GrExpression): PsiType? {
return getAssignmentExpectedType(expression)
?: getReturnExpectedType(expression)
}
fun getAssignmentExpectedType(expression: GrExpression): PsiType? {
val parent: PsiElement = expression.parent
if (parent is GrAssignmentExpression && expression == parent.rValue) {
val lValue: PsiElement? = skipParentheses(parent.lValue, false)
return if (lValue is GrExpression && lValue !is GrIndexProperty) lValue.nominalType else null
}
else if (parent is GrVariable) {
return parent.declaredType
}
else if (parent is GrListOrMap) {
val pParent: PsiElement? = parent.parent
if (pParent is GrVariableDeclaration && pParent.isTuple) {
val index: Int = parent.initializers.indexOf(expression)
return pParent.variables.getOrNull(index)?.declaredType
}
else if (pParent is GrTupleAssignmentExpression) {
val index: Int = parent.initializers.indexOf(expression)
val expressions: Array<out GrReferenceExpression> = pParent.lValue.expressions
val lValue: GrReferenceExpression = expressions.getOrNull(index) ?: return null
val variable: GrVariable? = lValue.staticReference.resolve() as? GrVariable
return variable?.declaredType
}
}
return null
}
private fun getReturnExpectedType(expression: GrExpression): PsiType? {
val parent: PsiElement = expression.parent
val parentMethod: GrMethod? = PsiTreeUtil.getParentOfType(parent, GrMethod::class.java, false, GrFunctionalExpression::class.java)
if (parentMethod == null) {
return null
}
if (parent is GrReturnStatement) {
return parentMethod.returnType
}
else if (isExitPoint(expression)) {
val returnType: PsiType = parentMethod.returnType ?: return null
if (TypeConversionUtil.isVoidType(returnType)) return null
return returnType
}
return null
}
private fun getArgumentExpectedType(expression: GrExpression): ExpectedType? {
val parent = expression.parent as? GrArgumentList ?: return null
val call = parent.parent as? GrCallExpression ?: return null
val result = call.advancedResolve() as? GroovyMethodResult ?: return null
val mapping = result.candidate?.argumentMapping ?: return null
val type = result.substitutor.substitute(mapping.expectedType(ExpressionArgument(expression))) ?: return null
return ExpectedType(type, METHOD_PARAMETER)
}
internal typealias ExpressionPredicate = (GrExpression) -> Boolean
private val ignoreFunctionalExpressions: ExpressionPredicate = { it !is GrFunctionalExpression }
private fun isExitPoint(place: GrExpression): Boolean {
return collectExitPoints(place).contains(place)
}
private fun collectExitPoints(place: GrExpression): List<GrStatement> {
return if (canBeExitPoint(place)) {
val flowOwner = ControlFlowUtils.findControlFlowOwner(place)
ControlFlowUtils.collectReturns(flowOwner)
}
else {
emptyList()
}
}
private fun canBeExitPoint(element: PsiElement?): Boolean {
var place = element
while (place != null) {
if (place is GrMethod || place is GrFunctionalExpression || place is GrClassInitializer) return true
if (place is GrThrowStatement || place is GrTypeDefinitionBody || place is GroovyFile) return false
place = place.parent
}
return false
}
| apache-2.0 | af5db7f4a74d9678dfbf912c2ae85416 | 40.553648 | 140 | 0.786511 | 4.790698 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/codeinsight/htl/annotator/HtlWrongQuotesXmlAttributeInvertQuotesIntentionAction.kt | 1 | 2821 | package com.aemtools.codeinsight.htl.annotator
import com.aemtools.common.intention.BaseHtlIntentionAction
import com.aemtools.common.util.findChildrenByType
import com.aemtools.common.util.findParentByType
import com.aemtools.common.util.isDoubleQuoted
import com.aemtools.common.util.psiDocumentManager
import com.aemtools.lang.htl.psi.HtlHtlEl
import com.aemtools.lang.htl.psi.mixin.HtlStringLiteralMixin
import com.aemtools.lang.util.getHtlFile
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.psi.templateLanguages.OuterLanguageElement
import com.intellij.psi.xml.XmlAttribute
/**
* Inverts [XmlAttribute] quotes.
*
* @author Dmytro Troynikov
*/
class HtlWrongQuotesXmlAttributeInvertQuotesIntentionAction(
private val pointer: SmartPsiElementPointer<XmlAttribute>
) : BaseHtlIntentionAction(
text = { "Invert XML Attribute quotes" }
) {
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val element = pointer.element ?: return
val valueElement = element.valueElement ?: return
val psiDocumentManager = project.psiDocumentManager()
val document = psiDocumentManager.getDocument(file)
?: return
val rootDoublequoted = element.isDoubleQuoted()
val htl = element.containingFile.getHtlFile()
?: return
if (rootDoublequoted) {
document.replaceString(
valueElement.textRange.startOffset,
valueElement.textRange.startOffset + 1,
"'"
)
document.replaceString(
valueElement.textRange.endOffset - 1,
valueElement.textRange.endOffset,
"'"
)
} else {
document.replaceString(
valueElement.textRange.startOffset,
valueElement.textRange.startOffset + 1,
"\""
)
document.replaceString(
valueElement.textRange.endOffset - 1,
valueElement.textRange.endOffset,
"\""
)
}
val htlLiterals = element.findChildrenByType(OuterLanguageElement::class.java)
.flatMap { outerLanguageElement ->
val htlEl = htl.findElementAt(outerLanguageElement.textOffset)
?.findParentByType(HtlHtlEl::class.java)
?: return@flatMap emptyList<HtlStringLiteralMixin>()
htlEl.findChildrenByType(HtlStringLiteralMixin::class.java)
}
htlLiterals.forEach { literal ->
val newVal = if (rootDoublequoted) {
literal.toDoubleQuoted()
} else {
literal.toSingleQuoted()
}
document.replaceString(
literal.textRange.startOffset,
literal.textRange.endOffset,
newVal
)
}
psiDocumentManager.commitDocument(document)
}
}
| gpl-3.0 | 882b07f44b4902c2b095eba86b4555a9 | 31.056818 | 82 | 0.704715 | 4.897569 | false | false | false | false |
google/Kotlin-FirViewer | src/main/kotlin/io/github/tgeng/firviewer/TreeObjectRenderer.kt | 1 | 6106 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package io.github.tgeng.firviewer
import com.intellij.icons.AllIcons
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.elementType
import org.jetbrains.kotlin.fir.FirLabel
import org.jetbrains.kotlin.fir.FirPureAbstractElement
import org.jetbrains.kotlin.fir.contracts.FirContractDescription
import org.jetbrains.kotlin.fir.contracts.FirEffectDeclaration
import org.jetbrains.kotlin.fir.declarations.FirAnonymousInitializer
import org.jetbrains.kotlin.fir.declarations.FirConstructor
import org.jetbrains.kotlin.fir.declarations.FirErrorFunction
import org.jetbrains.kotlin.fir.declarations.FirFile
import org.jetbrains.kotlin.fir.declarations.FirImport
import org.jetbrains.kotlin.fir.declarations.FirProperty
import org.jetbrains.kotlin.fir.declarations.FirPropertyAccessor
import org.jetbrains.kotlin.fir.declarations.FirRegularClass
import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction
import org.jetbrains.kotlin.fir.declarations.FirTypeAlias
import org.jetbrains.kotlin.fir.declarations.FirTypeParameter
import org.jetbrains.kotlin.fir.declarations.FirTypeParameterRef
import org.jetbrains.kotlin.fir.declarations.FirVariable
import org.jetbrains.kotlin.fir.declarations.impl.FirDeclarationStatusImpl
import org.jetbrains.kotlin.fir.expressions.FirArgumentList
import org.jetbrains.kotlin.fir.expressions.FirAssignmentOperatorStatement
import org.jetbrains.kotlin.fir.expressions.FirAugmentedArraySetCall
import org.jetbrains.kotlin.fir.expressions.FirCatch
import org.jetbrains.kotlin.fir.expressions.FirDelegatedConstructorCall
import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.expressions.FirLoop
import org.jetbrains.kotlin.fir.expressions.FirVariableAssignment
import org.jetbrains.kotlin.fir.expressions.FirWhenBranch
import org.jetbrains.kotlin.fir.expressions.impl.FirStubStatement
import org.jetbrains.kotlin.fir.references.FirReference
import org.jetbrains.kotlin.fir.types.FirTypeProjection
import org.jetbrains.kotlin.fir.types.FirTypeRef
import org.jetbrains.kotlin.psi.*
import java.awt.Component
import javax.swing.JTree
import javax.swing.tree.TreeCellRenderer
class TreeObjectRenderer : TreeCellRenderer {
override fun getTreeCellRendererComponent(
tree: JTree,
value: Any,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean
): Component {
val node = value as? TreeNode<*> ?: return label("nothing to show")
return when (val e = node.t) {
is FirAnonymousInitializer -> type(node) + render(e)
is FirArgumentList -> type(node) + render(e)
is FirAssignmentOperatorStatement -> type(node) + render(e)
is FirAugmentedArraySetCall -> type(node) + render(e)
is FirCatch -> type(node) + render(e)
is FirConstructor -> type(node) + label("<init>", icon = AllIcons.Nodes.Function)
is FirContractDescription -> type(node) + render(e)
is FirDeclarationStatusImpl -> type(node) + render(e)
is FirDelegatedConstructorCall -> type(node) + render(e)
is FirEffectDeclaration -> type(node) + render(e)
is FirErrorFunction -> type(node) + render(e)
is FirExpression -> type(node) + render(e)
is FirFile -> type(node) + label(e.name)
is FirImport -> type(node) + render(e)
is FirLabel -> type(node) + render(e)
is FirLoop -> type(node) + render(e)
is FirPropertyAccessor -> type(node) + render(e)
is FirReference -> type(node) + render(e)
is FirRegularClass -> type(node) + label(e.name.asString(), icon = AllIcons.Nodes.Class)
is FirSimpleFunction -> type(node) + label(e.name.asString(), icon = AllIcons.Nodes.Function)
is FirStubStatement -> type(node) + render(e)
is FirTypeAlias -> type(node) + render(e)
is FirTypeParameter -> type(node) + render(e)
is FirTypeProjection -> type(node) + render(e)
is FirTypeRef -> type(node) + render(e)
is FirProperty -> type(node) + label(e.name.asString(), icon = AllIcons.Nodes.Property)
is FirVariable -> type(node) + label(e.name.asString(), icon = AllIcons.Nodes.Variable)
is FirVariableAssignment -> type(node) + render(e)
is FirWhenBranch -> type(node) + render(e)
// is FirConstructedClassTypeParameterRef,
// is FirOuterClassTypeParameterRef,
is FirTypeParameterRef -> type(node) + render(e as FirPureAbstractElement)
is PsiFile -> type(node) + label(e.name)
is PsiElement -> type(node) +
e.elementType?.let { label("[$it]", italic = true) } +
when (e) {
is KtDeclaration -> label(
e.name ?: "<anonymous>", icon = when (e) {
is KtClassOrObject -> AllIcons.Nodes.Class
is KtFunction -> AllIcons.Nodes.Function
is KtProperty -> AllIcons.Nodes.Property
is KtVariableDeclaration -> AllIcons.Nodes.Variable
else -> null
}
)
else -> label(e.text)
}
else -> label(e.toString())
}
}
} | apache-2.0 | 3c69ab854302b08b0721f92207efec9c | 50.319328 | 105 | 0.679004 | 4.373926 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit/src/main/kotlin/slatekit/SlateKitServices.kt | 1 | 1045 | package slatekit
import slatekit.apis.SetupType
import slatekit.apis.routes.Api
import slatekit.apis.tools.code.CodeGenApi
import slatekit.common.conf.Conf
import slatekit.context.Context
import slatekit.docs.DocApi
import slatekit.generator.*
interface SlateKitServices {
val ctx: Context
fun apis(settings:Conf): List<Api> {
// APIs
val toolSettings = ToolSettings(settings.getString("slatekit.version"), settings.getString("slatekit.version.beta"), "logs/logback.log")
val buildSettings = BuildSettings(settings.getString("kotlin.version"))
val logger = ctx.logs.getLogger("gen")
return listOf(
Api(GeneratorApi(ctx, GeneratorService(ctx, settings, SlateKit::class.java, GeneratorSettings(toolSettings, buildSettings), logger = logger)), declaredOnly = true, setup = SetupType.Annotated),
Api(DocApi(ctx), declaredOnly = true, setup = SetupType.Annotated),
Api(CodeGenApi(), declaredOnly = true, setup = SetupType.Annotated)
)
}
} | apache-2.0 | fb947830c89f6a4277fe98682179e384 | 39.230769 | 209 | 0.711005 | 4.282787 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-query/src/main/kotlin/slatekit/query/Const.kt | 1 | 205 | package slatekit.query
object Const {
@JvmStatic val Null = "null"
@JvmStatic val Asc = "asc"
@JvmStatic val Desc = "desc"
@JvmStatic val All = "*"
@JvmStatic val EmptyString = "''"
}
| apache-2.0 | 8646bc3b440be3f377eb1affd2bcd646 | 21.777778 | 37 | 0.619512 | 3.727273 | false | false | false | false |
leafclick/intellij-community | java/java-tests/testSrc/com/intellij/java/refactoring/suggested/JavaSuggestedRefactoringTest.kt | 1 | 24965 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.refactoring.suggested
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElementFactory
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.suggested.BaseSuggestedRefactoringTest
import com.intellij.refactoring.suggested.SuggestedRefactoringExecution
import com.intellij.refactoring.suggested._suggestedChangeSignatureNewParameterValuesForTests
class JavaSuggestedRefactoringTest : BaseSuggestedRefactoringTest() {
override val fileType: LanguageFileType
get() = JavaFileType.INSTANCE
override fun setUp() {
super.setUp()
_suggestedChangeSignatureNewParameterValuesForTests = {
SuggestedRefactoringExecution.NewParameterValue.Expression(
PsiElementFactory.getInstance(project).createExpressionFromText("default$it", null)
)
}
}
fun testRenameClass() {
doTestRename(
"""
class C {
private class Inner<caret> {
}
private void foo(Inner inner) {
}
}
""".trimIndent(),
"""
class C {
private class InnerNew<caret> {
}
private void foo(InnerNew innerNew) {
}
}
""".trimIndent(),
"Inner",
"InnerNew",
{ myFixture.type("New") }
)
}
fun testRenameMethod() {
doTestRename(
"""
class C {
void foo<caret>(float f) {
foo(1);
}
void bar() {
foo(2);
}
}
""".trimIndent(),
"""
class C {
void fooNew<caret>(float f) {
fooNew(1);
}
void bar() {
fooNew(2);
}
}
""".trimIndent(),
"foo",
"fooNew",
{ myFixture.type("New") }
)
}
fun testRenameField() {
doTestRename(
"""
class C {
private int <caret>field;
public C(int field) {
this.field = field;
}
void foo() {
field++;
}
}
""".trimIndent(),
"""
class C {
private int newField<caret>;
public C(int newField) {
this.newField = newField;
}
void foo() {
newField++;
}
}
""".trimIndent(),
"field",
"newField",
{
myFixture.performEditorAction(IdeActions.ACTION_EDITOR_SELECT_WORD_AT_CARET)
myFixture.type("newField")
}
)
}
fun testRenameLocal() {
doTestRename(
"""
class C {
void foo(float f) {
float local<caret> = f;
local += 1;
}
}
""".trimIndent(),
"""
class C {
void foo(float f) {
float localNew<caret> = f;
localNew += 1;
}
}
""".trimIndent(),
"local",
"localNew",
{ myFixture.type("New") }
)
}
fun testRenameClass2() {
doTestRename(
"""
class C {
private class <caret>Inner {
}
private void foo(Inner inner) {
}
}
""".trimIndent(),
"""
class C {
private class New<caret>Inner {
}
private void foo(NewInner newInner) {
}
}
""".trimIndent(),
"Inner",
"NewInner",
{ myFixture.type("New") }
)
}
fun testChangeReturnType() {
ignoreErrorsAfter = true
doTestChangeSignature(
"""
interface I {
<caret>void foo(float f);
}
class C implements I {
public void foo(float f) {
}
}
""".trimIndent(),
"""
interface I {
<caret>int foo(float f);
}
class C implements I {
public int foo(float f) {
}
}
""".trimIndent(),
"implementations",
{
replaceTextAtCaret("void", "int")
}
)
}
fun testAddParameter() {
ignoreErrorsAfter = true
doTestChangeSignature(
"""
package ppp;
import java.io.IOException;
interface I {
void foo(String s<caret>) throws IOException;
}
class C implements I {
public void foo(String s) throws IOException {
}
void bar(I i) {
try {
i.foo("");
} catch(Exception e) {}
}
}
class C1 implements I {
public void foo(String s) /* don't add IOException here! */ {
}
}
""".trimIndent(),
"""
package ppp;
import java.io.IOException;
interface I {
void foo(String s, I p<caret>) throws IOException;
}
class C implements I {
public void foo(String s, I p) throws IOException {
}
void bar(I i) {
try {
i.foo("", default0);
} catch(Exception e) {}
}
}
class C1 implements I {
public void foo(String s, I p) /* don't add IOException here! */ {
}
}
""".trimIndent(),
"usages",
{ myFixture.type(", I p") },
expectedPresentation = """
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'String'
' '
's'
LineBreak('', false)
')'
LineBreak(' ', false)
'throws'
LineBreak(' ', true)
'IOException'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'String'
' '
's'
','
LineBreak(' ', true)
Group (added):
'I'
' '
'p'
LineBreak('', false)
')'
LineBreak(' ', false)
'throws'
LineBreak(' ', true)
'IOException'
""".trimIndent()
)
}
fun testRemoveParameter() {
doTestChangeSignature(
"""
interface I {
void foo(float f, int i<caret>);
}
class C implements I {
public void foo(float f, int i) {
}
void bar(I i) {
i.foo(1, 2);
}
}
""".trimIndent(),
"""
interface I {
void foo(float f<caret>);
}
class C implements I {
public void foo(float f) {
}
void bar(I i) {
i.foo(1);
}
}
""".trimIndent(),
"usages",
{
deleteTextBeforeCaret(", int i")
}
)
}
fun testReorderParameters() {
doTestChangeSignature(
"""
interface I {
void foo(float p1, int p2, boolean p3<caret>);
}
class C implements I {
public void foo(float p1, int p2, boolean p3) {
}
void bar(I i) {
i.foo(1, 2, false);
}
}
""".trimIndent(),
"""
interface I {
void foo(boolean p3, float p1, int p2);
}
class C implements I {
public void foo(boolean p3, float p1, int p2) {
}
void bar(I i) {
i.foo(false, 1, 2);
}
}
""".trimIndent(),
"usages",
{ myFixture.performEditorAction(IdeActions.MOVE_ELEMENT_LEFT) },
{ myFixture.performEditorAction(IdeActions.MOVE_ELEMENT_LEFT) },
wrapIntoCommandAndWriteAction = false
)
}
fun testChangeParameterType() {
doTestChangeSignature(
"""
interface I {
void foo(float<caret> f);
}
class C implements I {
public void foo(float f) {
}
void bar(I i) {
i.foo(1);
}
}
""".trimIndent(),
"""
interface I {
void foo(int<caret> f);
}
class C implements I {
public void foo(int f) {
}
void bar(I i) {
i.foo(1);
}
}
""".trimIndent(),
"implementations",
{
repeat("float".length) { myFixture.performEditorAction(IdeActions.ACTION_EDITOR_BACKSPACE) }
},
{
myFixture.type("int")
}
)
}
fun testChangeParameterTypeWithImportInsertion() {
myFixture.addFileToProject(
"X.java",
"""
package xxx;
public class X {}
""".trimIndent()
)
val otherFile = myFixture.addFileToProject(
"Other.java",
"""
class D implements I {
public void foo(float p) {
}
}
""".trimIndent()
)
doTestChangeSignature(
"""
interface I {
void foo(<caret>float p);
}
class C implements I {
public void foo(float p) {
}
}
""".trimIndent(),
"""
import xxx.X;
interface I {
void foo(<caret>X p);
}
class C implements I {
public void foo(X p) {
}
}
""".trimIndent(),
"implementations",
{
replaceTextAtCaret("float", "X")
},
{
addImport("xxx.X")
}
)
assertEquals(
"""
import xxx.X;
class D implements I {
public void foo(X p) {
}
}
""".trimIndent(),
otherFile.text
)
}
fun testChangeParameterTypeWithImportReplaced() {
myFixture.addFileToProject(
"X.java",
"""
package xxx;
public class X {}
""".trimIndent()
)
myFixture.addFileToProject(
"Y.java",
"""
package xxx;
public class Y {}
""".trimIndent()
)
val otherFile = myFixture.addFileToProject(
"Other.java",
"""
import xxx.X;
class D implements I {
public void foo(X p) {
}
}
""".trimIndent()
)
doTestChangeSignature(
"""
import xxx.X;
interface I {
void foo(<caret>X p);
}
""".trimIndent(),
"""
import xxx.Y;
interface I {
void foo(<caret>Y p);
}
""".trimIndent(),
"implementations",
{
val offset = editor.caretModel.offset
editor.document.replaceString(offset, offset + "X".length, "Y")
},
{
addImport("xxx.Y")
removeImport("xxx.X")
}
)
assertEquals(
"""
import xxx.Y;
class D implements I {
public void foo(Y p) {
}
}
""".trimIndent(),
otherFile.text
)
}
fun testAddConstructorParameter() {
ignoreErrorsAfter = true
doTestChangeSignature(
"""
class C {
C(float f<caret>) {
}
void bar() {
C c = new C(1);
}
}
""".trimIndent(),
"""
class C {
C(float f, int p<caret>) {
}
void bar() {
C c = new C(1, default0);
}
}
""".trimIndent(),
"usages",
{ myFixture.type(", int p") }
)
}
fun testAddParameterWithAnnotations() {
addFileWithAnnotations()
val otherFile = myFixture.addFileToProject(
"Other.java",
"""
class C implements I {
@Override
public void foo() {
}
}
""".trimIndent()
)
doTestChangeSignature(
"""
interface I {
void foo(<caret>);
}
""".trimIndent(),
"""
import annotations.Language;
import annotations.NonStandard;
import annotations.NotNull;
import org.jetbrains.annotations.Nls;
interface I {
void foo(@NotNull @Language("JAVA") @Nls @NonStandard("X") String s<caret>);
}
""".trimIndent(),
"usages",
{
myFixture.type("@NotNull")
},
{
addImport("annotations.NotNull")
},
{
myFixture.type(" @Language(\"JAVA\") @Nls @NonStandard(\"X\")")
},
{
addImport("annotations.Language")
addImport("org.jetbrains.annotations.Nls")
addImport("annotations.NonStandard")
},
{
myFixture.type(" String s")
},
expectedPresentation = """
Old:
'void'
' '
'foo'
'('
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group (added):
'@Nls @NotNull @NonStandard("X")'
' '
'String'
' '
's'
LineBreak('', false)
')'
""".trimIndent()
)
assertEquals(
"""
import annotations.NonStandard;
import annotations.NotNull;
import org.jetbrains.annotations.Nls;
class C implements I {
@Override
public void foo(@Nls @NotNull @NonStandard("X") String s) {
}
}
""".trimIndent(),
otherFile.text
)
}
fun testChangeNullableToNotNull() {
addFileWithAnnotations()
val otherFile = myFixture.addFileToProject(
"Other.java",
"""
import annotations.Nullable;
class C implements I {
@Override
public void foo(@Nullable Object o) {
}
}
""".trimIndent()
)
doTestChangeSignature(
"""
import annotations.Nullable;
interface I {
void foo(@Nullable<caret> Object o);
}
""".trimIndent(),
"""
import annotations.NotNull;
interface I {
void foo(@NotNull<caret> Object o);
}
""".trimIndent(),
"implementations",
{
val offset = editor.caretModel.offset
editor.document.replaceString(offset - "Nullable".length, offset, "NotNull")
},
{
addImport("annotations.NotNull")
removeImport("annotations.Nullable")
},
expectedPresentation = """
Old:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'@Nullable' (modified)
' '
'Object'
' '
'o'
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', true)
Group:
'@NotNull' (modified)
' '
'Object'
' '
'o'
LineBreak('', false)
')'
""".trimIndent()
)
assertEquals(
"""
import annotations.NotNull;
class C implements I {
@Override
public void foo(@NotNull Object o) {
}
}
""".trimIndent(),
otherFile.text
)
}
// TODO: see IDEA-230807
fun testNotNullAnnotation() {
addFileWithAnnotations()
doTestChangeSignature(
"""
interface I {<caret>
Object foo();
}
class C implements I {
@Override
public Object foo() {
return "";
}
}
""".trimIndent(),
"""
import annotations.NotNull;
interface I {
@NotNull<caret>
Object foo();
}
class C implements I {
@Override
public @annotations.NotNull Object foo() {
return "";
}
}
""".trimIndent(),
"implementations",
{
myFixture.performEditorAction(IdeActions.ACTION_EDITOR_ENTER)
myFixture.type("@NotNull")
},
{
addImport("annotations.NotNull")
}
)
}
fun testAddThrowsList() {
val otherFile = myFixture.addFileToProject(
"Other.java",
"""
class C implements I {
@Override
public void foo() {
}
}
""".trimIndent()
)
doTestChangeSignature(
"""
interface I {
void foo()<caret>;
}
""".trimIndent(),
"""
import java.io.IOException;
interface I {
void foo() throws IOException<caret>;
}
""".trimIndent(),
"implementations",
{ myFixture.type(" throws IOException") },
{ addImport("java.io.IOException") },
expectedPresentation = """
Old:
'void'
' '
'foo'
'('
LineBreak('', false)
')'
New:
'void'
' '
'foo'
'('
LineBreak('', false)
')'
LineBreak(' ', false)
Group (added):
'throws'
LineBreak(' ', true)
'IOException'
""".trimIndent()
)
assertEquals(
"""
import java.io.IOException;
class C implements I {
@Override
public void foo() throws IOException {
}
}
""".trimIndent(),
otherFile.text
)
}
fun testRemoveThrowsList() {
doTestChangeSignature(
"""
import java.io.IOException;
interface I {
void foo() throws IOException<caret>;
}
class C implements I {
@Override
public void foo() throws IOException {
}
}
""".trimIndent(),
"""
interface I {
void foo()<caret>;
}
class C implements I {
@Override
public void foo() {
}
}
""".trimIndent(),
"implementations",
{
deleteTextBeforeCaret(" throws IOException")
},
expectedPresentation = """
Old:
'void'
' '
'foo'
'('
LineBreak('', false)
')'
LineBreak(' ', false)
Group (removed):
'throws'
LineBreak(' ', true)
'IOException'
New:
'void'
' '
'foo'
'('
LineBreak('', false)
')'
""".trimIndent()
)
}
fun testAddSecondException() {
doTestChangeSignature(
"""
import java.io.IOException;
interface I {
void foo() throws IOException<caret>;
}
class C implements I {
@Override
public void foo() throws IOException {
}
}
""".trimIndent(),
"""
import java.io.IOException;
interface I {
void foo() throws IOException, NumberFormatException<caret>;
}
class C implements I {
@Override
public void foo() throws IOException, NumberFormatException {
}
}
""".trimIndent(),
"implementations",
{ myFixture.type(", NumberFormatException") },
expectedPresentation = """
Old:
'void'
' '
'foo'
'('
LineBreak('', false)
')'
LineBreak(' ', false)
'throws'
LineBreak(' ', true)
'IOException'
New:
'void'
' '
'foo'
'('
LineBreak('', false)
')'
LineBreak(' ', false)
'throws'
LineBreak(' ', true)
'IOException'
','
LineBreak(' ', true)
'NumberFormatException' (added)
""".trimIndent()
)
}
fun testChangeVisibility1() {
//TODO: see IDEA-230741
BaseRefactoringProcessor.ConflictsInTestsException.withIgnoredConflicts<Throwable> {
doTestChangeSignature(
"""
abstract class Base {
<caret>protected abstract void foo();
}
class C extends Base {
@Override
protected void foo() {
}
}
""".trimIndent(),
"""
abstract class Base {
<caret>public abstract void foo();
}
class C extends Base {
@Override
public void foo() {
}
}
""".trimIndent(),
"implementations",
{
val offset = editor.caretModel.offset
editor.document.replaceString(offset, offset + "protected".length, "public")
},
expectedPresentation = """
Old:
'protected' (modified)
' '
'void'
' '
'foo'
'('
LineBreak('', false)
')'
New:
'public' (modified)
' '
'void'
' '
'foo'
'('
LineBreak('', false)
')'
""".trimIndent()
)
}
}
fun testChangeVisibility2() {
//TODO: see IDEA-230741
BaseRefactoringProcessor.ConflictsInTestsException.withIgnoredConflicts<Throwable> {
doTestChangeSignature(
"""
abstract class Base {
<caret>abstract void foo();
}
class C extends Base {
@Override
void foo() {
}
}
""".trimIndent(),
"""
abstract class Base {
public <caret>abstract void foo();
}
class C extends Base {
@Override
public void foo() {
}
}
""".trimIndent(),
"implementations",
{
myFixture.type("public ")
},
expectedPresentation = """
Old:
'void'
' '
'foo'
'('
LineBreak('', false)
')'
New:
'public' (added)
' '
'void'
' '
'foo'
'('
LineBreak('', false)
')'
""".trimIndent()
)
}
}
private fun addFileWithAnnotations() {
myFixture.addFileToProject(
"Annotations.java",
"""
package annotations;
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE})
public @interface NotNull {}
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE})
public @interface Nullable {}
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.ANNOTATION_TYPE})
public @interface Language {
String value();
}
@Target({ElementType.TYPE_USE})
public @interface NonStandard {
String value();
}
""".trimIndent()
)
}
private fun addImport(fqName: String) {
val psiClass = JavaPsiFacade.getInstance(project).findClass(fqName, GlobalSearchScope.allScope(project))!!
val importStatement = PsiElementFactory.getInstance(project).createImportStatement(psiClass)
(file as PsiJavaFile).importList!!.add(importStatement)
}
private fun removeImport(fqName: String) {
(file as PsiJavaFile).importList!!.findSingleClassImportStatement(fqName)!!.delete()
}
}
| apache-2.0 | 744942198cb83189f4d8d1e43ff1b5c8 | 21.370072 | 140 | 0.438975 | 5.249159 | false | false | false | false |
ktoolz/file-finder | core/src/main/kotlin/com/github/ktoolz/filefinder/model/bangs.kt | 1 | 4606 | /*
* File-Finder - KToolZ
*
* Copyright (c) 2016
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.github.ktoolz.filefinder.model
import com.github.ktoolz.filefinder.utils.ExecutionContext
import javaslang.collection.List
import java.io.File
/**
* Provides the list of all registered Bangs to be used during a search
*
* @return a List of all [Bang] to be used during the search process
*/
fun registeredBangs() = List.of(TargetBang(), SourceBang(), IgnoredBang())!!
// ---------------------------------------------------------------------------------------------------------------------
/**
* Definition of a [Bang] element.
*
* A [Bang] is actually kind of a filter on the search process.
*/
interface Bang {
/**
* Name of the [Bang].
* The name will actually be used in the search field for calling the Bang.
* User will have to write it using the syntax: `!name`
*/
val name: String
/**
* The actual behavior of the [Bang] which allows to say if a particular File matches the
* [Bang] filter criteria
*
* @param result the result of the search which we want to filter - basically a File which we found
* @return a Boolean stating if that File must be considered in the results depending of the Bang.
*/
fun filter(result: File): Boolean
}
// ---------------------------------------------------------------------------------------------------------------------
/**
* [Bang] allowing to filter only source files by their extensions.
* It'll allow to keep in the results only source files. If negated, it'll only keep only non-source files. (Cap'tain obvious).
*/
class SourceBang : Bang {
/**
* Just a List of all the extensions we consider as "source" files. Surely not complete though, and might be extended in the future.
*/
val sourceExtensions = listOf("kt", "java", "c", "sh", "cpp", "scala", "xml", "js", "html", "css", "yml", "md")
/**
* @see [Bang.name]
*/
override val name = "src"
/**
* @see [Bang.filter]
*/
override fun filter(result: File) =
sourceExtensions.foldRight(false) { extension, keep ->
keep || result.name.endsWith(".$extension")
}
}
// ---------------------------------------------------------------------------------------------------------------------
/**
* [Bang] allowing to filter only files from a target repository (usual folder used for results of builds).
* It'll allow to keep only files coming from those target repositories, or the opposite while negated.
*/
class TargetBang : Bang {
/**
* @see [Bang.name]
*/
override val name = "target"
/**
* @see [Bang.filter]
*/
override fun filter(result: File) = result.canonicalPath.contains("/target/")
}
// ---------------------------------------------------------------------------------------------------------------------
/**
* [Bang] allowing to filter only files which are considered as ignored. Ignored files are determined through their
* extension, using the ones provided in the [ExecutionContext] configuration (ie. the configuration file of
* the application).
* It'll allow to keep only the ones which are considered ignored, or the opposite if it's negated.
*/
class IgnoredBang : Bang {
/**
* @see [Bang.name]
*/
override val name = "ignored"
/**
* @see [Bang.filter]
*/
override fun filter(result: File) = ExecutionContext.ignored.fold(false) {
keep, extension ->
keep || result.name.endsWith(".$extension")
}
}
| mit | d10b6551436a535eaf02c4489eb2c622 | 38.706897 | 463 | 0.612462 | 4.587649 | false | false | false | false |
samirma/MeteoriteLandings | app/src/main/java/com/antonio/samir/meteoritelandingsspots/data/repository/model/Meteorite.kt | 1 | 783 | package com.antonio.samir.meteoritelandingsspots.data.repository.model
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
@Entity(tableName = "meteorites", indices = [Index("id")])
@Parcelize
data class Meteorite(
@PrimaryKey
@SerializedName("id")
var id: Int = 0,
var mass: String? = null,
var nametype: String? = null,
var recclass: String? = null,
var name: String? = null,
var fall: String? = null,
var year: String? = null,
var reclong: String? = null,
var reclat: String? = null,
var address: String? = null
) : Parcelable
| mit | 37412d2f4203dbba29406fb4a848af8d | 29.115385 | 70 | 0.666667 | 4.015385 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/stash/GitStashCache.kt | 1 | 2959 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.stash
import com.github.benmanes.caffeine.cache.CacheLoader
import com.github.benmanes.caffeine.cache.Caffeine
import com.google.common.util.concurrent.MoreExecutors
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.LowMemoryWatcher
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.vcs.log.Hash
import git4idea.GitCommit
import git4idea.ui.StashInfo
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionException
class GitStashCache(val project: Project) : Disposable {
private val executor = MoreExecutors.listeningDecorator(AppExecutorUtil.createBoundedApplicationPoolExecutor("Git Stash Loader", 1))
private val cache = Caffeine.newBuilder()
.maximumSize(100)
.executor(executor)
.buildAsync<StashId, StashData>(CacheLoader { stashId -> doLoadStashData(stashId) })
init {
LowMemoryWatcher.register(Runnable { cache.synchronous().invalidateAll() }, this)
}
private fun doLoadStashData(stashId: StashId): StashData {
try {
LOG.debug("Loading stash at '${stashId.hash}' in '${stashId.root}'")
val (changes, indexChanges) = GitStashOperations.loadStashChanges(project, stashId.root, stashId.hash, stashId.parentHashes)
return StashData.Changes(changes, indexChanges)
}
catch (e: VcsException) {
LOG.warn("Could not load stash at '${stashId.hash}' in '${stashId.root}'", e)
return StashData.Error(e)
}
catch (e: Exception) {
if (e !is ProcessCanceledException) LOG.error("Could not load stash at '${stashId.hash}' in '${stashId.root}'", e)
throw CompletionException(e);
}
}
fun loadStashData(stashInfo: StashInfo): CompletableFuture<StashData>? {
if (Disposer.isDisposed(this)) return null
val commitId = StashId(stashInfo.hash, stashInfo.parentHashes, stashInfo.root)
val future = cache.get(commitId)
if (future.isCancelled) return cache.synchronous().refresh(commitId)
return future
}
override fun dispose() {
executor.shutdown()
cache.synchronous().invalidateAll()
}
companion object {
private val LOG = Logger.getInstance(GitStashCache::class.java)
}
sealed class StashData {
class Changes(val changes: Collection<Change>, val parentCommits: Collection<GitCommit>) : StashData()
class Error(val error: VcsException) : StashData()
}
private data class StashId(val hash: Hash, val parentHashes: List<Hash>, val root: VirtualFile)
} | apache-2.0 | 88810772e23ee96079a1d9c85711d1a4 | 38.466667 | 140 | 0.759378 | 4.245337 | false | false | false | false |
smmribeiro/intellij-community | json/src/com/intellij/jsonpath/ui/JsonPathExportEvaluateResultAction.kt | 6 | 2096 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.jsonpath.ui
import com.intellij.ide.scratch.ScratchFileService
import com.intellij.ide.scratch.ScratchRootType
import com.intellij.json.JsonBundle
import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_RESULT_KEY
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.vfs.VfsUtil
internal class JsonPathExportEvaluateResultAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val editor = e.getData(CommonDataKeys.EDITOR) ?: return
if (editor.getUserData(JSON_PATH_EVALUATE_RESULT_KEY) != true) return
ProgressManager.getInstance().runProcessWithProgressSynchronously(
Runnable {
WriteCommandAction.runWriteCommandAction(project, JsonBundle.message("jsonpath.evaluate.export.result"), null, Runnable {
val file = ScratchRootType.getInstance()
.findFile(project, "jsonpath-result.json", ScratchFileService.Option.create_new_always)
VfsUtil.saveText(file, editor.document.text)
val fileEditorManager = FileEditorManager.getInstance(project)
if (!fileEditorManager.isFileOpen(file)) {
fileEditorManager.openEditor(OpenFileDescriptor(project, file), true)
}
})
}, JsonBundle.message("jsonpath.evaluate.progress.export.result"), false, project)
}
override fun update(e: AnActionEvent) {
val editor = e.getData(CommonDataKeys.EDITOR)
e.presentation.isEnabledAndVisible = editor != null && editor.getUserData(JSON_PATH_EVALUATE_RESULT_KEY) == true
}
} | apache-2.0 | 7a72d3d4f938a0fcc5850616d42d5169 | 45.6 | 140 | 0.773855 | 4.689038 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/MeshBuilderUiExtensions.kt | 1 | 1525 | package de.fabmax.kool.modules.ui2
import de.fabmax.kool.math.toRad
import de.fabmax.kool.scene.geometry.MeshBuilder
import kotlin.math.cos
import kotlin.math.sin
fun MeshBuilder.arrow(centerX: Float, centerY: Float, size: Float, rotation: Float) {
val si = size * 0.3f * 0.7f
val so = size * 0.5f * 0.7f
val off = size * 0.15f * 0.7f
val m11 = cos((rotation - 45).toRad())
val m12 = -sin((rotation - 45).toRad())
val m21 = sin((rotation - 45).toRad())
val m22 = m11
val x1 = -so - off; val y1 = so - off
val x2 = so - off; val y2 = so - off
val x3 = so - off; val y3 = -so - off
val x4 = si - off; val y4 = -so - off
val x5 = si - off; val y5 = si - off
val x6 = -so - off; val y6 = si - off
val i1 = vertex {
set(centerX + m11 * x1 + m12 * y1, centerY + m21 * x1 + m22 * y1, 0f)
}
val i2 = vertex {
set(centerX + m11 * x2 + m12 * y2, centerY + m21 * x2 + m22 * y2, 0f)
}
val i3 = vertex {
set(centerX + m11 * x3 + m12 * y3, centerY + m21 * x3 + m22 * y3, 0f)
}
val i4 = vertex {
set(centerX + m11 * x4 + m12 * y4, centerY + m21 * x4 + m22 * y4, 0f)
}
val i5 = vertex {
set(centerX + m11 * x5 + m12 * y5, centerY + m21 * x5 + m22 * y5, 0f)
}
val i6 = vertex {
set(centerX + m11 * x6 + m12 * y6, centerY + m21 * x6 + m22 * y6, 0f)
}
addTriIndices(i1, i2, i6)
addTriIndices(i6, i2, i5)
addTriIndices(i5, i2, i3)
addTriIndices(i5, i3, i4)
}
| apache-2.0 | a095ff7adb078a909b4d12e64d9a66c9 | 30.770833 | 85 | 0.540984 | 2.597956 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/audio/synth/Snare.kt | 1 | 539 | package de.fabmax.kool.modules.audio.synth
/**
* @author fabmax
*/
class Snare(val bpm: Float) : SampleNode() {
private val osc = Oscillator(Wave.SQUARE, 175f).apply { gain = 0.156f }
private val lowPass = LowPassFilter(30f, this)
override fun generate(dt: Float): Float {
val s = osc.next(dt) + noise(0.73f)
val pc2 = ((t + 0.5) % (60f / bpm)).toFloat()
var pc1 = 120f
if ((t % 2) > 1) {
pc1 = 105f
}
return lowPass.filter(perc(s, pc1, pc2) * 0.6f) * 5
}
} | apache-2.0 | 2c5dbff5691ad9203656a5b9c7117a6e | 24.714286 | 75 | 0.552876 | 2.961538 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/gltf/GltfImage.kt | 1 | 756 | package de.fabmax.kool.modules.gltf
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
/**
* Image data used to create a texture. Image can be referenced by URI or bufferView index. mimeType is required in the
* latter case.
*
* @param uri The uri of the image.
* @param mimeType The image's MIME type.
* @param bufferView The index of the bufferView that contains the image. Use this instead of the image's uri property.
* @param name The user-defined name of this object.
*/
@Serializable
data class GltfImage(
var uri: String? = null,
val mimeType: String? = null,
val bufferView: Int = -1,
val name: String? = null
) {
@Transient
var bufferViewRef: GltfBufferView? = null
} | apache-2.0 | e958a6c18cf1c538e606299d15ea1bbb | 30.541667 | 119 | 0.71164 | 4 | false | false | false | false |
rei-m/HBFav_material | app/src/main/kotlin/me/rei_m/hbfavmaterial/viewmodel/widget/fragment/OthersBookmarkFragmentViewModel.kt | 1 | 4799 | /*
* Copyright (c) 2017. Rei Matsushita
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package me.rei_m.hbfavmaterial.viewmodel.widget.fragment
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.databinding.Observable
import android.databinding.ObservableArrayList
import android.databinding.ObservableBoolean
import android.view.View
import android.widget.AbsListView
import android.widget.AdapterView
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import me.rei_m.hbfavmaterial.constant.ReadAfterFilter
import me.rei_m.hbfavmaterial.model.UserBookmarkModel
import me.rei_m.hbfavmaterial.model.entity.Bookmark
class OthersBookmarkFragmentViewModel(private val userBookmarkModel: UserBookmarkModel,
private val bookmarkUserId: String) : ViewModel() {
val bookmarkList: ObservableArrayList<Bookmark> = ObservableArrayList()
val hasNextPage: ObservableBoolean = ObservableBoolean(false)
val isVisibleEmpty: ObservableBoolean = ObservableBoolean(false)
val isVisibleProgress: ObservableBoolean = ObservableBoolean(false)
val isRefreshing: ObservableBoolean = ObservableBoolean(false)
val isVisibleError: ObservableBoolean = ObservableBoolean(false)
private var hasNextPageUpdatedEventSubject = BehaviorSubject.create<Boolean>()
val hasNextPageUpdatedEvent: io.reactivex.Observable<Boolean> = hasNextPageUpdatedEventSubject
private val onItemClickEventSubject = PublishSubject.create<Bookmark>()
val onItemClickEvent: io.reactivex.Observable<Bookmark> = onItemClickEventSubject
val onRaiseGetNextPageErrorEvent = userBookmarkModel.isRaisedGetNextPageError
val onRaiseRefreshErrorEvent = userBookmarkModel.isRaisedRefreshError
private val disposable: CompositeDisposable = CompositeDisposable()
private val hasNextPageChangedCallback = object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
hasNextPageUpdatedEventSubject.onNext(hasNextPage.get())
}
}
init {
disposable.addAll(userBookmarkModel.bookmarkList.subscribe {
if (it.isEmpty()) {
bookmarkList.clear()
} else {
bookmarkList.addAll(it - bookmarkList)
}
isVisibleEmpty.set(bookmarkList.isEmpty())
}, userBookmarkModel.hasNextPage.subscribe {
hasNextPage.set(it)
}, userBookmarkModel.isLoading.subscribe {
isVisibleProgress.set(it)
}, userBookmarkModel.isRefreshing.subscribe {
isRefreshing.set(it)
}, userBookmarkModel.isRaisedError.subscribe {
isVisibleError.set(it)
})
hasNextPage.addOnPropertyChangedCallback(hasNextPageChangedCallback)
userBookmarkModel.getList(bookmarkUserId, ReadAfterFilter.ALL)
}
override fun onCleared() {
hasNextPage.removeOnPropertyChangedCallback(hasNextPageChangedCallback)
disposable.dispose()
super.onCleared()
}
@Suppress("UNUSED_PARAMETER")
fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
onItemClickEventSubject.onNext(bookmarkList[position])
}
@Suppress("UNUSED_PARAMETER")
fun onScroll(listView: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
if (0 < totalItemCount && totalItemCount == firstVisibleItem + visibleItemCount) {
userBookmarkModel.getNextPage(bookmarkUserId)
}
}
fun onRefresh() {
userBookmarkModel.refreshList(bookmarkUserId)
}
class Factory(private val userBookmarkModel: UserBookmarkModel,
private val userId: String) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(OthersBookmarkFragmentViewModel::class.java)) {
return OthersBookmarkFragmentViewModel(userBookmarkModel, userId) as T
}
throw IllegalArgumentException("Unknown class name")
}
}
}
| apache-2.0 | 133b448fbe19115cc5377826059ac56c | 39.327731 | 112 | 0.732028 | 5.37402 | false | false | false | false |
Briseus/Lurker | app/src/main/java/torille/fi/lurkforreddit/comments/CommentFragment.kt | 1 | 4599 | package torille.fi.lurkforreddit.comments
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_comments.*
import timber.log.Timber
import torille.fi.lurkforreddit.R
import torille.fi.lurkforreddit.data.models.view.Comment
import torille.fi.lurkforreddit.data.models.view.Post
import torille.fi.lurkforreddit.utils.AppLinkActivity
import javax.inject.Inject
class CommentFragment @Inject constructor() : DaggerFragment(), CommentContract.View {
@Inject
internal lateinit var post: Post
@Inject
internal lateinit var actionsListener: CommentContract.Presenter
@Inject
@JvmField
var singleCommentThread: Boolean = false
private lateinit var commentAdapter: CommentRecyclerViewAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
commentAdapter = CommentRecyclerViewAdapter(
mutableListOf(post),
clickListener,
ContextCompat.getColor(context!!, R.color.colorAccent)
)
}
override fun onResume() {
super.onResume()
actionsListener.takeView(this)
}
override fun onDestroy() {
super.onDestroy()
actionsListener.dropView()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_comments, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
context?.let { context ->
commentRecyclerView.setHasFixedSize(true)
commentRecyclerView.addItemDecoration(
CommentsItemDecoration(
ContextCompat.getDrawable(
context,
R.drawable.comment_item_decorator
)!!
)
)
commentRecyclerView.layoutManager = LinearLayoutManager(context)
commentRecyclerView.adapter = commentAdapter
refreshLayout.setColorSchemeColors(
ContextCompat.getColor(context, R.color.colorPrimary),
ContextCompat.getColor(context, R.color.colorAccent),
ContextCompat.getColor(context, R.color.colorPrimaryDark)
)
refreshLayout.setOnRefreshListener {
actionsListener.loadComments(
post.permaLink,
singleCommentThread
)
}
}
}
override fun showComments(comments: List<Any>) {
commentAdapter.replaceData(comments)
}
override fun showProgressbarAt(position: Int, level: Int) {
commentAdapter.addProgressbar(position, level)
}
override fun hideProgressbarAt(position: Int) {
commentAdapter.removeAt(position)
}
override fun addCommentsAt(comments: List<Comment>, position: Int) {
if (!comments.isEmpty()) {
commentAdapter.addAllCommentsTo(position, comments)
}
}
override fun showError(errorText: String) {
Toast.makeText(context, errorText, Toast.LENGTH_SHORT).show()
}
override fun showErrorAt(position: Int) {
commentAdapter.changeToErrorAt(position)
}
override fun setProgressIndicator(active: Boolean) {
refreshLayout?.post { refreshLayout.isRefreshing = active }
}
/**
* Listener for clicks on notes in the RecyclerView.
*/
private val clickListener = object : CommentClickListener {
override fun onClick(parentComment: Comment, linkId: String, position: Int) {
actionsListener.loadMoreCommentsAt(parentComment, linkId, position)
}
override fun onContinueThreadClick(permaLinkurl: String) {
Timber.d("Opening comments for $permaLinkurl")
val intent = Intent(context, AppLinkActivity::class.java)
intent.data = Uri.parse(permaLinkurl)
startActivity(intent)
}
}
internal interface CommentClickListener {
fun onClick(parentComment: Comment, linkId: String, position: Int)
fun onContinueThreadClick(permaLinkurl: String)
}
}
| mit | dd449ae9dced84543cf40e3ca49197c8 | 30.5 | 86 | 0.668624 | 5.310624 | false | false | false | false |
chemouna/Nearby | app/src/main/kotlin/com/mounacheikhna/nearby/ui/CheckableFab.kt | 1 | 2134 | package com.mounacheikhna.nearby.ui
import android.content.Context
import android.support.design.widget.FloatingActionButton
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.Checkable
import android.widget.ImageButton
import android.widget.LinearLayout
import com.mounacheikhna.nearby.R
/**
* A {@link Checkable} {@link FloatingActionButton} that toggle its state.
*/
class CheckableFab: FloatingActionButton, Checkable {
private var isChecked = false
private var minOffset: Int = 0
public constructor(context: Context) : super(context) {
init();
}
public constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init();
}
public constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context,
attrs, defStyleAttr) {
init();
}
private fun init() {
setOnClickListener({ toggle() })
}
fun setOffset(offset: Int) {
var offset = offset
offset = Math.max(minOffset, offset)
if (translationY != offset.toFloat()) {
translationY = offset.toFloat()
ViewCompat.postInvalidateOnAnimation(this)
}
}
fun setMinOffset(minOffset: Int) {
this.minOffset = minOffset
}
override fun isChecked(): Boolean {
return isChecked
}
override fun setChecked(isChecked: Boolean) {
if (this.isChecked != isChecked) {
this.isChecked = isChecked
refreshDrawableState()
}
}
override fun toggle() {
setChecked(!isChecked)
jumpDrawablesToCurrentState()
}
override fun onCreateDrawableState(extraSpace: Int): IntArray {
val drawableState = super.onCreateDrawableState(extraSpace + 1)
if (isChecked()) {
View.mergeDrawableStates(drawableState, CHECKED_STATE_SET)
}
return drawableState
}
companion object {
private val CHECKED_STATE_SET = intArrayOf(android.R.attr.state_checked)
}
}
| apache-2.0 | 52e5fce83a7c5343ca7d1ebc4935fa86 | 25.02439 | 97 | 0.664011 | 4.752784 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/OoWriterBiddingOrderDetailsPage.kt | 1 | 12617 | package alraune
import alraune.entity.*
import pieces100.*
import vgrechka.*
import kotlin.math.max
class OoWriterBiddingOrderDetailsPage {
companion object {
val path = "/bidding-order-details"
val conversationTabId = "Conversation"
fun href(orderId: Long) = hrefThunk(orderId).makeHref()
fun hrefThunk(orderId: Long) = HrefThunk(path) {
it.longId.set(orderId)
}
}
val c = AlCSS.fartus1
val getParams = GetParams()
val order = dbSelectOrderOrBailOut(getParamOrBailOut(getParams.longId))
init {init()}
fun init() {
val titlePrefix = t("TOTE", "Пиздоторги: ")
btfDocumentTitle(titlePrefix + t("TOTE", "Заказ ${AlText.numString(order.id)}"))
if (order.state != Order.State.LookingForWriters) {
oo(div("По этому заказу торгов (уже) нет"))
return
}
Context1.get().withProjectStuff({it.copy(
composeOrderParams_showCustomerInfo = false)}) {
val ovb = OrderViewBoobs(order)
ovb.ooTitle(prefix = titlePrefix)
oo(composeBidBanner())
ovb.ooTabs(hrefThunk(order.id)) {
it.tabs += Tabopezdal.Tab(conversationTabId, t("TOTE", "Общение"),
ooContent = {
ooApplicantConversation(order, rctx0.al.user)
}
)
}
}
btfStartStalenessWatcher()
}
fun composeBidBanner(): Renderable {
// ce82cbc6-a172-41d4-823b-2b5a754b8583
val state = order.computeUserBiddingState(rctx0.al.user)
val money = state?.money
return !ComposeActionBanner()
.message(div().with {
if (money == null)
oo(div()
.add("Принимаем заявки: ")
.add(span(
displayMoney(order.data.bidding!!.minWriterMoney) +
" " + AlText0.endash + " " +
displayMoney(order.data.bidding!!.maxWriterMoney)).style("font-weight: bold;"))
.add(" Желаешь запрячься?"))
else
oo(div()
.add("Ты хочешь сделать это за ")
.add(span(displayMoney(money)).style("font-weight: bold;")))
})
.backgroundColor(Color.Gray200)
.leftBorderColor(Color.Gray500)
.accept {
it.buttonBarWithTicker.addOpenFormModalButton(
title = "Задать вопрос",
level = AlButtonStyle.Default,
modalWithScripts = bakeModal2(order.toHandle()))
it.buttonBarWithTicker.addOpenFormModalButton(
title = if (money == null) "Предложить цену" else "Изменить цену",
level = AlButtonStyle.Success,
modalWithScripts = bakeModal3(order.toHandle()))
if (money != null) {
it.buttonBarWithTicker.addOpenFormModalButton(
title = "Передумал делать",
level = AlButtonStyle.Danger,
modalWithScripts = bakeModal4(order.toHandle()))
}
}
}
}
fun doCommentDuringBidding(toUser: User? = null, orderHandle: OrderHandle, fs: CommentFields) {
updateOrderSimple(orderHandle, ::new_Order_Operation_CommentDuringBidding) {
it.order.data.biddingActions.add(new_Order_BiddingAction(
kind = Order.BiddingAction.Kind.Comment,
userId = rctx0.al.user.id, commentRecipientId = toUser?.id,
time = it.now, money = null, comment = fs.comment.value(), isCancelation = false))
}
}
fun doBid(orderHandle: OrderHandle, fs: BidFields) {
updateOrderSimple(orderHandle, ::new_Order_Operation_Bid) {
it.order.data.biddingActions.add(new_Order_BiddingAction(
kind = Order.BiddingAction.Kind.Bid,
userId = rctx0.al.user.id, commentRecipientId = null, time = it.now,
money = fs.money.value().toInt(), comment = fs.comment.value(), isCancelation = false))
}
}
fun doCancelBid(orderHandle: OrderHandle, fs: CommentFields) {
updateOrderSimple(orderHandle, ::new_Order_Operation_CancelBid) {
it.order.data.biddingActions.add(new_Order_BiddingAction(
kind = Order.BiddingAction.Kind.Cancel,
userId = rctx0.al.user.id, commentRecipientId = null, time = it.now,
money = null, comment = fs.comment.value(), isCancelation = true))
}
}
fun ooApplicantConversation(order: Order, applicant: User) {
val pageSize = AlConst.pageSize
var bids = order.data.biddingActions.filter {it.userId == applicant.id || it.commentRecipientId == applicant.id}
if (GetParams().ordering.get() == Ordering.NewerFirst)
bids = bids.reversed()
oo(dance(object : ComposePaginatedShit<Order.BiddingAction>(
object : PaginationPussy<Order.BiddingAction> {
override fun pageSize() = pageSize
override fun selectItems(offset: Long): List<Order.BiddingAction> {
val fromIndex = Math.toIntExact(offset)
val toIndex = Math.toIntExact(offset + pageSize)
val size = bids.size
return bids.subList(clamp(fromIndex, 0, max(size - 1, 0)), clamp(toIndex, 0, size))
}
override fun count() = bids.size.toLong()
}) {
override fun initShitGivenItems(items: List<Order.BiddingAction>) {}
override fun renderItem(item: Order.BiddingAction, index: Int): AlTag {
val sender = rctx0.al.dbCache.user(item.userId)
val iconWithStyle = Iconography.iconWithStyle(sender)
return div().with {
ooItemTitle(
iconWithStyle = iconWithStyle,
title = sender.fullNameOrEmail() + ": " +
when {
item.isCancelation -> t("TOTE", "Отмена")
item.money == null -> t("TOTE", "Комментарий")
else -> t("TOTE", "Заявка")
},
tinySubtitle = TimePile.kievTimeString(item.time),
afterTinySubtitle = {
if (item.isCancelation)
oo(composeRedBombForItemTitle())
},
buildDropdown = {},
amendTitleBarDiv = {gimmeName1(index, it, iconWithStyle)})
oo(div().style("position: relative;").with {
oo(div().style("position: absolute; right: 0px; top: 0px;").with {
})
// 0fe1d8cd-73a5-4780-b37c-8f6161c29eb0
item.money?.let {m->
oo(div().style("font-weight: bold; text-decoration: underline; margin-bottom: 0.5em;")
.add(FA.dollar().appendStyle("margin-right: 0.5em;"))
.add("Деньги: $m грн."))
}
oo(composePreWrapDiv(item.comment))
})
}
}
override fun makePageHref(pageFrom1: Int) = defaultPaginationPageHref(pageFrom1)
}))
}
fun gimmeName1(index: Int, tag: AlTag, iconWithStyle: FAIconWithStyle) {
if (index > 0) tag.appendClassName(iconWithStyle.nonFirstItemClass)
}
//fun ooApplicantConversation_killme(order: Order, applicant: User) {
// oo(!object : OoUsualPaginatedShit<Bid>(
// itemClass = Bid::class, table = Bid.Meta.table,
// notDeleted = false) {
//
// override fun composeItem(item: Bid): AlTag {
// val sender = rctx.dbCache.user(item.userId)
// val iconWithStyle = Iconography.iconWithStyle(sender)
// return div().className(iconWithStyle.spacer).with {
// ooItemTitle(
// iconWithStyle = iconWithStyle,
// title = sender.fullNameOrEmail() + ": " +
// when {
// item.data.isCancelation -> t("TOTE", "Отмена")
// item.money == null -> t("TOTE", "Комментарий")
// else -> t("TOTE", "Заявка")
// },
// tinySubtitle = AlText.numString(item.id) + ", " + TimePile.kievTimeString(item.time),
// afterTinySubtitle = {
// if (item.data.isCancelation)
// oo(composeRedBombForItemTitle())
// },
// buildDropdown = {})
//
// oo(div().style("position: relative;").with {
// oo(div().style("position: absolute; right: 0px; top: 0px;").with {
// })
//
// // 0fe1d8cd-73a5-4780-b37c-8f6161c29eb0
// item.money?.let {m->
// oo(div().style("font-weight: bold; text-decoration: underline; margin-bottom: 0.5em;")
// .add(FA.dollar().appendStyle("margin-right: 0.5em;"))
// .add("Деньги: $m грн."))
// }
//
// oo(composePreWrapDiv(item.data.comment))
// })
// }
// }
//
// override fun shitIntoWhere(q: AlQueryBuilder) {
// q.text("and ${Bid.Meta.orderId} =", order.id)
// q.text("and (${Bid.Meta.userId} =", applicant.id)
// q.text(" or ${Bid.Meta.commentRecipientId} =", applicant.id)
// q.text(" )")
// }
// })
//}
fun bakeModal2(orderHandle: OrderHandle): ShitWithContext<ModalShit, Context1> {
return !object : Kate<CommentFields>(
modalTitle = t("TOTE", "Вопрос"),
submitButtonTitle = t("TOTE", "Запостить"),
submitButtonLevel = AlButtonStyle.Primary) {
override fun setInitialFields(fs: CommentFields) {}
override fun serveGivenValidFields(fs: CommentFields) {
doCommentDuringBidding(toUser = null, orderHandle = orderHandle, fs = fs)
reloadToConversationTab(orderHandle.id)
}
override fun makeFields() = CommentFields()
override fun ooModalBody(fs: CommentFields) {
oo(fs.comment.begin().focused().compose())
}
}
}
fun reloadToConversationTab(orderId: Long) {
btfEval(jsProgressyNavigate(OoWriterBiddingOrderDetailsPage.hrefThunk(orderId).makeHref {
it.tab.set(OoWriterBiddingOrderDetailsPage.conversationTabId)
}, replaceState = true))
}
fun bakeModal3(orderHandle: OrderHandle): ShitWithContext<ModalShit, Context1> {
return !object : Kate<BidFields>(
modalTitle = t("TOTE", "Заявка"),
submitButtonTitle = t("TOTE", "Хочу"),
submitButtonLevel = AlButtonStyle.Primary) {
override fun setInitialFields(fs: BidFields) {
fs.comment.set("Без блядских комментариев")
}
override fun serveGivenValidFields(fs: BidFields) {
doBid(orderHandle, fs)
reloadToConversationTab(orderHandle.id)
}
override fun makeFields() = BidFields(orderHandle.id)
override fun ooModalBody(fs: BidFields) {
oo(fs.money.begin().focused().compose())
oo(fs.comment.begin().compose())
}
}
}
fun bakeModal4(orderHandle: OrderHandle): ShitWithContext<ModalShit, Context1> {
return !object : Kate<CommentFields>(
modalTitle = t("TOTE", "Отмена заявки"),
submitButtonTitle = t("TOTE", "Не хочу работать"),
submitButtonLevel = AlButtonStyle.Danger) {
override fun decorateModal(it: ComposeModalContent) {it.redLeftMargin()}
override fun setInitialFields(fs: CommentFields) {
fs.comment.set("Я ленивый засранец")
}
override fun serveGivenValidFields(fs: CommentFields) {
doCancelBid(orderHandle, fs)
reloadToConversationTab(orderHandle.id)
}
override fun makeFields() = CommentFields()
override fun ooModalBody(fs: CommentFields) {
oo(fs.comment.begin().focused().compose())
}
}
}
| apache-2.0 | a67ed4814a79d6f14c0745f878fbd3d7 | 35.211765 | 116 | 0.552225 | 4.266112 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Statements.kt | 6 | 6247 | // 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.j2k.ast
import org.jetbrains.kotlin.j2k.CodeBuilder
import org.jetbrains.kotlin.j2k.append
abstract class Statement : Element() {
object Empty : Statement() {
override fun generateCode(builder: CodeBuilder) { }
override val isEmpty: Boolean get() = true
}
}
class DeclarationStatement(val elements: List<Element>) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder.append(elements, "\n")
}
}
class ExpressionListStatement(val expressions: List<Expression>) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append(expressions, "\n")
}
}
class LabeledStatement(val name: Identifier, val statement: Element) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder append name append "@" append " " append statement
}
}
class ReturnStatement(val expression: Expression, val label: Identifier? = null) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder append "return"
if (label != null) {
builder append "@" append label
}
builder append " " append expression
}
}
class IfStatement(
val condition: Expression,
val thenStatement: Element,
val elseStatement: Element,
singleLine: Boolean
) : Expression() {
private val br = if (singleLine) " " else "\n"
private val brAfterElse = if (singleLine || elseStatement is IfStatement) " " else "\n"
override fun generateCode(builder: CodeBuilder) {
builder append "if (" append condition append ")" append br append thenStatement.wrapToBlockIfRequired()
if (!elseStatement.isEmpty) {
builder append br append "else" append brAfterElse append elseStatement.wrapToBlockIfRequired()
}
else if (thenStatement.isEmpty) {
builder append ";"
}
}
}
// Loops --------------------------------------------------------------------------------------------------
class WhileStatement(val condition: Expression, val body: Element, singleLine: Boolean) : Statement() {
private val br = if (singleLine) " " else "\n"
override fun generateCode(builder: CodeBuilder) {
builder append "while (" append condition append ")" append br append body.wrapToBlockIfRequired()
if (body.isEmpty) {
builder append ";"
}
}
}
class DoWhileStatement(val condition: Expression, val body: Element, singleLine: Boolean) : Statement() {
private val br = if (singleLine) " " else "\n"
override fun generateCode(builder: CodeBuilder) {
builder append "do" append br append body.wrapToBlockIfRequired() append br append "while (" append condition append ")"
}
}
class ForeachStatement(
val variableName: Identifier,
val explicitVariableType: Type?,
val collection: Expression,
val body: Element,
singleLine: Boolean
) : Statement() {
private val br = if (singleLine) " " else "\n"
override fun generateCode(builder: CodeBuilder) {
builder append "for (" append variableName
if (explicitVariableType != null) {
builder append ":" append explicitVariableType
}
builder append " in " append collection append ")" append br append body.wrapToBlockIfRequired()
if (body.isEmpty) {
builder append ";"
}
}
}
class BreakStatement(val label: Identifier = Identifier.Empty) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder.append("break").appendWithPrefix(label, "@")
}
}
class ContinueStatement(val label: Identifier = Identifier.Empty) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder.append("continue").appendWithPrefix(label, "@")
}
}
// Exceptions ----------------------------------------------------------------------------------------------
class TryStatement(val block: Block, val catches: List<CatchStatement>, val finallyBlock: Block) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder.append("try\n").append(block).append("\n").append(catches, "\n").append("\n")
if (!finallyBlock.isEmpty) {
builder append "finally\n" append finallyBlock
}
}
}
class ThrowStatement(val expression: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder append "throw " append expression
}
}
class CatchStatement(val variable: FunctionParameter, val block: Block) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder append "catch (" append variable append ") " append block
}
}
// when --------------------------------------------------------------------------------------------------
class WhenStatement(val subject: Expression, val caseContainers: List<WhenEntry>) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder.append("when (").append(subject).append(") {\n").append(caseContainers, "\n").append("\n}")
}
}
class WhenEntry(val selectors: List<WhenEntrySelector>, val body: Statement) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder.append(selectors, ", ").append(" -> ").append(body)
}
}
abstract class WhenEntrySelector : Statement()
class ValueWhenEntrySelector(val expression: Expression) : WhenEntrySelector() {
override fun generateCode(builder: CodeBuilder) {
builder.append(expression)
}
}
class ElseWhenEntrySelector : WhenEntrySelector() {
override fun generateCode(builder: CodeBuilder) {
builder.append("else")
}
}
// Other ------------------------------------------------------------------------------------------------------
class SynchronizedStatement(val expression: Expression, val block: Block) : Statement() {
override fun generateCode(builder: CodeBuilder) {
builder append "synchronized (" append expression append ") " append block
}
}
| apache-2.0 | 7efb4ba714d72c4c49e181f005f56d7e | 34.494318 | 158 | 0.631503 | 4.93834 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/slicer/Slicer.kt | 1 | 16437 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.slicer
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.SearchScope
import com.intellij.psi.util.parentOfType
import com.intellij.slicer.JavaSliceUsage
import com.intellij.slicer.SliceUsage
import com.intellij.usageView.UsageInfo
import com.intellij.util.Processor
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.cfg.pseudocode.PseudoValue
import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode
import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode
import org.jetbrains.kotlin.cfg.pseudocode.getContainingPseudocode
import org.jetbrains.kotlin.cfg.pseudocode.instructions.KtElementInstruction
import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.*
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.psi.hasInlineModifier
import org.jetbrains.kotlin.idea.base.searching.usages.KotlinFunctionFindUsagesOptions
import org.jetbrains.kotlin.idea.base.searching.usages.KotlinPropertyFindUsagesOptions
import org.jetbrains.kotlin.idea.base.searching.usages.processAllExactUsages
import org.jetbrains.kotlin.idea.base.searching.usages.processAllUsages
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.getDeepestSuperDeclarations
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchOverriders
import org.jetbrains.kotlin.idea.util.actualsForExpected
import org.jetbrains.kotlin.idea.util.expectedDescriptor
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.contains
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addIfNotNull
abstract class Slicer(
protected val element: KtElement,
protected val processor: Processor<in SliceUsage>,
protected val parentUsage: KotlinSliceUsage
) {
abstract fun processChildren(forcedExpressionMode: Boolean)
protected val analysisScope: SearchScope = parentUsage.scope.toSearchScope()
protected val mode: KotlinSliceAnalysisMode = parentUsage.mode
protected val project = element.project
protected class PseudocodeCache {
private val computedPseudocodes = HashMap<KtElement, Pseudocode>()
operator fun get(element: KtElement): Pseudocode? {
val container = element.containingDeclarationForPseudocode ?: return null
return computedPseudocodes.getOrPut(container) {
container.getContainingPseudocode(container.analyzeWithContent())?.apply { computedPseudocodes[container] = this }
?: return null
}
}
}
protected val pseudocodeCache = PseudocodeCache()
protected fun PsiElement.passToProcessor(mode: KotlinSliceAnalysisMode = [email protected]) {
processor.process(KotlinSliceUsage(this, parentUsage, mode, false))
}
protected fun PsiElement.passToProcessorAsValue(mode: KotlinSliceAnalysisMode = [email protected]) {
processor.process(KotlinSliceUsage(this, parentUsage, mode, forcedExpressionMode = true))
}
protected fun PsiElement.passToProcessorInCallMode(
callElement: KtElement,
mode: KotlinSliceAnalysisMode = [email protected],
withOverriders: Boolean = false
) {
val newMode = when (this) {
is KtNamedFunction -> this.callMode(callElement, mode)
is KtParameter -> ownerFunction.callMode(callElement, mode)
is KtTypeReference -> {
val declaration = parent
require(declaration is KtCallableDeclaration)
require(this == declaration.receiverTypeReference)
declaration.callMode(callElement, mode)
}
else -> mode
}
if (withOverriders) {
passDeclarationToProcessorWithOverriders(newMode)
} else {
passToProcessor(newMode)
}
}
protected fun PsiElement.passDeclarationToProcessorWithOverriders(mode: KotlinSliceAnalysisMode = [email protected]) {
passToProcessor(mode)
HierarchySearchRequest(this, analysisScope)
.searchOverriders()
.forEach { it.namedUnwrappedElement?.passToProcessor(mode) }
if (this is KtCallableDeclaration && isExpectDeclaration()) {
resolveToDescriptorIfAny()
?.actualsForExpected()
?.forEach {
(it as? DeclarationDescriptorWithSource)?.toPsi()?.passToProcessor(mode)
}
}
}
protected open fun processCalls(
callable: KtCallableDeclaration,
includeOverriders: Boolean,
sliceProducer: SliceProducer,
) {
if (callable is KtFunctionLiteral || callable is KtFunction && callable.name == null) {
callable.passToProcessorAsValue(mode.withBehaviour(LambdaCallsBehaviour(sliceProducer)))
return
}
val options = when (callable) {
is KtFunction -> {
KotlinFunctionFindUsagesOptions(project).apply {
isSearchForTextOccurrences = false
isSkipImportStatements = true
searchScope = analysisScope
}
}
is KtProperty -> {
KotlinPropertyFindUsagesOptions(project).apply {
isSearchForTextOccurrences = false
isSkipImportStatements = true
searchScope = analysisScope
}
}
else -> return
}
val descriptor = callable.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return
val superDescriptors = if (includeOverriders) {
descriptor.getDeepestSuperDeclarations()
} else {
mutableListOf<CallableMemberDescriptor>().apply {
add(descriptor)
addAll(DescriptorUtils.getAllOverriddenDeclarations(descriptor))
if (descriptor.isActual) {
addIfNotNull(descriptor.expectedDescriptor() as CallableMemberDescriptor?)
}
}
}
for (superDescriptor in superDescriptors) {
val declaration = superDescriptor.toPsi() ?: continue
when (declaration) {
is KtDeclaration -> {
val usageProcessor: (UsageInfo) -> Unit = processor@{ usageInfo ->
val element = usageInfo.element ?: return@processor
if (element.parentOfType<PsiComment>() != null) return@processor
val sliceUsage = KotlinSliceUsage(element, parentUsage, mode, false)
sliceProducer.produceAndProcess(sliceUsage, mode, parentUsage, processor)
}
if (includeOverriders) {
declaration.processAllUsages(options, usageProcessor)
} else {
declaration.processAllExactUsages(options, usageProcessor)
}
}
is PsiMethod -> {
val sliceUsage = JavaSliceUsage.createRootUsage(declaration, parentUsage.params)
sliceProducer.produceAndProcess(sliceUsage, mode, parentUsage, processor)
}
else -> {
val sliceUsage = KotlinSliceUsage(declaration, parentUsage, mode, false)
sliceProducer.produceAndProcess(sliceUsage, mode, parentUsage, processor)
}
}
}
}
protected enum class AccessKind {
READ_ONLY, WRITE_ONLY, WRITE_WITH_OPTIONAL_READ, READ_OR_WRITE
}
protected fun processVariableAccesses(
declaration: KtCallableDeclaration,
scope: SearchScope,
kind: AccessKind,
usageProcessor: (UsageInfo) -> Unit
) {
val options = KotlinPropertyFindUsagesOptions(project).apply {
isReadAccess = kind == AccessKind.READ_ONLY || kind == AccessKind.READ_OR_WRITE
isWriteAccess =
kind == AccessKind.WRITE_ONLY || kind == AccessKind.WRITE_WITH_OPTIONAL_READ || kind == AccessKind.READ_OR_WRITE
isReadWriteAccess = kind == AccessKind.WRITE_WITH_OPTIONAL_READ || kind == AccessKind.READ_OR_WRITE
isSearchForTextOccurrences = false
isSkipImportStatements = true
searchScope = scope
}
val allDeclarations = mutableListOf(declaration)
val descriptor = declaration.resolveToDescriptorIfAny()
if (descriptor is CallableMemberDescriptor) {
val additionalDescriptors = if (descriptor.isActual) {
listOfNotNull(descriptor.expectedDescriptor() as? CallableMemberDescriptor)
} else {
DescriptorUtils.getAllOverriddenDeclarations(descriptor)
}
additionalDescriptors.mapNotNullTo(allDeclarations) {
it.toPsi() as? KtCallableDeclaration
}
}
allDeclarations.forEach {
it.processAllExactUsages(options) { usageInfo ->
if (!shouldIgnoreVariableUsage(usageInfo)) {
usageProcessor.invoke(usageInfo)
}
}
}
}
// ignore parameter usages in function contract
private fun shouldIgnoreVariableUsage(usage: UsageInfo): Boolean {
val element = usage.element ?: return true
return element.parents.any {
it is KtCallExpression &&
(it.calleeExpression as? KtSimpleNameExpression)?.getReferencedName() == "contract" &&
it.resolveToCall()?.resultingDescriptor?.fqNameOrNull()?.asString() == "kotlin.contracts.contract"
}
}
protected fun canProcessParameter(parameter: KtParameter) = !parameter.isVarArg
protected fun processExtensionReceiverUsages(
declaration: KtCallableDeclaration,
body: KtExpression?,
mode: KotlinSliceAnalysisMode,
) {
if (body == null) return
//TODO: overriders
val resolutionFacade = declaration.getResolutionFacade()
val callableDescriptor = declaration.resolveToDescriptorIfAny(resolutionFacade) as? CallableDescriptor ?: return
val extensionReceiver = callableDescriptor.extensionReceiverParameter ?: return
body.forEachDescendantOfType<KtThisExpression> { thisExpression ->
val receiverDescriptor = thisExpression.resolveToCall(resolutionFacade)?.resultingDescriptor
if (receiverDescriptor == extensionReceiver) {
thisExpression.passToProcessor(mode)
}
}
// process implicit receiver usages
val pseudocode = pseudocodeCache[body]
if (pseudocode != null) {
for (instruction in pseudocode.instructions) {
if (instruction is MagicInstruction && instruction.kind == MagicKind.IMPLICIT_RECEIVER) {
val receiverPseudoValue = instruction.outputValue
pseudocode.getUsages(receiverPseudoValue).forEach { receiverUseInstruction ->
if (receiverUseInstruction is KtElementInstruction) {
receiverPseudoValue.processIfReceiverValue(
receiverUseInstruction,
mode,
filter = { receiverValue, resolvedCall ->
receiverValue == resolvedCall.extensionReceiver &&
(receiverValue as? ImplicitReceiver)?.declarationDescriptor == callableDescriptor
}
)
}
}
}
}
}
}
protected fun PseudoValue.processIfReceiverValue(
instruction: KtElementInstruction,
mode: KotlinSliceAnalysisMode,
filter: (ReceiverValue, ResolvedCall<out CallableDescriptor>) -> Boolean = { _, _ -> true }
): Boolean {
val receiverValue = (instruction as? InstructionWithReceivers)?.receiverValues?.get(this) ?: return false
val resolvedCall = instruction.element.resolveToCall() ?: return true
if (!filter(receiverValue, resolvedCall)) return true
val descriptor = resolvedCall.resultingDescriptor
if (descriptor.isImplicitInvokeFunction()) {
when (receiverValue) {
resolvedCall.dispatchReceiver -> {
if (mode.currentBehaviour is LambdaCallsBehaviour) {
instruction.element.passToProcessor(mode)
}
}
resolvedCall.extensionReceiver -> {
val dispatchReceiver = resolvedCall.dispatchReceiver ?: return true
val dispatchReceiverPseudoValue = instruction.receiverValues.entries
.singleOrNull { it.value == dispatchReceiver }?.key
?: return true
val createdAt = dispatchReceiverPseudoValue.createdAt
val accessedDescriptor = (createdAt as ReadValueInstruction?)?.target?.accessedDescriptor
if (accessedDescriptor is VariableDescriptor) {
accessedDescriptor.toPsi()?.passToProcessor(mode.withBehaviour(LambdaReceiverInflowBehaviour))
}
}
}
} else {
if (receiverValue == resolvedCall.extensionReceiver) {
(descriptor.toPsi() as? KtCallableDeclaration)?.receiverTypeReference
?.passToProcessorInCallMode(instruction.element, mode)
}
}
return true
}
protected fun DeclarationDescriptor.toPsi(): PsiElement? {
return descriptorToPsi(this, project, analysisScope)
}
companion object {
protected fun KtDeclaration?.callMode(callElement: KtElement, defaultMode: KotlinSliceAnalysisMode): KotlinSliceAnalysisMode {
return if (this is KtNamedFunction && hasInlineModifier())
defaultMode.withInlineFunctionCall(callElement, this)
else
defaultMode
}
fun descriptorToPsi(descriptor: DeclarationDescriptor, project: Project, analysisScope: SearchScope): PsiElement? {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) ?: return null
if (analysisScope.contains(declaration)) return declaration.navigationElement
// we ignore access scope for inline declarations
val isInline = when (declaration) {
is KtNamedFunction -> declaration.hasInlineModifier()
is KtParameter -> declaration.ownerFunction?.hasInlineModifier() == true
else -> false
}
return if (isInline) declaration.navigationElement else null
}
}
}
fun CallableDescriptor.isImplicitInvokeFunction(): Boolean {
if (this !is FunctionDescriptor) return false
if (!isOperator) return false
if (name != OperatorNameConventions.INVOKE) return false
return source.getPsi() == null
}
| apache-2.0 | 910a54819e3f5d4b8d1ed2b17b9ec904 | 43.424324 | 158 | 0.655837 | 6.003287 | false | false | false | false |
siosio/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/IonSerializer.kt | 1 | 3539 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl
import com.intellij.serialization.ObjectSerializer
import com.intellij.serialization.ReadConfiguration
import com.intellij.serialization.WriteConfiguration
import com.intellij.util.containers.BidirectionalMultiMap
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.impl.indices.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap
import java.io.InputStream
import java.io.OutputStream
class IonSerializer(virtualFileManager: VirtualFileUrlManager) : EntityStorageSerializer {
override val serializerDataFormatVersion: String = "v1"
override fun serializeCache(stream: OutputStream, storage: WorkspaceEntityStorage): SerializationResult {
storage as WorkspaceEntityStorageImpl
val configuration = WriteConfiguration(allowAnySubTypes = true)
val ion = ObjectSerializer.instance
ion.write(storage.entitiesByType, stream, configuration)
ion.write(storage.refs, stream, configuration)
ion.write(storage.indexes.softLinks, stream, configuration)
ion.write(storage.indexes.virtualFileIndex.entityId2VirtualFileUrl, stream, configuration)
ion.write(storage.indexes.virtualFileIndex.vfu2EntityId, stream, configuration)
ion.write(storage.indexes.virtualFileIndex.entityId2JarDir, stream, configuration)
ion.write(storage.indexes.entitySourceIndex, stream, configuration)
ion.write(storage.indexes.persistentIdIndex, stream, configuration)
return SerializationResult.Success
}
override fun deserializeCache(stream: InputStream): WorkspaceEntityStorageBuilder? {
val configuration = ReadConfiguration(allowAnySubTypes = true)
val ion = ObjectSerializer.instance
// Read entity data and references
val entitiesBarrel = ion.read(ImmutableEntitiesBarrel::class.java, stream, configuration)
val refsTable = ion.read(RefsTable::class.java, stream, configuration)
val softLinks = ion.read(MultimapStorageIndex::class.java, stream, configuration)
val entityId2VirtualFileUrlInfo = ion.read(Object2ObjectOpenHashMap::class.java, stream, configuration) as EntityId2Vfu
val vfu2VirtualFileUrlInfo = ion.read(Object2ObjectOpenHashMap::class.java, stream, configuration) as Vfu2EntityId
val entityId2JarDir = ion.read(BidirectionalMultiMap::class.java, stream, configuration) as BidirectionalMultiMap<EntityId, VirtualFileUrl>
val virtualFileIndex = VirtualFileIndex(entityId2VirtualFileUrlInfo, vfu2VirtualFileUrlInfo, entityId2JarDir)
val entitySourceIndex = ion.read(EntityStorageInternalIndex::class.java, stream, configuration) as EntityStorageInternalIndex<EntitySource>
val persistentIdIndex = ion.read(EntityStorageInternalIndex::class.java, stream, configuration) as PersistentIdInternalIndex
val storageIndexes = StorageIndexes(softLinks, virtualFileIndex, entitySourceIndex, persistentIdIndex)
val storage = WorkspaceEntityStorageImpl(entitiesBarrel, refsTable, storageIndexes)
val builder = WorkspaceEntityStorageBuilderImpl.from(storage)
builder.entitiesByType.entityFamilies.forEach { family ->
family?.entities?.asSequence()?.filterNotNull()?.forEach { entityData -> builder.createAddEvent(entityData) }
}
return builder
}
}
| apache-2.0 | fcaca2e714db654c7a4c9511b02b934f | 51.820896 | 143 | 0.814637 | 5.034139 | false | true | false | false |
jwren/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/renderers/PackageNameCellRenderer.kt | 1 | 7003 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.JBColor
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.normalizeWhitespace
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.PackagesTableItem
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.TagComponent
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.colors
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaledInsets
import net.miginfocom.layout.AC
import net.miginfocom.layout.BoundSize
import net.miginfocom.layout.CC
import net.miginfocom.layout.DimConstraint
import net.miginfocom.layout.LC
import net.miginfocom.layout.UnitValue
import net.miginfocom.swing.MigLayout
import java.awt.Dimension
import java.awt.Graphics
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.JTable
import javax.swing.table.TableCellRenderer
@Suppress("MagicNumber") // Swing dimension constants
internal object PackageNameCellRenderer : TableCellRenderer {
private val layoutConstraints = LC().align("left", "center")
.scaledInsets(left = 8, right = 0)
private val componentGapX = 4.scaled()
private val columnConstraints = AC().apply {
gap(componentGapX.toString())
constaints = arrayOf(
DimConstraint().apply {
gap(componentGapX.toString())
size = BoundSize(UnitValue(150F, UnitValue.PIXEL, ""), "")
},
DimConstraint().apply {
gapBefore = BoundSize(UnitValue(componentGapX / 2F), "")
}
)
}
private val tagForeground = JBColor.namedColor("PackageSearch.PackageTag.foreground", 0x808080, 0x9C9C9C)
private val tagBackground = JBColor.namedColor("PackageSearch.PackageTag.background", 0xE5E5E5, 0x666B6E)
private val tagForegroundSelected = JBColor.namedColor("PackageSearch.PackageTagSelected.foreground", 0xFFFFFF, 0xFFFFFF)
private val tagBackgroundSelected = JBColor.namedColor("PackageSearch.PackageTagSelected.background", 0x4395E2, 0x78ADE2)
private fun componentConstraint(x: Int = 0, y: Int = 0, gapAfter: Int? = null): CC = CC().apply {
cellX = x
cellY = y
if (gapAfter != null) gapAfter(gapAfter.toString())
}
override fun getTableCellRendererComponent(
table: JTable,
value: Any,
isSelected: Boolean,
hasFocus: Boolean,
row: Int,
column: Int
): JPanel {
val columnWidth = table.tableHeader.columnModel.getColumn(0).width
return when (value as PackagesTableItem<*>) {
is PackagesTableItem.InstalledPackage -> {
val packageModel = value.packageModel
val name: String? = packageModel.remoteInfo?.name.normalizeWhitespace()
val rawIdentifier = packageModel.identifier.rawValue
createNamePanel(columnWidth, name, rawIdentifier, packageModel.isKotlinMultiplatform, isSelected).apply {
table.colors.applyTo(this, isSelected)
}
}
is PackagesTableItem.InstallablePackage -> {
val packageModel = value.packageModel
val name: String? = packageModel.remoteInfo?.name.normalizeWhitespace()
val rawIdentifier = packageModel.identifier.rawValue
createNamePanel(columnWidth, name, rawIdentifier, packageModel.isKotlinMultiplatform, isSelected).apply {
table.colors.applyTo(this, isSelected)
if (!isSelected) background = PackageSearchUI.ListRowHighlightBackground
}
}
}
}
private fun createNamePanel(
columnWidth: Int,
@NlsSafe name: String?,
@NlsSafe identifier: String,
isKotlinMultiplatform: Boolean,
isSelected: Boolean
) = TagPaintingJPanel(columnWidth, isSelected).apply {
if (!name.isNullOrBlank() && name != identifier) {
add(
JLabel(name).apply {
foreground = PackageSearchUI.getTextColorPrimary(isSelected)
},
componentConstraint(gapAfter = componentGapX)
)
add(
JLabel(identifier).apply {
foreground = PackageSearchUI.getTextColorSecondary(isSelected)
},
componentConstraint().gapAfter("0:push")
)
} else {
add(
JLabel(identifier).apply {
foreground = PackageSearchUI.getTextColorPrimary(isSelected)
},
componentConstraint()
)
}
if (isKotlinMultiplatform) {
add(
TagComponent(PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform"))
.apply { isVisible = false },
componentConstraint(1, 0)
)
}
}
// This is a hack; ideally we should have this done by the layout itself,
// but MigLayout wasn't cooperating
// TODO Use a custom layout to do this in a less hacky fashion
private class TagPaintingJPanel(private val columnWidth: Int, private val isSelected: Boolean) : JPanel(
MigLayout(layoutConstraints.width("${columnWidth}px!"), columnConstraints)
) {
init {
size = Dimension(columnWidth, height)
maximumSize = Dimension(columnWidth, Int.MAX_VALUE)
}
override fun paintChildren(g: Graphics) {
super.paintChildren(g)
val tagComponent = components.find { it is TagComponent } as? TagComponent ?: return
val tagX = columnWidth - tagComponent.width
val tagY = height / 2 - tagComponent.height / 2
g.apply {
// We first paint over the gap between the text and the tag, to have a pretend margin if needed
color = background
fillRect(tagX - componentGapX, 0, columnWidth - tagX, height)
// Then we manually translate the tag to the right-hand side of the row and paint it
translate(tagX, tagY)
tagComponent.apply {
isVisible = true
foreground = JBColor.namedColor("Plugins.tagForeground", if (isSelected) tagForegroundSelected else tagForeground)
background = JBColor.namedColor("Plugins.tagBackground", if (isSelected) tagBackgroundSelected else tagBackground)
paint(g)
}
}
}
}
}
| apache-2.0 | d5510a78393259fb113023222f7a6748 | 40.934132 | 134 | 0.649722 | 5.195104 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/live-templates/tests/testData/inn.exp.kt | 13 | 238 | val a: String = ""
val b: String? = ""
class MyClass {
val x: String = ""
val y: String? = ""
fun foo() {
val s: String = ""
val t: String? = ""
if (b != null) {
<caret>
}
}
} | apache-2.0 | ff88b1642b8eddca559395409bee18a7 | 13.9375 | 27 | 0.378151 | 3.305556 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/search/filters/KotlinSSCountFilterTest.kt | 1 | 11290 | // 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.structuralsearch.search.filters
import org.jetbrains.kotlin.idea.structuralsearch.KotlinSSResourceInspectionTest
class KotlinSSCountFilterTest : KotlinSSResourceInspectionTest() {
override fun getBasePath(): String = "countFilter"
// isApplicableMinCount
fun testMinProperty() { doTest("var '_ = '_{0,0}", """
class A {
<warning descr="SSR">lateinit var x: String</warning>
var y = 1
fun init() { x = "a" }
}
""".trimIndent()) }
fun testMinDotQualifierExpression() { doTest("'_{0,0}.'_", """
class A {
companion object {
const val FOO = 3.14
}
}
fun main() {
val a = A.FOO
<warning descr="SSR">print(Int.hashCode())</warning>
<warning descr="SSR">print(<warning descr="SSR">a</warning>)</warning>
}
""".trimIndent()) }
fun testMinFunctionTypeReference() { doTest("fun '_{0,0}.'_()", """
class One
fun One.myFun() {}
<warning descr="SSR">fun myFun() {}</warning>
""".trimIndent()) }
fun testMinCallableReferenceExpression() { doTest("'_{0,0}::'_", """
fun Int.isOddExtension() = this % 2 != 0
class MyClazz {
fun isOddMember(x: Int) = x % 2 != 0
fun constructorReference(init: () -> MyClazz) { print(init) }
fun foo() {
val functionTwo: (Int) -> Boolean = Int::isOddExtension
val functionOne: (Int) -> Boolean = <warning descr="SSR">::isOddMember</warning>
constructorReference(<warning descr="SSR">::MyClazz</warning>)
print(functionOne(1) == functionTwo(2))
}
}
""".trimIndent()) }
fun testMinWhenExpression() { doTest("when ('_{0,0}) {}", """
fun foo() {
print(<warning descr="SSR">when (1) {
in 0..3 -> 2
else -> 3
}</warning>)
print(<warning descr="SSR">when { else -> true }</warning>)
}
""".trimIndent()) }
fun testMinConstructorCallee() { doTest("class '_ : '_{0,0}('_*)", """
<warning descr="SSR">open class Foo</warning>
class Bar: Foo()
""".trimIndent()) }
fun testMinSuperType() { doTest("class '_ : '_{0,0}()", """
<warning descr="SSR">open class A</warning>
class B : A()
""".trimIndent()) }
// isApplicableMaxCount
fun testMaxDestructuringDeclarationEntry() { doTest("for (('_{3,3}) in '_) { '_* }", """
data class Foo(val foo1: Int, val foo2: Int)
data class Bar(val bar1: String, val bar2: String, val bar3: String)
fun foo() = Foo(1, 2)
fun bar() = Bar("a", "b", "c")
fun main() {
val (f1, f2) = foo()
val (b1, b2, b3) = bar()
print(f1 + f2)
print(b1 + b2 + b3)
val l1 = listOf(Foo(1, 1))
for ((x1, x2) in l1) { print(x1 + x2) }
val l2 = listOf(Bar("a", "a", "a"))
<warning descr="SSR">for ((x1, x2, x3) in l2) { print(x1 + x2 + x3) }</warning>
for (i in 1..2) { print(i) }
}
""".trimIndent()) }
fun testMaxWhenConditionWithExpression() { doTest("when ('_?) { '_{2,2} -> '_ }", """
fun foo(): Int {
fun f() {}
<warning descr="SSR">when (1) {
in 1..10 -> f()
in 11..20 -> f()
}</warning>
val x1 = when { else -> 1 }
val x2 = <warning descr="SSR">when {
<warning>1 < 2</warning> -> 3
else -> 1
}</warning>
val x3 = when {
<warning>1 < 3</warning> -> 1
<warning>2 > 1</warning> -> 4
else -> 1
}
return x1 + x2 + x3
}
""".trimIndent()) }
// isApplicableMinMaxCount
fun testMmClassBodyElement() {
doTest("""
class '_Class {
var '_Field{0,2} = '_Init?
}
""".trimIndent(), """
<warning descr="SSR">class A</warning>
<warning descr="SSR">class B {
var x = 1
}</warning>
<warning descr="SSR">class C {
var x = 1
var y = "1"
}</warning>
class D {
var x = 1
var y = "1"
var z = false
}
""".trimIndent()
)
}
fun testMmParameter() { doTest("fun '_('_{0,2})", """
<warning descr="SSR">fun foo1() {}</warning>
<warning descr="SSR">fun foo2(p1: Int) { print(p1) }</warning>
<warning descr="SSR">fun foo3(p1: Int, p2: Int) { print(p1 + p2) }</warning>
fun bar(p1: Int, p2: Int, p3: Int) { print(p1 + p2 + p3) }
""".trimIndent()) }
fun testMmTypeParameter() { doTest("fun <'_{0,2}> '_('_*)", """
<warning descr="SSR">fun foo1() {}</warning>
<warning descr="SSR">fun <A> foo2(x: A) { x.hashCode() }</warning>
<warning descr="SSR">fun <A, B> foo3(x: A, y: B) { x.hashCode() + y.hashCode() }</warning>
fun <A, B, C> bar(x: A, y: B, z: C) { x.hashCode() + y.hashCode() + z.hashCode() }
""".trimIndent()) }
fun testMmTypeParameterFunctionType() { doTest("fun '_('_ : ('_{0,2}) -> '_)", """
<warning descr="SSR">fun foo1(x : () -> Unit) { print(x) }</warning>
<warning descr="SSR">fun foo2(x : (Int) -> Unit) { print(x) }</warning>
<warning descr="SSR">fun foo3(x : (Int, String) -> Unit) { print(x) }</warning>
fun bar(x : (Int, String, Boolean) -> Unit) { print(x) }
""".trimIndent()) }
fun testMmTypeReference() { doTest("val '_ : ('_{0,2}) -> '_", """
<warning descr="SSR">val foo1 : () -> String = { "" }</warning>
<warning descr="SSR">val foo2 : (Int) -> String = { x -> "${"$"}x" }</warning>
<warning descr="SSR">val foo3 : (Int, String) -> String = { x, y -> "${"$"}x${"$"}y" }</warning>
val bar : (Int, String, Boolean) -> String = { x, y, z -> "${"$"}x${"$"}y${"$"}z" }
""".trimIndent()) }
fun testMmSuperTypeEntry() { doTest("class '_ : '_{0,2}", """
interface IOne
interface ITwo
interface IThree
<warning descr="SSR">open class A</warning>
<warning descr="SSR">class B : IOne</warning>
<warning descr="SSR">class B2 : IOne, A()</warning>
<warning descr="SSR">class C : IOne, ITwo</warning>
<warning descr="SSR">class C2 : IOne, ITwo, A()</warning>
class D : IOne, ITwo, IThree
class D2 : IOne, ITwo, IThree, A()
""".trimIndent()) }
fun testMmValueArgument() { doTest("listOf('_{0,2})", """
val foo1: List<Int> = <warning descr="SSR">listOf()</warning>
val foo2 = <warning descr="SSR">listOf(1)</warning>
val foo3 = <warning descr="SSR">listOf(1, 2)</warning>
val bar = listOf(1, 2, 3)
""".trimIndent()) }
fun testMmStatementInDoWhile() { doTest("do { '_{0,2} } while ('_)", """
fun foo() {
var x = 0
<warning descr="SSR">do { } while (false)</warning>
<warning descr="SSR">do {
x += 1
} while (false)</warning>
<warning descr="SSR">do {
x += 1
x *= 2
} while (false)</warning>
do {
x += 1
x *= 2
x *= x
} while (false)
print(x)
}
""".trimIndent()) }
fun testMmStatementInBlock() { doTest("fun '_('_*) { '_{0,2} }", """
<warning descr="SSR">fun foo1() {}</warning>
<warning descr="SSR">fun foo2() {
print(1)
}</warning>
<warning descr="SSR">fun foo3() {
print(1)
print(2)
}</warning>
fun bar() {
print(1)
print(2)
print(3)
}
""".trimIndent()) }
fun testMmAnnotation() { doTest("@'_{0,2} class '_", """
<warning descr="SSR">annotation class FirstAnnotation</warning>
<warning descr="SSR">annotation class SecondAnnotation</warning>
<warning descr="SSR">annotation class ThirdAnnotation</warning>
<warning descr="SSR">class ZeroClass</warning>
<warning descr="SSR">@FirstAnnotation class FirstClass</warning>
<warning descr="SSR">@FirstAnnotation @SecondAnnotation class SecondClass</warning>
@FirstAnnotation @SecondAnnotation @ThirdAnnotation class ThirdClass
""".trimIndent()) }
fun testMmSimpleNameStringTemplateEntry() { doTest(""" "$$'_{0,2}" """, """
val foo1 = <warning descr="SSR">""</warning>
val foo2 = <warning descr="SSR">"foo"</warning>
val foo3 = <warning descr="SSR">"foo${"$"}foo1"</warning>
val bar = "foo${"$"}foo1${"$"}foo2"
""".trimIndent()) }
fun testMmTypeProjection() { doTest("fun '_('_ : '_<'_{0,2}>)", """
class X<A> {}
class Y<A, B> {}
class Z<A, B, C> {}
<warning descr="SSR">fun foo1(par: Int) { print(par) }</warning>
<warning descr="SSR">fun foo2(par: X<String>) { print(par) }</warning>
<warning descr="SSR">fun foo3(par: Y<String, Int>) { print(par) }</warning>
fun bar(par: Z<String, Int, Boolean>) { print(par) }
""".trimIndent()) }
fun testMmKDocTag() { doTest("""
/**
* @'_{0,2}
*/
""".trimIndent(), """
<warning descr="SSR">/**
* lorem
*/</warning>
<warning descr="SSR">/**
* ipsum
* @a
*/</warning>
<warning descr="SSR">/**
* dolor
* @a
* @b
*/</warning>
/**
* sit
* @a
* @b
* @c
*/
""".trimIndent()) }
// Misc
fun testZeroLambdaParameter() { doTest("{ '_{0,0} -> '_ }", """
val p0: () -> Int = <warning descr="SSR">{ 31 }</warning>
val p1: (Int) -> Int = { x -> x }
val p1b: (Int) -> Int = <warning descr="SSR">{ it }</warning>
val p2: (Int, Int) -> Int = { x, y -> x + y }
val p3: (Int, Int, Int) -> Int = { x, y, z -> x + y + z }
""".trimIndent()) }
fun testOneLambdaParameter() { doTest("{ '_{1,1} -> '_ }", """
val p0: () -> Int = { 31 }
val p1: (Int) -> Int = <warning descr="SSR">{ x -> x }</warning>
val p1b: (Int) -> Int = <warning descr="SSR">{ it }</warning>
val p2: (Int, Int) -> Int = { x, y -> x + y }
val p3: (Int, Int, Int) -> Int = { x, y, z -> x + y + z }
""".trimIndent()) }
fun testMmLambdaParameter() { doTest("{ '_{0,2} -> '_ }", """
val p0: () -> Int = <warning descr="SSR">{ 31 }</warning>
val p1: (Int) -> Int = <warning descr="SSR">{ x -> x }</warning>
val p1b: (Int) -> Int = <warning descr="SSR">{ it }</warning>
val p2: (Int, Int) -> Int = <warning descr="SSR">{ x, y -> x + y }</warning>
val p3: (Int, Int, Int) -> Int = { x, y, z -> x + y + z }
""".trimIndent()) }
} | apache-2.0 | 7d239fb395fd32a902601a7057210b03 | 34.844444 | 120 | 0.474668 | 3.753324 | false | true | false | false |
GunoH/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/ClassFileChecker.kt | 2 | 9193 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("BlockingMethodInNonBlockingContext")
package org.jetbrains.intellij.build.impl
import com.intellij.diagnostic.telemetry.useWithScope2
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.util.lang.JavaVersion
import io.opentelemetry.api.trace.Span
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import org.apache.commons.compress.archivers.zip.ZipFile
import org.apache.commons.compress.utils.SeekableInMemoryByteChannel
import org.jetbrains.intellij.build.BuildMessages
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import java.io.BufferedInputStream
import java.io.DataInputStream
import java.io.InputStream
import java.nio.channels.FileChannel
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.*
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicInteger
import java.util.zip.ZipException
/**
* <p>
* Recursively checks .class files in directories and .jar/.zip files to ensure that their versions
* do not exceed limits specified in the config map.
* </p>
* <p>
* The config map contains pairs of path prefixes (relative to the check root) to version limits.
* The limits are Java version strings (<code>"1.3"</code>, <code>"8"</code> etc.);
* empty strings are ignored (making the check always pass).
* The map must contain an empty path prefix (<code>""</code>) denoting the default version limit.
* </p>
* <p>Example: <code>["": "1.8", "lib/idea_rt.jar": "1.3"]</code>.</p>
*/
internal suspend fun checkClassFiles(versionCheckConfig: Map<String, String>,
forbiddenSubPaths: List<String>,
root: Path,
messages: BuildMessages) {
spanBuilder("verify class files")
.setAttribute("ruleCount", versionCheckConfig.size.toLong())
.setAttribute("forbiddenSubPathCount", forbiddenSubPaths.size.toLong())
.setAttribute("root", root.toString())
.useWithScope2 {
val rules = ArrayList<Rule>(versionCheckConfig.size)
for (entry in versionCheckConfig.entries) {
rules.add(Rule(path = entry.key, version = classVersion(entry.value)))
}
rules.sortWith { o1, o2 -> (-o1.path.length).compareTo(-o2.path.length) }
check(rules.isEmpty() || rules.last().path.isEmpty()) {
throw ClassFileCheckError("Invalid configuration: missing default version $rules")
}
val defaultVersion = rules.lastOrNull()?.version
check(defaultVersion == null || rules.dropLast(1).none { it.version == defaultVersion }) {
throw ClassFileCheckError("Redundant rules with default version: " + rules.dropLast(1).filter {
it.version == defaultVersion
})
}
val checker = ClassFileChecker(rules, forbiddenSubPaths)
val errors = ConcurrentLinkedQueue<String>()
if (Files.isDirectory(root)) {
coroutineScope {
checker.apply {
visitDirectory(root, "", errors)
}
}
}
else {
checker.visitFile(root, "", errors)
}
check(rules.isEmpty() || checker.checkedClassCount.get() != 0) {
throw ClassFileCheckError("No classes found under $root - please check the configuration")
}
val errorCount = errors.size
Span.current()
.setAttribute("checkedClasses", checker.checkedClassCount.get().toLong())
.setAttribute("checkedJarCount", checker.checkedJarCount.get().toLong())
.setAttribute("errorCount", errorCount.toLong())
for (error in errors) {
messages.warning("---\n$error")
}
check(errorCount == 0) {
throw ClassFileCheckError("Failed with $errorCount problems", errors)
}
val unusedRules = rules.filter { !it.wasUsed }
check(unusedRules.isEmpty()) {
throw ClassFileCheckError("Class version check rules for the following paths don't match any files, probably entries in " +
"ProductProperties::versionCheckerConfig are out of date:\n${unusedRules.joinToString(separator = "\n")}")
}
}
}
class ClassFileCheckError(message: String, val errors: Collection<String> = emptyList()) : Exception(message)
private val READ = EnumSet.of(StandardOpenOption.READ)
private class ClassFileChecker(private val versionRules: List<Rule>, private val forbiddenSubPaths: List<String>) {
val checkedJarCount = AtomicInteger()
val checkedClassCount = AtomicInteger()
fun CoroutineScope.visitDirectory(directory: Path, relPath: String, errors: MutableCollection<String>) {
Files.newDirectoryStream(directory).use { dirStream ->
// closure must be used, otherwise variables are not captured by FJT
for (child in dirStream) {
if (Files.isDirectory(child)) {
launch {
visitDirectory(directory = child, relPath = join(relPath, "/", child.fileName.toString()), errors = errors)
}
}
else {
launch {
visitFile(file = child, relPath = join(relPath, "/", child.fileName.toString()), errors = errors)
}
}
}
}
}
fun visitFile(file: Path, relPath: String, errors: MutableCollection<String>) {
val fullPath = file.toString()
if (fullPath.endsWith(".zip") || fullPath.endsWith(".jar")) {
visitZip(fullPath, relPath, ZipFile(FileChannel.open(file, READ)), errors)
}
else if (fullPath.endsWith(".class")) {
checkIfSubPathIsForbidden(relPath, errors)
val contentCheckRequired = versionRules.isNotEmpty() && !fullPath.endsWith("module-info.class") && !isMultiVersion(fullPath)
if (contentCheckRequired) {
BufferedInputStream(Files.newInputStream(file)).use { checkVersion(relPath, it, errors) }
}
}
}
// use ZipFile - avoid a lot of small lookups to read entry headers (ZipFile uses central directory)
private fun visitZip(zipPath: String, zipRelPath: String, file: ZipFile, errors: MutableCollection<String>) {
file.use {
checkedJarCount.incrementAndGet()
val entries = file.entries
while (entries.hasMoreElements()) {
val entry = entries.nextElement()
if (entry.isDirectory) {
continue
}
val name = entry.name
if (name.endsWith(".zip") || name.endsWith(".jar")) {
val childZipPath = "$zipPath!/$name"
try {
visitZip(zipPath = childZipPath,
zipRelPath = join(zipRelPath, "!/", name),
file = ZipFile(SeekableInMemoryByteChannel(file.getInputStream(entry).readAllBytes())),
errors = errors)
}
catch (e: ZipException) {
throw RuntimeException("Cannot read $childZipPath", e)
}
}
else if (name.endsWith(".class")) {
val relPath = join(zipRelPath, "!/", name)
checkIfSubPathIsForbidden(relPath, errors)
val contentCheckRequired = versionRules.isNotEmpty() && !name.endsWith("module-info.class") && !isMultiVersion(name)
if (contentCheckRequired) {
checkVersion(relPath, file.getInputStream(entry), errors)
}
}
}
}
}
private fun checkIfSubPathIsForbidden(relPath: String, errors: MutableCollection<String>) {
for (f in forbiddenSubPaths) {
if (relPath.contains(f)) {
errors.add("$relPath: .class file has a forbidden sub-path: $f")
}
}
}
private fun checkVersion(path: String, stream: InputStream, errors: MutableCollection<String>) {
checkedClassCount.incrementAndGet()
val dataStream = DataInputStream(stream)
if (dataStream.readInt() != 0xCAFEBABE.toInt() || dataStream.skipBytes(3) != 3) {
errors.add("$path: invalid .class file header")
return
}
val major = dataStream.readUnsignedByte()
if (major < 44 || major >= 100) {
errors.add("$path: suspicious .class file version: $major")
return
}
val rule = versionRules.first { it.path.isEmpty() || path.startsWith(it.path) }
rule.wasUsed = true
val expected = rule.version
@Suppress("ConvertTwoComparisonsToRangeCheck")
if (expected > 0 && major > expected) {
errors.add("$path: .class file version $major exceeds expected $expected")
}
}
}
private fun isMultiVersion(path: String): Boolean {
return path.startsWith("META-INF/versions/") ||
path.contains("/META-INF/versions/") ||
(SystemInfoRt.isWindows && path.contains("\\META-INF\\versions\\"))
}
private fun classVersion(version: String) = if (version.isEmpty()) -1 else JavaVersion.parse(version).feature + 44 // 1.1 = 45
private fun join(prefix: String, separator: String, suffix: String) = if (prefix.isEmpty()) suffix else (prefix + separator + suffix)
private data class Rule(@JvmField val path: String, @JvmField val version: Int) {
@Volatile
@JvmField
var wasUsed = false
} | apache-2.0 | 13a37d1e47bd50e138d0f431d8d7866e | 38.973913 | 140 | 0.664745 | 4.434636 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/frame/nestedInlineFun.kt | 13 | 352 | package nestedInlineFun
fun main() {
val a = 1
foo {
val b = 2
//Breakpoint!
val c = 0
}
}
inline fun foo(block: () -> Unit) {
val x = 3
bar(1, block)
}
inline fun bar(count: Int, block: () -> Unit) {
var i = count
while (i-- > 0) {
block()
}
}
// SHOW_KOTLIN_VARIABLES
// PRINT_FRAME | apache-2.0 | c6495b88397d903079e0f63fb1fe4719 | 13.12 | 47 | 0.485795 | 3.115044 | false | false | false | false |
android/sunflower | app/src/main/java/com/google/samples/apps/sunflower/compose/plantdetail/PlantDetailScroller.kt | 1 | 2150 | /*
* 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.samples.apps.sunflower.compose.plantdetail
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.foundation.ScrollState
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
// Value obtained empirically so that the header buttons don't surpass the header container
private val HeaderTransitionOffset = 190.dp
/**
* Class that contains derived state for when the toolbar should be shown
*/
data class PlantDetailsScroller(
val scrollState: ScrollState,
val namePosition: Float
) {
val toolbarTransitionState = MutableTransitionState(ToolbarState.HIDDEN)
fun getToolbarState(density: Density): ToolbarState {
// When the namePosition is placed correctly on the screen (position > 1f) and it's
// position is close to the header, then show the toolbar.
return if (namePosition > 1f &&
scrollState.value > (namePosition - getTransitionOffset(density))
) {
toolbarTransitionState.targetState = ToolbarState.SHOWN
ToolbarState.SHOWN
} else {
toolbarTransitionState.targetState = ToolbarState.HIDDEN
ToolbarState.HIDDEN
}
}
private fun getTransitionOffset(density: Density): Float = with(density) {
HeaderTransitionOffset.toPx()
}
}
// Toolbar state related classes and functions to achieve the CollapsingToolbarLayout animation
enum class ToolbarState { HIDDEN, SHOWN }
val ToolbarState.isShown
get() = this == ToolbarState.SHOWN
| apache-2.0 | d06159dff29047939d8a4bec640cba0c | 35.440678 | 95 | 0.733023 | 4.673913 | false | false | false | false |
marverenic/Paper | app/src/main/java/com/marverenic/reader/ui/home/categories/CategoriesViewModel.kt | 1 | 1651 | package com.marverenic.reader.ui.home.categories
import android.content.Context
import android.databinding.BaseObservable
import android.databinding.Bindable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import com.marverenic.reader.BR
import com.marverenic.reader.R
import com.marverenic.reader.model.Category
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
class CategoriesViewModel(context: Context,
categories: List<Category>? = null)
: BaseObservable() {
var categories: List<Category>? = categories
set(value) {
adapter.categories = value.orEmpty()
field = value
}
var refreshing: Boolean = (categories == null)
set(value) {
if (value != field) {
refreshSubject.onNext(value)
field = value
notifyPropertyChanged(BR.refreshing)
}
}
@Bindable get() = field
private val refreshSubject = BehaviorSubject.createDefault(refreshing)
val adapter: CategoryAdapter by lazy(mode = LazyThreadSafetyMode.NONE) {
CategoryAdapter().also {
it.categories = categories.orEmpty()
}
}
val layoutManager = LinearLayoutManager(context)
val swipeRefreshColors = intArrayOf(
ContextCompat.getColor(context, R.color.colorPrimary),
ContextCompat.getColor(context, R.color.colorPrimaryDark),
ContextCompat.getColor(context, R.color.colorAccent)
)
fun getRefreshObservable(): Observable<Boolean> = refreshSubject
} | apache-2.0 | e481b7490b7b4c543c781f922f1b5f2e | 30.769231 | 76 | 0.678982 | 5.04893 | false | false | false | false |
mystdeim/vertx-web | vertx-web-client/src/main/kotlin/io/vertx/kotlin/ext/web/client/WebClientOptions.kt | 1 | 9993 | package io.vertx.kotlin.ext.web.client
import io.vertx.ext.web.client.WebClientOptions
import io.vertx.core.http.Http2Settings
import io.vertx.core.http.HttpVersion
import io.vertx.core.net.JdkSSLEngineOptions
import io.vertx.core.net.JksOptions
import io.vertx.core.net.OpenSSLEngineOptions
import io.vertx.core.net.PemKeyCertOptions
import io.vertx.core.net.PemTrustOptions
import io.vertx.core.net.PfxOptions
import io.vertx.core.net.ProxyOptions
/**
* A function providing a DSL for building [io.vertx.ext.web.client.WebClientOptions] objects.
*
*
* @param alpnVersions
* @param connectTimeout
* @param crlPaths
* @param crlValues
* @param decoderInitialBufferSize
* @param defaultHost
* @param defaultPort
* @param enabledCipherSuites
* @param enabledSecureTransportProtocols
* @param followRedirects Configure the default behavior of the client to follow HTTP <code>30x</code> redirections.
* @param forceSni
* @param http2ClearTextUpgrade
* @param http2ConnectionWindowSize
* @param http2MaxPoolSize
* @param http2MultiplexingLimit
* @param idleTimeout
* @param initialSettings
* @param jdkSslEngineOptions
* @param keepAlive
* @param keyStoreOptions
* @param localAddress
* @param logActivity
* @param maxChunkSize
* @param maxHeaderSize
* @param maxInitialLineLength
* @param maxPoolSize
* @param maxRedirects
* @param maxWaitQueueSize
* @param maxWebsocketFrameSize
* @param maxWebsocketMessageSize
* @param metricsName
* @param openSslEngineOptions
* @param pemKeyCertOptions
* @param pemTrustOptions
* @param pfxKeyCertOptions
* @param pfxTrustOptions
* @param pipelining
* @param pipeliningLimit
* @param protocolVersion
* @param proxyOptions
* @param receiveBufferSize
* @param reuseAddress
* @param reusePort
* @param sendBufferSize
* @param sendUnmaskedFrames
* @param soLinger
* @param ssl
* @param tcpCork
* @param tcpFastOpen
* @param tcpKeepAlive
* @param tcpNoDelay
* @param tcpQuickAck
* @param trafficClass
* @param trustAll
* @param trustStoreOptions
* @param tryUseCompression
* @param useAlpn
* @param usePooledBuffers
* @param userAgent Sets the Web Client user agent header. Defaults to Vert.x-WebClient/<version>.
* @param userAgentEnabled Sets whether the Web Client should send a user agent header. Defaults to true.
* @param verifyHost
*
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.web.client.WebClientOptions original] using Vert.x codegen.
*/
fun WebClientOptions(
alpnVersions: Iterable<HttpVersion>? = null,
connectTimeout: Int? = null,
crlPaths: Iterable<String>? = null,
crlValues: Iterable<io.vertx.core.buffer.Buffer>? = null,
decoderInitialBufferSize: Int? = null,
defaultHost: String? = null,
defaultPort: Int? = null,
enabledCipherSuites: Iterable<String>? = null,
enabledSecureTransportProtocols: Iterable<String>? = null,
followRedirects: Boolean? = null,
forceSni: Boolean? = null,
http2ClearTextUpgrade: Boolean? = null,
http2ConnectionWindowSize: Int? = null,
http2MaxPoolSize: Int? = null,
http2MultiplexingLimit: Int? = null,
idleTimeout: Int? = null,
initialSettings: io.vertx.core.http.Http2Settings? = null,
jdkSslEngineOptions: io.vertx.core.net.JdkSSLEngineOptions? = null,
keepAlive: Boolean? = null,
keyStoreOptions: io.vertx.core.net.JksOptions? = null,
localAddress: String? = null,
logActivity: Boolean? = null,
maxChunkSize: Int? = null,
maxHeaderSize: Int? = null,
maxInitialLineLength: Int? = null,
maxPoolSize: Int? = null,
maxRedirects: Int? = null,
maxWaitQueueSize: Int? = null,
maxWebsocketFrameSize: Int? = null,
maxWebsocketMessageSize: Int? = null,
metricsName: String? = null,
openSslEngineOptions: io.vertx.core.net.OpenSSLEngineOptions? = null,
pemKeyCertOptions: io.vertx.core.net.PemKeyCertOptions? = null,
pemTrustOptions: io.vertx.core.net.PemTrustOptions? = null,
pfxKeyCertOptions: io.vertx.core.net.PfxOptions? = null,
pfxTrustOptions: io.vertx.core.net.PfxOptions? = null,
pipelining: Boolean? = null,
pipeliningLimit: Int? = null,
protocolVersion: HttpVersion? = null,
proxyOptions: io.vertx.core.net.ProxyOptions? = null,
receiveBufferSize: Int? = null,
reuseAddress: Boolean? = null,
reusePort: Boolean? = null,
sendBufferSize: Int? = null,
sendUnmaskedFrames: Boolean? = null,
soLinger: Int? = null,
ssl: Boolean? = null,
tcpCork: Boolean? = null,
tcpFastOpen: Boolean? = null,
tcpKeepAlive: Boolean? = null,
tcpNoDelay: Boolean? = null,
tcpQuickAck: Boolean? = null,
trafficClass: Int? = null,
trustAll: Boolean? = null,
trustStoreOptions: io.vertx.core.net.JksOptions? = null,
tryUseCompression: Boolean? = null,
useAlpn: Boolean? = null,
usePooledBuffers: Boolean? = null,
userAgent: String? = null,
userAgentEnabled: Boolean? = null,
verifyHost: Boolean? = null): WebClientOptions = io.vertx.ext.web.client.WebClientOptions().apply {
if (alpnVersions != null) {
this.setAlpnVersions(alpnVersions.toList())
}
if (connectTimeout != null) {
this.setConnectTimeout(connectTimeout)
}
if (crlPaths != null) {
for (item in crlPaths) {
this.addCrlPath(item)
}
}
if (crlValues != null) {
for (item in crlValues) {
this.addCrlValue(item)
}
}
if (decoderInitialBufferSize != null) {
this.setDecoderInitialBufferSize(decoderInitialBufferSize)
}
if (defaultHost != null) {
this.setDefaultHost(defaultHost)
}
if (defaultPort != null) {
this.setDefaultPort(defaultPort)
}
if (enabledCipherSuites != null) {
for (item in enabledCipherSuites) {
this.addEnabledCipherSuite(item)
}
}
if (enabledSecureTransportProtocols != null) {
for (item in enabledSecureTransportProtocols) {
this.addEnabledSecureTransportProtocol(item)
}
}
if (followRedirects != null) {
this.setFollowRedirects(followRedirects)
}
if (forceSni != null) {
this.setForceSni(forceSni)
}
if (http2ClearTextUpgrade != null) {
this.setHttp2ClearTextUpgrade(http2ClearTextUpgrade)
}
if (http2ConnectionWindowSize != null) {
this.setHttp2ConnectionWindowSize(http2ConnectionWindowSize)
}
if (http2MaxPoolSize != null) {
this.setHttp2MaxPoolSize(http2MaxPoolSize)
}
if (http2MultiplexingLimit != null) {
this.setHttp2MultiplexingLimit(http2MultiplexingLimit)
}
if (idleTimeout != null) {
this.setIdleTimeout(idleTimeout)
}
if (initialSettings != null) {
this.setInitialSettings(initialSettings)
}
if (jdkSslEngineOptions != null) {
this.setJdkSslEngineOptions(jdkSslEngineOptions)
}
if (keepAlive != null) {
this.setKeepAlive(keepAlive)
}
if (keyStoreOptions != null) {
this.setKeyStoreOptions(keyStoreOptions)
}
if (localAddress != null) {
this.setLocalAddress(localAddress)
}
if (logActivity != null) {
this.setLogActivity(logActivity)
}
if (maxChunkSize != null) {
this.setMaxChunkSize(maxChunkSize)
}
if (maxHeaderSize != null) {
this.setMaxHeaderSize(maxHeaderSize)
}
if (maxInitialLineLength != null) {
this.setMaxInitialLineLength(maxInitialLineLength)
}
if (maxPoolSize != null) {
this.setMaxPoolSize(maxPoolSize)
}
if (maxRedirects != null) {
this.setMaxRedirects(maxRedirects)
}
if (maxWaitQueueSize != null) {
this.setMaxWaitQueueSize(maxWaitQueueSize)
}
if (maxWebsocketFrameSize != null) {
this.setMaxWebsocketFrameSize(maxWebsocketFrameSize)
}
if (maxWebsocketMessageSize != null) {
this.setMaxWebsocketMessageSize(maxWebsocketMessageSize)
}
if (metricsName != null) {
this.setMetricsName(metricsName)
}
if (openSslEngineOptions != null) {
this.setOpenSslEngineOptions(openSslEngineOptions)
}
if (pemKeyCertOptions != null) {
this.setPemKeyCertOptions(pemKeyCertOptions)
}
if (pemTrustOptions != null) {
this.setPemTrustOptions(pemTrustOptions)
}
if (pfxKeyCertOptions != null) {
this.setPfxKeyCertOptions(pfxKeyCertOptions)
}
if (pfxTrustOptions != null) {
this.setPfxTrustOptions(pfxTrustOptions)
}
if (pipelining != null) {
this.setPipelining(pipelining)
}
if (pipeliningLimit != null) {
this.setPipeliningLimit(pipeliningLimit)
}
if (protocolVersion != null) {
this.setProtocolVersion(protocolVersion)
}
if (proxyOptions != null) {
this.setProxyOptions(proxyOptions)
}
if (receiveBufferSize != null) {
this.setReceiveBufferSize(receiveBufferSize)
}
if (reuseAddress != null) {
this.setReuseAddress(reuseAddress)
}
if (reusePort != null) {
this.setReusePort(reusePort)
}
if (sendBufferSize != null) {
this.setSendBufferSize(sendBufferSize)
}
if (sendUnmaskedFrames != null) {
this.setSendUnmaskedFrames(sendUnmaskedFrames)
}
if (soLinger != null) {
this.setSoLinger(soLinger)
}
if (ssl != null) {
this.setSsl(ssl)
}
if (tcpCork != null) {
this.setTcpCork(tcpCork)
}
if (tcpFastOpen != null) {
this.setTcpFastOpen(tcpFastOpen)
}
if (tcpKeepAlive != null) {
this.setTcpKeepAlive(tcpKeepAlive)
}
if (tcpNoDelay != null) {
this.setTcpNoDelay(tcpNoDelay)
}
if (tcpQuickAck != null) {
this.setTcpQuickAck(tcpQuickAck)
}
if (trafficClass != null) {
this.setTrafficClass(trafficClass)
}
if (trustAll != null) {
this.setTrustAll(trustAll)
}
if (trustStoreOptions != null) {
this.setTrustStoreOptions(trustStoreOptions)
}
if (tryUseCompression != null) {
this.setTryUseCompression(tryUseCompression)
}
if (useAlpn != null) {
this.setUseAlpn(useAlpn)
}
if (usePooledBuffers != null) {
this.setUsePooledBuffers(usePooledBuffers)
}
if (userAgent != null) {
this.setUserAgent(userAgent)
}
if (userAgentEnabled != null) {
this.setUserAgentEnabled(userAgentEnabled)
}
if (verifyHost != null) {
this.setVerifyHost(verifyHost)
}
}
| apache-2.0 | f8fa519807e385ae18ff85f2b15309c5 | 28.565089 | 138 | 0.7144 | 3.786662 | false | false | false | false |
wn1/LNotes | app/src/main/java/ru/qdev/lnotes/mvp/QDVNotesHomePresenter.kt | 1 | 3640 | package ru.qdev.lnotes.mvp
import android.support.annotation.AnyThread
import android.support.annotation.MainThread
import android.support.annotation.UiThread
import com.arellomobile.mvp.InjectViewState
import com.arellomobile.mvp.MvpPresenter
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import ru.qdev.lnotes.db.entity.QDVDbFolder
import ru.qdev.lnotes.db.entity.QDVDbNote
/**
* Created by Vladimir Kudashov on 04.10.18.
*/
@InjectViewState
class QDVNotesHomePresenter : MvpPresenter <QDVNotesHomeView> () {
private val state: QDVNotesHomeState = QDVNotesHomeState()
var editNoteFilterState = QDVFilterByFolderState()
init {
EventBus.getDefault().register(this)
}
@UiThread
fun doSelectFolder (filterType: QDVFilterByFolderState.FilterType, folder: QDVDbFolder?) {
editNoteFilterState = QDVFilterByFolderState()
editNoteFilterState.filterType = filterType
if (filterType == QDVFilterByFolderState.FilterType.FOLDER_ID) {
editNoteFilterState.folderId = folder?.id
} else {
editNoteFilterState.folder = folder
}
state.uiState = QDVNotesHomeState.UiState.LIST
viewState.initNotesList(editNoteFilterState)
stateChanged()
}
class DoSelectFolderEvent (val filterType: QDVFilterByFolderState.FilterType,
val folder: QDVDbFolder?)
@Subscribe(threadMode = ThreadMode.MAIN)
@MainThread
fun onEvent(event: DoSelectFolderEvent) {
doSelectFolder(event.filterType, event.folder)
}
@UiThread
fun doEditNote (note: QDVDbNote) {
state.uiState = QDVNotesHomeState.UiState.EDIT
viewState.initEditNote(note)
stateChanged()
}
class DoEditNoteEvent (val note: QDVDbNote)
@Subscribe(threadMode = ThreadMode.MAIN)
@MainThread
fun onEvent(event: DoEditNoteEvent) {
doEditNote(event.note)
}
@UiThread
fun doAddNote (folderIdForAdding: Long?) {
state.uiState = QDVNotesHomeState.UiState.EDIT
viewState.initAddNote(folderIdForAdding)
stateChanged()
}
class DoAddNoteEvent(val folderIdForAdding: Long? = null)
@Subscribe(threadMode = ThreadMode.MAIN)
@MainThread
fun onEvent(event: DoAddNoteEvent) {
doAddNote(event.folderIdForAdding)
}
@UiThread
fun doGoBack () {
if (state.uiState == QDVNotesHomeState.UiState.EDIT) {
viewState.initNotesList(editNoteFilterState)
viewState.setNavigationDrawerFolderEnabled(true)
state.uiState = QDVNotesHomeState.UiState.LIST
stateChanged()
}
}
@UiThread
private fun stateChanged(){
if (state.uiState == QDVNotesHomeState.UiState.LIST &&
QDVStatisticState.isTimeForShowUserRatingQuest()) {
viewState.showUserRatingQuest()
}
}
class DoGoBackEvent
@Subscribe(threadMode = ThreadMode.MAIN)
@MainThread
fun onEvent(event: DoGoBackEvent) {
doGoBack()
}
@AnyThread
fun onFolderNameClick() {
EventBus.getDefault().post(QDVNavigationDrawerPresenter.DoDrawerOpenOrClose())
}
@AnyThread
fun doReloadDb() {
QDVNavigationDrawerState().selectedFolderOrMenu = null
EventBus.getDefault().post(QDVMvpDbPresenter.DoCloseDatabase())
EventBus.getDefault().post(QDVMvpDbPresenter.DoReloadDatabase())
}
@AnyThread
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().unregister(this)
}
} | mit | 76275fba5cb69539bbd6b0a888bafb5f | 29.341667 | 94 | 0.692308 | 4.745763 | false | false | false | false |
nelosan/yeoman-kotlin-clean | generators/app/templates/clean-architecture/domain/src/main/kotlin/com/nelosan/clean/domain/interactor/UseCase.kt | 1 | 1446 | package <%= appPackage %>.domain.interactor
import <%= appPackage %>.domain.check.Preconditions
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.disposables.Disposable
/**
* Created by nelo on 16/2/17.
*/
abstract class UseCase<T, Params> {
val uiThread: Scheduler
val mExecutorThread: Scheduler
var disposables: CompositeDisposable
constructor(uiThread: Scheduler, mExecutorThread: Scheduler){
this.uiThread = uiThread
this.mExecutorThread = mExecutorThread
this.disposables = CompositeDisposable()
}
abstract fun buildUseCaseObservable(params: Params): Observable<T>
open fun execute(observer: DisposableObserver<T>, params: Params) {
Preconditions.checkNotNull(params)
Preconditions.checkNotNull(observer)
val observable: Observable<T> = this.buildUseCaseObservable(params)
.subscribeOn(mExecutorThread)
.observeOn(uiThread)
addDisposable(observable.subscribeWith(observer))
}
fun dispose() {
if (!disposables.isDisposed) {
disposables.dispose()
}
}
private fun addDisposable(disposable: Disposable) {
Preconditions.checkNotNull(disposable)
Preconditions.checkNotNull(disposables)
disposables.add(disposable)
}
} | apache-2.0 | e34942b96eb42cbc03836785b91ecc19 | 29.787234 | 75 | 0.710235 | 5.182796 | false | false | false | false |
quran/quran_android | feature/downloadmanager/src/main/kotlin/com/quran/mobile/feature/downloadmanager/ui/sheikhdownload/AutoCompleteDropdown.kt | 2 | 3434 | package com.quran.mobile.feature.downloadmanager.ui.sheikhdownload
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Text
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import com.quran.common.search.SearchTextUtil
import com.quran.mobile.feature.downloadmanager.model.sheikhdownload.SuraOption
@Composable
fun AutoCompleteDropdown(
label: String,
initialText: String,
items: List<SuraOption>,
onItemSelected: ((Int) -> Unit)
) {
val textState = remember { mutableStateOf(TextFieldValue(initialText)) }
val isExpanded = remember { mutableStateOf(false) }
val restoreSelection = remember { mutableStateOf(false) }
val filtered by remember(items) {
derivedStateOf {
val searchTerm = SearchTextUtil.asSearchableString(
textState.value.text,
SearchTextUtil.isRtl(textState.value.text)
)
// if you typed in "١٢" for example, `toIntOrNull` would give you 12.
val numericSearchTerm = searchTerm.toIntOrNull()
items.filter {
it.searchName.contains(searchTerm, ignoreCase = true) ||
// support English numbers in Arabic search
it.number == numericSearchTerm
}
}
}
ExposedDropdownMenuBox(
expanded = isExpanded.value,
onExpandedChange = { isExpanded.value = !isExpanded.value }
) {
TextField(
value = textState.value,
onValueChange = {
if (restoreSelection.value) {
textState.value = it.copy(selection = TextRange(0, it.text.length))
restoreSelection.value = false
} else {
textState.value = it
}
},
label = { Text(label, color = MaterialTheme.colorScheme.onSurfaceVariant) },
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(
expanded = isExpanded.value
)
},
colors = ExposedDropdownMenuDefaults.textFieldColors(),
modifier = Modifier.onFocusChanged { focusState ->
if (focusState.isFocused) {
val text = textState.value.text
textState.value = textState.value.copy(selection = TextRange(0, text.length))
restoreSelection.value = true
}
}
)
if (filtered.isNotEmpty()) {
ExposedDropdownMenu(
expanded = isExpanded.value,
onDismissRequest = { isExpanded.value = false },
modifier = Modifier.heightIn(max = 150.dp)
) {
filtered.forEach {
DropdownMenuItem(
onClick = {
textState.value = textState.value.copy(text = it.name)
isExpanded.value = false
onItemSelected(it.number)
}
) {
Text(it.name, color = MaterialTheme.colorScheme.onSecondaryContainer)
}
}
}
}
}
}
| gpl-3.0 | 8b43be5743df6d3cb98a40ed0cc508f7 | 32.647059 | 87 | 0.690268 | 4.688525 | false | false | false | false |
syrop/Wiktor-Navigator | navigator/src/main/kotlin/pl/org/seva/navigator/contact/FriendshipObservable.kt | 1 | 1868 | /*
* Copyright (C) 2017 Wiktor Nizio
*
* 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/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.navigator.contact
import io.reactivex.disposables.CompositeDisposable
import pl.org.seva.navigator.main.data.fb.fbReader
import pl.org.seva.navigator.main.init.instance
val friendshipObservable by instance<FriendshipObservable>()
fun cleanFriendshipListeners() = friendshipObservable.clearFriendshipListeners()
fun addFriendshipListener() = friendshipObservable addFriendshipListener friendshipListener
class FriendshipObservable {
private val cd = CompositeDisposable()
infix fun addFriendshipListener(friendshipListener: FriendshipListener) = with (fbReader) {
cd.addAll(
friendshipRequestedListener()
.subscribe { friendshipListener.onPeerRequestedFriendship(it) },
friendshipAcceptedListener()
.subscribe { friendshipListener.onPeerAcceptedFriendship(it) },
friendshipDeletedListener()
.subscribe { friendshipListener.onPeerDeletedFriendship(it) })
}
fun clearFriendshipListeners() = cd.clear()
}
| gpl-3.0 | 73040f0934ac1b7c8ef65704df0e6bd1 | 37.916667 | 98 | 0.736617 | 4.589681 | false | false | false | false |
badoualy/kotlogram | mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/auth/ResPQ.kt | 1 | 1464 | package com.github.badoualy.telegram.mtproto.tl.auth
import com.github.badoualy.telegram.tl.StreamUtils.*
import com.github.badoualy.telegram.tl.TLContext
import com.github.badoualy.telegram.tl.core.TLLongVector
import com.github.badoualy.telegram.tl.core.TLObject
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class ResPQ @JvmOverloads constructor(var nonce: ByteArray = ByteArray(0),
var serverNonce: ByteArray = ByteArray(0),
var pq: ByteArray = ByteArray(0),
var fingerprints: TLLongVector = TLLongVector()) : TLObject() {
override fun getConstructorId(): Int {
return CONSTRUCTOR_ID
}
@Throws(IOException::class)
override fun serializeBody(stream: OutputStream) {
writeByteArray(nonce, stream)
writeByteArray(serverNonce, stream)
writeTLBytes(pq, stream)
writeTLVector(fingerprints, stream)
}
@Throws(IOException::class)
override fun deserializeBody(stream: InputStream, context: TLContext) {
nonce = readBytes(16, stream)
serverNonce = readBytes(16, stream)
pq = readTLBytes(stream)
fingerprints = readTLLongVector(stream, context)
}
override fun toString(): String {
return "resPQ#05162463"
}
companion object {
@JvmField
val CONSTRUCTOR_ID = 85337187
}
}
| mit | 771f9e469dd0f7023a01a25b2c33a0a8 | 32.272727 | 101 | 0.656421 | 4.504615 | false | false | false | false |
antoniolg/Kotlin-for-Android-Developers | app/src/main/java/com/antonioleiva/weatherapp/data/db/Tables.kt | 1 | 477 | package com.antonioleiva.weatherapp.data.db
object CityForecastTable {
const val NAME = "CityForecast"
const val ID = "_id"
const val CITY = "city"
const val COUNTRY = "country"
}
object DayForecastTable {
const val NAME = "DayForecast"
const val ID = "_id"
const val DATE = "date"
const val DESCRIPTION = "description"
const val HIGH = "high"
const val LOW = "low"
const val ICON_URL = "iconUrl"
const val CITY_ID = "cityId"
} | apache-2.0 | 63e4ff630a505772a49371e0da00d120 | 24.157895 | 43 | 0.649895 | 3.816 | false | false | false | false |
mikkokar/styx | components/proxy/src/test/kotlin/com/hotels/styx/admin/handlers/UrlPatternRouterTest.kt | 1 | 9266 | /*
Copyright (C) 2013-2020 Expedia 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.hotels.styx.admin.handlers
import ch.qos.logback.classic.Level
import com.hotels.styx.api.Eventual
import com.hotels.styx.api.HttpInterceptor
import com.hotels.styx.api.HttpRequest
import com.hotels.styx.api.HttpRequest.post
import com.hotels.styx.api.HttpResponse
import com.hotels.styx.api.HttpResponse.response
import com.hotels.styx.api.HttpResponseStatus.ACCEPTED
import com.hotels.styx.api.HttpResponseStatus.CREATED
import com.hotels.styx.api.HttpResponseStatus.INTERNAL_SERVER_ERROR
import com.hotels.styx.api.HttpResponseStatus.NO_CONTENT
import com.hotels.styx.api.HttpResponseStatus.OK
import com.hotels.styx.requestContext
import com.hotels.styx.support.matchers.LoggingTestSupport
import io.kotlintest.shouldBe
import io.kotlintest.specs.FeatureSpec
import reactor.core.publisher.toMono
import java.util.Optional
import java.util.concurrent.atomic.AtomicReference
class UrlPatternRouterTest : FeatureSpec({
val LOGGER = LoggingTestSupport(UrlPatternRouter::class.java);
val router = UrlPatternRouter.Builder()
.get("/admin/apps/:appId") { request, context ->
Eventual.of(
response(OK)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.build())
}
.get("/admin/apps/:appId/origin/:originId") { request, context ->
Eventual.of(
response(OK)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.header("originId", UrlPatternRouter.placeholders(context)["originId"])
.build())
}
.post("/admin/apps/:appId") { request, context ->
Eventual.of(
response(CREATED)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.build()
)
}
.post("/admin/apps/:appId/origin/:originId") { request, context ->
Eventual.of(
response(CREATED)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.header("originId", UrlPatternRouter.placeholders(context)["originId"])
.build()
)
}
.put("/admin/apps/:appId") { request, context ->
Eventual.of(
response(NO_CONTENT)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.build()
)
}
.put("/admin/apps/:appId/origin/:originId") { request, context ->
Eventual.of(
response(NO_CONTENT)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.header("originId", UrlPatternRouter.placeholders(context)["originId"])
.build()
)
}
.delete("/admin/apps/:appId") { request, context ->
Eventual.of(
response(ACCEPTED)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.build()
)
}
.delete("/admin/apps/:appId/origin/:originId") { request, context ->
Eventual.of(
response(ACCEPTED)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.header("originId", UrlPatternRouter.placeholders(context)["originId"])
.build()
)
}
.build()
feature("Request routing") {
scenario("GET requests") {
val response1 = router.handle(HttpRequest.get("/admin/apps/234").build(), requestContext())
.toMono()
.block()
response1!!.status() shouldBe OK
response1.header("appId") shouldBe Optional.of("234")
response1.header("originId") shouldBe Optional.empty()
val response2 = router.handle(HttpRequest.get("/admin/apps/234/origin/123").build(), requestContext())
.toMono()
.block()
response2!!.status() shouldBe OK
response2.header("appId") shouldBe Optional.of("234")
response2.header("originId") shouldBe Optional.of("123")
}
scenario("POST requests") {
val response1 = router.handle(HttpRequest.post("/admin/apps/234").build(), requestContext())
.toMono()
.block()
response1!!.status() shouldBe CREATED
response1.header("appId") shouldBe Optional.of("234")
response1.header("originId") shouldBe Optional.empty()
val response2 = router.handle(HttpRequest.post("/admin/apps/234/origin/123").build(), requestContext())
.toMono()
.block()
response2!!.status() shouldBe CREATED
response2.header("appId") shouldBe Optional.of("234")
response2.header("originId") shouldBe Optional.of("123")
}
scenario("PUT requests") {
val response1 = router.handle(HttpRequest.put("/admin/apps/234").build(), requestContext())
.toMono()
.block()
response1!!.status() shouldBe NO_CONTENT
response1.header("appId") shouldBe Optional.of("234")
response1.header("originId") shouldBe Optional.empty()
val response2 = router.handle(HttpRequest.put("/admin/apps/234/origin/123").build(), requestContext())
.toMono()
.block()
response2!!.status() shouldBe NO_CONTENT
response2.header("appId") shouldBe Optional.of("234")
response2.header("originId") shouldBe Optional.of("123")
}
scenario("DELETE requests") {
val response1 = router.handle(HttpRequest.delete("/admin/apps/234").build(), requestContext())
.toMono()
.block()
response1!!.status() shouldBe ACCEPTED
response1.header("appId") shouldBe Optional.of("234")
response1.header("originId") shouldBe Optional.empty()
val response2 = router.handle(HttpRequest.delete("/admin/apps/234/origin/123").build(), requestContext())
.toMono()
.block()
response2!!.status() shouldBe ACCEPTED
response2.header("appId") shouldBe Optional.of("234")
response2.header("originId") shouldBe Optional.of("123")
}
}
feature("Route Callbacks Invocation") {
scenario("Catches and logs user exceptions") {
val contextCapture = AtomicReference<HttpInterceptor.Context>()
val router = UrlPatternRouter.Builder()
.post("/admin/apps/:appId/:originId") { request, context -> throw RuntimeException("Something went wrong") }
.build()
val response = router.handle(post("/admin/apps/appx/appx-01").build(), requestContext())
.toMono()
.block()
response!!.status() shouldBe INTERNAL_SERVER_ERROR
LOGGER.lastMessage().level shouldBe Level.ERROR
LOGGER.lastMessage().formattedMessage shouldBe "ERROR: POST /admin/apps/appx/appx-01"
}
}
feature("Placeholders") {
scenario("Are exposed in HTTP context") {
val contextCapture = AtomicReference<HttpInterceptor.Context>()
val router = UrlPatternRouter.Builder()
.post("/admin/apps/:appId/:originId") { request, context ->
contextCapture.set(context)
Eventual.of<HttpResponse>(response(OK).build())
}
.build()
val response = router.handle(post("/admin/apps/appx/appx-01").build(), requestContext())
.toMono()
.block()
response!!.status() shouldBe OK
val placeholders = UrlPatternRouter.placeholders(contextCapture.get())
placeholders["appId"] shouldBe "appx"
placeholders["originId"] shouldBe "appx-01"
}
}
}) | apache-2.0 | d770d3f4195558dbe28a55ea5f0208bd | 41.122727 | 128 | 0.555472 | 5.273762 | false | false | false | false |
AlmasB/FXGL | fxgl/src/main/kotlin/com/almasb/fxgl/dev/DevService.kt | 1 | 5238 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.dev
import com.almasb.fxgl.app.scene.GameView
import com.almasb.fxgl.core.EngineService
import com.almasb.fxgl.core.collection.PropertyMap
import com.almasb.fxgl.dsl.FXGL
import com.almasb.fxgl.dsl.isReleaseMode
import com.almasb.fxgl.entity.Entity
import com.almasb.fxgl.entity.EntityWorldListener
import com.almasb.fxgl.logging.Logger
import com.almasb.fxgl.logging.LoggerLevel
import com.almasb.fxgl.logging.LoggerOutput
import com.almasb.fxgl.physics.*
import com.almasb.fxgl.scene.SceneService
import javafx.scene.Group
import javafx.scene.shape.*
/**
* Provides developer options when the application is in DEVELOPER or DEBUG modes.
* In RELEASE mode all public functions are NO-OP and return immediately.
*
* @author Almas Baimagambetov ([email protected])
*/
class DevService : EngineService() {
private lateinit var sceneService: SceneService
private lateinit var devPane: DevPane
private val console by lazy { Console() }
val isConsoleOpen: Boolean
get() = console.isOpen()
val isDevPaneOpen: Boolean
get() = devPane.isOpen
private val consoleOutput = object : LoggerOutput {
override fun append(message: String) {
console.pushMessage(message)
}
override fun close() { }
}
private val isDevEnabled: Boolean
get() = !isReleaseMode() && FXGL.getSettings().isDeveloperMenuEnabled
override fun onInit() {
if (!isDevEnabled)
return
devPane = DevPane(sceneService, FXGL.getSettings())
}
fun openConsole() {
if (!isDevEnabled)
return
console.open()
}
fun closeConsole() {
if (!isDevEnabled)
return
console.close()
}
fun openDevPane() {
if (!isDevEnabled)
return
devPane.open()
}
fun closeDevPane() {
if (!isDevEnabled)
return
devPane.close()
}
fun pushDebugMessage(message: String) {
if (!isDevEnabled)
return
devPane.pushMessage(message)
}
override fun onMainLoopStarting() {
if (!isDevEnabled)
return
Logger.addOutput(consoleOutput, LoggerLevel.DEBUG)
FXGL.getSettings().devShowBBox.addListener { _, _, isSelected ->
if (isSelected) {
FXGL.getGameWorld().entities.forEach {
addDebugView(it)
}
} else {
FXGL.getGameWorld().entities.forEach {
removeDebugView(it)
}
}
}
FXGL.getGameWorld().addWorldListener(object : EntityWorldListener {
override fun onEntityAdded(entity: Entity) {
if (FXGL.getSettings().devShowBBox.value) {
addDebugView(entity)
}
}
override fun onEntityRemoved(entity: Entity) {
if (FXGL.getSettings().devShowBBox.value) {
removeDebugView(entity)
}
}
})
}
private val debugViews = hashMapOf<Entity, GameView>()
private fun addDebugView(entity: Entity) {
val group = Group()
entity.boundingBoxComponent.hitBoxesProperty().forEach {
val shape: Shape = when (val data = it.shape) {
is CircleShapeData -> {
Circle(data.radius, data.radius, data.radius)
}
is BoxShapeData -> {
val bboxView = Rectangle()
bboxView.widthProperty().value = data.width
bboxView.heightProperty().value = data.height
bboxView.visibleProperty().bind(
bboxView.widthProperty().greaterThan(0).and(bboxView.heightProperty().greaterThan(0))
)
bboxView
}
is PolygonShapeData -> {
Polygon(*data.points.flatMap { listOf(it.x, it.y) }.toDoubleArray())
}
is ChainShapeData -> {
Polyline(*data.points.flatMap { listOf(it.x, it.y) }.toDoubleArray())
}
is Box3DShapeData -> {
// not implemented
Rectangle()
}
}
shape.fill = null
shape.translateX = it.minX
shape.translateY = it.minY
shape.strokeWidth = 2.0
shape.strokeProperty().bind(FXGL.getSettings().devBBoxColor)
group.children += shape
}
entity.viewComponent.addChild(group)
val view = GameView(group, Int.MAX_VALUE)
debugViews[entity] = view
}
private fun removeDebugView(entity: Entity) {
debugViews.remove(entity)?.let { view ->
entity.viewComponent.removeChild(view.node)
}
}
override fun onGameReady(vars: PropertyMap) {
if (!isDevEnabled)
return
devPane.onGameReady(vars)
}
} | mit | b4eb67d98c5696800b17fafc8bda3ffc | 25.593909 | 113 | 0.569301 | 4.779197 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-shops-bukkit/src/main/kotlin/com/rpkit/shops/bukkit/database/table/RPKShopCountTable.kt | 1 | 5682 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.shops.bukkit.database.table
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.characters.bukkit.character.RPKCharacterId
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.shops.bukkit.RPKShopsBukkit
import com.rpkit.shops.bukkit.database.create
import com.rpkit.shops.bukkit.database.jooq.Tables.RPKIT_SHOP_COUNT
import com.rpkit.shops.bukkit.shopcount.RPKShopCount
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.runAsync
import java.util.logging.Level.SEVERE
/**
* Represents the shop count table.
*/
class RPKShopCountTable(private val database: Database, private val plugin: RPKShopsBukkit) : Table {
private val characterCache = if (plugin.config.getBoolean("caching.rpkit_shop_count.character_id.enabled")) {
database.cacheManager.createCache(
"rpk-shops-bukkit.rpkit_shop_count.character_id",
Int::class.javaObjectType,
RPKShopCount::class.java,
plugin.config.getLong("caching.rpkit_shop_count.character_id.size")
)
} else {
null
}
fun insert(entity: RPKShopCount): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
return runAsync {
database.create
.insertInto(
RPKIT_SHOP_COUNT,
RPKIT_SHOP_COUNT.CHARACTER_ID,
RPKIT_SHOP_COUNT.COUNT
)
.values(
characterId.value,
entity.count
)
.execute()
characterCache?.set(characterId.value, entity)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to insert shop count", exception)
throw exception
}
}
fun update(entity: RPKShopCount): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
return runAsync {
database.create
.update(RPKIT_SHOP_COUNT)
.set(RPKIT_SHOP_COUNT.COUNT, entity.count)
.where(RPKIT_SHOP_COUNT.CHARACTER_ID.eq(characterId.value))
.execute()
characterCache?.set(characterId.value, entity)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to update shop count", exception)
throw exception
}
}
/**
* Gets the shop count for a character.
* If there is no shop count for the given character
*
* @param character The character
* @return The shop count for the character, or null if there is no shop count for the given character
*/
operator fun get(character: RPKCharacter): CompletableFuture<RPKShopCount?> {
val characterId = character.id ?: return CompletableFuture.completedFuture(null)
if (characterCache?.containsKey(characterId.value) == true) {
return CompletableFuture.completedFuture(characterCache[characterId.value])
} else {
return CompletableFuture.supplyAsync {
val result = database.create
.select(
RPKIT_SHOP_COUNT.CHARACTER_ID,
RPKIT_SHOP_COUNT.COUNT
)
.from(RPKIT_SHOP_COUNT)
.where(RPKIT_SHOP_COUNT.CHARACTER_ID.eq(characterId.value))
.fetchOne() ?: return@supplyAsync null
val shopCount = RPKShopCount(
character,
result.get(RPKIT_SHOP_COUNT.COUNT)
)
characterCache?.set(characterId.value, shopCount)
return@supplyAsync shopCount
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to get shop count", exception)
throw exception
}
}
}
fun delete(entity: RPKShopCount): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
return runAsync {
database.create
.deleteFrom(RPKIT_SHOP_COUNT)
.where(RPKIT_SHOP_COUNT.CHARACTER_ID.eq(characterId.value))
.execute()
characterCache?.remove(characterId.value)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to delete shop count", exception)
throw exception
}
}
fun delete(characterId: RPKCharacterId): CompletableFuture<Void> = runAsync {
database.create
.deleteFrom(RPKIT_SHOP_COUNT)
.where(RPKIT_SHOP_COUNT.CHARACTER_ID.eq(characterId.value))
.execute()
characterCache?.remove(characterId.value)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to delete shop count for character id", exception)
throw exception
}
} | apache-2.0 | 9dd5bd43106ef9af4d7f5fc60f1f84d0 | 39.304965 | 113 | 0.630236 | 4.852263 | false | false | false | false |
industrial-data-space/trusted-connector | ids-api/src/main/java/de/fhg/aisec/ids/api/router/graph/GraphData.kt | 1 | 1197 | /*-
* ========================LICENSE_START=================================
* ids-api
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.api.router.graph
class GraphData {
private val nodes: MutableSet<Node> = LinkedHashSet()
private val links: MutableSet<Edge> = LinkedHashSet()
fun addNode(node: Node) {
nodes.add(node)
}
fun addEdge(edge: Edge) {
links.add(edge)
}
fun getNodes(): Set<Node> {
return nodes
}
fun getLinks(): Set<Edge> {
return links
}
}
| apache-2.0 | 422d6e214abf05e232bab74364a5c7e0 | 28.195122 | 75 | 0.60401 | 4.305755 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/action/movement/MoveBy.kt | 1 | 2443 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.action.movement
import org.joml.Vector2d
import uk.co.nickthecoder.tickle.action.animation.AnimationAction
import uk.co.nickthecoder.tickle.action.animation.Ease
import uk.co.nickthecoder.tickle.action.animation.LinearEase
import uk.co.nickthecoder.tickle.action.animation.lerp
open class MoveBy(
val position: Vector2d,
val amount: Vector2d,
seconds: Double,
ease: Ease = LinearEase())
: AnimationAction(seconds, ease) {
var initialPosition = Vector2d()
var finalPosition = Vector2d()
override fun storeInitialValue() {
initialPosition.set(position)
initialPosition.add(amount, finalPosition)
}
override fun update(t: Double) {
lerp(initialPosition, finalPosition, t, position)
}
}
open class MoveXBy(
val position: Vector2d,
val amount: Double,
seconds: Double,
ease: Ease = LinearEase.instance)
: AnimationAction(seconds, ease) {
var initialPosition = 0.0
var finalPosition = 0.0
override fun storeInitialValue() {
initialPosition = position.x
finalPosition = initialPosition + amount
}
override fun update(t: Double) {
position.x = lerp(initialPosition, finalPosition, t)
}
}
open class MoveYBy(
val position: Vector2d,
val amount: Double,
seconds: Double,
ease: Ease = LinearEase.instance)
: AnimationAction(seconds, ease) {
var initialPosition = 0.0
var finalPosition = 0.0
override fun storeInitialValue() {
initialPosition = position.y
finalPosition = initialPosition + amount
}
override fun update(t: Double) {
position.y = lerp(initialPosition, finalPosition, t)
}
}
| gpl-3.0 | ad5371ee16ff95e5799d3e43c0bc353e | 25.554348 | 69 | 0.700368 | 4.323894 | false | false | false | false |
chrix75/domino | src/main/kotlin/domain/processing/entities/objects/StepEntity.kt | 1 | 1723 | package domain.processing.entities.objects
import domain.global.entities.NamedEntity
import domain.global.validators.EntityValidator
import domain.global.validators.StepValidator
import domain.global.validators.Validable
import org.neo4j.ogm.annotation.NodeEntity
import org.neo4j.ogm.annotation.Property
import org.neo4j.ogm.annotation.Relationship
/**
* The Step class is the Step entity saved into the DB.
*
* A step has one parameter at least and may have substeps.
*
* Created by Christian Sperandio on 09/04/2016.
*
*/
@NodeEntity(label = "Step")
class StepEntity(_name: String = "") : NamedEntity(_name), Validable<StepEntity> {
@Property
var state: RunningState? = null
@Relationship(type = "HAS_STEP", direction = Relationship.OUTGOING)
var steps: Set<StepEntity>? = null
@Relationship(type = "HAS_PARAMETER", direction = Relationship.OUTGOING)
var parameters: Set<ParameterEntity>? = null
@Relationship(type = "PRODUCES", direction = Relationship.OUTGOING)
var outputs: Set<OutputEntity>? = null
@Property
var complete: Boolean = false
override fun toString(): String {
return "[Step ID=$id Name=$name}"
}
/**
* Returns an instance of the validator checks the validity of the step before saving into the DB.
*/
override fun buildValidator(): EntityValidator<StepEntity> {
return StepValidator()
}
/**
* Resets the id of the current steps and the id for all its parameters and substeps.
*/
override fun resetId() {
id = null
parameters?.forEach { it.resetId() }
steps?.forEach {
it.resetId()
}
outputs?.forEach { it.resetId() }
}
}
| mpl-2.0 | d4df2c2e318564269d1935117d21de0b | 25.921875 | 102 | 0.68253 | 4.141827 | false | false | false | false |
dslomov/intellij-community | plugins/settings-repository/src/git/pull.kt | 6 | 13684 | package org.jetbrains.settingsRepository.git
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.vfs.VirtualFile
import org.eclipse.jgit.api.MergeCommand.FastForwardMode
import org.eclipse.jgit.api.MergeResult
import org.eclipse.jgit.api.MergeResult.MergeStatus
import org.eclipse.jgit.api.errors.CheckoutConflictException
import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException
import org.eclipse.jgit.api.errors.JGitInternalException
import org.eclipse.jgit.api.errors.NoHeadException
import org.eclipse.jgit.dircache.DirCacheCheckout
import org.eclipse.jgit.internal.JGitText
import org.eclipse.jgit.lib.*
import org.eclipse.jgit.merge.MergeMessageFormatter
import org.eclipse.jgit.merge.MergeStrategy
import org.eclipse.jgit.merge.ResolveMerger
import org.eclipse.jgit.merge.SquashMessageFormatter
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.revwalk.RevWalkUtils
import org.eclipse.jgit.transport.RemoteConfig
import org.eclipse.jgit.treewalk.FileTreeIterator
import org.jetbrains.settingsRepository.*
import java.io.IOException
import java.text.MessageFormat
import java.util.ArrayList
open class Pull(val manager: GitRepositoryManager, val indicator: ProgressIndicator, val commitMessageFormatter: CommitMessageFormatter = IdeaCommitMessageFormatter()) {
val repository = manager.repository
// we must use the same StoredConfig instance during the operation
val config = repository.getConfig()
val remoteConfig = RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME)
fun pull(mergeStrategy: MergeStrategy = MergeStrategy.RECURSIVE, commitMessage: String? = null, prefetchedRefToMerge: Ref? = null): UpdateResult? {
indicator.checkCanceled()
LOG.debug("Pull")
val repository = manager.repository
val repositoryState = repository.getRepositoryState()
if (repositoryState != RepositoryState.SAFE) {
LOG.warn(MessageFormat.format(JGitText.get().cannotPullOnARepoWithState, repositoryState.name()))
}
val refToMerge = prefetchedRefToMerge ?: fetch() ?: return null
val mergeResult = merge(refToMerge, mergeStrategy, commitMessage = commitMessage)
val mergeStatus = mergeResult.mergeStatus
if (LOG.isDebugEnabled()) {
LOG.debug(mergeStatus.toString())
}
if (mergeStatus == MergeStatus.CONFLICTING) {
val mergedCommits = mergeResult.mergedCommits
assert(mergedCommits.size() == 2)
val conflicts = mergeResult.conflicts!!
var unresolvedFiles = conflictsToVirtualFiles(conflicts)
val mergeProvider = JGitMergeProvider(repository, mergedCommits[0]!!, mergedCommits[1]!!, conflicts)
val resolvedFiles: List<VirtualFile>
val mergedFiles = ArrayList<String>()
while (true) {
resolvedFiles = resolveConflicts(unresolvedFiles, mergeProvider)
for (file in resolvedFiles) {
mergedFiles.add(file.getPath())
}
if (resolvedFiles.size() == unresolvedFiles.size()) {
break
}
else {
unresolvedFiles.removeAll(mergedFiles)
}
}
repository.commit()
return mergeResult.result.toMutable().addChanged(mergedFiles)
}
else if (!mergeStatus.isSuccessful()) {
throw IllegalStateException(mergeResult.toString())
}
else {
return mergeResult.result
}
}
fun fetch(prevRefUpdateResult: RefUpdate.Result? = null): Ref? {
indicator.checkCanceled()
val repository = manager.repository
val fetchResult = repository.fetch(remoteConfig, manager.credentialsProvider, indicator.asProgressMonitor()) ?: return null
if (LOG.isDebugEnabled()) {
printMessages(fetchResult)
for (refUpdate in fetchResult.getTrackingRefUpdates()) {
LOG.debug(refUpdate.toString())
}
}
indicator.checkCanceled()
var hasChanges = false
for (fetchRefSpec in remoteConfig.getFetchRefSpecs()) {
val refUpdate = fetchResult.getTrackingRefUpdate(fetchRefSpec.getDestination())
if (refUpdate == null) {
LOG.debug("No ref update for $fetchRefSpec")
continue
}
val refUpdateResult = refUpdate.getResult()
// we can have more than one fetch ref spec, but currently we don't worry about it
if (refUpdateResult == RefUpdate.Result.LOCK_FAILURE || refUpdateResult == RefUpdate.Result.IO_FAILURE) {
if (prevRefUpdateResult == refUpdateResult) {
throw IOException("Ref update result " + refUpdateResult.name() + ", we have already tried to fetch again, but no luck")
}
LOG.warn("Ref update result " + refUpdateResult.name() + ", trying again after 500 ms")
Thread.sleep(500)
return fetch(refUpdateResult)
}
if (!(refUpdateResult == RefUpdate.Result.FAST_FORWARD || refUpdateResult == RefUpdate.Result.NEW || refUpdateResult == RefUpdate.Result.FORCED)) {
throw UnsupportedOperationException("Unsupported ref update result")
}
if (!hasChanges) {
hasChanges = refUpdateResult != RefUpdate.Result.NO_CHANGE
}
}
if (!hasChanges) {
LOG.debug("No remote changes")
return null
}
return fetchResult.getAdvertisedRef(config.getRemoteBranchFullName()) ?: throw IllegalStateException("Could not get advertised ref")
}
fun merge(unpeeledRef: Ref,
mergeStrategy: MergeStrategy = MergeStrategy.RECURSIVE,
commit: Boolean = true,
fastForwardMode: FastForwardMode = FastForwardMode.FF,
squash: Boolean = false,
forceMerge: Boolean = false,
commitMessage: String? = null): MergeResultEx {
indicator.checkCanceled()
val head = repository.getRef(Constants.HEAD) ?: throw NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported)
// Check for FAST_FORWARD, ALREADY_UP_TO_DATE
val revWalk = RevWalk(repository)
var dirCacheCheckout: DirCacheCheckout? = null
try {
// handle annotated tags
val ref = repository.peel(unpeeledRef)
var objectId = ref.getPeeledObjectId()
if (objectId == null) {
objectId = ref.getObjectId()
}
val srcCommit = revWalk.lookupCommit(objectId)
val headId = head.getObjectId()
if (headId == null) {
revWalk.parseHeaders(srcCommit)
dirCacheCheckout = DirCacheCheckout(repository, repository.lockDirCache(), srcCommit.getTree())
dirCacheCheckout.setFailOnConflict(true)
dirCacheCheckout.checkout()
val refUpdate = repository.updateRef(head.getTarget().getName())
refUpdate.setNewObjectId(objectId)
refUpdate.setExpectedOldObjectId(null)
refUpdate.setRefLogMessage("initial pull", false)
if (refUpdate.update() != RefUpdate.Result.NEW) {
throw NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported)
}
return MergeResultEx(srcCommit, MergeStatus.FAST_FORWARD, arrayOf<ObjectId?>(null, srcCommit), ImmutableUpdateResult(dirCacheCheckout.getUpdated().keySet(), dirCacheCheckout.getRemoved()))
}
val refLogMessage = StringBuilder("merge ")
refLogMessage.append(ref.getName())
val headCommit = revWalk.lookupCommit(headId)
if (!forceMerge && revWalk.isMergedInto(srcCommit, headCommit)) {
return MergeResultEx(headCommit, MergeStatus.ALREADY_UP_TO_DATE, arrayOf<ObjectId?>(headCommit, srcCommit), EMPTY_UPDATE_RESULT)
//return MergeResult(headCommit, srcCommit, array(headCommit, srcCommit), MergeStatus.ALREADY_UP_TO_DATE, mergeStrategy, null)
}
else if (!forceMerge && fastForwardMode != FastForwardMode.NO_FF && revWalk.isMergedInto(headCommit, srcCommit)) {
// FAST_FORWARD detected: skip doing a real merge but only update HEAD
refLogMessage.append(": ").append(MergeStatus.FAST_FORWARD)
dirCacheCheckout = DirCacheCheckout(repository, headCommit.getTree(), repository.lockDirCache(), srcCommit.getTree())
dirCacheCheckout.setFailOnConflict(true)
dirCacheCheckout.checkout()
val newHead: ObjectId
val mergeStatus: MergeStatus
if (squash) {
newHead = headId
mergeStatus = MergeStatus.FAST_FORWARD_SQUASHED
val squashedCommits = RevWalkUtils.find(revWalk, srcCommit, headCommit)
repository.writeSquashCommitMsg(SquashMessageFormatter().format(squashedCommits, head))
}
else {
updateHead(refLogMessage, srcCommit, headId, repository)
newHead = srcCommit
mergeStatus = MergeStatus.FAST_FORWARD
}
return MergeResultEx(newHead, mergeStatus, arrayOf<ObjectId?>(headCommit, srcCommit), ImmutableUpdateResult(dirCacheCheckout.getUpdated().keySet(), dirCacheCheckout.getRemoved()))
}
else {
if (fastForwardMode == FastForwardMode.FF_ONLY) {
return MergeResultEx(headCommit, MergeStatus.ABORTED, arrayOf<ObjectId?>(headCommit, srcCommit), EMPTY_UPDATE_RESULT)
}
val mergeMessage: String
if (squash) {
mergeMessage = ""
repository.writeSquashCommitMsg(SquashMessageFormatter().format(RevWalkUtils.find(revWalk, srcCommit, headCommit), head))
}
else {
mergeMessage = commitMessageFormatter.mergeMessage(listOf(ref), head)
repository.writeMergeCommitMsg(mergeMessage)
repository.writeMergeHeads(arrayListOf(ref.getObjectId()))
}
val merger = mergeStrategy.newMerger(repository)
val noProblems: Boolean
var lowLevelResults: Map<String, org.eclipse.jgit.merge.MergeResult<*>>? = null
var failingPaths: Map<String, ResolveMerger.MergeFailureReason>? = null
var unmergedPaths: List<String>? = null
if (merger is ResolveMerger) {
merger.setCommitNames(arrayOf("BASE", "HEAD", ref.getName()))
merger.setWorkingTreeIterator(FileTreeIterator(repository))
noProblems = merger.merge(headCommit, srcCommit)
lowLevelResults = merger.getMergeResults()
failingPaths = merger.getFailingPaths()
unmergedPaths = merger.getUnmergedPaths()
}
else {
noProblems = merger.merge(headCommit, srcCommit)
}
refLogMessage.append(": Merge made by ")
refLogMessage.append(if (revWalk.isMergedInto(headCommit, srcCommit)) "recursive" else mergeStrategy.getName())
refLogMessage.append('.')
var result = if (merger is ResolveMerger) ImmutableUpdateResult(merger.getToBeCheckedOut().keySet(), merger.getToBeDeleted()) else null
if (noProblems) {
// ResolveMerger does checkout
if (merger !is ResolveMerger) {
dirCacheCheckout = DirCacheCheckout(repository, headCommit.getTree(), repository.lockDirCache(), merger.getResultTreeId())
dirCacheCheckout.setFailOnConflict(true)
dirCacheCheckout.checkout()
result = ImmutableUpdateResult(dirCacheCheckout.getUpdated().keySet(), dirCacheCheckout.getRemoved())
}
var newHeadId: ObjectId? = null
var mergeStatus: MergeResult.MergeStatus? = null
if (!commit && squash) {
mergeStatus = MergeResult.MergeStatus.MERGED_SQUASHED_NOT_COMMITTED
}
if (!commit && !squash) {
mergeStatus = MergeResult.MergeStatus.MERGED_NOT_COMMITTED
}
if (commit && !squash) {
newHeadId = repository.commit(commitMessage, refLogMessage.toString()).getId()
mergeStatus = MergeResult.MergeStatus.MERGED
}
if (commit && squash) {
newHeadId = headCommit.getId()
mergeStatus = MergeResult.MergeStatus.MERGED_SQUASHED
}
return MergeResultEx(newHeadId, mergeStatus!!, arrayOf(headCommit.getId(), srcCommit.getId()), result!!)
}
else if (failingPaths == null) {
repository.writeMergeCommitMsg(MergeMessageFormatter().formatWithConflicts(mergeMessage, unmergedPaths))
return MergeResultEx(null, MergeResult.MergeStatus.CONFLICTING, arrayOf(headCommit.getId(), srcCommit.getId()), result!!, lowLevelResults)
}
else {
repository.writeMergeCommitMsg(null)
repository.writeMergeHeads(null)
return MergeResultEx(null, MergeResult.MergeStatus.FAILED, arrayOf(headCommit.getId(), srcCommit.getId()), result!!, lowLevelResults)
}
}
}
catch (e: org.eclipse.jgit.errors.CheckoutConflictException) {
throw CheckoutConflictException(if (dirCacheCheckout == null) listOf<String>() else dirCacheCheckout.getConflicts(), e)
}
finally {
revWalk.close()
}
}
}
class MergeResultEx(val newHead: ObjectId?, val mergeStatus: MergeStatus, val mergedCommits: Array<ObjectId?>, val result: ImmutableUpdateResult, val conflicts: Map<String, org.eclipse.jgit.merge.MergeResult<*>>? = null)
private fun updateHead(refLogMessage: StringBuilder, newHeadId: ObjectId, oldHeadID: ObjectId, repository: Repository) {
val refUpdate = repository.updateRef(Constants.HEAD)
refUpdate.setNewObjectId(newHeadId)
refUpdate.setRefLogMessage(refLogMessage.toString(), false)
refUpdate.setExpectedOldObjectId(oldHeadID)
val rc = refUpdate.update()
when (rc) {
RefUpdate.Result.NEW, RefUpdate.Result.FAST_FORWARD -> return
RefUpdate.Result.REJECTED, RefUpdate.Result.LOCK_FAILURE -> throw ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, refUpdate.getRef(), rc)
else -> throw JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, Constants.HEAD, newHeadId.toString(), rc))
}
}
| apache-2.0 | 2ff817fb3d562aa63e1181600ae55c7f | 43.57329 | 220 | 0.703742 | 4.855926 | false | false | false | false |
google/grpc-kapt | processor/src/main/kotlin/com/google/api/grpc/kapt/generator/ServerGenerator.kt | 1 | 20897 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.grpc.kapt.generator
import com.google.api.grpc.kapt.GrpcClient
import com.google.api.grpc.kapt.GrpcServer
import com.google.api.grpc.kapt.generator.proto.ProtoInterfaceGenerator
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.LambdaTypeName
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeAliasSpec
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.asTypeName
import io.grpc.BindableService
import io.grpc.MethodDescriptor
import io.grpc.Server
import io.grpc.ServerBuilder
import io.grpc.ServerCallHandler
import io.grpc.ServerServiceDefinition
import io.grpc.ServiceDescriptor
import io.grpc.stub.ServerCalls
import io.grpc.stub.StreamObserver
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.Element
/**
* Generates a gRPC [io.grpc.BindableService] from an interface annotated with [GrpcServer].
*/
internal class ServerGenerator(
environment: ProcessingEnvironment,
private val clientElements: Collection<Element>
) : Generator<List<FileSpec>>(environment) {
private val protoGenerator by lazy {
ProtoInterfaceGenerator(environment)
}
override fun generate(element: Element): List<FileSpec> {
val files = mutableListOf<FileSpec>()
val annotation = element.getAnnotation(GrpcServer::class.java)
?: throw CodeGenerationException("Unsupported element: $element")
val interfaceType = element.asGeneratedInterfaceType()
// get metadata required for generation
val kmetadata = element.asKotlinMetadata()
val typeInfo = annotation.extractTypeInfo(element, annotation.suffix)
// determine marshaller to use
val marshallerType = annotation.asMarshallerType()
// determine the full service name (use the implemented interfaces, if available)
val clientInterfaceTypeInfo = getClientAnnotation(element)
val fullServiceName = clientInterfaceTypeInfo?.fullName ?: typeInfo.fullName
val provider = clientInterfaceTypeInfo?.source ?: typeInfo.source
// create the server
val server = FileSpec.builder(typeInfo.type.packageName, typeInfo.type.simpleName)
.addFunction(
FunSpec.builder("asGrpcService")
.addParameter(
ParameterSpec.builder("coroutineScope", CoroutineScope::class)
.defaultValue("%T", GlobalScope::class)
.build()
)
.receiver(interfaceType)
.returns(BindableService::class)
.addStatement("return %T(this, coroutineScope)", typeInfo.type)
.addKdoc(
"""
|Create a new service that can be bound to a gRPC server.
|
|Server methods are launched in the [coroutineScope], which is the [%T] by default.
""".trimMargin(),
GlobalScope::class.asTypeName()
)
.build()
)
.addFunction(
FunSpec.builder("asGrpcServer")
.addParameter("port", Int::class)
.addParameter(
ParameterSpec.builder("coroutineScope", CoroutineScope::class)
.defaultValue("%T", GlobalScope::class)
.build()
)
.receiver(interfaceType)
.returns(Server::class)
.addStatement(
"""
|return %T.forPort(port)
| .addService(this.asGrpcService(coroutineScope))
| .build()
""".trimMargin(),
ServerBuilder::class
)
.addKdoc(
"""
|Create a new gRPC server on the given [port] running the [%T] service.
|
|Server methods are launched in the [coroutineScope], which is the [%T] by default.
""".trimMargin(),
interfaceType,
GlobalScope::class.asTypeName()
)
.build()
)
.addFunction(
FunSpec.builder("asGrpcServer")
.addModifiers(KModifier.SUSPEND)
.addParameter("port", Int::class)
.addParameter(
"block",
LambdaTypeName.get(
receiver = CoroutineScope::class.asClassName(),
returnType = Unit::class.asTypeName()
).copy(suspending = true)
)
.receiver(interfaceType)
.addCode(
"""
|coroutineScope {
| launch {
| val server = [email protected](port, this)
| server.start()
| block()
| server.shutdown().awaitTermination()
| }
|}
|""".trimMargin()
)
.addKdoc(
"""
|Create a new gRPC server and execute the given block before shutting down.
|
|This method is intended for testing and examples.
|""".trimMargin()
)
.build()
)
.addTypeAlias(methodListTypeAlias)
.addTypeAlias(methodBindingTypeAlias)
.addFunction(methodBindingFun)
.addType(
TypeSpec.classBuilder(typeInfo.type)
.addModifiers(KModifier.PRIVATE)
.addSuperinterface(BindableService::class)
.primaryConstructor(
FunSpec.constructorBuilder()
.addParameter("implementation", interfaceType)
.addParameter("coroutineScope", CoroutineScope::class)
.build()
)
.addProperty(
PropertySpec.builder("implementation", interfaceType)
.addModifiers(KModifier.PRIVATE)
.initializer("implementation")
.build()
)
.addProperty(
PropertySpec.builder("name", String::class)
.addModifiers(KModifier.PRIVATE)
.initializer("%S", fullServiceName)
.build()
)
.addProperty(
element.filterRpcMethods().map {
kmetadata.describeElement(it)
}.asMethodDescriptor(marshallerType, provider)
)
.addProperty(generateServiceDescriptor(provider))
.addProperty(generateServiceDefinition())
.addFunction(
FunSpec.builder("bindService")
.addModifiers(KModifier.OVERRIDE)
.returns(ServerServiceDefinition::class.asTypeName())
.addStatement("return serviceDefinition")
.build()
)
.build()
)
.addImport("kotlinx.coroutines", "launch", "runBlocking")
.addImport("kotlinx.coroutines", "coroutineScope")
val schemaDescriptorType = provider?.getSchemaDescriptorType()
if (schemaDescriptorType != null) {
server.addType(schemaDescriptorType)
}
files += server.build()
return files
}
private fun List<KotlinMethodInfo>.asMethodDescriptor(
marshallerType: TypeName,
provider: SchemaDescriptorProvider?
): PropertySpec {
val methodsInitializers = this.map { it.asMethodDescriptor(marshallerType, provider) }
return PropertySpec.builder("methods", methodListTypeAlias.type)
.addModifiers(KModifier.PRIVATE)
.initializer(with(CodeBlock.builder()) {
add("listOf(\n")
indent()
for ((idx, code) in methodsInitializers.withIndex()) {
if (idx == methodsInitializers.size - 1) {
addStatement("%L", code)
} else {
addStatement("%L,", code)
}
}
unindent()
add(")")
build()
})
.build()
}
private fun KotlinMethodInfo.asMethodDescriptor(
marshallerType: TypeName,
provider: SchemaDescriptorProvider?
): CodeBlock {
val serverCall = with(CodeBlock.builder()) {
indent()
if (rpc.type == MethodDescriptor.MethodType.SERVER_STREAMING) {
add(
"""
|%T.asyncServerStreamingCall { request: %T, responseObserver: %T ->
| coroutineScope.launch {
| try {
| for (data in implementation.%L(request)) {
| responseObserver.onNext(data)
| }
| responseObserver.onCompleted()
| } catch(t: Throwable) {
| responseObserver.onError(t)
| }
| }
|}
""".trimMargin(),
ServerCalls::class.asClassName(), rpc.inputType,
StreamObserver::class.asClassName().parameterizedBy(rpc.outputType),
name
)
} else if (rpc.type == MethodDescriptor.MethodType.CLIENT_STREAMING) {
add(
"""
|%T.asyncClientStreamingCall { responseObserver: %T ->
| val requestChannel: %T = Channel()
| val requestObserver = object : %T {
| override fun onNext(value: %T) {
| runBlocking { requestChannel.send(value) }
| }
|
| override fun onError(t: Throwable) {
| requestChannel.close(t)
| }
|
| override fun onCompleted() {
| requestChannel.close()
| }
| }
|
| coroutineScope.launch {
| try {
| responseObserver.onNext(implementation.%L(requestChannel))
| } finally {
| responseObserver.onCompleted()
| }
| }
|
| requestObserver
|}
""".trimMargin(),
ServerCalls::class.asClassName(),
StreamObserver::class.asClassName().parameterizedBy(rpc.outputType),
Channel::class.asClassName().parameterizedBy(rpc.inputType),
StreamObserver::class.asClassName().parameterizedBy(rpc.inputType),
rpc.inputType,
name
)
} else if (rpc.type == MethodDescriptor.MethodType.BIDI_STREAMING) {
add(
"""
|%T.asyncBidiStreamingCall { responseObserver: %T ->
| val requestChannel: %T = Channel()
| val requestObserver = object : %T {
| override fun onNext(value: %T) {
| runBlocking { requestChannel.send(value) }
| }
|
| override fun onError(t: Throwable) {
| requestChannel.close(t)
| }
|
| override fun onCompleted() {
| requestChannel.close()
| }
| }
|
| coroutineScope.launch {
| try {
| for (data in implementation.%L(requestChannel)) {
| responseObserver.onNext(data)
| }
| responseObserver.onCompleted()
| } catch(t: Throwable) {
| responseObserver.onError(t)
| }
| }
|
| requestObserver
|}
""".trimMargin(),
ServerCalls::class.asClassName(),
StreamObserver::class.asClassName().parameterizedBy(rpc.outputType),
Channel::class.asClassName().parameterizedBy(rpc.inputType),
StreamObserver::class.asClassName().parameterizedBy(rpc.inputType),
rpc.inputType,
name
)
} else { // MethodDescriptor.MethodType.UNARY
add(
"""
|%T.asyncUnaryCall { request: %T, responseObserver: %T ->
| coroutineScope.launch {
| try {
| responseObserver.onNext(implementation.%L(request))
| responseObserver.onCompleted()
| } catch(t: Throwable) {
| responseObserver.onError(t)
| }
| }
|}
""".trimMargin(),
ServerCalls::class.asClassName(), rpc.inputType,
StreamObserver::class.asClassName().parameterizedBy(rpc.outputType),
name
)
}
unindent()
}.build()
return CodeBlock.of(
"""
|methodBinding(
| with(
| %T.newBuilder(
| %T.of(%T::class.java),
| %T.of(%T::class.java)
| )
| ) {
| setFullMethodName(
| MethodDescriptor.generateFullMethodName(name, %S)
| )
| setType(MethodDescriptor.MethodType.%L)
| setSchemaDescriptor(%L)
| build()
| },
| %L
|)
""".trimMargin(),
MethodDescriptor::class.asTypeName(),
marshallerType, rpc.inputType,
marshallerType, rpc.outputType,
rpc.name,
rpc.type.name,
provider?.getSchemaDescriptorFor(rpc.name) ?: "null",
serverCall
)
}
private fun generateServiceDescriptor(provider: SchemaDescriptorProvider?) =
PropertySpec.builder("serviceDescriptor", ServiceDescriptor::class.asTypeName())
.addModifiers(KModifier.PRIVATE)
.initializer(
"""
|with(
| %T.newBuilder(name)
|) {
| for ((method, _) in methods) {
| addMethod(method)
| }
| setSchemaDescriptor(%L)
| build()
|}
|""".trimMargin(),
ServiceDescriptor::class.asTypeName(),
provider?.getSchemaDescriptorFor() ?: "null"
)
.build()
private fun generateServiceDefinition() =
PropertySpec.builder("serviceDefinition", ServerServiceDefinition::class.asTypeName())
.addModifiers(KModifier.PRIVATE)
.initializer(
"""
|with(
| %T.builder(serviceDescriptor)
|) {
| for ((method, handler) in methods) {
| @Suppress("UNCHECKED_CAST")
| addMethod(method as %T, handler as %T)
| }
| build()
|}
|""".trimMargin(),
ServerServiceDefinition::class.asTypeName(),
MethodDescriptor::class.asClassName().parameterizedBy(Any::class.asTypeName(), Any::class.asTypeName()),
ServerCallHandler::class.asClassName().parameterizedBy(Any::class.asTypeName(), Any::class.asTypeName())
)
.build()
// get the matching @GrpcClient annotation for this element (if it exists)
private fun getClientAnnotation(element: Element): AnnotatedTypeInfo? {
for (superType in environment.typeUtils.directSupertypes(element.asType())) {
val clientInterface = clientElements.firstOrNull {
environment.typeUtils.isSameType(it.asType(), superType)
}
val clientAnnotation = clientInterface?.getAnnotation(GrpcClient::class.java)
if (clientAnnotation != null) {
return clientAnnotation.extractTypeInfo(clientInterface, "")
}
}
return null
}
private fun GrpcClient.extractTypeInfo(
element: Element,
suffix: String
): AnnotatedTypeInfo = extractTypeInfo(element, suffix, listOf(protoGenerator))
}
// various type aliases and help functions to simplify the generated code
private val methodBindingTypeAlias = TypeAliasSpec.builder(
"MethodBinding<ReqT, RespT>",
Pair::class.asClassName().parameterizedBy(
MethodDescriptor::class.asClassName().parameterizedBy(
TypeVariableName("ReqT"), TypeVariableName("RespT")
),
ServerCallHandler::class.asClassName().parameterizedBy(
TypeVariableName("ReqT"), TypeVariableName("RespT")
)
)
)
.addModifiers(KModifier.PRIVATE)
.build()
private val methodListTypeAlias = TypeAliasSpec.builder(
"MethodList",
List::class.asClassName().parameterizedBy(TypeVariableName("MethodBinding<*, *>"))
)
.addModifiers(KModifier.PRIVATE)
.build()
private val methodBindingFun = FunSpec.builder("methodBinding")
.addTypeVariable(TypeVariableName("ReqT"))
.addTypeVariable(TypeVariableName("RespT"))
.addParameter(
"descriptor", MethodDescriptor::class.asClassName().parameterizedBy(
TypeVariableName("ReqT"), TypeVariableName("RespT")
)
)
.addParameter(
"handler", ServerCallHandler::class.asClassName().parameterizedBy(
TypeVariableName("ReqT"), TypeVariableName("RespT")
)
)
.returns(methodBindingTypeAlias.type)
.addStatement("return %T(descriptor, handler)", Pair::class.asClassName())
.addModifiers(KModifier.PRIVATE)
.build()
| apache-2.0 | 8467e9a0e2a54bbd00cf72f0cea0e920 | 40.877756 | 120 | 0.497009 | 6.036106 | false | false | false | false |
nt-ca-aqe/library-app | library-service/src/main/kotlin/library/service/api/books/BooksController.kt | 1 | 4345 | package library.service.api.books
import library.service.api.books.payload.*
import library.service.business.books.BookCollection
import library.service.business.books.domain.composites.Book
import library.service.business.books.domain.types.*
import library.service.logging.LogMethodEntryAndExit
import org.springframework.hateoas.CollectionModel
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn
import org.springframework.http.HttpStatus
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import java.util.*
import javax.validation.Valid
@Validated
@RestController
@CrossOrigin
@RequestMapping("/api/books")
@LogMethodEntryAndExit
class BooksController(
private val collection: BookCollection,
private val assembler: BookResourceAssembler
) {
@GetMapping
@ResponseStatus(HttpStatus.OK)
fun getBooks(): CollectionModel<BookResource> {
val allBookRecords = collection.getAllBooks()
val selfLink = linkTo(methodOn(javaClass).getBooks()).withSelfRel()
return assembler.toCollectionModel(allBookRecords)
.apply { add(selfLink) }
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
fun postBook(@Valid @RequestBody body: CreateBookRequest): BookResource {
val book = Book(
isbn = Isbn13.parse(body.isbn!!),
title = Title(body.title!!),
authors = emptyList(),
numberOfPages = null
)
val bookRecord = collection.addBook(book)
return assembler.toModel(bookRecord)
}
@PutMapping("/{id}/title")
@ResponseStatus(HttpStatus.OK)
fun putBookTitle(@PathVariable id: UUID, @Valid @RequestBody body: UpdateTitleRequest): BookResource {
val bookRecord = collection.updateBook(BookId(id)) {
it.changeTitle(Title(body.title!!))
}
return assembler.toModel(bookRecord)
}
@PutMapping("/{id}/authors")
@ResponseStatus(HttpStatus.OK)
fun putBookAuthors(@PathVariable id: UUID, @Valid @RequestBody body: UpdateAuthorsRequest): BookResource {
val bookRecord = collection.updateBook(BookId(id)) {
it.changeAuthors(body.authors!!.map { Author(it) })
}
return assembler.toModel(bookRecord)
}
@DeleteMapping("/{id}/authors")
@ResponseStatus(HttpStatus.OK)
fun deleteBookAuthors(@PathVariable id: UUID): BookResource {
val bookRecord = collection.updateBook(BookId(id)) {
it.changeAuthors(emptyList())
}
return assembler.toModel(bookRecord)
}
@PutMapping("/{id}/numberOfPages")
@ResponseStatus(HttpStatus.OK)
fun putBookNumberOfPages(@PathVariable id: UUID, @Valid @RequestBody body: UpdateNumberOfPagesRequest): BookResource {
val bookRecord = collection.updateBook(BookId(id)) {
it.changeNumberOfPages(body.numberOfPages)
}
return assembler.toModel(bookRecord)
}
@DeleteMapping("/{id}/numberOfPages")
@ResponseStatus(HttpStatus.OK)
fun deleteBookNumberOfPages(@PathVariable id: UUID): BookResource {
val bookRecord = collection.updateBook(BookId(id)) {
it.changeNumberOfPages(null)
}
return assembler.toModel(bookRecord)
}
@GetMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
fun getBook(@PathVariable id: UUID): BookResource {
val bookRecord = collection.getBook(BookId(id))
return assembler.toModel(bookRecord)
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun deleteBook(@PathVariable id: UUID) {
collection.removeBook(BookId(id))
}
@PostMapping("/{id}/borrow")
@ResponseStatus(HttpStatus.OK)
fun postBorrowBook(@PathVariable id: UUID, @Valid @RequestBody body: BorrowBookRequest): BookResource {
val bookRecord = collection.borrowBook(BookId(id), Borrower(body.borrower!!))
return assembler.toModel(bookRecord)
}
@PostMapping("/{id}/return")
@ResponseStatus(HttpStatus.OK)
fun postReturnBook(@PathVariable id: UUID): BookResource {
val bookRecord = collection.returnBook(BookId(id))
return assembler.toModel(bookRecord)
}
} | apache-2.0 | f46a71ad2baccb010152d565738c608b | 34.917355 | 122 | 0.696893 | 4.65702 | false | false | false | false |
vsch/SmartData | src/com/vladsch/smart/SmartTableColumnBalancer.kt | 1 | 16086 | /*
* Copyright (c) 2015-2020 Vladimir Schneider <[email protected]>
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.vladsch.smart
import java.util.*
class SmartTableColumnBalancer(charWidthProvider: CharWidthProvider?) {
companion object {
private val IMMUTABLE_ZERO = SmartImmutableData(0)
private val IMMUTABLE_DEFAULT_ALIGNMENT = SmartImmutableData(TextAlignment.DEFAULT)
private val IMMUTABLE_CENTER_ALIGNMENT = SmartImmutableData(TextAlignment.CENTER)
}
protected val myCharWidthProvider = charWidthProvider ?: CharWidthProvider.UNITY_PROVIDER
// inputs
protected val myColumnLengths = HashMap<Int, ArrayList<SmartVersionedDataHolder<Int>>>()
protected val myColumnSpans = ArrayList<TableColumnSpan>()
protected var myMinColumnWidth = 3
// values during balancing computation
protected var myColumnWidths = Array(0, { 0 })
protected var myAdditionalColumnWidths = Array(0, { 0 })
// these are outputs
protected val myAlignmentDataPoints = ArrayList<SmartVersionedDataAlias<TextAlignment>>()
protected val myColumnWidthDataPoints = ArrayList<SmartVersionedDataAlias<Int>>()
protected val myVersionData: SmartVersionedDataAlias<Int> = SmartVersionedDataAlias(IMMUTABLE_ZERO)
protected var myDependencies: List<SmartVersionedDataHolder<Int>> = listOf()
val columnCount: Int get() = myColumnWidthDataPoints.size
val columnWidthDataPoints: List<SmartVersionedDataAlias<Int>> get() = myColumnWidthDataPoints
val columnAlignmentDataPoints: List<SmartVersionedDataAlias<TextAlignment>> get() = myAlignmentDataPoints
var minColumnWidth: Int
get() = myMinColumnWidth
set(value) {
myMinColumnWidth = value.minLimit(0);
}
fun columnWidthDataPoint(index: Int): SmartVersionedDataAlias<Int> {
return myColumnWidthDataPoints[index]
}
fun columnAlignmentDataPoint(index: Int): SmartVersionedDataAlias<TextAlignment> {
return myAlignmentDataPoints[index]
}
fun width(index: Int, textLength: SmartVersionedDataHolder<Int>): SmartVersionedDataHolder<Int> {
return width(index, textLength, 1, 0)
}
fun width(index: Int, textWidth: SmartVersionedDataHolder<Int>, columnSpan: Int, widthOffset: Int): SmartVersionedDataHolder<Int> {
if (columnSpan < 1) throw IllegalArgumentException("columnSpan must be >= 1")
ensureColumnDataPoints(index + columnSpan - 1)
if (columnSpan == 1) {
// regular column
addColumnLength(index, textWidth)
return myColumnWidthDataPoints[index]
} else {
// this one is a span
val colSpan = TableColumnSpan(this, index, columnSpan, textWidth, widthOffset)
myColumnSpans.add(colSpan)
return colSpan.widthDataPoint
}
}
protected fun addColumnLength(index: Int, textWidth: SmartVersionedDataHolder<Int>) {
val list = myColumnLengths[index]
if (list == null) {
myColumnLengths.put(index, arrayListOf(textWidth))
} else {
list.add(textWidth)
}
}
protected fun ensureColumnDataPoints(index: Int) {
while (myAlignmentDataPoints.size < index + 1) {
myAlignmentDataPoints.add(SmartVersionedDataAlias(IMMUTABLE_DEFAULT_ALIGNMENT))
}
while (myColumnWidthDataPoints.size < index + 1) {
myColumnWidthDataPoints.add(SmartVersionedDataAlias(IMMUTABLE_ZERO))
}
}
fun alignmentDataPoint(index: Int): SmartVersionedDataHolder<TextAlignment> {
ensureColumnDataPoints(index)
return myAlignmentDataPoints[index]
}
class SmartVersionedDefaultTextAlignment(val delegate: SmartVersionedDataAlias<TextAlignment>, val isHeader: Boolean) : SmartVersionedDataHolder<TextAlignment> {
override fun get(): TextAlignment {
return if (delegate.get() == TextAlignment.DEFAULT && isHeader) TextAlignment.CENTER else TextAlignment.LEFT
}
override val versionSerial: Int
get() = delegate.versionSerial
override val isStale: Boolean
get() = delegate.isStale
override val isMutable: Boolean
get() = delegate.isMutable
override val dependencies: Iterable<SmartVersion>
get() = delegate.dependencies
override fun nextVersion() {
delegate.nextVersion()
}
override var dataSnapshot: DataSnapshot<TextAlignment>
get() {
return if (isHeader && delegate.dataSnapshot.value == TextAlignment.DEFAULT) DataSnapshot(delegate.dataSnapshot.serial, TextAlignment.CENTER) else delegate.dataSnapshot
}
set(value) {
delegate.dataSnapshot = value
}
}
fun alignmentDataPoint(index: Int, isHeader: Boolean): SmartVersionedDataHolder<TextAlignment> {
ensureColumnDataPoints(index)
return SmartVersionedDefaultTextAlignment(myAlignmentDataPoints[index], isHeader);
}
fun alignment(index: Int, alignment: SmartVersionedDataHolder<TextAlignment>): SmartVersionedDataHolder<TextAlignment> {
ensureColumnDataPoints(index)
if (myAlignmentDataPoints[index].alias === IMMUTABLE_DEFAULT_ALIGNMENT) {
//throw IllegalStateException("Alignment provider for index $index is already defined ${myAlignmentDataPoints[index]}, new one is in error $alignment")
myAlignmentDataPoints[index].alias = alignment
}
return myAlignmentDataPoints[index].alias
}
// here is the meat of the wiring
fun finalizeTable() {
// column width data points depend on all the lengths of columns and all the spans that span those columns
val dependencies = arrayListOf<SmartVersionedDataHolder<Int>>()
for (index in 0..myColumnWidthDataPoints.lastIndex) {
val lengths = myColumnLengths[index]
if (lengths != null) {
for (length in lengths) {
if (length !== IMMUTABLE_ZERO) dependencies.add(length)
}
}
}
// now add any spanning columns
for (columnSpan in myColumnSpans) {
dependencies.add(columnSpan.textLengthDataPoint)
}
myDependencies = dependencies
myColumnWidths = Array(myColumnWidthDataPoints.size, { 0 })
myAdditionalColumnWidths = Array(myColumnWidthDataPoints.size, { 0 })
for (index in 0..myColumnWidthDataPoints.lastIndex) {
myColumnWidthDataPoints[index].alias = SmartDependentData(myVersionData, { columnWidth(index) })
}
for (columnSpan in myColumnSpans) {
columnSpan.widthDataPoint.alias = SmartDependentData(myVersionData, { spanWidth(columnSpan.startIndex, columnSpan.endIndex) - columnSpan.widthOffset })
}
// we now set our version alias to dependent data that will do the column balancing computations
myVersionData.alias = SmartDependentData(dependencies, { balanceColumns(); 0 })
}
private fun additionalColumnWidth(index: Int): Int {
return myAdditionalColumnWidths[index]
}
// called when something has changed in the dependencies, so here we recompute everything
fun balanceColumns() {
// get all the single column text lengths
for (index in 0..myColumnWidthDataPoints.lastIndex) {
var width = myMinColumnWidth
val lengths = myColumnLengths[index]
if (lengths != null) {
for (length in lengths) {
if (width < length.get()) width = length.get()
}
}
myColumnWidths[index] = width
}
// get all the span lengths
for (columnSpan in myColumnSpans) {
columnSpan.textLength = columnSpan.textLengthDataPoint.get()
}
// compute unfixed columns, which are all columns at first
var haveUnfixedColumns = myColumnSpans.size > 0
while (haveUnfixedColumns) {
haveUnfixedColumns = false
for (columnSpan in myColumnSpans) {
columnSpan.distributeLength()
}
var fixedAdditionalWidth = 0
var unfixedColumns = setOf<Int>()
for (columnSpan in myColumnSpans) {
unfixedColumns = unfixedColumns.union(columnSpan.unfixedColumns)
}
// need to reset all unfixed additional columns so we recompute them
for (index in unfixedColumns) {
myAdditionalColumnWidths[index] = 0
}
for (columnSpan in myColumnSpans) {
if (!columnSpan.unfixedColumns.isEmpty()) {
for (index in columnSpan.unfixedColumns) {
val additionalWidth = columnSpan.additionalWidths[index - columnSpan.startIndex]
if (myAdditionalColumnWidths[index] < additionalWidth) {
myAdditionalColumnWidths[index] = additionalWidth
if (fixedAdditionalWidth < additionalWidth) {
fixedAdditionalWidth = additionalWidth
}
}
}
}
}
for (columnSpan in myColumnSpans) {
if (!columnSpan.unfixedColumns.isEmpty()) {
columnSpan.fixLengths(fixedAdditionalWidth)
if (!columnSpan.unfixedColumns.isEmpty()) haveUnfixedColumns = true
}
}
}
// we now have everything computed, can clear the
for (columnSpan in myColumnSpans) {
columnSpan.clearIterationData()
}
}
internal fun spanWidth(startIndex: Int, endIndex: Int): Int {
if (myCharWidthProvider === CharWidthProvider.UNITY_PROVIDER) {
var width = 0
for (index in startIndex..endIndex - 1) {
width += columnWidth(index)
}
return width
}
var preWidth = 0
var spanWidth = 0
for (i in 0..endIndex - 1) {
val rawWidth = myColumnWidths[i] + myAdditionalColumnWidths[i]
if (i < startIndex) preWidth += rawWidth
if (i < endIndex) spanWidth += rawWidth
}
val spaceWidth = myCharWidthProvider.spaceWidth
return ((spanWidth + spaceWidth / 2) / spaceWidth) * spaceWidth - preWidth
}
internal fun columnWidth(index: Int): Int {
// here due to uneven char widths we need to compute the delta of the width by converting previous column widths to spaceWidths, rounding and then back to full width
if (index == 0 || myCharWidthProvider === CharWidthProvider.UNITY_PROVIDER) {
return myColumnWidths[index] + myAdditionalColumnWidths[index]
}
var preWidth = 0
for (i in 0..index - 1) {
preWidth += myColumnWidths[i] + myAdditionalColumnWidths[i]
}
val spaceWidth = myCharWidthProvider.spaceWidth
return (((myColumnWidths[index] + myAdditionalColumnWidths[index] + preWidth) + spaceWidth / 2) / spaceWidth) * spaceWidth - preWidth
}
internal fun columnLength(index: Int): Int = myColumnWidths[index]
class TableColumnSpan(tableColumnBalancer: SmartTableColumnBalancer, index: Int, columnSpan: Int, textLength: SmartVersionedDataHolder<Int>, widthOffset: Int) {
protected val myTableColumnBalancer = tableColumnBalancer
protected val myStartIndex = index
protected val myEndIndex = index + columnSpan
protected val myTextLengthDataPoint = textLength
protected val myWidthOffset: Int = widthOffset
protected val myWidthDataPoint = SmartVersionedDataAlias(IMMUTABLE_ZERO)
protected val myColumns: Set<Int>
// used during balancing
protected var myFixedColumns = setOf<Int>()
protected var myUnfixedColumns = setOf<Int>()
protected val myAddColumnWidth: Array<Int>
protected var myTextLength: Int = 0
init {
val columns = HashSet<Int>()
for (span in startIndex..lastIndex) {
columns.add(span)
}
myColumns = columns
myAddColumnWidth = Array(columnSpan, { 0 })
}
val startIndex: Int get() = myStartIndex
val endIndex: Int get() = myEndIndex
val lastIndex: Int get() = myEndIndex - 1
val widthOffset: Int get() = myWidthOffset
val textLengthDataPoint: SmartVersionedDataHolder<Int> get() = myTextLengthDataPoint
val widthDataPoint: SmartVersionedDataAlias<Int> get() = myWidthDataPoint
val additionalWidths: Array<Int> get() = myAddColumnWidth
var textLength: Int
get() = myTextLength
set(value) {
myTextLength = value
}
val fixedColumns: Set<Int> get() = myFixedColumns
val unfixedColumns: Set<Int> get() = myUnfixedColumns
// distribute length difference to unfixed columns
fun distributeLength() {
val unfixed = HashSet<Int>()
var fixedWidth = 0
for (index in startIndex..lastIndex) {
if (fixedColumns.contains(index)) {
// this one is fixed
fixedWidth += myTableColumnBalancer.columnWidth(index)
} else {
fixedWidth += myTableColumnBalancer.columnLength(index)
unfixed.add(index)
}
}
myUnfixedColumns = unfixed
if (!unfixed.isEmpty()) {
val extraLength = (myTextLength + myWidthOffset - fixedWidth).minLimit(0)
val whole = extraLength / unfixed.size
var remainder = extraLength - whole * unfixed.size
for (index in unfixed.sortedByDescending { myTableColumnBalancer.columnLength(it) }) {
additionalWidths[index - myStartIndex] = whole + if (remainder > 0) 1 else 0
if (remainder > 0) remainder--
}
}
}
fun fixLengths(fixedLength: Int) {
val fixedColumns = HashSet<Int>()
val unfixedColumns = HashSet<Int>()
fixedColumns.addAll(myFixedColumns)
for (index in myUnfixedColumns) {
val additionalColumnWidth = myTableColumnBalancer.additionalColumnWidth(index)
if (additionalColumnWidth == fixedLength) {
// this one is fixed
myAddColumnWidth[index - myStartIndex] = fixedLength
fixedColumns.add(index)
} else {
if (fixedLength < additionalColumnWidth) {
fixedColumns.add(index)
} else {
unfixedColumns.add(index)
}
}
}
myFixedColumns = fixedColumns
myUnfixedColumns = unfixedColumns
}
fun clearIterationData() {
myFixedColumns = setOf()
myUnfixedColumns = setOf()
}
}
}
| apache-2.0 | aa21efb6ff65dc8213111e9a06b85db5 | 39.014925 | 184 | 0.630735 | 5.634326 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/core/activity/MainActivity.kt | 1 | 8628 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.activity
import android.app.Activity
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import com.google.android.material.navigation.NavigationView
import fr.cph.chicago.Constants.SELECTED_ID
import fr.cph.chicago.R
import fr.cph.chicago.core.App
import fr.cph.chicago.core.fragment.Fragment
import fr.cph.chicago.core.fragment.buildFragment
import fr.cph.chicago.databinding.ActivityMainBinding
import fr.cph.chicago.redux.store
import fr.cph.chicago.util.RateUtil
import org.apache.commons.lang3.StringUtils
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
companion object {
private val rateUtil: RateUtil = RateUtil
}
private var currentPosition: Int = 0
private lateinit var drawerToggle: ActionBarDrawerToggle
private lateinit var favoriteMenuItem: MenuItem
private lateinit var inputMethodManager: InputMethodManager
lateinit var toolBar: Toolbar
private var title: String? = null
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!this.isFinishing) {
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
this.toolBar = binding.included.toolbar
if (store.state.ctaTrainKey == StringUtils.EMPTY) {
// Start error activity when state is empty (usually when android restart the activity on error)
App.startErrorActivity()
finish()
}
currentPosition = when {
savedInstanceState != null -> savedInstanceState.getInt(SELECTED_ID, R.id.navigation_favorites)
intent.extras != null -> intent.extras!!.getInt(SELECTED_ID, R.id.navigation_favorites)
else -> R.id.navigation_favorites
}
title = when {
savedInstanceState != null -> savedInstanceState.getString(getString(R.string.bundle_title), getString(R.string.favorites))
intent.extras != null -> intent.extras!!.getString(getString(R.string.bundle_title), getString(R.string.favorites))
else -> getString(R.string.favorites)
}
binding.drawer.setNavigationItemSelectedListener(this)
favoriteMenuItem = binding.drawer.menu.getItem(0)
if (currentPosition == R.id.navigation_favorites) {
favoriteMenuItem.isChecked = true
}
this.toolBar.inflateMenu(R.menu.main)
this.toolBar.elevation = 4f
inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
drawerToggle = object : ActionBarDrawerToggle(this, binding.drawerLayout, this.toolBar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
override fun onDrawerClosed(drawerView: View) {
super.onDrawerClosed(drawerView)
updateFragment(currentPosition)
}
}
binding.drawerLayout.addDrawerListener(drawerToggle)
drawerToggle.syncState()
setBarTitle(title!!)
updateFragment(currentPosition)
}
}
override fun onResume() {
super.onResume()
if (title != null)
setBarTitle(title!!)
}
override fun onBackPressed() {
if (currentPosition == R.id.navigation_favorites) {
finish()
} else {
// Switch to favorites if in another fragment
onNavigationItemSelected(favoriteMenuItem)
loadFragment(currentPosition)
}
}
private fun setBarTitle(title: String) {
this.title = title
this.toolBar.title = title
}
private fun updateFragment(position: Int) {
when (position) {
R.id.navigation_favorites -> loadFragment(R.id.navigation_favorites)
R.id.navigation_train -> loadFragment(R.id.navigation_train)
R.id.navigation_bus -> loadFragment(R.id.navigation_bus)
R.id.navigation_bike -> loadFragment(R.id.navigation_bike)
R.id.navigation_nearby -> loadFragment(R.id.navigation_nearby)
R.id.navigation_cta_map -> loadFragment(R.id.navigation_cta_map)
R.id.navigation_alert_cta -> loadFragment(R.id.navigation_alert_cta)
R.id.navigation_settings -> loadFragment(R.id.navigation_settings)
}
}
private fun loadFragment(navigationId: Int) {
val transaction = supportFragmentManager.beginTransaction()
var fragment = supportFragmentManager.findFragmentByTag(navigationId.toString())
if (fragment == null) {
fragment = buildFragment(navigationId)
transaction.add(fragment, navigationId.toString())
}
transaction.replace(R.id.searchContainer, fragment).commit()
showHideActionBarMenu((fragment as Fragment).hasActionBar())
binding.searchContainer.animate().alpha(1.0f)
}
private fun itemSelected(title: String) {
binding.searchContainer.animate().alpha(0.0f)
setBarTitle(title)
closeDrawerAndUpdateActionBar()
}
private fun closeDrawerAndUpdateActionBar() {
binding.drawerLayout.closeDrawer(GravityCompat.START)
// Force keyboard to hide if present
inputMethodManager.hideSoftInputFromWindow(binding.drawerLayout.windowToken, 0)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
drawerToggle.onConfigurationChanged(newConfig)
}
override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
if (!isFinishing) {
menuItem.isChecked = true
if (currentPosition != menuItem.itemId) {
currentPosition = menuItem.itemId
when (menuItem.itemId) {
R.id.navigation_favorites -> itemSelected(getString(R.string.favorites))
R.id.navigation_train -> itemSelected(getString(R.string.train))
R.id.navigation_bus -> itemSelected(getString(R.string.bus))
R.id.navigation_bike -> itemSelected(getString(R.string.divvy))
R.id.navigation_nearby -> itemSelected(getString(R.string.nearby))
R.id.navigation_cta_map -> itemSelected(getString(R.string.cta_map))
R.id.navigation_alert_cta -> itemSelected(getString(R.string.cta_alert))
R.id.navigation_rate_this_app -> rateUtil.rateThisApp(this)
R.id.navigation_settings -> itemSelected(getString(R.string.settings))
}
} else {
currentPosition = menuItem.itemId
binding.drawerLayout.closeDrawer(GravityCompat.START)
}
}
return true
}
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
savedInstanceState.putInt(SELECTED_ID, currentPosition)
if (title != null) savedInstanceState.putString(getString(R.string.bundle_title), title)
super.onSaveInstanceState(savedInstanceState)
}
public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
title = savedInstanceState.getString(getString(R.string.bundle_title))
currentPosition = savedInstanceState.getInt(SELECTED_ID)
}
private fun showHideActionBarMenu(show: Boolean) {
this.toolBar.menu.getItem(0).isVisible = show
}
}
| apache-2.0 | 63a5174a04e9012c04bd6a1db450d79f | 40.681159 | 168 | 0.672346 | 4.921848 | false | false | false | false |
edsilfer/presence-control | app/src/main/java/br/com/edsilfer/android/presence_control/commons/layout/EmptyCollection.kt | 1 | 3680 | package br.com.edsilfer.android.presence_control.commons.layout
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import br.com.edsilfer.android.presence_control.R
import kotlinx.android.synthetic.main.util_collection_loading.view.*
class EmptyCollection : LinearLayout {
/**
* CONSTRUCTORS
*/
constructor(context: Context) : super(context) {
init(null)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
init(attrs)
}
/**
* LIFECYCLE
*/
private fun init(attrs: AttributeSet?) {
val rootView = View.inflate(context, R.layout.util_collection_loading, this)
val image = rootView.findViewById<ImageView>(R.id.empty_collection_image)
val label = rootView.findViewById<TextView>(R.id.empty_collection_text)
val disclaimer = getMessage(attrs!!)
if (!disclaimer.isNullOrEmpty()) {
label.text = disclaimer
} else {
label.text = String.format(context.getString(R.string.str_commons_utils_empty_collection), getCollectionName(attrs))
}
image.setImageResource(getIcon(attrs))
}
private fun getIcon(attrs: AttributeSet): Int {
val a = context.theme.obtainStyledAttributes(
attrs,
R.styleable.EmptyCollection,
0, 0)
try {
return a.getResourceId(R.styleable.EmptyCollection_icon, -1)
} finally {
a.recycle()
}
}
private fun getCollectionName(attrs: AttributeSet): String {
val a = context.theme.obtainStyledAttributes(
attrs,
R.styleable.EmptyCollection,
0, 0)
try {
return a.getString(R.styleable.EmptyCollection_name)
} finally {
a.recycle()
}
}
private fun getMessage(attrs: AttributeSet): String {
val a = context.theme.obtainStyledAttributes(
attrs,
R.styleable.EmptyCollection,
0, 0)
try {
return a.getString(R.styleable.EmptyCollection_message)
} catch (e: Exception) {
return ""
} finally {
a.recycle()
}
}
/**
* PUBLIC INTERFACE
*/
fun showFeedback(recyclerView: RecyclerView, collection: Collection<*>?) {
if (collection == null || collection.isEmpty()) {
recyclerView.visibility = RecyclerView.GONE
loading.visibility = LinearLayout.GONE
empty_collection.visibility = LinearLayout.VISIBLE
} else if (!collection.isEmpty()) {
recyclerView.visibility = RecyclerView.VISIBLE
loading.visibility = LinearLayout.GONE
empty_collection.visibility = LinearLayout.GONE
} else {
hideAll()
recyclerView.visibility = RecyclerView.VISIBLE
}
}
fun showLoading() {
loading.visibility = LinearLayout.VISIBLE
empty_collection.visibility = LinearLayout.GONE
}
fun hideAll() {
wrapper.visibility = RelativeLayout.GONE
}
}
| apache-2.0 | a9381ddabf360127963609ffeef61985 | 29.666667 | 144 | 0.623098 | 4.791667 | false | false | false | false |
PizzaGames/emulio | core/src/main/com/github/emulio/ui/screens/util/ColorCache.kt | 1 | 849 | package com.github.emulio.ui.screens.util
import com.badlogic.gdx.graphics.Color
import java.math.BigInteger
object ColorCache {
val colorCache = HashMap<String, Color>()
fun getColor(rgba: String?): Color = when {
rgba == null -> defaultColor()
rgba.length == 6 -> cachedColor(rgba.toUpperCase() + "FF")
rgba.length == 8 -> cachedColor(rgba.toUpperCase())
else -> defaultColor()
}
private fun cachedColor(rgba: String): Color {
check(rgba.length == 8)
return colorCache[rgba] ?: storeColor(rgba)
}
private fun storeColor(rgba: String): Color {
val color = createColor(rgba)
colorCache[rgba] = color
return color
}
private fun createColor(rgba: String) = Color(BigInteger(rgba, 16).toInt())
private fun defaultColor() = Color.BLACK
} | gpl-3.0 | 6a8d5daa634a3206eb202c632d1ebaf2 | 26.419355 | 79 | 0.640754 | 4.121359 | false | false | false | false |
wireapp/wire-android | storage/src/main/kotlin/com/waz/zclient/storage/db/errors/ErrorsEntity.kt | 1 | 892 | package com.waz.zclient.storage.db.errors
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "Errors")
data class ErrorsEntity(
@PrimaryKey
@ColumnInfo(name = "_id")
val id: String,
@ColumnInfo(name = "err_type", defaultValue = "")
val errorType: String,
@ColumnInfo(name = "users", defaultValue = "")
val users: String,
@ColumnInfo(name = "messages", defaultValue = "")
val messages: String,
@ColumnInfo(name = "conv_id")
val conversationId: String?,
@ColumnInfo(name = "res_code", defaultValue = "0")
val responseCode: Int,
@ColumnInfo(name = "res_msg", defaultValue = "")
val responseMessage: String,
@ColumnInfo(name = "res_label", defaultValue = "")
val responseLabel: String,
@ColumnInfo(name = "time", defaultValue = "0")
val time: Int
)
| gpl-3.0 | b67c7facb03195f90cf7ffa003912ed6 | 23.777778 | 54 | 0.660314 | 3.946903 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/fragment/about/SecretSettingsUnlocker.kt | 1 | 2012 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.fragment.about
import android.content.Context
import android.widget.Toast
import org.mozilla.focus.R
import org.mozilla.focus.ext.components
import org.mozilla.focus.state.AppAction
/**
* Triggers the "secret" debug menu when logoView is tapped 5 times.
*/
class SecretSettingsUnlocker(private val context: Context) {
private var secretSettingsClicks = 0
private var lastDebugMenuToast: Toast? = null
/**
* Reset the [secretSettingsClicks] counter.
*/
fun resetCounter() {
secretSettingsClicks = 0
}
fun increment() {
// Because the user will mostly likely tap the logo in rapid succession,
// we ensure only 1 toast is shown at any given time.
lastDebugMenuToast?.cancel()
secretSettingsClicks += 1
when (secretSettingsClicks) {
in 2 until SECRET_DEBUG_MENU_CLICKS -> {
val clicksLeft = SECRET_DEBUG_MENU_CLICKS - secretSettingsClicks
val toast = Toast.makeText(
context,
context.getString(R.string.about_debug_menu_toast_progress, clicksLeft),
Toast.LENGTH_SHORT,
)
toast.show()
lastDebugMenuToast = toast
}
SECRET_DEBUG_MENU_CLICKS -> {
Toast.makeText(
context,
R.string.about_debug_menu_toast_done,
Toast.LENGTH_LONG,
).show()
context.components.appStore.dispatch(AppAction.SecretSettingsStateChange(true))
}
}
}
companion object {
// Number of clicks on the app logo to enable the "secret" debug menu.
private const val SECRET_DEBUG_MENU_CLICKS = 5
}
}
| mpl-2.0 | 53a7f1e28163a52ebae3bb2504344f7e | 33.101695 | 95 | 0.608847 | 4.583144 | false | false | false | false |
square/leakcanary | shark/src/main/java/shark/LeakTraceObject.kt | 2 | 3647 | package shark
import shark.LeakTrace.Companion.ZERO_WIDTH_SPACE
import shark.LeakTraceObject.LeakingStatus
import shark.LeakTraceObject.LeakingStatus.LEAKING
import shark.LeakTraceObject.LeakingStatus.NOT_LEAKING
import shark.LeakTraceObject.LeakingStatus.UNKNOWN
import shark.internal.lastSegment
import java.io.Serializable
import java.util.Locale
import kotlin.math.ln
import kotlin.math.pow
data class LeakTraceObject(
val type: ObjectType,
/**
* Class name of the object.
* The class name format is the same as what would be returned by [Class.getName].
*/
val className: String,
/**
* Labels that were computed during analysis. A label provides extra information that helps
* understand the state of the leak trace object.
*/
val labels: Set<String>,
val leakingStatus: LeakingStatus,
val leakingStatusReason: String,
/**
* The minimum number of bytes which would be freed if all references to this object were
* released. Not null only if the retained heap size was computed AND [leakingStatus] is
* equal to [LeakingStatus.UNKNOWN] or [LeakingStatus.LEAKING].
*/
val retainedHeapByteSize: Int?,
/**
* The minimum number of objects which would be unreachable if all references to this object were
* released. Not null only if the retained heap size was computed AND [leakingStatus] is
* equal to [LeakingStatus.UNKNOWN] or [LeakingStatus.LEAKING].
*/
val retainedObjectCount: Int?
) : Serializable {
/**
* Returns {@link #className} without the package, ie stripped of any string content before the
* last period (included).
*/
val classSimpleName: String get() = className.lastSegment('.')
val typeName
get() = type.name.toLowerCase(Locale.US)
override fun toString(): String {
val firstLinePrefix = ""
val additionalLinesPrefix = "$ZERO_WIDTH_SPACE "
return toString(firstLinePrefix, additionalLinesPrefix, true)
}
internal fun toString(
firstLinePrefix: String,
additionalLinesPrefix: String,
showLeakingStatus: Boolean,
typeName: String = this.typeName
): String {
val leakStatus = when (leakingStatus) {
UNKNOWN -> "UNKNOWN"
NOT_LEAKING -> "NO ($leakingStatusReason)"
LEAKING -> "YES ($leakingStatusReason)"
}
var result = ""
result += "$firstLinePrefix$className $typeName"
if (showLeakingStatus) {
result += "\n${additionalLinesPrefix}Leaking: $leakStatus"
}
if (retainedHeapByteSize != null) {
val humanReadableRetainedHeapSize =
humanReadableByteCount(retainedHeapByteSize.toLong())
result += "\n${additionalLinesPrefix}Retaining $humanReadableRetainedHeapSize in $retainedObjectCount objects"
}
for (label in labels) {
result += "\n${additionalLinesPrefix}$label"
}
return result
}
enum class ObjectType {
CLASS,
ARRAY,
INSTANCE
}
enum class LeakingStatus {
/** The object was needed and therefore expected to be reachable. */
NOT_LEAKING,
/** The object was no longer needed and therefore expected to be unreachable. */
LEAKING,
/** No decision can be made about the provided object. */
UNKNOWN;
}
companion object {
private const val serialVersionUID = -3616216391305196341L
// https://stackoverflow.com/a/3758880
private fun humanReadableByteCount(bytes: Long): String {
val unit = 1000
if (bytes < unit) return "$bytes B"
val exp = (ln(bytes.toDouble()) / ln(unit.toDouble())).toInt()
val pre = "kMGTPE"[exp - 1]
return String.format("%.1f %sB", bytes / unit.toDouble().pow(exp.toDouble()), pre)
}
}
} | apache-2.0 | 8123bca22c1918a84fc6479e267b9fc2 | 30.448276 | 116 | 0.702495 | 4.43674 | false | false | false | false |
toastkidjp/Jitte | search/src/main/java/jp/toastkid/search/SearchQueryExtractor.kt | 1 | 5501 | package jp.toastkid.search
import android.net.Uri
import androidx.core.net.toUri
/**
* @author toastkidjp
*/
class SearchQueryExtractor {
private val commonQueryParameterNames = setOf("q", "query", "text", "word")
operator fun invoke(url: String?) = invoke(url?.toUri())
operator fun invoke(uri: Uri?): String? {
val host = uri?.host ?: return null
return when {
host.startsWith("www.google.")
or host.startsWith("play.google.")
or host.startsWith("www.bing.")
or host.endsWith("developer.android.com")
or host.endsWith("scholar.google.com")
or host.endsWith("www.aolsearch.com")
or host.endsWith("www.ask.com")
or host.endsWith("twitter.com")
or host.endsWith("stackoverflow.com")
or host.endsWith("github.com")
or host.endsWith("mvnrepository.com")
or host.endsWith("searchcode.com")
or host.equals("www.qwant.com")
or host.equals("www.reddit.com")
or host.equals("www.economist.com")
or host.equals("www.ft.com")
or host.equals("www.startpage.com")
or host.equals("www.imdb.com")
or host.equals("duckduckgo.com")
or host.equals("news.google.com")
or host.endsWith("medium.com")
or host.endsWith("ted.com")
or host.endsWith(".slideshare.net")
or host.endsWith("cse.google.com")
or host.endsWith(".buzzfeed.com")
or host.endsWith("openweathermap.org")
or host.endsWith(".quora.com")
or host.endsWith(".livejournal.com")
or host.endsWith("search.daum.net")
or host.endsWith(".teoma.com")
or host.endsWith("www.info.com")
or host.endsWith("results.looksmart.com")
or host.equals("www.privacywall.org")
or host.equals("alohafind.com")
or host.equals("www.mojeek.com")
or host.equals("www.ecosia.org")
or host.equals("www.findx.com")
or host.equals("www.bbc.co.uk")
or host.equals("hn.algolia.com")
or host.endsWith("search.gmx.com")
or host.equals("search.sify.com")
or host.equals("www.forbes.com")
or host.equals("search.brave.com")
or host.equals("you.com")
or host.equals("seekingalpha.com")
or host.equals("www.givero.com") ->
uri.getQueryParameter("q")
host.startsWith("www.amazon.") ->
uri.getQueryParameter("field-keywords")
host.endsWith(".linkedin.com") ->
uri.getQueryParameter("keywords")
host.contains("yandex.") ->
uri.getQueryParameter("text")
host.endsWith(".youtube.com") ->
uri.getQueryParameter("search_query")
host.startsWith("www.flickr.") ->
uri.getQueryParameter("text")
host.endsWith(".yelp.com") ->
uri.getQueryParameter("find_desc")
host.equals("www.tumblr.com")
or host.equals("ejje.weblio.jp")
or host.equals("web.archive.org")-> uri.lastPathSegment
host.endsWith("archive.org")
or host.endsWith("search.naver.com")
or host.endsWith("www.morningstar.com")
or host.endsWith("info.finance.yahoo.co.jp")
or host.endsWith(".rambler.ru") ->
uri.getQueryParameter("query")
host.endsWith(".wikipedia.org")
or host.endsWith(".wikimedia.org") ->
if (uri.queryParameterNames.contains("search")) {
uri.getQueryParameter("search")
} else {
// "/wiki/"'s length.
Uri.decode(uri.encodedPath?.substring(6))
}
host.endsWith("search.yahoo.com")
or host.endsWith("search.yahoo.co.jp") ->
uri.getQueryParameter("p")
host.endsWith("www.baidu.com") ->
uri.getQueryParameter("wd")
host.endsWith("myindex.jp") ->
uri.getQueryParameter("w")
host == "www.wolframalpha.com" ->
uri.getQueryParameter("i")
host == "search.goo.ne.jp" ->
uri.getQueryParameter("MT")
host == "bgr.com" ->
uri.getQueryParameter("s")?.replace("#$".toRegex(), "")
host == "www.ebay.com" ->
uri.getQueryParameter("_nkw")
host.endsWith("facebook.com")
or host.equals("www.merriam-webster.com")
or host.equals("www.instagram.com")
or host.equals("www.espn.com") ->
Uri.decode(uri.lastPathSegment)
else -> uri.getQueryParameter(
commonQueryParameterNames
.find { uri.queryParameterNames.contains(it) } ?: ""
)
}
}
} | epl-1.0 | ef92053b4aeb9156b43532ac51b03a2f | 44.85 | 80 | 0.491183 | 4.626577 | false | false | false | false |
inorichi/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/manga/info/MangaFullCoverDialog.kt | 1 | 4091 | package eu.kanade.tachiyomi.ui.manga.info
import android.app.Dialog
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import androidx.core.graphics.ColorUtils
import androidx.core.os.bundleOf
import androidx.core.view.WindowCompat
import coil.imageLoader
import coil.request.Disposable
import coil.request.ImageRequest
import dev.chrisbanes.insetter.applyInsetter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.databinding.MangaFullCoverDialogBinding
import eu.kanade.tachiyomi.ui.base.controller.DialogController
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.ui.reader.viewer.ReaderPageImageView
import eu.kanade.tachiyomi.util.view.setNavigationBarTransparentCompat
import eu.kanade.tachiyomi.widget.TachiyomiFullscreenDialog
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class MangaFullCoverDialog : DialogController {
private var manga: Manga? = null
private var binding: MangaFullCoverDialogBinding? = null
private var disposable: Disposable? = null
private val mangaController
get() = targetController as MangaController
constructor(targetController: MangaController, manga: Manga) : super(bundleOf("mangaId" to manga.id)) {
this.targetController = targetController
this.manga = manga
}
@Suppress("unused")
constructor(bundle: Bundle) : super(bundle) {
val db = Injekt.get<DatabaseHelper>()
manga = db.getManga(bundle.getLong("mangaId")).executeAsBlocking()
}
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
binding = MangaFullCoverDialogBinding.inflate(activity!!.layoutInflater)
binding?.toolbar?.apply {
setNavigationOnClickListener { dialog?.dismiss() }
setOnMenuItemClickListener {
when (it.itemId) {
R.id.action_share_cover -> mangaController.shareCover()
R.id.action_save_cover -> mangaController.saveCover()
R.id.action_edit_cover -> mangaController.changeCover()
}
true
}
menu?.findItem(R.id.action_edit_cover)?.isVisible = manga?.favorite ?: false
}
setImage(manga)
binding?.appbar?.applyInsetter {
type(navigationBars = true, statusBars = true) {
padding(left = true, top = true, right = true)
}
}
binding?.container?.onViewClicked = { dialog?.dismiss() }
binding?.container?.applyInsetter {
type(navigationBars = true) {
padding(bottom = true)
}
}
return TachiyomiFullscreenDialog(activity!!, binding!!.root).apply {
val typedValue = TypedValue()
val theme = context.theme
theme.resolveAttribute(android.R.attr.colorBackground, typedValue, true)
window?.setBackgroundDrawable(ColorDrawable(ColorUtils.setAlphaComponent(typedValue.data, 230)))
}
}
override fun onAttach(view: View) {
super.onAttach(view)
dialog?.window?.let { window ->
window.setNavigationBarTransparentCompat(window.context)
WindowCompat.setDecorFitsSystemWindows(window, false)
}
}
override fun onDetach(view: View) {
super.onDetach(view)
disposable?.dispose()
disposable = null
}
fun setImage(manga: Manga?) {
if (manga == null) return
val request = ImageRequest.Builder(applicationContext!!)
.data(manga)
.target {
binding?.container?.setImage(
it,
ReaderPageImageView.Config(
zoomDuration = 500
)
)
}
.build()
disposable = applicationContext?.imageLoader?.enqueue(request)
}
}
| apache-2.0 | 08729e8d40e4c6da472b214848d22fa2 | 33.669492 | 108 | 0.656808 | 4.887694 | false | false | false | false |
google/horologist | network-awareness/src/main/java/com/google/android/horologist/networks/data/InMemoryDataRequestRepository.kt | 1 | 2238 | /*
* 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.google.android.horologist.networks.data
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import java.time.Instant
/**
* Simple In-memory implementation of Data Request Repository for recording network
* data usage.
*/
@ExperimentalHorologistNetworksApi
public class InMemoryDataRequestRepository : DataRequestRepository {
private val from = Instant.now()
private var ble = 0L
private var wifi = 0L
private var cell = 0L
private var unknown = 0L
private val _currentPeriodUsage: MutableStateFlow<DataUsageReport> =
MutableStateFlow(DataUsageReport(dataByType = mapOf(), from = from, to = from))
override fun currentPeriodUsage(): Flow<DataUsageReport> = _currentPeriodUsage
override fun storeRequest(dataRequest: DataRequest) {
when (dataRequest.networkInfo) {
is NetworkInfo.Cellular -> cell += dataRequest.dataBytes
is NetworkInfo.Bluetooth -> ble += dataRequest.dataBytes
is NetworkInfo.Wifi -> wifi += dataRequest.dataBytes
is NetworkInfo.Unknown -> unknown += dataRequest.dataBytes
}
_currentPeriodUsage.value =
DataUsageReport(
dataByType = mapOf(
NetworkType.Cell to cell,
NetworkType.BT to ble,
NetworkType.Wifi to wifi,
NetworkType.Unknown to unknown
),
from = from,
to = Instant.now()
)
}
}
| apache-2.0 | 513947ddfed2292d0b4d96b52054fe38 | 35.688525 | 87 | 0.682306 | 5.029213 | false | false | false | false |
Ekito/koin | koin-projects/koin-androidx-compose/src/main/java/org/koin/androidx/compose/ComposeExt.kt | 1 | 963 | package org.koin.androidx.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import org.koin.core.Koin
import org.koin.core.context.GlobalContext
import org.koin.core.parameter.ParametersDefinition
import org.koin.core.qualifier.Qualifier
/**
* Inject lazily a given dependency for [Composable] functions
* @param qualifier
* @param parameters
*
* @return Lazy instance of type T
*
* @author Henrique Horbovyi
*/
@Composable
inline fun <reified T> inject(
qualifier: Qualifier? = null,
noinline parameters: ParametersDefinition? = null
): Lazy<T> = remember {
GlobalContext.get().inject(qualifier, parameters)
}
@Composable
inline fun <reified T> get(
qualifier: Qualifier? = null,
noinline parameters: ParametersDefinition? = null
): T = remember {
GlobalContext.get().get(qualifier, parameters)
}
@Composable
fun getKoin(): Koin = remember {
GlobalContext.get()
}
| apache-2.0 | 4e3b59320768dd489447579d335b9173 | 24.342105 | 62 | 0.735202 | 4.046218 | false | false | false | false |
Kotlin/dokka | plugins/base/src/main/kotlin/translators/parseWithNormalisedSpaces.kt | 1 | 2081 | package org.jetbrains.dokka.base.translators
import org.intellij.markdown.lexer.Compat.codePointToString
import org.intellij.markdown.lexer.Compat.forEachCodePoint
import org.jetbrains.dokka.model.doc.DocTag
import org.jetbrains.dokka.model.doc.DocTag.Companion.contentTypeParam
import org.jetbrains.dokka.model.doc.Text
import org.jsoup.Jsoup
import org.jsoup.internal.StringUtil
import org.jsoup.nodes.Entities
internal fun String.parseHtmlEncodedWithNormalisedSpaces(
renderWhiteCharactersAsSpaces: Boolean
): List<DocTag> {
val accum = StringBuilder()
val tags = mutableListOf<DocTag>()
var lastWasWhite = false
forEachCodePoint { c ->
if (renderWhiteCharactersAsSpaces && StringUtil.isWhitespace(c)) {
if (!lastWasWhite) {
accum.append(' ')
lastWasWhite = true
}
} else if (codePointToString(c).let { it != Entities.escape(it) }) {
accum.toString().takeIf { it.isNotBlank() }?.let { tags.add(Text(it)) }
accum.delete(0, accum.length)
accum.appendCodePoint(c)
tags.add(Text(accum.toString(), params = contentTypeParam("html")))
accum.delete(0, accum.length)
} else if (!StringUtil.isInvisibleChar(c)) {
accum.appendCodePoint(c)
lastWasWhite = false
}
}
accum.toString().takeIf { it.isNotBlank() }?.let { tags.add(Text(it)) }
return tags
}
/**
* Parses string into [Text] doc tags that can have either value of the string or html-encoded value with content-type=html parameter.
* Content type is added when dealing with html entries like ` `
*/
internal fun String.parseWithNormalisedSpaces(
renderWhiteCharactersAsSpaces: Boolean
): List<DocTag> =
//parsing it using jsoup is required to get codePoints, otherwise they are interpreted separately, as chars
//But we dont need to do it for java as it is already parsed with jsoup
Jsoup.parseBodyFragment(this).body().wholeText().parseHtmlEncodedWithNormalisedSpaces(renderWhiteCharactersAsSpaces) | apache-2.0 | 36cbe77203aab931c4f6d2cdfdc64849 | 40.64 | 134 | 0.702547 | 4.212551 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/utils/crypto/AesCrypto.kt | 1 | 3044 | package me.mrkirby153.KirBot.utils.crypto
import me.mrkirby153.KirBot.Bot
import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.binary.Hex
import org.json.JSONObject
import org.json.JSONTokener
import java.nio.charset.Charset
import java.util.Arrays
import javax.crypto.Cipher
import javax.crypto.Mac
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
object AesCrypto {
private val key by lazy {
Base64.decodeBase64(Bot.properties.getProperty("encryption-key") ?: throw Exception("no key provided"))
}
fun encrypt(plaintext: String, serialize: Boolean = true) : String {
val key = SecretKeySpec(this.key, "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, key)
val serializedPlaintext = "s:" + plaintext.toByteArray().size + ":\"" + plaintext + "\";"
val toUse = if(serialize) serializedPlaintext else plaintext
val iv = cipher.iv
val encVal = cipher.doFinal(toUse.toByteArray())
val encrypted = Base64.encodeBase64String(encVal)
val macKey = SecretKeySpec(this.key, "HmacSHA256")
val hmacSha256 = Mac.getInstance("HmacSha256")
hmacSha256.init(macKey)
hmacSha256.update(Base64.encodeBase64(iv))
val calcMac = hmacSha256.doFinal(encrypted.toByteArray())
val mac = String(Hex.encodeHex(calcMac))
val json = JSONObject()
json.put("iv", Base64.encodeBase64String(iv))
json.put("value", encrypted)
json.put("mac", mac)
return Base64.encodeBase64String(json.toString().toByteArray())
}
fun decrypt(ivValue: String, encryptedData: String, macValue: String): String {
val key = SecretKeySpec(this.key, "AES")
val iv = Base64.decodeBase64(ivValue.toByteArray())
val decodedValue = Base64.decodeBase64(encryptedData.toByteArray())
val macKey = SecretKeySpec(this.key, "HmacSHA256")
val hmacSha256 = Mac.getInstance("HmacSHA256")
hmacSha256.init(macKey)
hmacSha256.update(ivValue.toByteArray())
val calcMac = hmacSha256.doFinal(encryptedData.toByteArray())
val mac = Hex.decodeHex(macValue.toCharArray())
if (!Arrays.equals(calcMac, mac))
throw IllegalArgumentException("MAC Mismatch")
val c = Cipher.getInstance("AES/CBC/PKCS5Padding") // or PKCS5Padding
c.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(iv))
val decValue = c.doFinal(decodedValue)
var firstQuoteIndex = 0
while (decValue[firstQuoteIndex] != '"'.toByte()) firstQuoteIndex++
return String(Arrays.copyOfRange(decValue, firstQuoteIndex + 1, decValue.size - 2))
}
fun decrypt(encData: String): String {
val rawJson = Base64.decodeBase64(encData).toString(Charset.defaultCharset())
val json = JSONObject(JSONTokener(rawJson))
return decrypt(json.getString("iv"), json.getString("value"), json.getString("mac"))
}
} | mit | 8d4fd343269130a79cbef386a92e6911 | 34.406977 | 111 | 0.684954 | 4.113514 | false | false | false | false |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/RewardEntity.kt | 1 | 2342 | @file:Suppress("UNCHECKED_CAST")
package com.github.shynixn.blockball.core.logic.persistence.entity
import com.github.shynixn.blockball.api.business.annotation.YamlSerialize
import com.github.shynixn.blockball.api.business.enumeration.RewardType
import com.github.shynixn.blockball.api.persistence.entity.CommandMeta
import com.github.shynixn.blockball.api.persistence.entity.RewardMeta
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class RewardEntity : RewardMeta {
/** Money which gets added via Vault when a player does a rewarded action. */
@YamlSerialize(orderNumber = 1, value = "money-reward")
override var moneyReward: MutableMap<RewardType, Int> = HashMap()
/** Commands which get executed when a player does a rewarded action. */
override var commandReward: MutableMap<RewardType, CommandMeta>
get() = internalCommandReward as MutableMap<RewardType, CommandMeta>
set(value) {
internalCommandReward = value as (MutableMap<RewardType, CommandMetaEntity>)
}
@YamlSerialize(orderNumber = 2, value = "command-reward")
private var internalCommandReward: MutableMap<RewardType, CommandMetaEntity> = HashMap()
} | apache-2.0 | 9ce7e886b20e0d941c623868f04f633f | 45.86 | 92 | 0.752348 | 4.32902 | false | false | false | false |
google/ksp | kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/impl/symbol/kotlin/KSClassDeclarationImpl.kt | 1 | 5986 | /*
* Copyright 2022 Google LLC
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.impl.symbol.kotlin
import com.google.devtools.ksp.KSObjectCache
import com.google.devtools.ksp.symbol.*
import org.jetbrains.kotlin.analysis.api.KtStarProjectionTypeArgument
import org.jetbrains.kotlin.analysis.api.components.buildClassType
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.psi.KtObjectDeclaration
class KSClassDeclarationImpl private constructor(internal val ktClassOrObjectSymbol: KtClassOrObjectSymbol) :
KSClassDeclaration,
AbstractKSDeclarationImpl(ktClassOrObjectSymbol),
KSExpectActual by KSExpectActualImpl(ktClassOrObjectSymbol) {
companion object : KSObjectCache<KtClassOrObjectSymbol, KSClassDeclarationImpl>() {
fun getCached(ktClassOrObjectSymbol: KtClassOrObjectSymbol) =
cache.getOrPut(ktClassOrObjectSymbol) { KSClassDeclarationImpl(ktClassOrObjectSymbol) }
}
override val qualifiedName: KSName? by lazy {
ktClassOrObjectSymbol.classIdIfNonLocal?.asFqNameString()?.let { KSNameImpl.getCached(it) }
}
override val classKind: ClassKind by lazy {
when (ktClassOrObjectSymbol.classKind) {
KtClassKind.CLASS -> ClassKind.CLASS
KtClassKind.ENUM_CLASS -> ClassKind.ENUM_CLASS
KtClassKind.ANNOTATION_CLASS -> ClassKind.ANNOTATION_CLASS
KtClassKind.INTERFACE -> ClassKind.INTERFACE
KtClassKind.COMPANION_OBJECT, KtClassKind.ANONYMOUS_OBJECT, KtClassKind.OBJECT -> ClassKind.OBJECT
}
}
override val primaryConstructor: KSFunctionDeclaration? by lazy {
if (ktClassOrObjectSymbol.origin == KtSymbolOrigin.JAVA) {
null
} else {
analyze {
ktClassOrObjectSymbol.getMemberScope().getConstructors().singleOrNull { it.isPrimary }?.let {
KSFunctionDeclarationImpl.getCached(it)
}
}
}
}
override val superTypes: Sequence<KSTypeReference> by lazy {
analyze {
val supers = ktClassOrObjectSymbol.superTypes.mapIndexed { index, type ->
KSTypeReferenceImpl.getCached(type, this@KSClassDeclarationImpl, index)
}
// AA is returning additional kotlin.Any for java classes, explicitly extending kotlin.Any will result in
// compile error, therefore filtering by name should work.
// TODO: reconsider how to model super types for interface.
if (supers.size > 1) {
supers.filterNot { it.resolve().declaration.qualifiedName?.asString() == "kotlin.Any" }
} else {
supers
}.asSequence()
}
}
override val isCompanionObject: Boolean by lazy {
(ktClassOrObjectSymbol.psi as? KtObjectDeclaration)?.isCompanion() ?: false
}
override fun getSealedSubclasses(): Sequence<KSClassDeclaration> {
TODO("Not yet implemented")
}
override fun getAllFunctions(): Sequence<KSFunctionDeclaration> {
return ktClassOrObjectSymbol.getAllFunctions()
}
override fun getAllProperties(): Sequence<KSPropertyDeclaration> {
return ktClassOrObjectSymbol.getAllProperties()
}
override fun asType(typeArguments: List<KSTypeArgument>): KSType {
return analyze {
analysisSession.buildClassType(ktClassOrObjectSymbol) {
typeArguments.forEach { argument(it.toKtTypeArgument()) }
}.let { KSTypeImpl.getCached(it) }
}
}
override fun asStarProjectedType(): KSType {
return analyze {
KSTypeImpl.getCached(
analysisSession.buildClassType(ktClassOrObjectSymbol) {
var current: KSNode? = this@KSClassDeclarationImpl
while (current is KSClassDeclarationImpl) {
current.ktClassOrObjectSymbol.typeParameters.forEach {
argument(
KtStarProjectionTypeArgument(
(current as KSClassDeclarationImpl).ktClassOrObjectSymbol.token
)
)
}
current = if (Modifier.INNER in current.modifiers) {
current.parent
} else {
null
}
}
}
)
}
}
override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R {
return visitor.visitClassDeclaration(this, data)
}
override val declarations: Sequence<KSDeclaration> by lazy {
ktClassOrObjectSymbol.declarations()
}
}
internal fun KtClassOrObjectSymbol.toModifiers(): Set<Modifier> {
val result = mutableSetOf<Modifier>()
if (this is KtNamedClassOrObjectSymbol) {
result.add(modality.toModifier())
result.add(visibility.toModifier())
if (isInline) {
result.add(Modifier.INLINE)
}
if (isData) {
result.add(Modifier.DATA)
}
if (isExternal) {
result.add(Modifier.EXTERNAL)
}
}
if (classKind == KtClassKind.ENUM_CLASS) {
result.add(Modifier.ENUM)
}
return result
}
| apache-2.0 | 690c2584fe9e4d2c48571b6e5e379b4d | 37.87013 | 117 | 0.638323 | 5.552876 | false | false | false | false |
toastkidjp/Yobidashi_kt | music/src/main/java/jp/toastkid/media/music/MusicFileFinder.kt | 1 | 3210 | /*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.media.music
import android.content.ContentResolver
import android.os.Build
import android.provider.MediaStore
import android.support.v4.media.MediaMetadataCompat
import androidx.core.net.toUri
/**
* @author toastkidjp
*/
class MusicFileFinder(private val contentResolver: ContentResolver) {
operator fun invoke(): MutableList<MediaMetadataCompat> {
val uri =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)
else
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val cursor = contentResolver.query(
uri,
null,
null,
null,
SORT_ORDER
)
val result = mutableListOf<MediaMetadataCompat>()
while (cursor?.moveToNext() == true) {
val meta = MediaMetadataCompat.Builder()
.putString(
MediaMetadataCompat.METADATA_KEY_MEDIA_ID,
cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)).toString()
)
.putString(
MediaMetadataCompat.METADATA_KEY_TITLE,
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE))
)
.putString(
MediaMetadataCompat.METADATA_KEY_ARTIST,
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST))
)
.putString(
MediaMetadataCompat.METADATA_KEY_ALBUM,
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM))
)
.putString(
MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI,
"content://media/external/audio/albumart".toUri().buildUpon().appendEncodedPath(cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)).toString()).build().toString()
)
.putString(
MediaMetadataCompat.METADATA_KEY_MEDIA_URI,
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA))
)
.putLong(
MediaMetadataCompat.METADATA_KEY_DURATION,
cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION))
)
.build()
result.add(meta)
}
cursor?.close()
return result
}
companion object {
private const val SORT_ORDER = "${MediaStore.Audio.AudioColumns.ALBUM} ASC"
}
} | epl-1.0 | 35aaaee2938efe73b0f6342625c55074 | 39.64557 | 216 | 0.570405 | 5.582609 | false | false | false | false |
krudayakumar/mahaperiyavaapp | app/src/main/java/com/kanchi/periyava/adapters/VolumeAdapter.kt | 1 | 2760 | package com.kanchi.periyava.version.dashboard.model
import android.content.Context
import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.kanchi.periyava.BR
import com.kanchi.periyava.R
import com.kanchi.periyava.model.OnItemClickListener
import com.kanchi.periyava.model.Volume
/**
* Created by m84098 on 2/15/18.
*/
class VolumeAdapter : RecyclerView.Adapter<VolumeAdapter.ViewHolder> {
lateinit var context: Context
var features = ArrayList<Volume>()
private var selectedPosition = 0
// Define listener member variable
private var listener: OnItemClickListener? = null
// Define the method that allows the parent activity or fragment to define the listener
fun setOnItemClickListener(listener: OnItemClickListener) {
this.listener = listener
}
constructor(context: Context, value: ArrayList<Volume>) : super() {
this.context = context
this.features = value
}
override fun getItemCount(): Int = features.size;
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent?.context)
val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, R.layout.list_item_volume, parent, false)
return ViewHolder(binding)
}
@RequiresApi(Build.VERSION_CODES.M)
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
if (features[position] != null) {
if(features[position].id != Volume.Type.NONE)
holder!!.bind(features[position]!!)
}
}
inner class ViewHolder(private var binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {
/* override fun onClick(v: View?) {
binding.root.setOnClickListener {
if (listener != null) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(itemView, position)
}
} }
}*/
fun bind(obj: Volume) {
binding.root.setOnClickListener {
if (listener != null) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener!!.onItemClick(itemView, position, obj)
}
}
}
binding.setVariable(BR.volume, obj)
binding.executePendingBindings()
}
}
}
| apache-2.0 | fffe1e5fb6128df621ba9c2c1da37086 | 33.5 | 120 | 0.646377 | 5.036496 | false | false | false | false |
stoman/CompetitiveProgramming | problems/2021adventofcode10b/submissions/accepted/Stefan.kt | 2 | 779 | import java.util.*
private fun computeScore(input: String): Long? {
val brackets = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>')
val scores = mapOf(')' to 1, ']' to 2, '}' to 3, '>' to 4)
val stack = ArrayDeque<Char>()
for (c in input) {
when (c) {
in brackets.keys -> stack.addFirst(c)
brackets[stack.first] -> stack.removeFirst()
else -> return null
}
}
var score = 0L
while(stack.isNotEmpty()) {
score *= 5
score += scores[brackets[stack.removeFirst()]]!!
}
return score
}
@ExperimentalStdlibApi
fun main() {
val s = Scanner(System.`in`)
val scores = buildList {
while (s.hasNext()) {
add(computeScore(s.next()))
}
}
println(scores.filterNotNull().sorted()[scores.filterNotNull().size/2])
}
| mit | 9e7d68d3c598c961dab4b6e930cc0292 | 23.34375 | 73 | 0.578947 | 3.557078 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.