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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Dmedina88/SSB | example/app/src/main/kotlin/com/grayherring/devtalks/data/model/Talk.kt | 1 | 725 | package com.grayherring.devtalks.data.model
import com.grayherring.devtalks.base.util.notBlank
import paperparcel.PaperParcel
import paperparcel.PaperParcelable
@PaperParcel
data class Talk(
val presenter: String = "",
val title: String = "",
val platform: String = "",
val description: String = "",
val date: String = "",
val email: String = "",
val slides: String = "",
val stream: String = "",
val tags: List<String> = ArrayList<String>(),
val id: String?
) : PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelTalk.CREATOR
}
fun isValid(): Boolean {
return notBlank(presenter, title, platform, description, date, email, slides, stream)
}
}
| apache-2.0 | d3089242f6a0e33f0dbba55c0b4e0a0c | 24.892857 | 89 | 0.675862 | 4.190751 | false | false | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/html/render/EmpireRendererHandler.kt | 1 | 3122 | package au.com.codeka.warworlds.server.html.render
import au.com.codeka.warworlds.common.Log
import java.awt.Color
import java.awt.color.ColorSpace
import java.awt.geom.AffineTransform
import java.awt.image.AffineTransformOp
import java.awt.image.BufferedImage
import java.io.File
import java.util.*
import javax.imageio.ImageIO
/** [RendererHandler] for rendering empire shields. */
class EmpireRendererHandler : RendererHandler() {
private val log = Log("EmpireRendererHandler")
override fun get() {
val empireId = getUrlParameter("empire")!!.toLong()
var width = getUrlParameter("width")!!.toInt()
var height = getUrlParameter("height")!!.toInt()
val bucket = getUrlParameter("bucket")
val factor = BUCKET_FACTORS[bucket]
if (factor == null) {
log.warning("Invalid bucket: %s", request.pathInfo)
response.status = 404
return
}
val cacheFile = File(String.format(Locale.ENGLISH,
"data/cache/empire/%d/%dx%d/%s.png", empireId, width, height, bucket))
if (cacheFile.exists()) {
serveCachedFile(cacheFile)
return
} else {
cacheFile.parentFile.mkdirs()
}
width = (width * factor).toInt()
height = (height * factor).toInt()
// TODO: if they have a custom one, use that
//WatchableObject<Empire> empire = EmpireManager.i.getEmpire(empireId);
var shieldImage = BufferedImage(128, 128, ColorSpace.TYPE_RGB)
val g = shieldImage.createGraphics()
g.paint = getShieldColour(empireId)
g.fillRect(0, 0, 128, 128)
// Merge the shield image with the outline image.
shieldImage = mergeShieldImage(shieldImage)
// Resize the image if required.
if (width != 128 || height != 128) {
val w = shieldImage.width
val h = shieldImage.height
val after = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
val at = AffineTransform()
at.scale(width.toFloat() / w.toDouble(), height.toFloat() / h.toDouble())
val scaleOp = AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC)
shieldImage = scaleOp.filter(shieldImage, after)
}
ImageIO.write(shieldImage, "png", cacheFile)
serveCachedFile(cacheFile)
}
private fun getShieldColour(empireID: Long): Color {
if (empireID == 0L) {
return Color(Color.TRANSLUCENT)
}
val rand = Random(empireID xor 7438274364563846L)
return Color(rand.nextInt(100) + 100, rand.nextInt(100) + 100, rand.nextInt(100) + 100)
}
private fun mergeShieldImage(shieldImage: BufferedImage): BufferedImage {
val finalImage = ImageIO.read(File("data/renderer/empire/shield.png"))
val width = finalImage.width
val height = finalImage.height
val fx = shieldImage.width.toFloat() / width.toFloat()
val fy = shieldImage.height.toFloat() / height.toFloat()
for (y in 0 until height) {
for (x in 0 until width) {
var pixel = finalImage.getRGB(x, y)
if (pixel and 0xffffff == 0xff00ff) {
pixel = shieldImage.getRGB((x * fx).toInt(), (y * fy).toInt())
finalImage.setRGB(x, y, pixel)
}
}
}
return finalImage
}
} | mit | 59aa67dd117a0c03267d9728c8cc1c03 | 34.089888 | 91 | 0.675208 | 3.798054 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/CustomizationEquipmentRecyclerViewAdapter.kt | 1 | 6390 | package com.habitrpg.android.habitica.ui.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.os.bundleOf
import com.facebook.drawee.view.SimpleDraweeView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.CustomizationGridItemBinding
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.models.inventory.CustomizationSet
import com.habitrpg.android.habitica.models.inventory.Equipment
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.subjects.PublishSubject
import java.util.*
class CustomizationEquipmentRecyclerViewAdapter : androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {
var gemBalance: Int = 0
var equipmentList
: MutableList<Equipment> = ArrayList()
set(value) {
field = value
notifyDataSetChanged()
}
var activeEquipment: String? = null
set(value) {
field = value
this.notifyDataSetChanged()
}
private val selectCustomizationEvents = PublishSubject.create<Equipment>()
private val unlockCustomizationEvents = PublishSubject.create<Equipment>()
private val unlockSetEvents = PublishSubject.create<CustomizationSet>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
val viewID: Int = R.layout.customization_grid_item
val view = LayoutInflater.from(parent.context).inflate(viewID, parent, false)
return EquipmentViewHolder(view)
}
override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
(holder as EquipmentViewHolder).bind(equipmentList[position])
}
override fun getItemCount(): Int {
return equipmentList.size
}
override fun getItemViewType(position: Int): Int {
return if (this.equipmentList[position].javaClass == CustomizationSet::class.java) {
0
} else {
1
}
}
fun setEquipment(newEquipmentList: List<Equipment>) {
this.equipmentList = newEquipmentList.toMutableList()
this.notifyDataSetChanged()
}
fun getSelectCustomizationEvents(): Flowable<Equipment> {
return selectCustomizationEvents.toFlowable(BackpressureStrategy.DROP)
}
fun getUnlockCustomizationEvents(): Flowable<Equipment> {
return unlockCustomizationEvents.toFlowable(BackpressureStrategy.DROP)
}
fun getUnlockSetEvents(): Flowable<CustomizationSet> {
return unlockSetEvents.toFlowable(BackpressureStrategy.DROP)
}
internal inner class EquipmentViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView), View.OnClickListener {
private val binding = CustomizationGridItemBinding.bind(itemView)
var equipment: Equipment? = null
init {
itemView.setOnClickListener(this)
}
fun bind(equipment: Equipment) {
this.equipment = equipment
DataBindingUtils.loadImage(binding.imageView, "shop_" + this.equipment?.key)
if (equipment.owned == true || equipment.value == 0.0) {
binding.buyButton.visibility = View.GONE
} else {
binding.buyButton.visibility = View.VISIBLE
binding.priceLabel.currency = "gems"
binding.priceLabel.value = if (equipment.gearSet == "animal") {
2.0
} else {
equipment.value
}
}
if (activeEquipment == equipment.key) {
binding.wrapper.background = itemView.context.getDrawable(R.drawable.layout_rounded_bg_gray_700_brand_border)
} else {
binding.wrapper.background = itemView.context.getDrawable(R.drawable.layout_rounded_bg_gray_700)
}
}
override fun onClick(v: View) {
if (equipment?.owned != true && (equipment?.value ?: 0.0) > 0.0) {
val dialogContent = LayoutInflater.from(itemView.context).inflate(R.layout.dialog_purchase_customization, null) as LinearLayout
val imageView = dialogContent.findViewById<SimpleDraweeView>(R.id.imageView)
DataBindingUtils.loadImage(imageView, "shop_" + this.equipment?.key)
val priceLabel = dialogContent.findViewById<TextView>(R.id.priceLabel)
priceLabel.text = if (equipment?.gearSet == "animal") {
2.0
} else {
equipment?.value ?: 0
}.toString()
(dialogContent.findViewById<View>(R.id.gem_icon) as? ImageView)?.setImageBitmap(HabiticaIconsHelper.imageOfGem())
val dialog = HabiticaAlertDialog(itemView.context)
dialog.addButton(R.string.purchase_button, true) { _, _ ->
if (equipment?.value ?: 0.0 > gemBalance) {
MainNavigationController.navigate(R.id.gemPurchaseActivity, bundleOf(Pair("openSubscription", false)))
return@addButton
}
equipment?.let {
unlockCustomizationEvents.onNext(it)
}
}
dialog.setTitle(R.string.purchase_customization)
dialog.setAdditionalContentView(dialogContent)
dialog.addButton(R.string.reward_dialog_dismiss, false)
dialog.show()
return
}
if (equipment?.key == activeEquipment) {
return
}
equipment?.let {
selectCustomizationEvents.onNext(it)
}
}
}
}
| gpl-3.0 | c0861b6e65c0b488d57e5259175aeeb8 | 38.700637 | 157 | 0.63975 | 5.140788 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/gltf/GltfAccessor.kt | 1 | 15381 | package de.fabmax.kool.modules.gltf
import de.fabmax.kool.math.*
import de.fabmax.kool.util.DataStream
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
/**
* A typed view into a bufferView. A bufferView contains raw binary data. An accessor provides a typed view into a
* bufferView or a subset of a bufferView similar to how WebGL's vertexAttribPointer() defines an attribute in a
* buffer.
*
* @param bufferView The index of the bufferView.
* @param byteOffset The offset relative to the start of the bufferView in bytes.
* @param componentType The datatype of components in the attribute.
* @param normalized Specifies whether integer data values should be normalized.
* @param count The number of attributes referenced by this accessor.
* @param type Specifies if the attribute is a scalar, vector, or matrix.
* @param max Maximum value of each component in this attribute.
* @param min Minimum value of each component in this attribute.
*/
@Serializable
data class GltfAccessor(
val bufferView: Int = -1,
val byteOffset: Int = 0,
val componentType: Int,
val normalized: Boolean = false,
val count: Int,
val type: String,
val max: List<Float>? = null,
val min: List<Float>? = null,
val sparse: Sparse? = null,
val name: String? = null
) {
@Transient
var bufferViewRef: GltfBufferView? = null
companion object {
const val TYPE_SCALAR = "SCALAR"
const val TYPE_VEC2 = "VEC2"
const val TYPE_VEC3 = "VEC3"
const val TYPE_VEC4 = "VEC4"
const val TYPE_MAT2 = "MAT2"
const val TYPE_MAT3 = "MAT3"
const val TYPE_MAT4 = "MAT4"
const val COMP_TYPE_BYTE = 5120
const val COMP_TYPE_UNSIGNED_BYTE = 5121
const val COMP_TYPE_SHORT = 5122
const val COMP_TYPE_UNSIGNED_SHORT = 5123
const val COMP_TYPE_INT = 5124
const val COMP_TYPE_UNSIGNED_INT = 5125
const val COMP_TYPE_FLOAT = 5126
val COMP_INT_TYPES = setOf(
COMP_TYPE_BYTE, COMP_TYPE_UNSIGNED_BYTE,
COMP_TYPE_SHORT, COMP_TYPE_UNSIGNED_SHORT,
COMP_TYPE_INT, COMP_TYPE_UNSIGNED_INT)
}
@Serializable
data class Sparse(
val count: Int,
val indices: SparseIndices,
val values: SparseValues
)
@Serializable
data class SparseIndices(
val bufferView: Int,
val byteOffset: Int = 0,
val componentType: Int
) {
@Transient
lateinit var bufferViewRef: GltfBufferView
}
@Serializable
data class SparseValues(
val bufferView: Int,
val byteOffset: Int = 0
) {
@Transient
lateinit var bufferViewRef: GltfBufferView
}
}
abstract class DataStreamAccessor(val accessor: GltfAccessor) {
private val elemByteSize: Int
private val byteStride: Int
private val buffer: GltfBufferView? = accessor.bufferViewRef
private val stream: DataStream?
private val sparseIndexStream: DataStream?
private val sparseValueStream: DataStream?
private val sparseIndexType: Int
private var nextSparseIndex: Int
var index: Int = 0
set(value) {
field = value
stream?.index = value * byteStride
}
init {
stream = if (buffer != null) {
DataStream(buffer.bufferRef.data, accessor.byteOffset + buffer.byteOffset)
} else {
null
}
if (accessor.sparse != null) {
sparseIndexStream = DataStream(accessor.sparse.indices.bufferViewRef.bufferRef.data, accessor.sparse.indices.bufferViewRef.byteOffset)
sparseValueStream = DataStream(accessor.sparse.values.bufferViewRef.bufferRef.data, accessor.sparse.values.bufferViewRef.byteOffset)
sparseIndexType = accessor.sparse.indices.componentType
nextSparseIndex = sparseIndexStream.nextIntComponent(sparseIndexType)
} else {
sparseIndexStream = null
sparseValueStream = null
sparseIndexType = 0
nextSparseIndex = -1
}
val compByteSize = when (accessor.componentType) {
GltfAccessor.COMP_TYPE_BYTE -> 1
GltfAccessor.COMP_TYPE_UNSIGNED_BYTE -> 1
GltfAccessor.COMP_TYPE_SHORT -> 2
GltfAccessor.COMP_TYPE_UNSIGNED_SHORT -> 2
GltfAccessor.COMP_TYPE_INT -> 4
GltfAccessor.COMP_TYPE_UNSIGNED_INT -> 4
GltfAccessor.COMP_TYPE_FLOAT -> 4
else -> throw IllegalArgumentException("Unknown accessor component type: ${accessor.componentType}")
}
val numComponents = when(accessor.type) {
GltfAccessor.TYPE_SCALAR -> 1
GltfAccessor.TYPE_VEC2 -> 2
GltfAccessor.TYPE_VEC3 -> 3
GltfAccessor.TYPE_VEC4 -> 4
GltfAccessor.TYPE_MAT2 -> 4
GltfAccessor.TYPE_MAT3 -> 9
GltfAccessor.TYPE_MAT4 -> 16
else -> throw IllegalArgumentException("Unsupported accessor type: ${accessor.type}")
}
// fixme: some mat types require padding (also depending on component type) which is currently not considered
elemByteSize = compByteSize * numComponents
byteStride = if (buffer != null && buffer.byteStride > 0) {
buffer.byteStride
} else {
elemByteSize
}
}
private fun selectDataStream() = if (index != nextSparseIndex) stream else sparseValueStream
protected fun nextInt(): Int {
if (index < accessor.count) {
return selectDataStream()?.nextIntComponent(accessor.componentType) ?: 0
} else {
throw IndexOutOfBoundsException("Accessor overflow")
}
}
protected fun nextFloat(): Float {
if (accessor.componentType == GltfAccessor.COMP_TYPE_FLOAT) {
if (index < accessor.count) {
return selectDataStream()?.readFloat() ?: 0f
} else {
throw IndexOutOfBoundsException("Accessor overflow")
}
} else {
// implicitly convert int type to normalized float
return nextInt() / when (accessor.componentType) {
GltfAccessor.COMP_TYPE_BYTE -> 128f
GltfAccessor.COMP_TYPE_UNSIGNED_BYTE -> 255f
GltfAccessor.COMP_TYPE_SHORT -> 32767f
GltfAccessor.COMP_TYPE_UNSIGNED_SHORT -> 65535f
GltfAccessor.COMP_TYPE_INT -> 2147483647f
GltfAccessor.COMP_TYPE_UNSIGNED_INT -> 4294967296f
else -> throw IllegalStateException("Unknown component type: ${accessor.componentType}")
}
}
}
protected fun nextDouble() = nextFloat().toDouble()
private fun DataStream.nextIntComponent(componentType: Int): Int {
return when (componentType) {
GltfAccessor.COMP_TYPE_BYTE -> readByte()
GltfAccessor.COMP_TYPE_UNSIGNED_BYTE -> readUByte()
GltfAccessor.COMP_TYPE_SHORT -> readShort()
GltfAccessor.COMP_TYPE_UNSIGNED_SHORT -> readUShort()
GltfAccessor.COMP_TYPE_INT -> readInt()
GltfAccessor.COMP_TYPE_UNSIGNED_INT -> readUInt()
else -> throw IllegalArgumentException("Invalid component type: $componentType")
}
}
protected fun advance() {
if (index == nextSparseIndex && sparseIndexStream?.hasRemaining() == true) {
nextSparseIndex = sparseIndexStream.nextIntComponent(sparseIndexType)
}
index++
}
}
/**
* Utility class to retrieve scalar integer values from an accessor. The provided accessor must have a non floating
* point component type (byte, short or int either signed or unsigned) and must be of type SCALAR.
*
* @param accessor [GltfAccessor] to use.
*/
class IntAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) {
init {
if (accessor.type != GltfAccessor.TYPE_SCALAR) {
throw IllegalArgumentException("IntAccessor requires accessor type ${GltfAccessor.TYPE_SCALAR}, provided was ${accessor.type}")
}
if (accessor.componentType !in GltfAccessor.COMP_INT_TYPES) {
throw IllegalArgumentException("IntAccessor requires a (byte / short / int) component type, provided was ${accessor.componentType}")
}
}
fun next(): Int {
if (index < accessor.count) {
val i = nextInt()
advance()
return i
} else {
throw IndexOutOfBoundsException("Accessor overflow")
}
}
}
/**
* Utility class to retrieve scalar float values from an accessor. The provided accessor must have a float component
* type and must be of type SCALAR.
*
* @param accessor [GltfAccessor] to use.
*/
class FloatAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) {
init {
if (accessor.type != GltfAccessor.TYPE_SCALAR) {
throw IllegalArgumentException("Vec2fAccessor requires accessor type ${GltfAccessor.TYPE_SCALAR}, provided was ${accessor.type}")
}
// if (accessor.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
// throw IllegalArgumentException("FloatAccessor requires a float component type, provided was ${accessor.componentType}")
// }
}
fun next(): Float {
val f = nextFloat()
advance()
return f
}
fun nextD() = next().toDouble()
}
/**
* Utility class to retrieve Vec2 float values from an accessor. The provided accessor must have a float component type
* and must be of type VEC2.
*
* @param accessor [GltfAccessor] to use.
*/
class Vec2fAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) {
init {
if (accessor.type != GltfAccessor.TYPE_VEC2) {
throw IllegalArgumentException("Vec2fAccessor requires accessor type ${GltfAccessor.TYPE_VEC2}, provided was ${accessor.type}")
}
// if (accessor.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
// throw IllegalArgumentException("Vec2fAccessor requires a float component type, provided was ${accessor.componentType}")
// }
}
fun next(): MutableVec2f = next(MutableVec2f())
fun next(result: MutableVec2f): MutableVec2f {
result.x = nextFloat()
result.y = nextFloat()
advance()
return result
}
fun nextD(): MutableVec2d = nextD(MutableVec2d())
fun nextD(result: MutableVec2d): MutableVec2d {
result.x = nextDouble()
result.y = nextDouble()
advance()
return result
}
}
/**
* Utility class to retrieve Vec3 float values from an accessor. The provided accessor must have a float component type
* and must be of type VEC3.
*
* @param accessor [GltfAccessor] to use.
*/
class Vec3fAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) {
init {
if (accessor.type != GltfAccessor.TYPE_VEC3) {
throw IllegalArgumentException("Vec3fAccessor requires accessor type ${GltfAccessor.TYPE_VEC3}, provided was ${accessor.type}")
}
// if (accessor.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
// throw IllegalArgumentException("Vec3fAccessor requires a float component type, provided was ${accessor.componentType}")
// }
}
fun next(): MutableVec3f = next(MutableVec3f())
fun next(result: MutableVec3f): MutableVec3f {
result.x = nextFloat()
result.y = nextFloat()
result.z = nextFloat()
advance()
return result
}
fun nextD(): MutableVec3d = nextD(MutableVec3d())
fun nextD(result: MutableVec3d): MutableVec3d {
result.x = nextDouble()
result.y = nextDouble()
result.z = nextDouble()
advance()
return result
}
}
/**
* Utility class to retrieve Vec4 float values from an accessor. The provided accessor must have a float component type
* and must be of type VEC4.
*
* @param accessor [GltfAccessor] to use.
*/
class Vec4fAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) {
init {
if (accessor.type != GltfAccessor.TYPE_VEC4) {
throw IllegalArgumentException("Vec4fAccessor requires accessor type ${GltfAccessor.TYPE_VEC4}, provided was ${accessor.type}")
}
// if (accessor.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
// throw IllegalArgumentException("Vec4fAccessor requires a float component type, provided was ${accessor.componentType}")
// }
}
fun next(): MutableVec4f = next(MutableVec4f())
fun next(result: MutableVec4f): MutableVec4f {
result.x = nextFloat()
result.y = nextFloat()
result.z = nextFloat()
result.w = nextFloat()
advance()
return result
}
fun nextD(): MutableVec4d = nextD(MutableVec4d())
fun nextD(result: MutableVec4d): MutableVec4d {
result.x = nextDouble()
result.y = nextDouble()
result.z = nextDouble()
result.w = nextDouble()
advance()
return result
}
}
/**
* Utility class to retrieve Vec4 int values from an accessor. The provided accessor must have a non floating
* point component type (byte, short or int either signed or unsigned) and must be of type VEC4.
*
* @param accessor [GltfAccessor] to use.
*/
class Vec4iAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) {
init {
if (accessor.type != GltfAccessor.TYPE_VEC4) {
throw IllegalArgumentException("Vec4iAccessor requires accessor type ${GltfAccessor.TYPE_VEC4}, provided was ${accessor.type}")
}
if (accessor.componentType !in GltfAccessor.COMP_INT_TYPES) {
throw IllegalArgumentException("Vec4fAccessor requires a (byte / short / int) component type, provided was ${accessor.componentType}")
}
}
fun next(): MutableVec4i = next(MutableVec4i())
fun next(result: MutableVec4i): MutableVec4i {
result.x = nextInt()
result.y = nextInt()
result.z = nextInt()
result.w = nextInt()
advance()
return result
}
}
/**
* Utility class to retrieve Mat4 float values from an accessor. The provided accessor must have a float component type
* and must be of type MAT4.
*
* @param accessor [GltfAccessor] to use.
*/
class Mat4fAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) {
init {
if (accessor.type != GltfAccessor.TYPE_MAT4) {
throw IllegalArgumentException("Mat4fAccessor requires accessor type ${GltfAccessor.TYPE_MAT4}, provided was ${accessor.type}")
}
if (accessor.componentType != GltfAccessor.COMP_TYPE_FLOAT) {
throw IllegalArgumentException("Mat4fAccessor requires a float component type, provided was ${accessor.componentType}")
}
}
fun next(): Mat4f = next(Mat4f())
fun next(result: Mat4f): Mat4f {
for (i in 0..15) {
result.matrix[i] = nextFloat()
}
advance()
return result
}
fun nextD(): Mat4d = nextD(Mat4d())
fun nextD(result: Mat4d): Mat4d {
for (i in 0..15) {
result.matrix[i] = nextDouble()
}
advance()
return result
}
} | apache-2.0 | a6d52a8a7ab0c151d9c54a8d03b9082b | 34.442396 | 146 | 0.636825 | 4.3858 | false | false | false | false |
550609334/Twobbble | app/src/main/java/com/twobbble/view/activity/BucketShotsActivity.kt | 1 | 6485 | package com.twobbble.view.activity
import android.app.ActivityOptions
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import com.twobbble.R
import com.twobbble.application.App
import com.twobbble.entity.Shot
import com.twobbble.presenter.BucketShotsPresenter
import com.twobbble.tools.hideErrorImg
import com.twobbble.tools.showErrorImg
import com.twobbble.tools.toast
import com.twobbble.view.adapter.ItemShotAdapter
import com.twobbble.view.api.IBucketShotsView
import com.twobbble.view.customview.ItemSwipeRemoveCallback
import kotlinx.android.synthetic.main.activity_bucket_shots.*
import kotlinx.android.synthetic.main.error_layout.*
import kotlinx.android.synthetic.main.list.*
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.doAsync
class BucketShotsActivity : BaseActivity(), IBucketShotsView {
private var mId: Long = 0
private var mTitle: String? = null
private val mPresenter: BucketShotsPresenter by lazy {
BucketShotsPresenter(this)
}
private var isLoading: Boolean = false
private var mPage: Int = 1
lateinit private var mShots: MutableList<Shot>
private var mListAdapter: ItemShotAdapter? = null
private var mDelPosition: Int = 0
private lateinit var mDelShot: Shot
companion object {
val KEY_ID = "id"
val KEY_TITLE = "title"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_bucket_shots)
mId = intent.getLongExtra(KEY_ID, 0)
mTitle = intent.getStringExtra(KEY_TITLE)
init()
getShots()
}
private fun init() {
Toolbar.title = mTitle
mRefresh.setColorSchemeResources(R.color.google_red, R.color.google_yellow, R.color.google_green, R.color.google_blue)
val layoutManager = LinearLayoutManager(App.instance, LinearLayoutManager.VERTICAL, false)
mRecyclerView.layoutManager = layoutManager
mRecyclerView.itemAnimator = DefaultItemAnimator()
}
fun getShots(isLoadMore: Boolean = false) {
isLoading = true
mPresenter.getBucketShots(id = mId, page = mPage, isLoadMore = isLoadMore)
}
override fun onStart() {
super.onStart()
bindEvent()
}
private fun bindEvent() {
Toolbar.setNavigationOnClickListener { finish() }
mRefresh.setOnRefreshListener {
mPage = 1
getShots(false)
}
mErrorLayout.setOnClickListener {
hideErrorImg(mErrorLayout)
getShots(false)
}
mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
val linearManager = recyclerView?.layoutManager as LinearLayoutManager
val position = linearManager.findLastVisibleItemPosition()
if (mShots.isNotEmpty() && position == mShots.size) {
if (!isLoading) {
mPage += 1
getShots(true)
}
}
}
})
val itemTouchHelper = ItemTouchHelper(ItemSwipeRemoveCallback { delPosition, _ ->
mDelShot = mShots[delPosition]
mListAdapter?.deleteItem(delPosition)
mDelPosition = delPosition
mDialogManager.showOptionDialog(
resources.getString(R.string.delete_shot),
resources.getString(R.string.whether_to_delete_shot_from_bucket),
confirmText = resources.getString(R.string.delete),
onConfirm = {
mPresenter.removeShotFromBucket(id = mId, shot_id = mDelShot.id)
}, onCancel = {
mListAdapter?.addItem(delPosition, mDelShot)
mRecyclerView.scrollToPosition(delPosition)
})
})
itemTouchHelper.attachToRecyclerView(mRecyclerView)
}
override fun onDestroy() {
super.onDestroy()
mPresenter.unSubscriber()
}
override fun showProgress() {
if (mListAdapter == null) mRefresh.isRefreshing = true
}
override fun hideProgress() {
mRefresh.isRefreshing = false
}
override fun showProgressDialog(msg: String?) {
mDialogManager.showCircleProgressDialog()
}
override fun hideProgressDialog() {
mDialogManager.dismissAll()
}
override fun getShotSuccess(shots: MutableList<Shot>?, isLoadMore: Boolean) {
isLoading = false
if (shots != null && shots.isNotEmpty()) {
if (!isLoadMore) {
mountList(shots)
} else {
mListAdapter?.addItems(shots)
}
} else {
if (!isLoadMore) {
showErrorImg(mErrorLayout, imgResID = R.mipmap.img_empty_buckets)
} else {
mListAdapter?.hideProgress()
}
}
}
private fun mountList(shots: MutableList<Shot>) {
mShots = shots
mListAdapter = ItemShotAdapter(mShots, {
EventBus.getDefault().postSticky(mShots[it])
startActivity(Intent(this, DetailsActivity::class.java),
ActivityOptions.makeSceneTransitionAnimation(this).toBundle())
}, {
EventBus.getDefault().postSticky(shots[it].user)
startActivity(Intent(applicationContext, UserActivity::class.java))
})
mRecyclerView.adapter = mListAdapter
}
override fun getShotFailed(msg: String, isLoadMore: Boolean) {
isLoading = false
toast(msg)
if (!isLoadMore) {
if (mListAdapter == null)
showErrorImg(mErrorLayout, msg, R.mipmap.img_network_error_2)
} else {
mListAdapter?.loadError {
getShots(true)
}
}
}
override fun removeShotSuccess() {
toast(R.string.delete_success)
}
override fun removeShotFailed(msg: String) {
toast("${resources.getString(R.string.delete_success)}:$msg")
mListAdapter?.addItem(mDelPosition, mDelShot)
mRecyclerView.scrollToPosition(mDelPosition)
}
}
| apache-2.0 | a33e6f1fc2c6d4283034b02138c9ed2a | 33.494681 | 126 | 0.638088 | 4.879609 | false | false | false | false |
lsmaira/gradle | buildSrc/subprojects/buildquality/src/main/kotlin/org/gradle/gradlebuild/buildquality/VerifyBuildEnvironmentPlugin.kt | 2 | 1483 | package org.gradle.gradlebuild.buildquality
import availableJavaInstallations
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.nio.charset.Charset
import org.gradle.api.tasks.compile.AbstractCompile
import org.gradle.kotlin.dsl.*
open class VerifyBuildEnvironmentPlugin : Plugin<Project> {
override fun apply(project: Project): Unit = project.run {
validateForProductionEnvironments(project)
validateForAllCompileTasks(project)
}
private
fun validateForProductionEnvironments(rootProject: Project) =
rootProject.tasks.register("verifyIsProductionBuildEnvironment") {
doLast {
rootProject.availableJavaInstallations.validateForProductionEnvironment()
val systemCharset = Charset.defaultCharset().name()
assert(systemCharset == "UTF-8") {
"Platform encoding must be UTF-8. Is currently $systemCharset. Set -Dfile.encoding=UTF-8"
}
}
}
private
fun validateForAllCompileTasks(rootProject: Project) {
val verifyBuildEnvironment = rootProject.tasks.register("verifyBuildEnvironment") {
doLast {
rootProject.availableJavaInstallations.validateForCompilation()
}
}
rootProject.subprojects {
tasks.withType<AbstractCompile>().configureEach {
dependsOn(verifyBuildEnvironment)
}
}
}
}
| apache-2.0 | 3f9383fa1fda355ff46ae23de6467a7c | 33.488372 | 109 | 0.670937 | 5.09622 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/bottom-mpp/src/jvmWithJavaiOSMain/kotlin/transitiveStory/midActual/sourceCalls/intemediateCall/SecondModCaller.kt | 2 | 2109 | package transitiveStory.midActual.sourceCalls.intemediateCall
import transitiveStory.bottomActual.mppBeginning.BottomActualDeclarations
import transitiveStory.bottomActual.mppBeginning.regularTLfunInTheBottomActualCommmon
// https://youtrack.jetbrains.com/issue/KT-33731
import transitiveStory.bottomActual.intermediateSrc.*
class SecondModCaller {
// ========= api calls (attempt to) ==========
// java
val jApiOne = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: JavaApiContainer'")!>JavaApiContainer<!>()
// kotlin
val kApiOne = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: KotlinApiContainer'")!>KotlinApiContainer<!>()
// ========= mpp-bottom-actual calls ==========
// common source set
val interCallOne = regularTLfunInTheBottomActualCommmon("Some string from `mpp-mid-actual` module")
val interCallTwo = BottomActualDeclarations.inTheCompanionOfBottomActualDeclarations
val interCallThree = BottomActualDeclarations().simpleVal
// https://youtrack.jetbrains.com/issue/KT-33731
// intermediate source set
val interCallFour = InBottomActualIntermediate().p
val interCallFive = IntermediateMPPClassInBottomActual()
// ========= jvm18 source set (attempt to) ==========
// java
val interCallSix = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: JApiCallerInJVM18'")!>JApiCallerInJVM18<!>()
// kotlin
val interCallSeven = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: Jvm18KApiInheritor'")!>Jvm18KApiInheritor<!>()
val interCallEight = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: Jvm18JApiInheritor'")!>Jvm18JApiInheritor<!>()
val interCallNine = IntermediateMPPClassInBottomActual()
}
// experiments with intermod inheritance
class BottomActualCommonInheritor : BottomActualDeclarations()
expect class <!LINE_MARKER("descr='Has actuals in Native, JVM'")!>BottomActualMPPInheritor<!> : BottomActualDeclarations
| apache-2.0 | cdbc606a4e8adf646d13e8c03da08cac | 50.439024 | 157 | 0.752963 | 4.893271 | false | false | false | false |
PeteGabriel/Yamda | app/src/main/java/com/dev/moviedb/mvvm/repository/remote/dto/ResultDTO.kt | 1 | 1924 | package com.dev.moviedb.mvvm.repository.remote.dto
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class Result {
@SerializedName("poster_path")
@Expose
var posterPath: Any? = null
@SerializedName("popularity")
@Expose
var popularity: Double? = null
@SerializedName("id")
@Expose
var id: Int? = null
@SerializedName("overview")
@Expose
var overview: String? = null
@SerializedName("backdrop_path")
@Expose
var backdropPath: Any? = null
@SerializedName("vote_average")
@Expose
var voteAverage: Int? = null
@SerializedName("media_type")
@Expose
var mediaType: String? = null
@SerializedName("first_air_date")
@Expose
var firstAirDate: String? = null
@SerializedName("origin_country")
@Expose
var originCountry: List<String>? = null
@SerializedName("genre_ids")
@Expose
var genreIds: List<Int>? = null
@SerializedName("original_language")
@Expose
var originalLanguage: String? = null
@SerializedName("vote_count")
@Expose
var voteCount: Int? = null
@SerializedName("name")
@Expose
var name: String? = null
@SerializedName("original_name")
@Expose
var originalName: String? = null
@SerializedName("adult")
@Expose
var adult: Boolean? = null
@SerializedName("release_date")
@Expose
var releaseDate: String? = null
@SerializedName("original_title")
@Expose
var originalTitle: String? = null
@SerializedName("title")
@Expose
var title: String? = null
@SerializedName("video")
@Expose
var video: Boolean? = null
@SerializedName("profile_path")
@Expose
var profilePath: String? = null
@SerializedName("known_for")
@Expose
var knownFor: List<KnownFor>? = null
} | gpl-3.0 | 881bdc10aca2fb0b5b73db78326aaa95 | 24.383562 | 50 | 0.630457 | 4.285078 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/components/TextFieldComponent.kt | 1 | 2108 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.entity.SettingValidator
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.componentWithCommentAtBottom
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.textField
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.JComponent
class TextFieldComponent(
context: Context,
labelText: String? = null,
description: String? = null,
initialValue: String? = null,
validator: SettingValidator<String>? = null,
onValueUpdate: (String, isByUser: Boolean) -> Unit = { _, _ -> }
) : UIComponent<String>(
context,
labelText,
validator,
onValueUpdate
) {
private var isDisabled: Boolean = false
private var cachedValueWhenDisabled: String? = null
private val textField = textField(initialValue.orEmpty(), ::fireValueUpdated)
override val alignTarget: JComponent? get() = textField
override val uiComponent = componentWithCommentAtBottom(textField, description)
override fun updateUiValue(newValue: String) = safeUpdateUi {
textField.text = newValue
}
fun onUserType(action: () -> Unit) {
textField.addKeyListener(object : KeyAdapter() {
override fun keyReleased(e: KeyEvent?) = action()
})
}
fun disable(@Nls message: String) {
cachedValueWhenDisabled = getUiValue()
textField.isEditable = false
textField.foreground = UIUtil.getLabelDisabledForeground()
isDisabled = true
updateUiValue(message)
}
override fun validate(value: String) {
if (isDisabled) return
super.validate(value)
}
override fun getUiValue(): String = cachedValueWhenDisabled ?: textField.text
} | apache-2.0 | 32f43aec7f2f2c67acccb3c4066a0647 | 34.15 | 158 | 0.725332 | 4.504274 | false | false | false | false |
siosio/intellij-community | java/idea-ui/src/com/intellij/ide/projectWizard/generators/JavaBuildSystemType.kt | 1 | 3039 | // 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.ide.projectWizard.generators
import com.intellij.ide.highlighter.ModuleFileType
import com.intellij.ide.util.projectWizard.JavaModuleBuilder
import com.intellij.ide.wizard.BuildSystemType
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.UIBundle
import com.intellij.ui.layout.*
import java.nio.file.Paths
abstract class JavaBuildSystemType<P>(override val name: String) : BuildSystemType<JavaSettings, P> {
companion object {
var EP_NAME = ExtensionPointName<JavaBuildSystemType<*>>("com.intellij.newProjectWizard.buildSystem.java")
}
}
class IntelliJJavaBuildSystemType : JavaBuildSystemType<IntelliJBuildSystemSettings>("IntelliJ") {
override var settingsFactory = { IntelliJBuildSystemSettings() }
override fun advancedSettings(settings: IntelliJBuildSystemSettings): DialogPanel =
panel {
hideableRow(UIBundle.message("label.project.wizard.new.project.advanced.settings")) {
row {
cell { label(UIBundle.message("label.project.wizard.new.project.module.name")) }
cell {
textField(settings::moduleName)
}
}
row {
cell { label(UIBundle.message("label.project.wizard.new.project.content.root")) }
cell {
textFieldWithBrowseButton(settings::contentRoot, UIBundle.message("label.project.wizard.new.project.content.root"), null,
FileChooserDescriptorFactory.createSingleFolderDescriptor())
}
}
row {
cell { label(UIBundle.message("label.project.wizard.new.project.module.file.location")) }
cell {
textFieldWithBrowseButton(settings::moduleFileLocation,
UIBundle.message("label.project.wizard.new.project.module.file.location"), null,
FileChooserDescriptorFactory.createSingleFolderDescriptor())
}
}
}.largeGapAfter()
}
override fun setupProject(project: Project, languageSettings: JavaSettings, settings: IntelliJBuildSystemSettings) {
val builder = JavaModuleBuilder()
val moduleFile = Paths.get(settings.moduleFileLocation, settings.moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION)
builder.name = settings.moduleName
builder.moduleFilePath = FileUtil.toSystemDependentName(moduleFile.toString())
builder.contentEntryPath = FileUtil.toSystemDependentName(settings.contentRoot)
builder.moduleJdk = languageSettings.sdk
builder.commit(project)
}
}
class IntelliJBuildSystemSettings {
var moduleName: String = ""
var contentRoot: String = ""
var moduleFileLocation: String = ""
} | apache-2.0 | d1badd5b5b350960b6cdea1ca9a03281 | 41.816901 | 140 | 0.723264 | 4.949511 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/org/jetbrains/kotlin/js/inline/util/rewriters/ReturnReplacingVisitor.kt | 3 | 2723 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.inline.util.rewriters
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.backend.ast.metadata.*
import org.jetbrains.kotlin.js.translate.context.Namer
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils
class ReturnReplacingVisitor(
private val resultRef: JsNameRef?,
private val breakLabel: JsNameRef?,
private val function: JsFunction,
private val isSuspend: Boolean
) : JsVisitorWithContextImpl() {
/**
* Prevents replacing returns in object literal
*/
override fun visit(x: JsObjectLiteral, ctx: JsContext<JsNode>): Boolean = false
/**
* Prevents replacing returns in inner function
*/
override fun visit(x: JsFunction, ctx: JsContext<JsNode>): Boolean = false
override fun endVisit(x: JsReturn, ctx: JsContext<JsNode>) {
if (x.returnTarget != null && function.functionDescriptor != x.returnTarget) return
ctx.removeMe()
val returnReplacement = getReturnReplacement(x.expression)
if (returnReplacement != null) {
ctx.addNext(JsExpressionStatement(returnReplacement).apply { synthetic = true })
}
if (breakLabel != null) {
ctx.addNext(JsBreak(breakLabel))
}
}
private fun getReturnReplacement(returnExpression: JsExpression?): JsExpression? {
return if (returnExpression != null) {
val assignment = resultRef?.let { lhs ->
val rhs = processCoroutineResult(returnExpression)!!
JsAstUtils.assignment(lhs, rhs).apply { synthetic = true }
}
assignment ?: processCoroutineResult(returnExpression)
}
else {
processCoroutineResult(null)
}
}
fun processCoroutineResult(expression: JsExpression?): JsExpression? {
if (!isSuspend) return expression
val lhs = JsNameRef("\$\$coroutineResult\$\$", JsAstUtils.stateMachineReceiver()).apply { coroutineResult = true }
return JsAstUtils.assignment(lhs, expression ?: Namer.getUndefinedExpression())
}
} | apache-2.0 | 28fb9d748c61dda7438cd679862f42bb | 35.810811 | 122 | 0.682703 | 4.576471 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/AbstractKotlinUVariable.kt | 1 | 6413 | // 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.uast.kotlin
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.asJava.elements.KtLightAbstractAnnotation
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable
@ApiStatus.Internal
abstract class AbstractKotlinUVariable(
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), PsiVariable, UVariableEx, UAnchorOwner {
override val uastInitializer: UExpression?
get() {
val psi = psi
val initializerExpression = when (psi) {
is UastKotlinPsiVariable -> psi.ktInitializer
is UastKotlinPsiParameter -> psi.ktDefaultValue
is KtLightElement<*, *> -> {
val origin = psi.kotlinOrigin?.takeIf { it.canAnalyze() } // EA-137191
when (origin) {
is KtVariableDeclaration -> origin.initializer
is KtParameter -> origin.defaultValue
else -> null
}
}
else -> null
} ?: return null
return languagePlugin?.convertElement(initializerExpression, this) as? UExpression ?: UastEmptyExpression(null)
}
protected val delegateExpression: UExpression? by lz {
val psi = psi
val expression = when (psi) {
is KtLightElement<*, *> -> (psi.kotlinOrigin as? KtProperty)?.delegateExpression
is UastKotlinPsiVariable -> (psi.ktElement as? KtProperty)?.delegateExpression
else -> null
}
expression?.let { languagePlugin?.convertElement(it, this) as? UExpression }
}
override fun getNameIdentifier(): PsiIdentifier {
val kotlinOrigin = (psi as? KtLightElement<*, *>)?.kotlinOrigin
return UastLightIdentifier(psi, kotlinOrigin as? KtDeclaration)
}
override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile)
override val uAnnotations by lz {
val sourcePsi = sourcePsi ?: return@lz psi.annotations.map { WrappedUAnnotation(it, this) }
val annotations = SmartList<UAnnotation>(KotlinNullabilityUAnnotation(baseResolveProviderService, sourcePsi, this))
if (sourcePsi is KtModifierListOwner) {
sourcePsi.annotationEntries
.filter { acceptsAnnotationTarget(it.useSiteTarget?.getAnnotationUseSiteTarget()) }
.mapTo(annotations) { baseResolveProviderService.baseKotlinConverter.convertAnnotation(it, this) }
}
annotations
}
protected abstract fun acceptsAnnotationTarget(target: AnnotationUseSiteTarget?): Boolean
override val typeReference: UTypeReferenceExpression? by lz {
KotlinUTypeReferenceExpression((sourcePsi as? KtCallableDeclaration)?.typeReference, this) { type }
}
override val uastAnchor: UIdentifier?
get() {
val identifierSourcePsi = when (val sourcePsi = sourcePsi) {
is KtNamedDeclaration -> sourcePsi.nameIdentifier
is KtTypeReference -> sourcePsi.typeElement?.let {
// receiver param in extension function
(it as? KtUserType)?.referenceExpression?.getIdentifier() ?: it
} ?: sourcePsi
is KtNameReferenceExpression -> sourcePsi.getReferencedNameElement()
is KtBinaryExpression, is KtCallExpression -> null // e.g. `foo("Lorem ipsum") ?: foo("dolor sit amet")`
is KtDestructuringDeclaration -> sourcePsi.valOrVarKeyword
is KtLambdaExpression -> sourcePsi.functionLiteral.lBrace
else -> sourcePsi
} ?: return null
return KotlinUIdentifier(nameIdentifier, identifierSourcePsi, this)
}
override fun equals(other: Any?) = other is AbstractKotlinUVariable && psi == other.psi
class WrappedUAnnotation(
psiAnnotation: PsiAnnotation,
override val uastParent: UElement
) : UAnnotation, UAnchorOwner, DelegatedMultiResolve {
override val javaPsi: PsiAnnotation = psiAnnotation
override val psi: PsiAnnotation = javaPsi
override val sourcePsi: PsiElement? = psiAnnotation.safeAs<KtLightAbstractAnnotation>()?.kotlinOrigin
override val attributeValues: List<UNamedExpression> by lz {
psi.parameterList.attributes.map { WrappedUNamedExpression(it, this) }
}
override val uastAnchor: UIdentifier by lz {
KotlinUIdentifier(
{ javaPsi.nameReferenceElement?.referenceNameElement },
sourcePsi.safeAs<KtAnnotationEntry>()?.typeReference?.nameElement,
this
)
}
class WrappedUNamedExpression(
pair: PsiNameValuePair,
override val uastParent: UElement?
) : UNamedExpression {
override val name: String? = pair.name
override val psi = pair
override val javaPsi: PsiElement = psi
override val sourcePsi: PsiElement? = null
override val uAnnotations: List<UAnnotation> = emptyList()
override val expression: UExpression by lz { toUExpression(psi.value) }
}
override val qualifiedName: String? = psi.qualifiedName
override fun findAttributeValue(name: String?): UExpression? =
psi.findAttributeValue(name)?.let { toUExpression(it) }
override fun findDeclaredAttributeValue(name: String?): UExpression? =
psi.findDeclaredAttributeValue(name)?.let { toUExpression(it) }
override fun resolve(): PsiClass? =
psi.nameReferenceElement?.resolve() as? PsiClass
}
}
private fun toUExpression(psi: PsiElement?): UExpression = psi.toUElementOfType() ?: UastEmptyExpression(null)
| apache-2.0 | 4fd61f3d22b8dc9ce9b807871ab53778 | 44.48227 | 158 | 0.667862 | 5.824705 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/codeVision/CodeVisionHost.kt | 1 | 21767 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.codeVision
import com.intellij.codeInsight.codeVision.settings.CodeVisionGroupDefaultSettingModel
import com.intellij.codeInsight.codeVision.settings.CodeVisionSettings
import com.intellij.codeInsight.codeVision.settings.CodeVisionSettingsLiveModel
import com.intellij.codeInsight.codeVision.ui.CodeVisionView
import com.intellij.codeInsight.codeVision.ui.model.PlaceholderCodeVisionEntry
import com.intellij.codeInsight.codeVision.ui.model.RichTextCodeVisionEntry
import com.intellij.codeInsight.codeVision.ui.model.richText.RichText
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.hints.InlayGroup
import com.intellij.codeInsight.hints.settings.InlayHintsConfigurable
import com.intellij.codeInsight.hints.settings.language.isInlaySettingsEditor
import com.intellij.ide.plugins.DynamicPluginListener
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.lang.Language
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorKind
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.openapi.fileEditor.*
import com.intellij.openapi.fileEditor.impl.BaseRemoteFileEditor
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.rd.createLifetime
import com.intellij.openapi.rd.createNestedDisposable
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.SyntaxTraverser
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.Alarm
import com.intellij.util.application
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import com.jetbrains.rd.util.error
import com.jetbrains.rd.util.getLogger
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.lifetime.SequentialLifetimes
import com.jetbrains.rd.util.lifetime.onTermination
import com.jetbrains.rd.util.reactive.Signal
import com.jetbrains.rd.util.reactive.whenTrue
import com.jetbrains.rd.util.trace
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.CompletableFuture
open class CodeVisionHost(val project: Project) {
companion object {
private val logger = getLogger<CodeVisionHost>()
@JvmStatic
fun getInstance(project: Project): CodeVisionHost = project.getService(CodeVisionHost::class.java)
const val defaultVisibleLenses = 5
const val settingsLensProviderId = "!Settings"
const val moreLensProviderId = "!More"
/**
* Flag which is enabled when executed test in [com.intellij.java.codeInsight.codeVision.CodeVisionTestCase].
* Code vision can access different files during its work (and it is expected, e.g. references). So it is better to disable
* particular implementations of code vision to make sure that other tests' performance is not hurt.
*/
val isCodeVisionTestKey: Key<Boolean> = Key.create("code.vision.test")
private val editorTrackingStart: Key<Long> = Key.create("editor.tracking.start")
/**
* Returns true iff we are in test in [com.intellij.java.codeInsight.codeVision.CodeVisionTestCase].
*/
@JvmStatic
fun isCodeLensTest(editor: Editor): Boolean {
return editor.project?.getUserData(isCodeVisionTestKey) == true
}
}
protected val codeVisionLifetime = project.createLifetime()
/**
* Pass empty list to update ALL providers in editor
*/
data class LensInvalidateSignal(val editor: Editor?, val providerIds: Collection<String> = emptyList())
val invalidateProviderSignal: Signal<LensInvalidateSignal> = Signal()
private val defaultSortedProvidersList = mutableListOf<String>()
@Suppress("MemberVisibilityCanBePrivate")
// Uses in Rider
protected val lifeSettingModel = CodeVisionSettingsLiveModel(codeVisionLifetime)
var providers: List<CodeVisionProvider<*>> = CodeVisionProviderFactory.createAllProviders(project)
init {
lifeSettingModel.isRegistryEnabled.whenTrue(codeVisionLifetime) { enableCodeVisionLifetime ->
ApplicationManager.getApplication().invokeLater {
runReadAction {
if (project.isDisposed) return@runReadAction
val liveEditorList = ProjectEditorLiveList(enableCodeVisionLifetime, project)
liveEditorList.editorList.view(enableCodeVisionLifetime) { editorLifetime, editor ->
if (isEditorApplicable(editor)) {
subscribeForFrontendEditor(editorLifetime, editor)
}
}
val viewService = project.service<CodeVisionView>()
viewService.setPerAnchorLimits(
CodeVisionAnchorKind.values().associateWith { (lifeSettingModel.getAnchorLimit(it) ?: defaultVisibleLenses) })
invalidateProviderSignal.advise(enableCodeVisionLifetime) { invalidateSignal ->
if (invalidateSignal.editor == null && invalidateSignal.providerIds.isEmpty())
viewService.setPerAnchorLimits(
CodeVisionAnchorKind.values().associateWith { (lifeSettingModel.getAnchorLimit(it) ?: defaultVisibleLenses) })
}
lifeSettingModel.visibleMetricsAboveDeclarationCount.advise(codeVisionLifetime) {
invalidateProviderSignal.fire(LensInvalidateSignal(null, emptyList()))
}
lifeSettingModel.visibleMetricsNextToDeclarationCount.advise(codeVisionLifetime) {
invalidateProviderSignal.fire(LensInvalidateSignal(null, emptyList()))
}
rearrangeProviders()
project.messageBus.connect(enableCodeVisionLifetime.createNestedDisposable())
.subscribe(DynamicPluginListener.TOPIC,
object : DynamicPluginListener {
private fun recollectAndRearrangeProviders() {
providers = CodeVisionProviderFactory.createAllProviders(
project)
rearrangeProviders()
}
override fun pluginLoaded(pluginDescriptor: IdeaPluginDescriptor) {
recollectAndRearrangeProviders()
}
override fun pluginUnloaded(pluginDescriptor: IdeaPluginDescriptor,
isUpdate: Boolean) {
recollectAndRearrangeProviders()
}
})
project.messageBus.connect(enableCodeVisionLifetime.createNestedDisposable())
.subscribe(CodeVisionSettings.CODE_LENS_SETTINGS_CHANGED, object : CodeVisionSettings.CodeVisionSettingsListener {
override fun groupPositionChanged(id: String, position: CodeVisionAnchorKind) {
}
override fun providerAvailabilityChanged(id: String, isEnabled: Boolean) {
PsiManager.getInstance(project).dropPsiCaches()
DaemonCodeAnalyzer.getInstance(project).restart()
}
})
}
}
}
}
// run in read action
fun collectPlaceholders(editor: Editor,
psiFile: PsiFile?): List<Pair<TextRange, CodeVisionEntry>> {
if (!lifeSettingModel.isEnabledWithRegistry.value) return emptyList()
val project = editor.project ?: return emptyList()
if (psiFile != null && psiFile.virtualFile != null &&
!ProjectRootManager.getInstance(project).fileIndex.isInSourceContent(psiFile.virtualFile)) return emptyList()
val bypassBasedCollectors = ArrayList<Pair<BypassBasedPlaceholderCollector, CodeVisionProvider<*>>>()
val placeholders = ArrayList<Pair<TextRange, CodeVisionEntry>>()
val settings = CodeVisionSettings.instance()
for (provider in providers) {
if (!settings.isProviderEnabled(provider.groupId)) continue
if (getAnchorForProvider(provider) != CodeVisionAnchorKind.Top) continue
val placeholderCollector: CodeVisionPlaceholderCollector = provider.getPlaceholderCollector(editor, psiFile) ?: continue
if (placeholderCollector is BypassBasedPlaceholderCollector) {
bypassBasedCollectors.add(placeholderCollector to provider)
}
else if (placeholderCollector is GenericPlaceholderCollector) {
for (placeholderRange in placeholderCollector.collectPlaceholders(editor)) {
placeholders.add(placeholderRange to PlaceholderCodeVisionEntry(provider.id))
}
}
}
if (bypassBasedCollectors.isNotEmpty()) {
val traverser = SyntaxTraverser.psiTraverser(psiFile)
for (element in traverser) {
for ((collector, provider) in bypassBasedCollectors) {
for (placeholderRange in collector.collectPlaceholders(element, editor)) {
placeholders.add(placeholderRange to PlaceholderCodeVisionEntry(provider.id))
}
}
}
}
return placeholders
}
protected fun rearrangeProviders() {
val allProviders = collectAllProviders()
defaultSortedProvidersList.clear()
defaultSortedProvidersList.addAll(allProviders.getTopSortedIdList())
}
protected open fun collectAllProviders(): List<Pair<String, CodeVisionProvider<*>>> {
return providers.map { it.id to it }
}
private fun isEditorApplicable(editor: Editor): Boolean {
return editor.editorKind == EditorKind.MAIN_EDITOR || editor.editorKind == EditorKind.UNTYPED
}
fun invalidateProvider(signal: LensInvalidateSignal) {
invalidateProviderSignal.fire(signal)
}
fun getNumber(providerId: String): Int {
if (lifeSettingModel.disabledCodeVisionProviderIds.contains(providerId)) return -1
return defaultSortedProvidersList.indexOf(providerId)
}
open fun handleLensClick(editor: Editor, range: TextRange, entry: CodeVisionEntry) {
//todo intellij statistic
logger.trace { "Handling click for entry with id: ${entry.providerId}" }
if (entry.providerId == settingsLensProviderId) {
openCodeVisionSettings()
return
}
val frontendProvider = providers.firstOrNull { it.id == entry.providerId }
if (frontendProvider != null) {
frontendProvider.handleClick(editor, range, entry)
return
}
logger.trace { "No provider found with id ${entry.providerId}" }
}
open fun handleLensExtraAction(editor: Editor, range: TextRange, entry: CodeVisionEntry, actionId: String) {
if (actionId == settingsLensProviderId) {
val provider = getProviderById(entry.providerId)
openCodeVisionSettings(provider?.groupId)
return
}
val frontendProvider = providers.firstOrNull { it.id == entry.providerId }
if (frontendProvider != null) {
frontendProvider.handleExtraAction(editor, range, actionId)
return
}
logger.trace { "No provider found with id ${entry.providerId}" }
}
protected fun CodeVisionAnchorKind?.nullIfDefault(): CodeVisionAnchorKind? = if (this === CodeVisionAnchorKind.Default) null else this
open fun getAnchorForEntry(entry: CodeVisionEntry): CodeVisionAnchorKind {
val provider = getProviderById(entry.providerId) ?: return lifeSettingModel.defaultPosition.value
return getAnchorForProvider(provider)
}
private fun getAnchorForProvider(provider: CodeVisionProvider<*>): CodeVisionAnchorKind {
return lifeSettingModel.codeVisionGroupToPosition[provider.groupId].nullIfDefault() ?: lifeSettingModel.defaultPosition.value
}
private fun getPriorityForId(id: String): Int {
return defaultSortedProvidersList.indexOf(id)
}
open fun getProviderById(id: String): CodeVisionProvider<*>? {
return providers.firstOrNull { it.id == id }
}
fun getPriorityForEntry(entry: CodeVisionEntry): Int {
return getPriorityForId(entry.providerId)
}
// we are only interested in text editors, and BRFE behaves exceptionally bad so ignore them
private fun isAllowedFileEditor(fileEditor: FileEditor?) = fileEditor is TextEditor && fileEditor !is BaseRemoteFileEditor
private fun subscribeForFrontendEditor(editorLifetime: Lifetime, editor: Editor) {
if (editor.document !is DocumentImpl) return
val calculationLifetimes = SequentialLifetimes(editorLifetime)
val editorManager = FileEditorManager.getInstance(project)
var recalculateWhenVisible = false
var previousLenses: List<Pair<TextRange, CodeVisionEntry>> = ArrayList()
val openTime = System.nanoTime()
editor.putUserData(editorTrackingStart, openTime)
val mergingQueueFront = MergingUpdateQueue(CodeVisionHost::class.simpleName!!, 100, true, null, editorLifetime.createNestedDisposable(),
null, Alarm.ThreadToUse.POOLED_THREAD)
mergingQueueFront.isPassThrough = false
var calcRunning = false
fun recalculateLenses(groupToRecalculate: Collection<String> = emptyList()) {
if (!isInlaySettingsEditor(editor) && !editorManager.selectedEditors.any {
isAllowedFileEditor(it) && (it as TextEditor).editor == editor
}) {
recalculateWhenVisible = true
return
}
recalculateWhenVisible = false
if (calcRunning && groupToRecalculate.isNotEmpty())
return recalculateLenses(emptyList())
calcRunning = true
val lt = calculationLifetimes.next()
calculateFrontendLenses(lt, editor, groupToRecalculate) { lenses, providersToUpdate ->
val newLenses = previousLenses.filter { !providersToUpdate.contains(it.second.providerId) } + lenses
editor.lensContextOrThrow.setResults(newLenses)
previousLenses = newLenses
calcRunning = false
}
}
fun pokeEditor(providersToRecalculate: Collection<String> = emptyList()) {
editor.lensContextOrThrow.notifyPendingLenses()
val shouldRecalculateAll = mergingQueueFront.isEmpty.not()
mergingQueueFront.cancelAllUpdates()
mergingQueueFront.queue(object : Update("") {
override fun run() {
application.invokeLater(
{ recalculateLenses(if (shouldRecalculateAll) emptyList() else providersToRecalculate) },
ModalityState.stateForComponent(editor.contentComponent))
}
})
}
invalidateProviderSignal.advise(editorLifetime) {
if (it.editor == null || it.editor === editor) {
pokeEditor(it.providerIds)
}
}
editor.lensContextOrThrow.notifyPendingLenses()
recalculateLenses()
application.messageBus.connect(editorLifetime.createNestedDisposable()).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER,
object : FileEditorManagerListener {
override fun selectionChanged(event: FileEditorManagerEvent) {
if (isAllowedFileEditor(
event.newEditor) && (event.newEditor as TextEditor).editor == editor && recalculateWhenVisible)
recalculateLenses()
}
})
editor.document.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
pokeEditor()
}
}, editorLifetime.createNestedDisposable())
editorLifetime.onTermination { editor.lensContextOrThrow.clearLenses() }
}
private fun calculateFrontendLenses(calcLifetime: Lifetime,
editor: Editor,
groupsToRecalculate: Collection<String> = emptyList(),
inTestSyncMode: Boolean = false,
consumer: (List<Pair<TextRange, CodeVisionEntry>>, List<String>) -> Unit) {
val precalculatedUiThings = providers.associate {
if (groupsToRecalculate.isNotEmpty() && !groupsToRecalculate.contains(it.id)) return@associate it.id to null
it.id to it.precomputeOnUiThread(editor)
}
// dropping all lenses if CV disabled
if (lifeSettingModel.isEnabled.value.not()) {
consumer(emptyList(), providers.map { it.id })
return
}
executeOnPooledThread(calcLifetime, inTestSyncMode) {
ProgressManager.checkCanceled()
var results = mutableListOf<Pair<TextRange, CodeVisionEntry>>()
val providerWhoWantToUpdate = mutableListOf<String>()
var everyProviderReadyToUpdate = true
val inlaySettingsEditor = isInlaySettingsEditor(editor)
val editorOpenTime = editor.getUserData(editorTrackingStart)
val watcher = project.service<CodeVisionProvidersWatcher>()
providers.forEach {
@Suppress("UNCHECKED_CAST")
it as CodeVisionProvider<Any?>
if (!inlaySettingsEditor && !lifeSettingModel.disabledCodeVisionProviderIds.contains(it.groupId)) {
if (!it.shouldRecomputeForEditor(editor, precalculatedUiThings[it.id])) {
everyProviderReadyToUpdate = false
return@forEach
}
}
if (groupsToRecalculate.isNotEmpty() && !groupsToRecalculate.contains(it.id)) return@forEach
ProgressManager.checkCanceled()
if (project.isDisposed) return@executeOnPooledThread
if (!inlaySettingsEditor && lifeSettingModel.disabledCodeVisionProviderIds.contains(it.groupId)) {
if (editor.lensContextOrThrow.hasProviderCodeVision(it.id)) {
providerWhoWantToUpdate.add(it.id)
}
return@forEach
}
providerWhoWantToUpdate.add(it.id)
try {
val state = it.computeCodeVision(editor, precalculatedUiThings[it.id])
if (state.isReady.not()) {
if (editorOpenTime != null) {
watcher.reportProvider(it.groupId, System.nanoTime() - editorOpenTime)
if (watcher.shouldConsiderProvider(it.groupId)) {
everyProviderReadyToUpdate = false
}
}
else {
everyProviderReadyToUpdate = false
}
}
else {
watcher.dropProvider(it.groupId)
results.addAll(state.result)
}
}
catch (e: Exception) {
if (e is ControlFlowException) throw e
logger.error("Exception during computeForEditor for ${it.id}", e)
}
}
val previewData = CodeVisionGroupDefaultSettingModel.isEnabledInPreview(editor)
if (previewData == false) {
results = results.map {
val richText = RichText()
richText.append(it.second.longPresentation, SimpleTextAttributes(SimpleTextAttributes.STYLE_STRIKEOUT, null))
val entry = RichTextCodeVisionEntry(it.second.providerId, richText)
it.first to entry
}.toMutableList()
}
if (!everyProviderReadyToUpdate) {
editor.lensContextOrThrow.discardPending()
return@executeOnPooledThread
}
if (providerWhoWantToUpdate.isEmpty()) {
editor.lensContextOrThrow.discardPending()
return@executeOnPooledThread
}
if (!inTestSyncMode) {
application.invokeLater({
calcLifetime.executeIfAlive { consumer(results, providerWhoWantToUpdate) }
}, ModalityState.stateForComponent(editor.component))
}
else {
consumer(results, providerWhoWantToUpdate)
}
}
}
private fun executeOnPooledThread(lifetime: Lifetime, inTestSyncMode: Boolean, runnable: () -> Unit): ProgressIndicator {
val indicator = EmptyProgressIndicator()
indicator.start()
if (!inTestSyncMode) {
CompletableFuture.runAsync(
{ ProgressManager.getInstance().runProcess(runnable, indicator) },
AppExecutorUtil.getAppExecutorService()
)
lifetime.onTermination {
if (indicator.isRunning) indicator.cancel()
}
}
else {
runnable()
}
return indicator
}
protected open fun openCodeVisionSettings(groupId: String? = null) {
InlayHintsConfigurable.showSettingsDialogForLanguage(project, Language.ANY) {
if (groupId == null) return@showSettingsDialogForLanguage it.group == InlayGroup.CODE_VISION_GROUP_NEW
return@showSettingsDialogForLanguage it.group == InlayGroup.CODE_VISION_GROUP_NEW && it.id == groupId
}
}
@TestOnly
fun calculateCodeVisionSync(editor: Editor, testRootDisposable: Disposable) {
calculateFrontendLenses(testRootDisposable.createLifetime(), editor, inTestSyncMode = true) { lenses, _ ->
editor.lensContextOrThrow.setResults(lenses)
}
}
} | apache-2.0 | fc8222fcc4cd5bcde611e385902c764b | 41.432749 | 189 | 0.692241 | 5.150734 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/attic/attic--SpitCompareOperationsPage.kt | 1 | 6981 | //package alraune
//
//import alraune.*
//import vgrechka.*
//
//class class SpitCompareOperationsPage : SpitPage {
// override fun spit() {Spit()}
// class Spit {
// val params = AlGetParams()
// val operationId = listOf(
// getParamOrBailOut(params.id1),
// getParamOrBailOut(params.id2))
//
// val operations = operationId.map {
// dbSelectMaybeOperationById(it)
// ?: bailOutToLittleErrorPage(rawHtml(t("TOTE", "Операции с ID <b>$it</b> не существует")))
// }
//
// init {
// operations.forEach {
// if (it.orderId == null)
// bailOutToLittleErrorPage(t("TOTE", "Операция <b>${it.id} не относится к заказам</b>"))
// }
// if (operations[0].orderId != operations[1].orderId)
// bailOutToLittleErrorPage(t("TOTE", "Операции относятся к разным заказам. Толку их сравнивать?"))
// }
// val operation0 = operations[0]; val operation1 = operations[1]
//
// val afterness = mutableListOf(
// params.afterness1.get() ?: Afterness.Before,
// params.afterness2.get() ?: Afterness.After)
//
// val afternessSelectDomid = listOf(nextJsIdent(), nextJsIdent())
//
// init {
// for (i in 0..1)
// if (!info[i].hasStateBefore())
// afterness[i] = Afterness.After
//
// val currentOrder = when (operation0) {
// is OperationInfo.UpdateOrder_V1 -> dbSelectOrderById(operation0.data.orderAfterOperation.id)
// else -> null
// }
//
// rctx2.htmlHeadTitle = when {
// currentOrder != null ->
// AlText.shortOrder(currentOrder.id) + ": " +
// AlText.shortOperation(operation0.operationId) + " ${AlText.leftRightArrow} " +
// AlText.shortOperation(operation1.operationId)
// else -> wtf()
// }
//
// spitUsualPage_withNewContext1 {
// composeMinimalMainContainer {
// oo(composePageHeader(t("TOTE", "Сравниваем операции ${AlText.numString(operation0.operationId)} и ${AlText.numString(operation1.operationId)}")))
//
// val tableStyle = nextJsIdent()
// drooStylesheet("""
// .$tableStyle td {padding: 4px;}
// .$tableStyle td:first-child {padding-left: 0px;}
// """)
//
// oo(div().style("margin-top: 1em;").with {
// if (currentOrder != null) {
// oo(div().with {
// oo(span(t("TOTE", "Заказ ") + AlText.numString(currentOrder.id))
// .style("font-weight: bold;"))
// oo(span(currentOrder.documentTitle)
// .style("margin-left: 0.5em;"))
// })
// }
//
// oo(table().className(tableStyle).with {
// oo(tr().with {
// oo(td().style("text-align: left;").add(t("TOTE", "Сравнить состояние")))
// oo(td().add(composeAfternessSelect(0)))
// oo(td().add(composeOperationDescrLine("1.", info[0])))
// })
// oo(tr().with {
// oo(td().style("text-align: left;").add(t("TOTE", "с состоянием")))
// oo(td().add(composeAfternessSelect(1)))
// oo(td().add(composeOperationDescrLine("2.", info[1])))
// })
// })
// })
//
// oo(div().style("margin-top: 0.5em;").with {
// oo(composeButton_primary(t("TOTE", "Поджигай"))
// .attachOnClickWhenDomReady("""
// const href = ${jsStringLiteral(makeUrlPart(`attic--SpitCompareOperationsPage`::class) {})}
// + "?${params.id1.name}=" + ${jsStringLiteral("" + operationId[0])}
// + "&${params.afterness1.name}=" + ${jsByIDSingle(afternessSelectDomid[0])}.val()
// + "&${params.id2.name}=" + ${jsStringLiteral("" + operationId[1])}
// + "&${params.afterness2.name}=" + ${jsByIDSingle(afternessSelectDomid[1])}.val()
// // console.log('href', href)
// ${!JsProgressyNavigate().jsHref("href")}
// """))
// })
//
// oo(div().style("margin-top: 1em; padding-top: 1em; border-top: 2px solid ${Color.Gray500};").with {
// when {
// operation0 is OperationInfo.UpdateOrder_V1 && operation1 is OperationInfo.UpdateOrder_V1 -> {
// val entity0 = bang(when (afterness[0]) {
// Afterness.Before -> operation0.data.orderBeforeOperation
// Afterness.After -> operation0.data.orderAfterOperation
// })
// val entity1 = bang(when (afterness[1]) {
// Afterness.Before -> operation1.data.orderBeforeOperation
// Afterness.After -> operation1.data.orderAfterOperation
// })
// drooOrderParamsComparison(entity0, entity1)
// }
// else -> wtf()
// }
// })
// }
// }
// }
//
// fun composeOperationDescrLine(num: String, info: OperationInfo) =
// divFlexCenter().with {
// oo(span().style("font-weight: bold; margin-right: 0.5em;")
// .add(num))
// oo(composeOperationTitle2(info))
// }
//
// fun composeAfternessSelect(index: Int): AlTag {
// val paramValue = afterness[index]
// return select().id(afternessSelectDomid[index]).className("form-control").style("width: inherit;").with {
// if (info[index].hasStateBefore())
// oo(option().value(Afterness.Before.name).selected(paramValue == Afterness.Before).add(t("TOTE", "до")))
// oo(option().value(Afterness.After.name).selected(paramValue == Afterness.After).add(t("TOTE", "после")))
// }
// }
// }
//
//}
| apache-2.0 | 6da52d1737c3b66b165c015b4c5b0872 | 48.405797 | 167 | 0.452332 | 3.994142 | false | false | false | false |
androidx/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/suspendfun/SuspendDoubleTapToLikeDemo.kt | 3 | 4392 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.demos.suspendfun
import androidx.compose.animation.core.animate
import androidx.compose.foundation.MutatorMutex
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.tooling.preview.Preview
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
@Preview
@Composable
fun SuspendDoubleTapToLikeDemo() {
var alpha by remember { mutableStateOf(0f) }
var scale by remember { mutableStateOf(0f) }
val mutatorMutex = MutatorMutex()
val scope = rememberCoroutineScope()
Box(
Modifier.fillMaxSize().background(Color.White).pointerInput(Unit) {
detectTapGestures(
onDoubleTap = {
scope.launch {
// MutatorMutex cancels the previous job (i.e. animations) before starting
// a new job. This ensures the mutable states only being mutated by one
// animation at a time.
mutatorMutex.mutate {
coroutineScope {
// `launch` creates a new coroutine without blocking. This allows
// the two animations in this CoroutineScope to run together.
launch {
animate(0f, 1f) { value, _ ->
alpha = value
}
}
launch {
animate(0f, 2f) { value, _ ->
scale = value
}
}
}
// CoroutineScope doesn't return until all animations in the scope
// finish. So by the time we get here, the enter animations from the
// previous CoroutineScope have all finished.
coroutineScope {
launch {
animate(alpha, 0f) { value, _ ->
alpha = value
}
}
launch {
animate(scale, 4f) { value, _ ->
scale = value
}
}
}
}
}
}
)
}
) {
Icon(
Icons.Filled.Favorite,
"Like",
Modifier.align(Alignment.Center)
.graphicsLayer(
alpha = alpha,
scaleX = scale,
scaleY = scale
),
tint = Color.Red
)
}
}
| apache-2.0 | 5de4ff52b7877954f3a9cdeb4445f596 | 40.046729 | 98 | 0.537568 | 5.76378 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/hints/ranges/simple.kt | 4 | 2589 | val range = 0<# ≤ #>..<# ≤ #>10
val rangeUntil = 0<# ≤ #>..<10
val errorRange = 4downTo 0
class Foo : Comparable<Foo> {
override fun compareTo(other: Foo): Int = TODO("Not yet implemented")
}
fun foo() {
// rangeTo and rangeUntil are not an infix functions and shouldn't have hints
for (index in 0 rangeTo 100) {}
for (index in 0 rangeUntil 100) {}
for (index in 0.rangeTo(100)) {}
for (index in 'a'.rangeTo('z')) {}
for (index in 0L.rangeTo(100L)) {}
for (index in Foo().rangeTo(Foo())) {}
for (index in 0.0.rangeTo(100.0)) {}
for (index in 0f.rangeTo(100f)) {}
for (index in 0<# ≤ #> .. <# ≤ #>100) {}
for (index in 'a'<# ≤ #> .. <# ≤ #>'z') {}
for (index in 0L<# ≤ #> .. <# ≤ #>100L) {}
for (index in Foo()<# ≤ #> .. <# ≤ #>Foo()) {}
for (index in 0.0<# ≤ #> .. <# ≤ #>100.0) {}
for (index in 0f<# ≤ #> .. <# ≤ #>100f) {}
for (index in 0<# ≤ #> ..< 100) {}
for (index in 'a'<# ≤ #> ..< 'z') {}
for (index in 0.0<# ≤ #> ..< 100.0) {}
for (index in 0f<# ≤ #> ..< 100f) {}
for (index in 0.rangeUntil(100)) {}
for (index in 'a'.rangeUntil('z')) {}
for (index in 0L.rangeUntil(100L)) {}
for (index in Foo().rangeUntil(Foo())) {}
for (index in 0.0.rangeUntil(100.0)) {}
for (index in 0f.rangeUntil(100f)) {}
for (index in 0<# ≤ #> until <# < #>100) {}
for (index in 'a'<# ≤ #> until <# < #>'z') {}
for (index in 0L<# ≤ #> until <# < #>100L) {}
for (index in 100<# ≥ #> downTo <# ≥ #>0) {}
for (index in 'z'<# ≥ #> downTo <# ≥ #>'a') {}
for (index in 100L<# ≥ #> downTo <# ≥ #>0L) {}
for (i in 0 until 0<# ≤ #>..<# ≤ #>5 ) {}
for (i in 1<# ≤ #> until <# < #>10 step 2) {}
run {
val left: Short = 0
val right: Short = 10
for (i in left.rangeTo(right)) {}
for (i in left<# ≤ #> .. <# ≤ #>right) {}
for (i in left<# ≤ #> ..< right) {}
for (i in left<# ≤ #> until <# < #>right) {}
for (index in right<# ≥ #> downTo <# ≥ #>left) {}
for (index in left.rangeUntil(right)) {}
}
for (index in someVeryVeryLongLongLongLongFunctionName(0)<# ≤ #> .. <# ≤ #>someVeryVeryLongLongLongLongFunctionName(100)) {}
}
private infix fun Int.until(intRange: IntRange): IntRange = TODO()
private fun someVeryVeryLongLongLongLongFunctionName(x: Int): Int = x
private fun check(x: Int, y: Int) {
val b = x in 8<# ≤ #>..<# ≤ #>9
if (x in 7<# ≤ #>..<# ≤ #>9 && y in 5<# ≤ #>..<# ≤ #>9) {
}
}
| apache-2.0 | fa2a2855a60087260cbb7bedf3a357b2 | 32.77027 | 128 | 0.487395 | 2.689989 | false | false | false | false |
GunoH/intellij-community | plugins/eclipse/src/org/jetbrains/idea/eclipse/config/EclipseModuleManagerSerializer.kt | 2 | 5029 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.eclipse.config
import com.intellij.workspaceModel.ide.impl.jps.serialization.CustomModuleComponentSerializer
import com.intellij.workspaceModel.ide.impl.jps.serialization.ErrorReporter
import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsFileContentReader
import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsFileContentWriter
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jdom.Element
import org.jetbrains.idea.eclipse.config.EclipseModuleManagerImpl.*
import org.jetbrains.jps.eclipse.model.JpsEclipseClasspathSerializer
import org.jetbrains.jps.model.serialization.JDomSerializationUtil
import org.jetbrains.jps.model.serialization.JpsProjectLoader
/**
* Implements loading and saving configuration from [EclipseModuleManagerImpl] in iml file when workspace model is used
*/
class EclipseModuleManagerSerializer : CustomModuleComponentSerializer {
override fun loadComponent(builder: MutableEntityStorage,
moduleEntity: ModuleEntity,
reader: JpsFileContentReader,
imlFileUrl: VirtualFileUrl,
errorReporter: ErrorReporter,
virtualFileManager: VirtualFileUrlManager) {
val componentTag = reader.loadComponent(imlFileUrl.url, "EclipseModuleManager") ?: return
val entity = builder.addEclipseProjectPropertiesEntity(moduleEntity, moduleEntity.entitySource)
builder.modifyEntity(entity) {
componentTag.getChildren(LIBELEMENT).forEach {
eclipseUrls.add(virtualFileManager.fromUrl(it.getAttributeValue(VALUE_ATTR)!!))
}
componentTag.getChildren(VARELEMENT).forEach {
variablePaths = variablePaths.toMutableMap().also { map -> map[it.getAttributeValue(VAR_ATTRIBUTE)!!] =
it.getAttributeValue(PREFIX_ATTR, "") + it.getAttributeValue(VALUE_ATTR) }
}
componentTag.getChildren(CONELEMENT).forEach {
unknownCons.add(it.getAttributeValue(VALUE_ATTR)!!)
}
forceConfigureJdk = componentTag.getAttributeValue(FORCED_JDK)?.toBoolean() ?: false
val srcDescriptionTag = componentTag.getChild(SRC_DESCRIPTION)
if (srcDescriptionTag != null) {
expectedModuleSourcePlace = srcDescriptionTag.getAttributeValue(EXPECTED_POSITION)?.toInt() ?: 0
srcDescriptionTag.getChildren(SRC_FOLDER).forEach {
srcPlace = srcPlace.toMutableMap().also { map ->
map[it.getAttributeValue(VALUE_ATTR)!!] = it.getAttributeValue(EXPECTED_POSITION)!!.toInt()
}
}
}
}
}
override fun saveComponent(moduleEntity: ModuleEntity, imlFileUrl: VirtualFileUrl, writer: JpsFileContentWriter) {
val moduleOptions = moduleEntity.customImlData?.customModuleOptions
if (moduleOptions != null && moduleOptions[JpsProjectLoader.CLASSPATH_ATTRIBUTE] == JpsEclipseClasspathSerializer.CLASSPATH_STORAGE_ID) {
return
}
val eclipseProperties = moduleEntity.eclipseProperties
if (eclipseProperties == null || eclipseProperties.eclipseUrls.isEmpty() && eclipseProperties.variablePaths.isEmpty()
&& !eclipseProperties.forceConfigureJdk && eclipseProperties.unknownCons.isEmpty()) {
return
}
val componentTag = JDomSerializationUtil.createComponentElement("EclipseModuleManager")
eclipseProperties.eclipseUrls.forEach {
componentTag.addContent(Element(LIBELEMENT).setAttribute(VALUE_ATTR, it.url))
}
eclipseProperties.variablePaths.forEach { name, path ->
val prefix = listOf(SRC_PREFIX, SRC_LINK_PREFIX, LINK_PREFIX).firstOrNull { name.startsWith(it) } ?: ""
val varTag = Element(VARELEMENT)
varTag.setAttribute(VAR_ATTRIBUTE, name.removePrefix(prefix))
if (prefix != "") {
varTag.setAttribute(PREFIX_ATTR, prefix)
}
varTag.setAttribute(VALUE_ATTR, path)
componentTag.addContent(varTag)
}
eclipseProperties.unknownCons.forEach {
componentTag.addContent(Element(CONELEMENT).setAttribute(VALUE_ATTR, it))
}
if (eclipseProperties.forceConfigureJdk) {
componentTag.setAttribute(FORCED_JDK, true.toString())
}
val srcDescriptionTag = Element(SRC_DESCRIPTION)
srcDescriptionTag.setAttribute(EXPECTED_POSITION, eclipseProperties.expectedModuleSourcePlace.toString())
eclipseProperties.srcPlace.forEach { url, position ->
srcDescriptionTag.addContent(Element(SRC_FOLDER).setAttribute(VALUE_ATTR, url).setAttribute(EXPECTED_POSITION, position.toString()))
}
componentTag.addContent(srcDescriptionTag)
writer.saveComponent(imlFileUrl.url, "EclipseModuleManager", componentTag)
}
} | apache-2.0 | ae81083f9f6840c8789a11f8dcfe4a4a | 53.086022 | 141 | 0.74826 | 4.930392 | false | true | false | false |
lnr0626/cfn-templates | base-models/src/main/kotlin/com/lloydramey/cfn/model/resources/Resource.kt | 1 | 1688 | /*
* Copyright 2017 Lloyd Ramey <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lloydramey.cfn.model.resources
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.lloydramey.cfn.model.functions.ReferencableWithAttributes
import com.lloydramey.cfn.model.resources.attributes.ResourceDefinitionAttribute
@Suppress("unused")
@JsonIgnoreProperties("Id", "Attributes")
class Resource<out T : ResourceProperties>(
id: String,
@JsonIgnore val attributes: List<ResourceDefinitionAttribute> = emptyList(),
val properties: T
) : ReferencableWithAttributes(id) {
val type = properties.resourceType
@JsonAnyGetter
fun json() = attributes.associateBy { it.name }
}
inline fun <reified T : ResourceProperties> resource(id: String, vararg attributes: ResourceDefinitionAttribute, init: T.() -> Unit): Resource<T> {
val properties = T::class.java.newInstance()
properties.init()
properties.validate()
return Resource(id = id, attributes = attributes.asList(), properties = properties)
}
| apache-2.0 | 23fe2a3c862693e20286321ec82ea3df | 37.363636 | 147 | 0.761848 | 4.295165 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/uast/uast-kotlin-base/test/org/jetbrains/uast/test/common/kotlin/IndentedPrintingVisitor.kt | 4 | 1320 | // 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.uast.test.common.kotlin
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.uast.UFile
import kotlin.reflect.KClass
abstract class IndentedPrintingVisitor(val shouldIndent: (PsiElement) -> Boolean) : PsiElementVisitor() {
constructor(vararg kClasses: KClass<*>) : this({ psi -> kClasses.any { it.isInstance(psi) } })
private val builder = StringBuilder()
var level = 0
private set
override fun visitElement(element: PsiElement) {
val charSequence = render(element)
if (charSequence != null) {
builder.append(" ".repeat(level))
builder.append(charSequence)
builder.appendLine()
}
val shouldIndent = shouldIndent(element)
if (shouldIndent) level++
element.acceptChildren(this)
if (shouldIndent) level--
}
protected abstract fun render(element: PsiElement): CharSequence?
val result: String
get() = builder.toString()
}
fun IndentedPrintingVisitor.visitUFileAndGetResult(uFile: UFile): String {
uFile.sourcePsi.accept(this)
return result
}
| apache-2.0 | 529352007ced7164d8e429b271084c38 | 32 | 158 | 0.693939 | 4.489796 | false | false | false | false |
kivensolo/UiUsingListView | module-Common/src/main/java/com/kingz/module/wanandroid/fragemnts/UserCollectionFragment.kt | 1 | 5489 | package com.kingz.module.wanandroid.fragemnts
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.animation.ScaleInAnimation
import com.kingz.base.factory.ViewModelFactory
import com.kingz.module.common.R
import com.kingz.module.common.utils.RvUtils
import com.kingz.module.wanandroid.adapter.ArticleAdapter
import com.kingz.module.wanandroid.bean.Article
import com.kingz.module.wanandroid.viewmodel.CollectArticleViewModel
import com.kingz.module.wanandroid.viewmodel.WanAndroidViewModelV2
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.zeke.kangaroo.utils.ZLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* author:ZekeWang
* date:2021/3/29
* description:用户文章收藏页面的Fragment
*
* FIXME 排查有网络请求时,从首页跳转时卡顿的问题
*/
class UserCollectionFragment : CommonFragment<WanAndroidViewModelV2>() {
private lateinit var mRecyclerView: RecyclerView
private var articleAdapter: ArticleAdapter? = null
private var swipeRefreshLayout: SmartRefreshLayout? = null
override val viewModel: CollectArticleViewModel by viewModels {
ViewModelFactory.build { CollectArticleViewModel() }
}
override fun getLayoutResID() = R.layout.fragment_common_page
override fun initView() {
super.initView()
initRecyclerView()
initFABInflate()
}
private fun initRecyclerView() {
ZLog.d("init recyclerView.")
mRecyclerView = rootView?.findViewById(R.id.recycler_view) as RecyclerView
mRecyclerView.apply {
isVerticalScrollBarEnabled = true
layoutManager = LinearLayoutManager(context)
articleAdapter = ArticleAdapter(mType = ArticleAdapter.TYPE_COLLECTION)
articleAdapter?.apply {
adapterAnimation = ScaleInAnimation()
setOnItemClickListener { adapter, view, position ->
if (articleAdapter!!.getDefItemCount() > position) {
openWeb(articleAdapter?.getItem(position))
}
}
//设置文章收藏监听器
likeListener = object : ArticleAdapter.LikeListener {
override fun liked(item: Article, adapterPosition: Int) {
viewModel.changeArticleLike(item, adapterPosition, true)
}
override fun unLiked(item: Article, adapterPosition: Int) {
viewModel.changeArticleLike(item, adapterPosition, false)
}
}
}
adapter = articleAdapter
}
}
private fun initSwipeRefreshLayout() {
swipeRefreshLayout = rootView?.findViewById(R.id.swipeRefreshLayout)!!
swipeRefreshLayout?.apply {
setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
override fun onRefresh(refreshLayout: RefreshLayout) {
ZLog.d("onRefresh")
fireVibrate()
}
override fun onLoadMore(refreshLayout: RefreshLayout) {
// finishLoadMore(2000/*,false*/)//传入false表示加载失败
}
})
}
}
private fun initFABInflate() {
val fabView = rootView?.findViewById<View>(R.id.app_fab_btn)
fabView?.setOnClickListener {
RvUtils.smoothScrollTop(mRecyclerView)
}
}
override fun initData() {
super.initData()
ZLog.d("articleAdapter?.itemCount = ${articleAdapter?.itemCount}")
getMyCollectArticalData()
}
override fun initViewModel() {
super.initViewModel()
viewModel.userCollectArticleListLiveData.observe(this, Observer {
ZLog.d("userCollectArticalListLiveData onChanged: $it")
if (it == null) {
ZLog.d("User collection data is null.")
swipeRefreshLayout?.apply {
finishRefresh()
visibility = View.GONE
}
showErrorStatus()
return@Observer
}
dismissLoading()
swipeRefreshLayout?.visibility = View.VISIBLE
loadStatusView?.visibility = View.GONE
launchIO {
val datas = it.datas
ZLog.d("collectionList Size = ${datas?.size};")
//当前数据为空时
if (articleAdapter?.getDefItemCount() == 0) {
withContext(Dispatchers.Main) {
articleAdapter?.addData(datas!!)
}
return@launchIO
}
// 数据非空时
val currentFirstData = articleAdapter?.getItem(0)
if (currentFirstData?.id != datas!![0].id) {
withContext(Dispatchers.Main) {
articleAdapter?.addData(datas)
}
}
}
})
}
private fun getMyCollectArticalData() {
viewModel.getCollectArticleData()
}
} | gpl-2.0 | 145957992de0c325eeea86a9f6101707 | 34.315789 | 83 | 0.614682 | 5.190522 | false | false | false | false |
jwren/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/EntityStorageExtensions.kt | 2 | 14289 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
// ------------------------- Updating references ------------------------
@Suppress("unused")
fun WorkspaceEntityStorage.updateOneToManyChildrenOfParent(connectionId: ConnectionId,
parent: WorkspaceEntity,
children: Sequence<WorkspaceEntity>) {
(this as WorkspaceEntityStorageBuilderImpl).updateOneToManyChildrenOfParent(connectionId, (parent as WorkspaceEntityBase).id,
children.map { (it as WorkspaceEntityBase).id.asChild() })
}
internal fun WorkspaceEntityStorageBuilderImpl.updateOneToManyChildrenOfParent(connectionId: ConnectionId,
parentId: EntityId,
childrenIds: Sequence<ChildEntityId>) {
if (!connectionId.isParentNullable) {
val existingChildren = extractOneToManyChildrenIds(connectionId, parentId).toHashSet()
childrenIds.forEach {
existingChildren.remove(it.id)
}
existingChildren.forEach { removeEntity(it) }
}
refs.updateOneToManyChildrenOfParent(connectionId, parentId.arrayId, childrenIds)
}
@Suppress("unused")
fun WorkspaceEntityStorage.updateOneToAbstractManyChildrenOfParent(connectionId: ConnectionId,
parent: WorkspaceEntity,
children: Sequence<WorkspaceEntity>) {
(this as WorkspaceEntityStorageBuilderImpl).updateOneToAbstractManyChildrenOfParent(connectionId,
(parent as WorkspaceEntityBase).id.asParent(),
children.map { (it as WorkspaceEntityBase).id.asChild() })
}
internal fun WorkspaceEntityStorageBuilderImpl.updateOneToAbstractManyChildrenOfParent(connectionId: ConnectionId,
parentId: ParentEntityId,
childrenIds: Sequence<ChildEntityId>) {
refs.updateOneToAbstractManyChildrenOfParent(connectionId, parentId, childrenIds)
}
@Suppress("unused")
fun WorkspaceEntityStorage.updateOneToAbstractOneChildOfParent(connectionId: ConnectionId,
parent: WorkspaceEntity,
child: WorkspaceEntity?) {
(this as WorkspaceEntityStorageBuilderImpl).updateOneToAbstractOneChildOfParent(connectionId,
(parent as WorkspaceEntityBase).id.asParent(),
(child as? WorkspaceEntityBase)?.id?.asChild())
}
internal fun WorkspaceEntityStorageBuilderImpl.updateOneToAbstractOneChildOfParent(connectionId: ConnectionId,
parentId: ParentEntityId,
childId: ChildEntityId?) {
if (childId != null) {
refs.updateOneToAbstractOneChildOfParent(connectionId, parentId, childId)
}
else {
refs.removeOneToAbstractOneRefByParent(connectionId, parentId)
}
}
@Suppress("unused")
fun WorkspaceEntityStorage.updateOneToOneChildOfParent(connectionId: ConnectionId,
parent: WorkspaceEntity,
childEntity: WorkspaceEntity?) {
(this as WorkspaceEntityStorageBuilderImpl).updateOneToOneChildOfParent(connectionId, (parent as WorkspaceEntityBase).id,
(childEntity as? WorkspaceEntityBase)?.id?.asChild())
}
internal fun WorkspaceEntityStorageBuilderImpl.updateOneToOneChildOfParent(connectionId: ConnectionId,
parentId: EntityId,
childEntityId: ChildEntityId?) {
if (childEntityId != null) {
refs.updateOneToOneChildOfParent(connectionId, parentId.arrayId, childEntityId)
}
else {
refs.removeOneToOneRefByParent(connectionId, parentId.arrayId)
}
}
@Suppress("unused")
fun <Parent : WorkspaceEntityBase> WorkspaceEntityStorage.updateOneToManyParentOfChild(connectionId: ConnectionId,
child: WorkspaceEntity,
parent: Parent?) {
(this as WorkspaceEntityStorageBuilderImpl).updateOneToManyParentOfChild(connectionId, (child as WorkspaceEntityBase).id, parent)
}
internal fun <Parent : WorkspaceEntityBase> WorkspaceEntityStorageBuilderImpl.updateOneToManyParentOfChild(connectionId: ConnectionId,
childId: EntityId,
parent: Parent?) {
if (parent != null) {
refs.updateOneToManyParentOfChild(connectionId, childId.arrayId, parent)
}
else {
refs.removeOneToManyRefsByChild(connectionId, childId.arrayId)
}
}
@Suppress("unused")
fun <Parent : WorkspaceEntityBase> WorkspaceEntityStorage.updateOneToOneParentOfChild(connectionId: ConnectionId,
child: WorkspaceEntity,
parent: Parent?) {
(this as WorkspaceEntityStorageBuilderImpl).updateOneToOneParentOfChild(connectionId, (child as WorkspaceEntityBase).id, parent)
}
internal fun <Parent : WorkspaceEntityBase> WorkspaceEntityStorageBuilderImpl.updateOneToOneParentOfChild(connectionId: ConnectionId,
childId: EntityId,
parent: Parent?) {
if (!connectionId.isParentNullable && parent != null) {
// A very important thing. If we replace a field in one-to-one connection, the previous entity is automatically removed.
val existingChild = extractOneToOneChild<WorkspaceEntityBase>(connectionId, parent.id)
if (existingChild != null) {
removeEntity(existingChild)
}
}
if (parent != null) {
refs.updateOneToOneParentOfChild(connectionId, childId.arrayId, parent)
}
else {
refs.removeOneToOneRefByChild(connectionId, childId.arrayId)
}
}
// ------------------------- Extracting references references ------------------------
@Suppress("unused")
fun <Child : WorkspaceEntity> WorkspaceEntityStorage.extractOneToManyChildren(connectionId: ConnectionId,
parent: WorkspaceEntity): Sequence<Child> {
return (this as AbstractEntityStorage).extractOneToManyChildren(connectionId, (parent as WorkspaceEntityBase).id)
}
@Suppress("UNCHECKED_CAST")
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToManyChildren(connectionId: ConnectionId,
parentId: EntityId): Sequence<Child> {
val entitiesList = entitiesByType[connectionId.childClass] ?: return emptySequence()
return refs.getOneToManyChildren(connectionId, parentId.arrayId)?.map {
val entityData = entitiesList[it]
if (entityData == null) {
if (!brokenConsistency) {
thisLogger().error(
"""Cannot resolve entity.
|Connection id: $connectionId
|Unresolved array id: $it
|All child array ids: ${refs.getOneToManyChildren(connectionId, parentId.arrayId)?.toArray()}
""".trimMargin()
)
}
null
}
else entityData.createEntity(this)
}?.filterNotNull() as? Sequence<Child> ?: emptySequence()
}
internal fun AbstractEntityStorage.extractOneToManyChildrenIds(connectionId: ConnectionId, parentId: EntityId): Sequence<EntityId> {
return refs.getOneToManyChildren(connectionId, parentId.arrayId)?.map { createEntityId(it, connectionId.childClass) } ?: emptySequence()
}
@Suppress("unused")
fun <Child : WorkspaceEntity> WorkspaceEntityStorage.extractOneToAbstractManyChildren(connectionId: ConnectionId,
parent: WorkspaceEntity): Sequence<Child> {
return (this as AbstractEntityStorage).extractOneToAbstractManyChildren(connectionId, (parent as WorkspaceEntityBase).id.asParent())
}
@Suppress("UNCHECKED_CAST")
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToAbstractManyChildren(connectionId: ConnectionId,
parentId: ParentEntityId): Sequence<Child> {
return refs.getOneToAbstractManyChildren(connectionId, parentId)?.asSequence()?.map { pid ->
entityDataByIdOrDie(pid.id).createEntity(this)
} as? Sequence<Child> ?: emptySequence()
}
@Suppress("unused")
fun <Child : WorkspaceEntity> WorkspaceEntityStorage.extractAbstractOneToOneChild(connectionId: ConnectionId,
parent: WorkspaceEntity): Child? {
return (this as AbstractEntityStorage).extractAbstractOneToOneChild(connectionId, (parent as WorkspaceEntityBase).id.asParent())
}
@Suppress("UNCHECKED_CAST")
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractAbstractOneToOneChild(connectionId: ConnectionId,
parentId: ParentEntityId): Child? {
return refs.getAbstractOneToOneChildren(connectionId, parentId)?.let { entityDataByIdOrDie(it.id).createEntity(this) as Child }
}
@Suppress("unused")
fun <Child : WorkspaceEntity> WorkspaceEntityStorage.extractOneToOneChild(connectionId: ConnectionId, parent: WorkspaceEntity): Child? {
return (this as AbstractEntityStorage).extractOneToOneChild(connectionId, (parent as WorkspaceEntityBase).id)
}
@Suppress("UNCHECKED_CAST")
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToOneChild(connectionId: ConnectionId, parentId: EntityId): Child? {
val entitiesList = entitiesByType[connectionId.childClass] ?: return null
return refs.getOneToOneChild(connectionId, parentId.arrayId) {
val childEntityData = entitiesList[it]
if (childEntityData == null) {
if (!brokenConsistency) {
logger<AbstractEntityStorage>().error("""
Consistency issue. Cannot get a child in one to one connection.
Connection id: $connectionId
Parent id: $parentId
Child array id: $it
""".trimIndent())
}
null
}
else childEntityData.createEntity(this) as Child
}
}
@Suppress("unused")
fun <Parent : WorkspaceEntity> WorkspaceEntityStorage.extractOneToOneParent(connectionId: ConnectionId,
child: WorkspaceEntity): Parent? {
return (this as AbstractEntityStorage).extractOneToOneParent(connectionId, (child as WorkspaceEntityBase).id)
}
@Suppress("UNCHECKED_CAST")
internal fun <Parent : WorkspaceEntity> AbstractEntityStorage.extractOneToOneParent(connectionId: ConnectionId,
childId: EntityId): Parent? {
val entitiesList = entitiesByType[connectionId.parentClass] ?: return null
return refs.getOneToOneParent(connectionId, childId.arrayId) {
val parentEntityData = entitiesList[it]
if (parentEntityData == null) {
if (!brokenConsistency) {
logger<AbstractEntityStorage>().error("""
Consistency issue. Cannot get a parent in one to one connection.
Connection id: $connectionId
Child id: $childId
Parent array id: $it
""".trimIndent())
}
null
}
else parentEntityData.createEntity(this) as Parent
}
}
@Suppress("unused")
fun <Parent : WorkspaceEntity> WorkspaceEntityStorage.extractOneToManyParent(connectionId: ConnectionId,
child: WorkspaceEntity): Parent? {
return (this as AbstractEntityStorage).extractOneToManyParent(connectionId, (child as WorkspaceEntityBase).id)
}
@Suppress("UNCHECKED_CAST")
internal fun <Parent : WorkspaceEntity> AbstractEntityStorage.extractOneToManyParent(connectionId: ConnectionId,
childId: EntityId): Parent? {
val entitiesList = entitiesByType[connectionId.parentClass] ?: return null
return refs.getOneToManyParent(connectionId, childId.arrayId) {
val parentEntityData = entitiesList[it]
if (parentEntityData == null) {
if (!brokenConsistency) {
logger<AbstractEntityStorage>().error("""
Consistency issue. Cannot get a parent in one to many connection.
Connection id: $connectionId
Child id: $childId
Parent array id: $it
""".trimIndent())
}
null
}
else parentEntityData.createEntity(this) as Parent
}
}
| apache-2.0 | c107676d04c1072fea9d6b904c9c585c | 52.118959 | 144 | 0.595773 | 6.714756 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt | 1 | 32457 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pullUp
import com.intellij.psi.*
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.impl.light.LightField
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.refactoring.classMembers.MemberInfoBase
import com.intellij.refactoring.memberPullUp.PullUpData
import com.intellij.refactoring.memberPullUp.PullUpHelper
import com.intellij.refactoring.util.RefactoringUtil
import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet
import org.jetbrains.kotlin.idea.core.dropDefaultValue
import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.idea.inspections.CONSTRUCTOR_VAL_VAR_MODIFIERS
import org.jetbrains.kotlin.idea.refactoring.createJavaField
import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary
import org.jetbrains.kotlin.idea.refactoring.isAbstract
import org.jetbrains.kotlin.idea.refactoring.isCompanionMemberOf
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper
import org.jetbrains.kotlin.idea.refactoring.memberInfo.toKtDeclarationWrapperAware
import org.jetbrains.kotlin.idea.refactoring.safeDelete.removeOverrideModifier
import org.jetbrains.kotlin.idea.util.anonymousObjectSuperTypeOrNull
import org.jetbrains.kotlin.idea.util.hasComments
import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier
import org.jetbrains.kotlin.idea.util.reformatted
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.Variance
class KotlinPullUpHelper(
private val javaData: PullUpData,
private val data: KotlinPullUpData
) : PullUpHelper<MemberInfoBase<PsiMember>> {
companion object {
private val MODIFIERS_TO_LIFT_IN_SUPERCLASS = listOf(KtTokens.PRIVATE_KEYWORD)
private val MODIFIERS_TO_LIFT_IN_INTERFACE = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.PROTECTED_KEYWORD, KtTokens.INTERNAL_KEYWORD)
}
private fun KtExpression.isMovable(): Boolean {
return accept(
object : KtVisitor<Boolean, Nothing?>() {
override fun visitKtElement(element: KtElement, arg: Nothing?): Boolean {
return element.allChildren.all { (it as? KtElement)?.accept(this, arg) ?: true }
}
override fun visitKtFile(file: KtFile, data: Nothing?) = false
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, arg: Nothing?): Boolean {
val resolvedCall = expression.getResolvedCall(data.resolutionFacade.analyze(expression)) ?: return true
val receiver = (resolvedCall.getExplicitReceiverValue() as? ExpressionReceiver)?.expression
if (receiver != null && receiver !is KtThisExpression && receiver !is KtSuperExpression) return true
var descriptor: DeclarationDescriptor = resolvedCall.resultingDescriptor
if (descriptor is ConstructorDescriptor) {
descriptor = descriptor.containingDeclaration
}
// todo: local functions
if (descriptor is ValueParameterDescriptor) return true
if (descriptor is ClassDescriptor && !descriptor.isInner) return true
if (descriptor is MemberDescriptor) {
if (descriptor.source.getPsi() in propertiesToMoveInitializers) return true
descriptor = descriptor.containingDeclaration
}
return descriptor is PackageFragmentDescriptor
|| (descriptor is ClassDescriptor && DescriptorUtils.isSubclass(data.targetClassDescriptor, descriptor))
}
},
null
)
}
private fun getCommonInitializer(
currentInitializer: KtExpression?,
scope: KtBlockExpression?,
propertyDescriptor: PropertyDescriptor,
elementsToRemove: MutableSet<KtElement>
): KtExpression? {
if (scope == null) return currentInitializer
var initializerCandidate: KtExpression? = null
for (statement in scope.statements) {
statement.asAssignment()?.let body@{
val lhs = KtPsiUtil.safeDeparenthesize(it.left ?: return@body)
val receiver = (lhs as? KtQualifiedExpression)?.receiverExpression
if (receiver != null && receiver !is KtThisExpression) return@body
val resolvedCall = lhs.getResolvedCall(data.resolutionFacade.analyze(it)) ?: return@body
if (resolvedCall.resultingDescriptor != propertyDescriptor) return@body
if (initializerCandidate == null) {
if (currentInitializer == null) {
if (!statement.isMovable()) return null
initializerCandidate = statement
elementsToRemove.add(statement)
} else {
if (!KotlinPsiUnifier.DEFAULT.unify(statement, currentInitializer).isMatched) return null
initializerCandidate = currentInitializer
elementsToRemove.add(statement)
}
} else if (!KotlinPsiUnifier.DEFAULT.unify(statement, initializerCandidate).isMatched) return null
}
}
return initializerCandidate
}
private data class InitializerInfo(
val initializer: KtExpression?,
val usedProperties: Set<KtProperty>,
val usedParameters: Set<KtParameter>,
val elementsToRemove: Set<KtElement>
)
private fun getInitializerInfo(
property: KtProperty,
propertyDescriptor: PropertyDescriptor,
targetConstructor: KtElement
): InitializerInfo? {
val sourceConstructors = targetToSourceConstructors[targetConstructor] ?: return null
val elementsToRemove = LinkedHashSet<KtElement>()
val commonInitializer = sourceConstructors.fold(null as KtExpression?) { commonInitializer, constructor ->
val body = (constructor as? KtSecondaryConstructor)?.bodyExpression
getCommonInitializer(commonInitializer, body, propertyDescriptor, elementsToRemove)
}
if (commonInitializer == null) {
elementsToRemove.clear()
}
val usedProperties = LinkedHashSet<KtProperty>()
val usedParameters = LinkedHashSet<KtParameter>()
val visitor = object : KtTreeVisitorVoid() {
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val context = data.resolutionFacade.analyze(expression)
val resolvedCall = expression.getResolvedCall(context) ?: return
val receiver = (resolvedCall.getExplicitReceiverValue() as? ExpressionReceiver)?.expression
if (receiver != null && receiver !is KtThisExpression) return
val target = (resolvedCall.resultingDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi()
when (target) {
is KtParameter -> usedParameters.add(target)
is KtProperty -> usedProperties.add(target)
}
}
}
commonInitializer?.accept(visitor)
if (targetConstructor == ((data.targetClass as? KtClass)?.primaryConstructor ?: data.targetClass)) {
property.initializer?.accept(visitor)
}
return InitializerInfo(commonInitializer, usedProperties, usedParameters, elementsToRemove)
}
private val propertiesToMoveInitializers = with(data) {
membersToMove
.filterIsInstance<KtProperty>()
.filter {
val descriptor = memberDescriptors[it] as? PropertyDescriptor
descriptor != null && data.sourceClassContext[BindingContext.BACKING_FIELD_REQUIRED, descriptor] ?: false
}
}
private val targetToSourceConstructors = LinkedHashMap<KtElement, MutableList<KtElement>>().let { result ->
if (!data.isInterfaceTarget && data.targetClass is KtClass) {
result[data.targetClass.primaryConstructor ?: data.targetClass] = ArrayList()
data.sourceClass.accept(
object : KtTreeVisitorVoid() {
private fun processConstructorReference(expression: KtReferenceExpression, callingConstructorElement: KtElement) {
val descriptor = data.resolutionFacade.analyze(expression)[BindingContext.REFERENCE_TARGET, expression]
val constructorElement = (descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return
if (constructorElement == data.targetClass || (constructorElement as? KtConstructor<*>)?.getContainingClassOrObject() == data.targetClass) {
result.getOrPut(constructorElement as KtElement) { ArrayList() }.add(callingConstructorElement)
}
}
override fun visitSuperTypeCallEntry(specifier: KtSuperTypeCallEntry) {
val constructorRef = specifier.calleeExpression.constructorReferenceExpression ?: return
val containingClass = specifier.getStrictParentOfType<KtClassOrObject>() ?: return
val callingConstructorElement = containingClass.primaryConstructor ?: containingClass
processConstructorReference(constructorRef, callingConstructorElement)
}
override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) {
val constructorRef = constructor.getDelegationCall().calleeExpression ?: return
processConstructorReference(constructorRef, constructor)
}
}
)
}
result
}
private val targetConstructorToPropertyInitializerInfoMap = LinkedHashMap<KtElement, Map<KtProperty, InitializerInfo>>().let { result ->
for (targetConstructor in targetToSourceConstructors.keys) {
val propertyToInitializerInfo = LinkedHashMap<KtProperty, InitializerInfo>()
for (property in propertiesToMoveInitializers) {
val propertyDescriptor = data.memberDescriptors[property] as? PropertyDescriptor ?: continue
propertyToInitializerInfo[property] = getInitializerInfo(property, propertyDescriptor, targetConstructor) ?: continue
}
val unmovableProperties = RefactoringUtil.transitiveClosure(
object : RefactoringUtil.Graph<KtProperty> {
override fun getVertices() = propertyToInitializerInfo.keys
override fun getTargets(source: KtProperty) = propertyToInitializerInfo[source]?.usedProperties
}
) { !propertyToInitializerInfo.containsKey(it) }
propertyToInitializerInfo.keys.removeAll(unmovableProperties)
result[targetConstructor] = propertyToInitializerInfo
}
result
}
private var dummyField: PsiField? = null
private fun addMovedMember(newMember: KtNamedDeclaration) {
if (newMember is KtProperty) {
// Add dummy light field since PullUpProcessor won't invoke moveFieldInitializations() if no PsiFields are present
if (dummyField == null) {
val factory = JavaPsiFacade.getElementFactory(newMember.project)
val dummyField = object : LightField(
newMember.manager,
factory.createField("dummy", PsiType.BOOLEAN),
factory.createClass("Dummy")
) {
// Prevent processing by JavaPullUpHelper
override fun getLanguage() = KotlinLanguage.INSTANCE
}
javaData.movedMembers.add(dummyField)
}
}
when (newMember) {
is KtProperty, is KtNamedFunction -> {
newMember.getRepresentativeLightMethod()?.let { javaData.movedMembers.add(it) }
}
is KtClassOrObject -> {
newMember.toLightClass()?.let { javaData.movedMembers.add(it) }
}
}
}
private fun liftVisibility(declaration: KtNamedDeclaration, ignoreUsages: Boolean = false) {
val newModifier = if (data.isInterfaceTarget) KtTokens.PUBLIC_KEYWORD else KtTokens.PROTECTED_KEYWORD
val modifiersToLift = if (data.isInterfaceTarget) MODIFIERS_TO_LIFT_IN_INTERFACE else MODIFIERS_TO_LIFT_IN_SUPERCLASS
val currentModifier = declaration.visibilityModifierTypeOrDefault()
if (currentModifier !in modifiersToLift) return
if (ignoreUsages || willBeUsedInSourceClass(declaration, data.sourceClass, data.membersToMove)) {
if (newModifier != KtTokens.DEFAULT_VISIBILITY_KEYWORD) {
declaration.addModifier(newModifier)
} else {
declaration.removeModifier(currentModifier)
}
}
}
override fun setCorrectVisibility(info: MemberInfoBase<PsiMember>) {
val member = info.member.namedUnwrappedElement as? KtNamedDeclaration ?: return
if (data.isInterfaceTarget) {
member.removeModifier(KtTokens.PUBLIC_KEYWORD)
}
val modifiersToLift = if (data.isInterfaceTarget) MODIFIERS_TO_LIFT_IN_INTERFACE else MODIFIERS_TO_LIFT_IN_SUPERCLASS
if (member.visibilityModifierTypeOrDefault() in modifiersToLift) {
member.accept(
object : KtVisitorVoid() {
override fun visitNamedDeclaration(declaration: KtNamedDeclaration) {
when (declaration) {
is KtClass -> {
liftVisibility(declaration)
declaration.declarations.forEach { it.accept(this) }
}
is KtNamedFunction, is KtProperty -> {
liftVisibility(declaration, declaration == member && info.isToAbstract)
}
}
}
}
)
}
}
override fun encodeContextInfo(info: MemberInfoBase<PsiMember>) {
}
private fun fixOverrideAndGetClashingSuper(
sourceMember: KtCallableDeclaration,
targetMember: KtCallableDeclaration
): KtCallableDeclaration? {
val memberDescriptor = data.memberDescriptors[sourceMember] as CallableMemberDescriptor
if (memberDescriptor.overriddenDescriptors.isEmpty()) {
targetMember.removeOverrideModifier()
return null
}
val clashingSuperDescriptor = data.getClashingMemberInTargetClass(memberDescriptor) ?: return null
if (clashingSuperDescriptor.overriddenDescriptors.isEmpty()) {
targetMember.removeOverrideModifier()
}
return clashingSuperDescriptor.source.getPsi() as? KtCallableDeclaration
}
private fun moveSuperInterface(member: PsiNamedElement, substitutor: PsiSubstitutor) {
val realMemberPsi = (member as? KtPsiClassWrapper)?.psiClass ?: member
val classDescriptor = data.memberDescriptors[member] as? ClassDescriptor ?: return
val currentSpecifier = data.sourceClass.getSuperTypeEntryByDescriptor(classDescriptor, data.sourceClassContext) ?: return
when (data.targetClass) {
is KtClass -> {
data.sourceClass.removeSuperTypeListEntry(currentSpecifier)
addSuperTypeEntry(
currentSpecifier,
data.targetClass,
data.targetClassDescriptor,
data.sourceClassContext,
data.sourceToTargetClassSubstitutor
)
}
is PsiClass -> {
val elementFactory = JavaPsiFacade.getElementFactory(member.project)
val sourcePsiClass = data.sourceClass.toLightClass() ?: return
val superRef = sourcePsiClass.implementsList
?.referenceElements
?.firstOrNull { it.resolve()?.unwrapped == realMemberPsi }
?: return
val superTypeForTarget = substitutor.substitute(elementFactory.createType(superRef))
data.sourceClass.removeSuperTypeListEntry(currentSpecifier)
if (DescriptorUtils.isSubclass(data.targetClassDescriptor, classDescriptor)) return
val refList = if (data.isInterfaceTarget) data.targetClass.extendsList else data.targetClass.implementsList
refList?.add(elementFactory.createReferenceFromText(superTypeForTarget.canonicalText, null))
}
}
return
}
private fun removeOriginalMemberOrAddOverride(member: KtCallableDeclaration) {
if (member.isAbstract()) {
member.deleteWithCompanion()
} else {
member.addModifier(KtTokens.OVERRIDE_KEYWORD)
KtTokens.VISIBILITY_MODIFIERS.types.forEach { member.removeModifier(it as KtModifierKeywordToken) }
(member as? KtNamedFunction)?.valueParameters?.forEach { it.dropDefaultValue() }
}
}
private fun moveToJavaClass(member: KtNamedDeclaration, substitutor: PsiSubstitutor) {
if (!(data.targetClass is PsiClass && member.canMoveMemberToJavaClass(data.targetClass))) return
// TODO: Drop after PsiTypes in light elements are properly generated
if (member is KtCallableDeclaration && member.typeReference == null) {
val returnType = (data.memberDescriptors[member] as CallableDescriptor).returnType
returnType?.anonymousObjectSuperTypeOrNull()?.let { member.setType(it, false) }
}
val project = member.project
val elementFactory = JavaPsiFacade.getElementFactory(project)
val lightMethod = member.getRepresentativeLightMethod()!!
val movedMember: PsiMember = when (member) {
is KtProperty, is KtParameter -> {
val newType = substitutor.substitute(lightMethod.returnType)
val newField = createJavaField(member, data.targetClass)
newField.typeElement?.replace(elementFactory.createTypeElement(newType))
if (member.isCompanionMemberOf(data.sourceClass)) {
newField.modifierList?.setModifierProperty(PsiModifier.STATIC, true)
}
if (member is KtParameter) {
(member.parent as? KtParameterList)?.removeParameter(member)
} else {
member.deleteWithCompanion()
}
newField
}
is KtNamedFunction -> {
val newReturnType = substitutor.substitute(lightMethod.returnType)
val newParameterTypes = lightMethod.parameterList.parameters.map { substitutor.substitute(it.type) }
val objectType = PsiType.getJavaLangObject(PsiManager.getInstance(project), GlobalSearchScope.allScope(project))
val newTypeParameterBounds = lightMethod.typeParameters.map {
it.superTypes.map { type -> substitutor.substitute(type) as? PsiClassType ?: objectType }
}
val newMethod = org.jetbrains.kotlin.idea.refactoring.createJavaMethod(member, data.targetClass)
RefactoringUtil.makeMethodAbstract(data.targetClass, newMethod)
newMethod.returnTypeElement?.replace(elementFactory.createTypeElement(newReturnType))
newMethod.parameterList.parameters.forEachIndexed { i, parameter ->
parameter.typeElement?.replace(elementFactory.createTypeElement(newParameterTypes[i]))
}
newMethod.typeParameters.forEachIndexed { i, typeParameter ->
typeParameter.extendsList.referenceElements.forEachIndexed { j, referenceElement ->
referenceElement.replace(elementFactory.createReferenceElementByType(newTypeParameterBounds[i][j]))
}
}
removeOriginalMemberOrAddOverride(member)
if (!data.isInterfaceTarget && !data.targetClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
data.targetClass.modifierList?.setModifierProperty(PsiModifier.ABSTRACT, true)
}
newMethod
}
else -> return
}
JavaCodeStyleManager.getInstance(project).shortenClassReferences(movedMember)
}
override fun move(info: MemberInfoBase<PsiMember>, substitutor: PsiSubstitutor) {
val member = info.member.toKtDeclarationWrapperAware() ?: return
if ((member is KtClass || member is KtPsiClassWrapper) && info.overrides != null) {
moveSuperInterface(member, substitutor)
return
}
if (data.targetClass is PsiClass) {
moveToJavaClass(member, substitutor)
return
}
val markedElements = markElements(member, data.sourceClassContext, data.sourceClassDescriptor, data.targetClassDescriptor)
val memberCopy = member.copy() as KtNamedDeclaration
fun moveClassOrObject(member: KtClassOrObject, memberCopy: KtClassOrObject): KtClassOrObject {
if (data.isInterfaceTarget) {
memberCopy.removeModifier(KtTokens.INNER_KEYWORD)
}
val movedMember = addMemberToTarget(memberCopy, data.targetClass as KtClass) as KtClassOrObject
member.deleteWithCompanion()
return movedMember
}
fun moveCallableMember(member: KtCallableDeclaration, memberCopy: KtCallableDeclaration): KtCallableDeclaration {
data.targetClass as KtClass
val movedMember: KtCallableDeclaration
val clashingSuper = fixOverrideAndGetClashingSuper(member, memberCopy)
val psiFactory = KtPsiFactory(member)
val originalIsAbstract = member.hasModifier(KtTokens.ABSTRACT_KEYWORD)
val toAbstract = when {
info.isToAbstract -> true
!data.isInterfaceTarget -> false
member is KtProperty -> member.mustBeAbstractInInterface()
else -> false
}
val classToAddTo =
if (member.isCompanionMemberOf(data.sourceClass)) data.targetClass.getOrCreateCompanionObject() else data.targetClass
if (toAbstract) {
if (!originalIsAbstract) {
makeAbstract(
memberCopy,
data.memberDescriptors[member] as CallableMemberDescriptor,
data.sourceToTargetClassSubstitutor,
data.targetClass
)
}
movedMember = doAddCallableMember(memberCopy, clashingSuper, classToAddTo)
if (member.typeReference == null) {
movedMember.typeReference?.addToShorteningWaitSet()
}
if (movedMember.nextSibling.hasComments()) {
movedMember.parent.addAfter(psiFactory.createNewLine(), movedMember)
}
removeOriginalMemberOrAddOverride(member)
} else {
movedMember = doAddCallableMember(memberCopy, clashingSuper, classToAddTo)
if (member is KtParameter && movedMember is KtParameter) {
member.valOrVarKeyword?.delete()
CONSTRUCTOR_VAL_VAR_MODIFIERS.forEach { member.removeModifier(it) }
val superEntry = data.superEntryForTargetClass
val superResolvedCall = data.targetClassSuperResolvedCall
if (superResolvedCall != null) {
val superCall = if (superEntry !is KtSuperTypeCallEntry || superEntry.valueArgumentList == null) {
superEntry!!.replaced(psiFactory.createSuperTypeCallEntry("${superEntry.text}()"))
} else superEntry
val argumentList = superCall.valueArgumentList!!
val parameterIndex = movedMember.parameterIndex()
val prevParameterDescriptor = superResolvedCall.resultingDescriptor.valueParameters.getOrNull(parameterIndex - 1)
val prevArgument =
superResolvedCall.valueArguments[prevParameterDescriptor]?.arguments?.singleOrNull() as? KtValueArgument
val newArgumentName = if (prevArgument != null && prevArgument.isNamed()) Name.identifier(member.name!!) else null
val newArgument = psiFactory.createArgument(psiFactory.createExpression(member.name!!), newArgumentName)
if (prevArgument == null) {
argumentList.addArgument(newArgument)
} else {
argumentList.addArgumentAfter(newArgument, prevArgument)
}
}
} else {
member.deleteWithCompanion()
}
}
if (originalIsAbstract && data.isInterfaceTarget) {
movedMember.removeModifier(KtTokens.ABSTRACT_KEYWORD)
}
if (movedMember.hasModifier(KtTokens.ABSTRACT_KEYWORD)) {
data.targetClass.makeAbstract()
}
return movedMember
}
try {
val movedMember = when (member) {
is KtCallableDeclaration -> moveCallableMember(member, memberCopy as KtCallableDeclaration)
is KtClassOrObject -> moveClassOrObject(member, memberCopy as KtClassOrObject)
else -> return
}
movedMember.modifierList?.reformatted()
applyMarking(movedMember, data.sourceToTargetClassSubstitutor, data.targetClassDescriptor)
addMovedMember(movedMember)
} finally {
clearMarking(markedElements)
}
}
override fun postProcessMember(member: PsiMember) {
val declaration = member.unwrapped as? KtNamedDeclaration ?: return
dropOverrideKeywordIfNecessary(declaration)
}
override fun moveFieldInitializations(movedFields: LinkedHashSet<PsiField>) {
val psiFactory = KtPsiFactory(data.sourceClass)
fun KtClassOrObject.getOrCreateClassInitializer(): KtAnonymousInitializer {
getOrCreateBody().declarations.lastOrNull { it is KtAnonymousInitializer }?.let { return it as KtAnonymousInitializer }
return addDeclaration(psiFactory.createAnonymousInitializer())
}
fun KtElement.getConstructorBodyBlock(): KtBlockExpression? {
return when (this) {
is KtClassOrObject -> {
getOrCreateClassInitializer().body
}
is KtPrimaryConstructor -> {
getContainingClassOrObject().getOrCreateClassInitializer().body
}
is KtSecondaryConstructor -> {
bodyExpression ?: add(psiFactory.createEmptyBody())
}
else -> null
} as? KtBlockExpression
}
fun KtClassOrObject.getDelegatorToSuperCall(): KtSuperTypeCallEntry? {
return superTypeListEntries.singleOrNull { it is KtSuperTypeCallEntry } as? KtSuperTypeCallEntry
}
fun addUsedParameters(constructorElement: KtElement, info: InitializerInfo) {
if (info.usedParameters.isEmpty()) return
val constructor: KtConstructor<*> = when (constructorElement) {
is KtConstructor<*> -> constructorElement
is KtClass -> constructorElement.createPrimaryConstructorIfAbsent()
else -> return
}
with(constructor.getValueParameterList()!!) {
info.usedParameters.forEach {
val newParameter = addParameter(it)
val originalType = data.sourceClassContext[BindingContext.VALUE_PARAMETER, it]!!.type
newParameter.setType(
data.sourceToTargetClassSubstitutor.substitute(originalType, Variance.INVARIANT) ?: originalType,
false
)
newParameter.typeReference!!.addToShorteningWaitSet()
}
}
targetToSourceConstructors[constructorElement]!!.forEach {
val superCall: KtCallElement? = when (it) {
is KtClassOrObject -> it.getDelegatorToSuperCall()
is KtPrimaryConstructor -> it.getContainingClassOrObject().getDelegatorToSuperCall()
is KtSecondaryConstructor -> {
if (it.hasImplicitDelegationCall()) {
it.replaceImplicitDelegationCallWithExplicit(false)
} else {
it.getDelegationCall()
}
}
else -> null
}
superCall?.valueArgumentList?.let { args ->
info.usedParameters.forEach { parameter ->
args.addArgument(psiFactory.createArgument(psiFactory.createExpression(parameter.name ?: "_")))
}
}
}
}
for ((constructorElement, propertyToInitializerInfo) in targetConstructorToPropertyInitializerInfoMap.entries) {
val properties = propertyToInitializerInfo.keys.sortedWith(
Comparator { property1, property2 ->
val info1 = propertyToInitializerInfo[property1]!!
val info2 = propertyToInitializerInfo[property2]!!
when {
property2 in info1.usedProperties -> -1
property1 in info2.usedProperties -> 1
else -> 0
}
}
)
for (oldProperty in properties) {
val info = propertyToInitializerInfo.getValue(oldProperty)
addUsedParameters(constructorElement, info)
info.initializer?.let {
val body = constructorElement.getConstructorBodyBlock()
body?.addAfter(it, body.statements.lastOrNull() ?: body.lBrace!!)
}
info.elementsToRemove.forEach { it.delete() }
}
}
}
override fun updateUsage(element: PsiElement) {
}
}
internal fun KtNamedDeclaration.deleteWithCompanion() {
val containingClass = this.containingClassOrObject
if (containingClass is KtObjectDeclaration &&
containingClass.isCompanion() &&
containingClass.declarations.size == 1 &&
containingClass.getSuperTypeList() == null
) {
containingClass.delete()
} else {
this.delete()
}
}
| apache-2.0 | c31c720f6fceafe76ebea3388dba9395 | 47.588323 | 164 | 0.633638 | 6.588916 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/AddMethodCreateCallableFromUsageFix.kt | 5 | 2799 | // 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.crossLanguage
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.CreateMethodRequest
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable.AbstractCreateCallableFromUsageFixWithTextAndFamilyName
import org.jetbrains.kotlin.idea.quickfix.crossLanguage.KotlinElementActionsFactory.Companion.toKotlinTypeInfo
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtModifierList
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
class AddMethodCreateCallableFromUsageFix(
private val request: CreateMethodRequest,
modifierList: KtModifierList,
providedText: String,
@Nls familyName: String,
targetContainer: KtElement
) : AbstractCreateCallableFromUsageFixWithTextAndFamilyName<KtElement>(
providedText = providedText,
familyName = familyName,
originalExpression = targetContainer
) {
private val modifierListPointer = modifierList.createSmartPointer()
init {
init()
}
override val callableInfo: FunctionInfo?
get() = run {
val targetContainer = element ?: return@run null
val modifierList = modifierListPointer.element ?: return@run null
val resolutionFacade = KotlinCacheService.getInstance(targetContainer.project)
.getResolutionFacadeByFile(targetContainer.containingFile, JvmPlatforms.unspecifiedJvmPlatform) ?: return null
val returnTypeInfo = request.returnType.toKotlinTypeInfo(resolutionFacade)
val parameters = request.expectedParameters
val parameterInfos = parameters.map { parameter ->
ParameterInfo(parameter.expectedTypes.toKotlinTypeInfo(resolutionFacade), parameter.semanticNames.toList())
}
val methodName = request.methodName
FunctionInfo(
methodName,
TypeInfo.Empty,
returnTypeInfo,
listOf(targetContainer),
parameterInfos,
isForCompanion = JvmModifier.STATIC in request.modifiers,
modifierList = modifierList,
preferEmptyBody = true
)
}
} | apache-2.0 | f999ecd7f83dbd646cd8634b25570371 | 47.275862 | 158 | 0.746338 | 5.542574 | false | false | false | false |
smmribeiro/intellij-community | plugins/editorconfig/src/org/editorconfig/language/codeinsight/EditorConfigCommenter.kt | 16 | 540 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.codeinsight
import com.intellij.lang.Commenter
class EditorConfigCommenter : Commenter {
override fun getLineCommentPrefix() = "# "
override fun getBlockCommentPrefix() = ""
override fun getBlockCommentSuffix(): String? = null
override fun getCommentedBlockCommentPrefix(): String? = null
override fun getCommentedBlockCommentSuffix(): String? = null
}
| apache-2.0 | 7ca82aa91adf3531112831b2c9594659 | 44 | 140 | 0.77963 | 4.821429 | false | true | false | false |
smmribeiro/intellij-community | python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypedDictInspection.kt | 1 | 17797 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.inspections
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiNameIdentifierOwner
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyPsiBundle
import com.jetbrains.python.codeInsight.typing.PyTypedDictTypeProvider
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.documentation.PythonDocumentationProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.impl.PyPsiUtils
import com.jetbrains.python.psi.types.*
import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_FIELDS_PARAMETER
import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_NAME_PARAMETER
import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_TOTAL_PARAMETER
class PyTypedDictInspection : PyInspection() {
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor {
return Visitor(holder, PyInspectionVisitor.getContext(session))
}
private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) {
override fun visitPySubscriptionExpression(node: PySubscriptionExpression) {
val operandType = myTypeEvalContext.getType(node.operand)
if (operandType !is PyTypedDictType || operandType.isInferred()) return
val indexExpression = node.indexExpression
val indexExpressionValueOptions = getIndexExpressionValueOptions(indexExpression)
if (indexExpressionValueOptions.isNullOrEmpty()) {
val keyList = operandType.fields.keys.joinToString(transform = { "'$it'" })
registerProblem(indexExpression, PyPsiBundle.message("INSP.typeddict.typeddict.key.must.be.string.literal.expected.one", keyList))
return
}
val nonMatchingFields = indexExpressionValueOptions.filterNot { it in operandType.fields }
if (nonMatchingFields.isNotEmpty()) {
registerProblem(indexExpression, if (nonMatchingFields.size == 1)
PyPsiBundle.message("INSP.typeddict.typeddict.has.no.key", operandType.name, nonMatchingFields[0])
else {
val nonMatchingFieldList = nonMatchingFields.joinToString(transform = { "'$it'" })
PyPsiBundle.message("INSP.typeddict.typeddict.has.no.keys", operandType.name, nonMatchingFieldList)
})
}
}
override fun visitPyTargetExpression(node: PyTargetExpression) {
val value = node.findAssignedValue()
if (value is PyCallExpression && value.callee != null && PyTypedDictTypeProvider.isTypedDict(value.callee!!, myTypeEvalContext)) {
val typedDictName = value.getArgument(0, TYPED_DICT_NAME_PARAMETER, PyExpression::class.java)
if (typedDictName is PyStringLiteralExpression && node.name != typedDictName.stringValue) {
registerProblem(typedDictName, PyPsiBundle.message("INSP.typeddict.first.argument.has.to.match.variable.name"))
}
}
}
override fun visitPyArgumentList(node: PyArgumentList) {
if (node.parent is PyClass && PyTypedDictTypeProvider.isTypingTypedDictInheritor(node.parent as PyClass, myTypeEvalContext)) {
val arguments = node.arguments
for (argument in arguments) {
val type = myTypeEvalContext.getType(argument)
if (argument !is PyKeywordArgument
&& type !is PyTypedDictType
&& !PyTypedDictTypeProvider.isTypedDict(argument, myTypeEvalContext)) {
registerProblem(argument, PyPsiBundle.message("INSP.typeddict.typeddict.cannot.inherit.from.non.typeddict.base.class"))
}
if (argument is PyKeywordArgument && argument.keyword == TYPED_DICT_TOTAL_PARAMETER && argument.valueExpression != null) {
checkValidTotality(argument.valueExpression!!)
}
}
}
else if (node.callExpression != null) {
val callExpression = node.callExpression
val callee = callExpression!!.callee
if (callee != null && PyTypedDictTypeProvider.isTypedDict(callee, myTypeEvalContext)) {
val fields = callExpression.getArgument(1, TYPED_DICT_FIELDS_PARAMETER, PyExpression::class.java)
if (fields !is PyDictLiteralExpression) {
return
}
fields.elements.forEach {
if (it !is PyKeyValueExpression) return
checkValueIsAType(it.value, it.value?.text)
}
val totalityArgument = callExpression.getArgument(2, TYPED_DICT_TOTAL_PARAMETER, PyExpression::class.java)
if (totalityArgument != null) {
checkValidTotality(totalityArgument)
}
}
}
}
override fun visitPyClass(node: PyClass) {
if (!PyTypedDictTypeProvider.isTypingTypedDictInheritor(node, myTypeEvalContext)) return
if (node.metaClassExpression != null) {
registerProblem((node.metaClassExpression as PyExpression).parent,
PyPsiBundle.message("INSP.typeddict.specifying.metaclass.not.allowed.in.typeddict"))
}
val ancestorsFields = mutableMapOf<String, PyTypedDictType.FieldTypeAndTotality>()
val typedDictAncestors = node.getAncestorTypes(myTypeEvalContext).filterIsInstance<PyTypedDictType>()
typedDictAncestors.forEach { typedDict ->
typedDict.fields.forEach { field ->
val key = field.key
val value = field.value
if (key in ancestorsFields && !matchTypedDictFieldTypeAndTotality(ancestorsFields[key]!!, value)) {
registerProblem(node.superClassExpressionList,
PyPsiBundle.message("INSP.typeddict.cannot.overwrite.typeddict.field.while.merging", key))
}
else {
ancestorsFields[key] = value
}
}
}
val singleStatement = node.statementList.statements.singleOrNull()
if (singleStatement != null &&
singleStatement is PyExpressionStatement &&
singleStatement.expression is PyNoneLiteralExpression &&
(singleStatement.expression as PyNoneLiteralExpression).isEllipsis) {
registerProblem(tryGetNameIdentifier(singleStatement),
PyPsiBundle.message("INSP.typeddict.invalid.statement.in.typeddict.definition.expected.field.name.field.type"),
ProblemHighlightType.WEAK_WARNING)
return
}
node.processClassLevelDeclarations { element, _ ->
if (element !is PyTargetExpression) {
registerProblem(tryGetNameIdentifier(element),
PyPsiBundle.message("INSP.typeddict.invalid.statement.in.typeddict.definition.expected.field.name.field.type"),
ProblemHighlightType.WEAK_WARNING)
return@processClassLevelDeclarations true
}
if (element.hasAssignedValue()) {
registerProblem(element.findAssignedValue(),
PyPsiBundle.message("INSP.typeddict.right.hand.side.values.are.not.supported.in.typeddict"))
return@processClassLevelDeclarations true
}
if (element.name in ancestorsFields) {
registerProblem(element, PyPsiBundle.message("INSP.typeddict.cannot.overwrite.typeddict.field"))
return@processClassLevelDeclarations true
}
checkValueIsAType(element.annotation?.value, element.annotationValue)
true
}
}
override fun visitPyDelStatement(node: PyDelStatement) {
for (target in node.targets) {
for (expr in PyUtil.flattenedParensAndTuples(target)) {
if (expr !is PySubscriptionExpression) continue
val type = myTypeEvalContext.getType(expr.operand)
if (type is PyTypedDictType && !type.isInferred()) {
val index = PyEvaluator.evaluate(expr.indexExpression, String::class.java)
if (index == null || index !in type.fields) continue
if (type.fields[index]!!.isRequired) {
registerProblem(expr.indexExpression, PyPsiBundle.message("INSP.typeddict.key.cannot.be.deleted", index, type.name))
}
}
}
}
}
override fun visitPyCallExpression(node: PyCallExpression) {
val callee = node.callee
if (callee !is PyReferenceExpression || callee.qualifier == null) return
val nodeType = myTypeEvalContext.getType(callee.qualifier!!)
if (nodeType !is PyTypedDictType || nodeType.isInferred()) return
val arguments = node.arguments
if (PyNames.UPDATE == callee.name) {
inspectUpdateSequenceArgument(
if (arguments.size == 1 && arguments[0] is PySequenceExpression) (arguments[0] as PySequenceExpression).elements else arguments,
nodeType)
}
if (PyNames.CLEAR == callee.name || PyNames.POPITEM == callee.name) {
if (nodeType.fields.any { it.value.isRequired }) {
registerProblem(callee.nameElement?.psi, PyPsiBundle.message("INSP.typeddict.this.operation.might.break.typeddict.consistency"),
if (PyNames.CLEAR == callee.name) ProblemHighlightType.WARNING else ProblemHighlightType.WEAK_WARNING)
}
}
if (PyNames.POP == callee.name) {
val key = if (arguments.isNotEmpty()) PyEvaluator.evaluate(arguments[0], String::class.java) else null
if (key != null && key in nodeType.fields && nodeType.fields[key]!!.isRequired) {
registerProblem(callee.nameElement?.psi, PyPsiBundle.message("INSP.typeddict.key.cannot.be.deleted", key, nodeType.name))
}
}
if (PyNames.SETDEFAULT == callee.name) {
val key = if (arguments.isNotEmpty()) PyEvaluator.evaluate(arguments[0], String::class.java) else null
if (key != null && key in nodeType.fields && !nodeType.fields[key]!!.isRequired) {
if (node.arguments.size > 1) {
val valueType = myTypeEvalContext.getType(arguments[1])
if (!PyTypeChecker.match(nodeType.fields[key]!!.type, valueType, myTypeEvalContext)) {
val expectedTypeName = PythonDocumentationProvider.getTypeName(nodeType.fields[key]!!.type,
myTypeEvalContext)
val actualTypeName = PythonDocumentationProvider.getTypeName(valueType, myTypeEvalContext)
registerProblem(arguments[1],
PyPsiBundle.message("INSP.type.checker.expected.type.got.type.instead", expectedTypeName, actualTypeName))
}
}
}
}
if (PyTypingTypeProvider.resolveToQualifiedNames(callee, myTypeEvalContext).contains(PyTypingTypeProvider.MAPPING_GET)) {
val keyArgument = node.getArgument(0, "key", PyExpression::class.java) ?: return
val key = PyEvaluator.evaluate(keyArgument, String::class.java)
if (key == null) {
registerProblem(keyArgument, PyPsiBundle.message("INSP.typeddict.key.should.be.string"))
return
}
if (!nodeType.fields.containsKey(key)) {
registerProblem(keyArgument, PyPsiBundle.message("INSP.typeddict.typeddict.has.no.key", nodeType.name, key))
}
}
}
override fun visitPyAssignmentStatement(node: PyAssignmentStatement) {
val targetsToValuesMapping = node.targetsToValuesMapping
node.targets.forEach { target ->
if (target !is PySubscriptionExpression) return@forEach
val targetType = myTypeEvalContext.getType(target.operand)
if (targetType !is PyTypedDictType) return@forEach
val indexString = PyEvaluator.evaluate(target.indexExpression, String::class.java)
if (indexString == null) return@forEach
val expected = targetType.getElementType(indexString)
val actualExpressions = targetsToValuesMapping.filter { it.first == target }.map { it.second }
actualExpressions.forEach { actual ->
val actualType = myTypeEvalContext.getType(actual)
if (!PyTypeChecker.match(expected, actualType, myTypeEvalContext)) {
val expectedTypeName = PythonDocumentationProvider.getTypeName(expected, myTypeEvalContext)
val actualTypeName = PythonDocumentationProvider.getTypeName(actualType, myTypeEvalContext)
registerProblem(actual,
PyPsiBundle.message("INSP.type.checker.expected.type.got.type.instead", expectedTypeName, actualTypeName))
}
}
}
}
private fun getIndexExpressionValueOptions(indexExpression: PyExpression?): List<String>? {
if (indexExpression == null) return null
val indexExprValue = PyEvaluator.evaluate(indexExpression, String::class.java)
if (indexExprValue == null) {
val type = myTypeEvalContext.getType(indexExpression) ?: return null
val members = PyTypeUtil.toStream(type)
.map { if (it is PyLiteralType) PyEvaluator.evaluate(it.expression, String::class.java) else null }
.toList()
return if (members.contains(null)) null
else members
.filterNotNull()
}
else {
return listOf(indexExprValue)
}
}
/**
* Checks that [expression] with [strType] name is a type
*/
private fun checkValueIsAType(expression: PyExpression?, strType: String?) {
if (expression !is PyReferenceExpression &&
expression !is PySubscriptionExpression &&
expression !is PyNoneLiteralExpression || strType == null) {
registerProblem(expression, PyPsiBundle.message("INSP.typeddict.value.must.be.type"), ProblemHighlightType.WEAK_WARNING)
return
}
val type = Ref.deref(PyTypingTypeProvider.getStringBasedType(strType, expression, myTypeEvalContext))
if (type == null && !PyTypingTypeProvider.resolveToQualifiedNames(expression, myTypeEvalContext).any { qualifiedName ->
PyTypingTypeProvider.ANY == qualifiedName
}) {
registerProblem(expression, PyPsiBundle.message("INSP.typeddict.value.must.be.type"), ProblemHighlightType.WEAK_WARNING)
}
}
private fun tryGetNameIdentifier(element: PsiElement): PsiElement {
return if (element is PsiNameIdentifierOwner) element.nameIdentifier ?: element else element
}
private fun checkValidTotality(totalityValue: PyExpression) {
if (LanguageLevel.forElement(totalityValue.originalElement).isPy3K && totalityValue !is PyBoolLiteralExpression ||
!listOf(PyNames.TRUE, PyNames.FALSE).contains(totalityValue.text)) {
registerProblem(totalityValue, PyPsiBundle.message("INSP.typeddict.total.value.must.be.true.or.false"))
}
}
private fun matchTypedDictFieldTypeAndTotality(expected: PyTypedDictType.FieldTypeAndTotality,
actual: PyTypedDictType.FieldTypeAndTotality): Boolean {
return expected.isRequired == actual.isRequired &&
PyTypeChecker.match(expected.type, actual.type, myTypeEvalContext)
}
private fun inspectUpdateSequenceArgument(sequenceElements: Array<PyExpression>, typedDictType: PyTypedDictType) {
sequenceElements.forEach {
var key: PsiElement? = null
var keyAsString: String? = null
var value: PyExpression? = null
if (it is PyKeyValueExpression && it.key is PyStringLiteralExpression) {
key = it.key
keyAsString = (it.key as PyStringLiteralExpression).stringValue
value = it.value
}
else if (it is PyParenthesizedExpression) {
val expression = PyPsiUtils.flattenParens(it)
if (expression == null) return@forEach
if (expression is PyTupleExpression && expression.elements.size == 2 && expression.elements[0] is PyStringLiteralExpression) {
key = expression.elements[0]
keyAsString = (expression.elements[0] as PyStringLiteralExpression).stringValue
value = expression.elements[1]
}
}
else if (it is PyKeywordArgument && it.valueExpression != null) {
key = it.keywordNode?.psi
keyAsString = it.keyword
value = it.valueExpression
}
else return@forEach
val fields = typedDictType.fields
if (value == null) {
return@forEach
}
if (keyAsString == null) {
registerProblem(key, PyPsiBundle.message("INSP.typeddict.cannot.add.non.string.key.to.typeddict", typedDictType.name))
return@forEach
}
if (!fields.containsKey(keyAsString)) {
registerProblem(key, PyPsiBundle.message("INSP.typeddict.typeddict.cannot.have.key", typedDictType.name, keyAsString))
return@forEach
}
val valueType = myTypeEvalContext.getType(value)
if (!PyTypeChecker.match(fields[keyAsString]?.type, valueType, myTypeEvalContext)) {
val expectedTypeName = PythonDocumentationProvider.getTypeName(fields[keyAsString]!!.type, myTypeEvalContext)
val actualTypeName = PythonDocumentationProvider.getTypeName(valueType, myTypeEvalContext)
registerProblem(value, PyPsiBundle.message("INSP.type.checker.expected.type.got.type.instead", expectedTypeName, actualTypeName))
return@forEach
}
}
}
}
} | apache-2.0 | 053421f3cef6c02c6b2c6a77d1ca0446 | 48.576602 | 140 | 0.683767 | 4.954621 | false | false | false | false |
craftsmenlabs/gareth-jvm | gareth-execution-ri/src/main/kotlin/org/craftsmenlabs/gareth/execution/definitions/InvokableMethod.kt | 1 | 4949 | package org.craftsmenlabs.gareth.execution.definitions
import org.craftsmenlabs.gareth.validator.GarethIllegalDefinitionException
import org.craftsmenlabs.gareth.validator.GarethInvocationException
import org.craftsmenlabs.gareth.validator.model.ExecutionRunContext
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.lang.reflect.Type
import java.util.*
import java.util.regex.Pattern
class InvokableMethod {
private val parameters = ArrayList<Class<*>>()
val pattern: Pattern
val method: Method
val description: String?
val humanReadable: String?
val runcontextParameter: Boolean
constructor(glueLine: String,
description: String? = null,
humanReadable: String,
method: Method,
runcontextParameter: Boolean) {
try {
this.runcontextParameter = runcontextParameter
pattern = Pattern.compile(glueLine)
this.method = method
this.description = description
this.humanReadable = humanReadable
parseMethod()
} catch (e: Exception) {
throw GarethIllegalDefinitionException(cause = e)
}
}
fun hasRunContext(): Boolean {
return this.runcontextParameter
}
fun getMethodName(): String {
return method.name
}
fun getClassName(): String {
return method.declaringClass.name
}
fun invokeWith(glueLineInExperiment: String, declaringClassInstance: Any, runContext: ExecutionRunContext): Any? {
val arguments = ArrayList<Any>()
if (hasRunContext())
arguments.add(runContext)
val argumentValuesFromInputString = getArgumentValuesFromInputString(glueLineInExperiment)
arguments.addAll(argumentValuesFromInputString)
try {
return method.invoke(declaringClassInstance, *arguments.toArray())
} catch (e: InvocationTargetException) {
throw GarethInvocationException(e.targetException.message, e.targetException)
} catch (e: Exception) {
throw GarethInvocationException(cause = e)
}
}
fun getRegexPatternForGlueLine(): String {
return pattern.pattern()
}
fun getRegularParameters() =
parameters.filter({ !isContextParameter(it) })
fun getPattern(): String {
return pattern.pattern()
}
private fun getArgumentValuesFromInputString(input: String): List<Any> {
val parametersFromPattern = getParametersFromPattern(input.trim { it <= ' ' })
val parameters = ArrayList<Any>()
for (i in parametersFromPattern.indices) {
val cls = getRegularParameters()[i]
parameters.add(getValueFromString(cls, parametersFromPattern[i]))
}
return parameters
}
private fun parseMethod() {
for (parameter in method.parameters) {
val cls = parameter.type
if (isValidType(parameter.parameterizedType)) {
if (!isValidType(cls)) {
throw IllegalStateException("Parameter type $cls is not supported")
}
parameters.add(cls)
}
}
}
private fun isValidType(type: Type): Boolean {
return type.typeName == "java.lang.String"
|| type.typeName == "int"
|| type.typeName == "long"
|| type.typeName == "double"
}
private fun getValueFromString(cls: Class<*>, stringVal: String): Any {
if (cls == String::class.java) {
return stringVal
} else if (cls == java.lang.Integer.TYPE) {
return java.lang.Integer.valueOf(stringVal).toInt()
} else if (cls == java.lang.Long.TYPE) {
return java.lang.Long.valueOf(stringVal).toLong()
} else if (cls == java.lang.Double.TYPE) {
return java.lang.Double.valueOf(stringVal).toDouble()
}
throw IllegalArgumentException("Parameter must be of class String, Int, Long or Double")
}
private fun getParametersFromPattern(s: String): List<String> {
val output = ArrayList<String>()
val matcher = pattern.matcher(s)
if (!matcher.matches()) {
throw IllegalArgumentException("Input string " + s + " could not be matched against pattern " + getPattern())
}
val groupCount = matcher.groupCount()
val expectedParameters = getRegularParameters().size
if (groupCount != expectedParameters) {
throw IllegalArgumentException("Input string $s must have $expectedParameters parameters.")
}
for (i in 1..groupCount) {
output.add(matcher.group(i))
}
return output
}
companion object {
fun isContextParameter(parameterClass: Class<*>) = ExecutionRunContext::class.java.isAssignableFrom(parameterClass)
}
} | gpl-2.0 | 98b253831bec89af5200ec5b00dc8637 | 34.611511 | 123 | 0.635482 | 4.904856 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/check/UnavailableCheck.kt | 1 | 2060 | package com.cognifide.gradle.aem.common.instance.check
import com.cognifide.gradle.aem.common.instance.LocalInstance
import com.cognifide.gradle.aem.common.instance.local.Status
import java.util.concurrent.TimeUnit
class UnavailableCheck(group: CheckGroup) : DefaultCheck(group) {
/**
* Status of remote instances cannot be checked easily. Because of that, check will work just a little bit longer.
*/
val utilisationTime = aem.obj.long { convention(TimeUnit.SECONDS.toMillis(15)) }
override fun check() {
if (instance.available) {
val bundleState = state(sync.osgiFramework.determineBundleState())
if (!bundleState.unknown) {
statusLogger.error(
"Bundles stable (${bundleState.stablePercent})",
"Bundles stable (${bundleState.stablePercent}). HTTP server still responding on $instance"
)
return
}
} else {
val reachableStatus = state(sync.status.checkReachableStatus())
if (reachableStatus >= 0) {
statusLogger.error(
"Reachable ($reachableStatus)",
"Reachable - status code ($reachableStatus). HTTP server still responding on $instance"
)
return
}
}
if (instance is LocalInstance) {
val status = state(instance.checkStatus())
if (!status.runnable) {
statusLogger.error(
"Awaiting not running",
"Unexpected instance status '$status'. Waiting for status '${Status.Type.RUNNABLE.map { it.name }}' of $instance"
)
}
} else {
if (utilisationTime.get() !in 0..progress.stateTime) {
statusLogger.error(
"Awaiting utilized",
"HTTP server not responding. Waiting for utilization (port releasing) of $instance"
)
}
}
}
}
| apache-2.0 | fa8c62601769efda4eeb11731f4bb715 | 38.615385 | 137 | 0.563592 | 5 | false | false | false | false |
TimePath/java-vfs | src/main/kotlin/com/timepath/vfs/provider/local/LocalFileProvider.kt | 1 | 2910 | package com.timepath.vfs.provider.local
import com.timepath.vfs.SimpleVFile
import java.io.File
import java.util.LinkedList
import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
import java.util.logging.Level
import java.util.logging.Logger
/**
* @author TimePath
*/
public open class LocalFileProvider(file: File) : LocalFile(file) {
init {
// TODO: lazy loading
if (file.isDirectory()) {
insert(file)
}
}
/**
* Insert children of a directory
*
* @param toInsert the directory
*/
private fun insert(toInsert: File) {
val start = System.currentTimeMillis()
val tasks = LinkedList<Future<Unit>>()
visit(toInsert, object : SimpleVFile.FileVisitor {
override fun visit(file: File, parent: SimpleVFile) {
val entry = LocalFile(file)
parent.add(entry)
if (file.isDirectory()) {
// Depth first search
entry.visit(file, this)
} else {
// Start background identification
tasks.add(SimpleVFile.pool.submit<Unit> {
SimpleVFile.handlers.forEach {
it.handle(file)?.let {
// Defensive copy
it.toTypedArray().forEach {
merge(it, parent)
}
}
}
})
}
}
})
// Await all
tasks.forEach {
try {
it.get()
} catch (e: InterruptedException) {
LOG.log(Level.SEVERE, null, e)
} catch (e: ExecutionException) {
LOG.log(Level.SEVERE, null, e)
}
}
LOG.log(Level.INFO, "Recursive file load took {0}ms", System.currentTimeMillis() - start)
}
companion object {
private val LOG = Logger.getLogger(javaClass<LocalFileProvider>().getName())
/**
* Adds one file to another, merging any directories.
* TODO: additive/union directories to avoid this kludge
*
* @param src
* @param parent
*/
synchronized private fun merge(src: SimpleVFile, parent: SimpleVFile) {
val existing = parent[src.name]
if (existing == null) {
// Parent does not have this file, simple case
parent.add(src)
} else {
// Add all child files, silently ignore duplicates
val children = src.list()
// Defensive copy
for (file in children.toTypedArray()) {
merge(file, existing)
}
}
}
}
}
| artistic-2.0 | 5498847fadf213c5b0e8e787506e1199 | 29.957447 | 97 | 0.493814 | 5.043328 | false | false | false | false |
juzraai/ted-xml-model | src/main/kotlin/hu/juzraai/ted/xml/model/tedexport/common/ContactContractingBody.kt | 1 | 2316 | package hu.juzraai.ted.xml.model.tedexport.common
import hu.juzraai.ted.xml.model.tedexport.coded.noticedata.Nuts
import org.simpleframework.xml.Element
/**
* @author Zsolt Jurányi
*/
open class ContactContractingBody(
@field:Element(name = "ADDRESS", required = false)
var address: String = "",
@field:Element(name = "TOWN")
var town: String = "",
@field:Element(name = "POSTAL_CODE", required = false)
var postalcode: String = "",
@field:Element(name = "COUNTRY")
var country: Country = Country(),
@field:Element(name = "CONTACT_POINT", required = false)
var contactpoint: String = "",
@field:Element(name = "PHONE", required = false)
var phone: String = "",
@field:Element(name = "E_MAIL")
var email: String = "",
@field:Element(name = "FAX", required = false)
var fax: String = "",
@field:Element(name = "NUTS")
var nuts: Nuts = Nuts(),
@field:Element(name = "URL_GENERAL")
var urlgeneral: String = "",
@field:Element(name = "URL_BUYER", required = false)
var urlbuyer: String = ""
) : OrgIdNew() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ContactContractingBody) return false
if (!super.equals(other)) return false
if (address != other.address) return false
if (town != other.town) return false
if (postalcode != other.postalcode) return false
if (country != other.country) return false
if (contactpoint != other.contactpoint) return false
if (phone != other.phone) return false
if (email != other.email) return false
if (fax != other.fax) return false
if (nuts != other.nuts) return false
if (urlgeneral != other.urlgeneral) return false
if (urlbuyer != other.urlbuyer) return false
return true
}
override fun hashCode(): Int {
var result = address.hashCode()
result = 31 * result + town.hashCode()
result = 31 * result + postalcode.hashCode()
result = 31 * result + country.hashCode()
result = 31 * result + contactpoint.hashCode()
result = 31 * result + phone.hashCode()
result = 31 * result + email.hashCode()
result = 31 * result + fax.hashCode()
result = 31 * result + nuts.hashCode()
result = 31 * result + urlgeneral.hashCode()
result = 31 * result + urlbuyer.hashCode()
result = 31 * result + super.hashCode()
return result
}
} | apache-2.0 | fc10123524d2408325977348140d42ba | 27.243902 | 63 | 0.671706 | 3.188705 | false | false | false | false |
koma-im/koma | src/main/kotlin/koma/gui/view/window/chatroom/messaging/reading/display/room_event/m_message/common/image.kt | 1 | 4280 | package koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message.common
import javafx.event.EventHandler
import javafx.scene.Scene
import javafx.scene.control.Alert
import javafx.scene.control.MenuItem
import javafx.scene.image.Image
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import javafx.scene.input.MouseButton
import javafx.stage.Stage
import koma.Server
import koma.gui.dialog.file.save.downloadFileAs
import koma.gui.view.window.chatroom.messaging.reading.display.ViewNode
import koma.network.media.MHUrl
import link.continuum.desktop.gui.JFX
import link.continuum.desktop.gui.StackPane
import link.continuum.desktop.gui.add
import link.continuum.desktop.gui.component.FitImageRegion
import link.continuum.desktop.gui.component.MxcImageView
import link.continuum.desktop.util.gui.alert
import mu.KotlinLogging
import java.util.concurrent.atomic.AtomicBoolean
private val logger = KotlinLogging.logger {}
class ImageElement(
private val imageSize: Double = 200.0
) : ViewNode {
override val node = StackPane()
override val menuItems: List<MenuItem>
private var imageView = MxcImageView().apply {
fitHeight = imageSize
fitWidth = imageSize
}
private var url: MHUrl? = null
private var server: Server? = null
fun update(mxc: MHUrl, server: Server) {
imageView.setMxc(mxc, server)
this.url = mxc
this.server = server
}
init {
node.add(imageView.root)
node.setOnMouseClicked { event ->
if (event.button == MouseButton.PRIMARY) {
BiggerViews.show(url.toString(), imageView.image, url, server)
}
}
menuItems = menuItems()
}
fun cancelScope() {
imageView.cancelScope()
}
private fun menuItems(): List<MenuItem> {
val tm = MenuItem("Save Image")
tm.setOnAction {
val u = url?: run {
alert(
Alert.AlertType.ERROR,
"Can't download",
"url is null"
)
return@setOnAction
}
val s = server ?: run {
alert(
Alert.AlertType.ERROR,
"Can't download",
"http client is null"
)
return@setOnAction
}
downloadFileAs(s.mxcToHttp(u), title = "Save Image As", httpClient = s.okHttpClient)
}
return listOf(tm)
}
}
object BiggerViews {
private val views = mutableListOf<View>()
fun show(title: String, image: Image?, url: MHUrl?, server: Server?) {
val view = if (views.isEmpty()) {
logger.info { "creating img viewer window" }
View()
} else views.removeAt(views.size - 1)
view.show(title, image)
if (url != null && server != null) {
view.imageView.setMxc(url, server)
} else {
logger.debug { "url=$url, server=$server"}
}
}
private class View {
val root = StackPane()
private val scene = Scene(root)
private val stage = Stage().apply {
isResizable = true
}
val imageView = FitImageRegion(cover = false)
private val closed = AtomicBoolean(false)
init {
stage.scene = scene
stage.initOwner(JFX.primaryStage)
root.add(imageView)
stage.addEventFilter(KeyEvent.KEY_RELEASED) {
if (it.code != KeyCode.ESCAPE) return@addEventFilter
it.consume()
stage.close()
}
stage.onHidden = EventHandler{ close() }
}
private fun close() {
imageView.image = null
if (closed.getAndSet(true)) {
logger.debug { "image viewer $this already closed" }
return
}
if (views.size < 3) views.add(this)
}
fun show(title: String, image: Image?) {
closed.set(false)
logger.debug { "viewing image $image" }
imageView.image = image
this.stage.title = title
stage.show()
}
}
}
| gpl-3.0 | 2729af236cf1e660c643920e3ebbfcf5 | 29.140845 | 96 | 0.580374 | 4.407827 | false | false | false | false |
Bambooin/trime | app/src/main/java/com/osfans/trime/util/ShortcutUtils.kt | 1 | 5963 | package com.osfans.trime.util
import android.app.SearchManager
import android.content.ClipboardManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.icu.text.DateFormat
import android.icu.util.Calendar
import android.icu.util.ULocale
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.SparseArray
import android.view.KeyEvent
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.IntentUtils
import com.osfans.trime.core.Rime
import com.osfans.trime.data.AppPrefs
import com.osfans.trime.ime.core.Trime
import com.osfans.trime.settings.LogActivity
import timber.log.Timber
import java.text.FieldPosition
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* Implementation to open/call specified application/function
*/
object ShortcutUtils {
fun call(context: Context, command: String, option: String): CharSequence? {
when (command) {
"broadcast" -> context.sendBroadcast(Intent(option))
"clipboard" -> return pasteFromClipboard(context)
"date" -> return getDate(option)
"run" -> startIntent(option)
"share_text" -> Trime.getService().shareText()
"liquid_keyboard" -> Trime.getService().selectLiquidKeyboard(option)
else -> startIntent(command, option)
}
return null
}
private fun startIntent(arg: String) {
val intent = when {
arg.indexOf(':') >= 0 -> {
Intent.parseUri(arg, Intent.URI_INTENT_SCHEME)
}
arg.indexOf('/') >= 0 -> {
Intent(Intent.ACTION_MAIN).apply {
addCategory(Intent.CATEGORY_LAUNCHER)
component = ComponentName.unflattenFromString(arg)
}
}
else -> IntentUtils.getLaunchAppIntent(arg)
}
intent.flags = (
Intent.FLAG_ACTIVITY_NEW_TASK
or Intent.FLAG_ACTIVITY_NO_HISTORY
)
ActivityUtils.startActivity(intent)
}
private fun startIntent(action: String, arg: String) {
val act = "android.intent.action.${action.uppercase()}"
var intent = Intent(act)
when (act) {
// Search or open link
// Note that web_search cannot directly open link
Intent.ACTION_WEB_SEARCH, Intent.ACTION_SEARCH -> {
if (arg.startsWith("http")) {
startIntent(arg)
ActivityUtils.startLauncherActivity()
return
} else {
intent.putExtra(SearchManager.QUERY, arg)
}
}
// Share text
Intent.ACTION_SEND -> intent = IntentUtils.getShareTextIntent(arg)
// Stage the data
else -> {
if (arg.isNotEmpty()) Intent(act).data = Uri.parse(arg) else Intent(act)
}
}
intent.flags = (Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY)
ActivityUtils.startActivity(intent)
}
private fun getDate(string: String): CharSequence {
var option = ""
var locale = ""
if (string.contains("@")) {
val opt = string.split(" ".toRegex(), 2)
if (opt.size == 2 && opt[0].contains("@")) {
locale = opt[0]
option = opt[1]
} else {
locale = opt[0]
}
}
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !TextUtils.isEmpty(locale)) {
val ul = ULocale(locale)
val cc = Calendar.getInstance(ul)
val df = if (option.isEmpty()) {
DateFormat.getDateInstance(DateFormat.LONG, ul)
} else {
android.icu.text.SimpleDateFormat(option, ul.toLocale())
}
df.format(cc, StringBuffer(256), FieldPosition(0)).toString()
} else {
SimpleDateFormat(string, Locale.getDefault()).format(Date()) // Time
}
}
fun pasteFromClipboard(context: Context): CharSequence? {
val systemClipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val systemPrimaryClip = systemClipboardManager.getPrimaryClip()
val clipItem = systemPrimaryClip?.getItemAt(0)
return clipItem?.coerceToText(context)
}
fun syncInBackground(context: Context) {
val prefs = AppPrefs.defaultInstance()
prefs.conf.lastBackgroundSync = Date().time
prefs.conf.lastSyncStatus = Rime.syncUserData(context)
}
fun openCategory(keyCode: Int): Boolean {
val category = applicationLaunchKeyCategories[keyCode]
return if (category != null) {
Timber.d("\t<TrimeInput>\topenCategory()\tkeycode=%d, app=%s", keyCode, category)
val intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY
ActivityUtils.startActivity(intent)
true
} else false
}
private val applicationLaunchKeyCategories = SparseArray<String>().apply {
append(KeyEvent.KEYCODE_EXPLORER, "android.intent.category.APP_BROWSER")
append(KeyEvent.KEYCODE_ENVELOPE, "android.intent.category.APP_EMAIL")
append(KeyEvent.KEYCODE_CONTACTS, "android.intent.category.APP_CONTACTS")
append(KeyEvent.KEYCODE_CALENDAR, "android.intent.category.APP_CALENDAR")
append(KeyEvent.KEYCODE_MUSIC, "android.intent.category.APP_MUSIC")
append(KeyEvent.KEYCODE_CALCULATOR, "android.intent.category.APP_CALCULATOR")
}
fun launchLogActivity(context: Context) {
context.startActivity(
Intent(context, LogActivity::class.java)
)
}
}
| gpl-3.0 | 7e932a2f9ce091480a76ab5d540105a3 | 37.470968 | 108 | 0.621164 | 4.486832 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/db/entity/NotePosition.kt | 1 | 936 | package com.orgzly.android.db.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
/**
* Note's position in the book.
*/
data class NotePosition(
@ColumnInfo(name = "book_id")
val bookId: Long,
/** Nested set model's left and right values */
val lft: Long = 0,
val rgt: Long = 0,
/** Level (depth) of a note */
val level: Int = 0,
/** ID of the parent note */
@ColumnInfo(name = "parent_id")
val parentId: Long = 0,
/** ID of the folded note which hides this one */
@ColumnInfo(name = "folded_under_id")
val foldedUnderId: Long = 0,
/** Is the note folded (collapsed) or unfolded (expanded) */
@ColumnInfo(name = "is_folded")
val isFolded: Boolean = false,
/** Number of descendants */
@ColumnInfo(name = "descendants_count")
val descendantsCount: Int = 0
) | gpl-3.0 | ae1f7ba82b27c2d280ec6ea46b6d9f8e | 25.771429 | 69 | 0.575855 | 3.949367 | false | false | false | false |
YouriAckx/AdventOfCode | 2017/src/day13/part2/part02-naive.kt | 1 | 1946 | package day13.part2
import java.io.File
/*
This solution works with the sample, but fails on the actual input because of the caching.
java.lang.OutOfMemoryError: GC overhead limit exceeded
Without caching, it is even slower to progress and it won't complete in a timely manner.
*/
data class Layer(val range: Int, val scanPosition: Int, private val direction: Int) {
fun roam(): Layer {
val newPosition = scanPosition + direction
return when {
newPosition < 0 -> this.copy(scanPosition = 1, direction = +1)
newPosition == range -> this.copy(scanPosition = range - 2, direction = -1)
else -> this.copy(scanPosition = newPosition)
}
}
companion object {
fun roamAll(layers: Map<Int, Layer>): Map<Int, Layer> {
val relayers = layers.toMutableMap()
relayers.forEach { n, l -> relayers[n] = l.roam() }
return relayers
}
}
}
class PacketWalker(val layers: Map<Int, Layer>) {
var waitedStates = mutableMapOf<Int, Map<Int, Layer>>()
private fun walk(delay: Int): Boolean {
println(delay)
var relayers = if (delay > 0) Layer.roamAll(waitedStates[delay - 1]!!) else layers
waitedStates[delay] = HashMap(relayers)//relayers.toMap()
return (0..layers.keys.max()!!).any { packet ->
val hit = relayers[packet]?.scanPosition == 0
relayers = Layer.roamAll(relayers)
hit
}
}
fun waitTimeBeforeCrossing() = generateSequence(0) { it + 1 }.dropWhile { walk(it) }.first()
}
fun main(args: Array<String>) {
val layers = File("src/day13/input.txt").readLines()
.map { it.split(": ").map { it.toInt() } }
.associateBy({ it[0] }, { Layer(it[1], 0, +1) })
.toMutableMap() // k=layer number; v=f/w layer
val packetWalker = PacketWalker(layers)
println(packetWalker.waitTimeBeforeCrossing())
}
| gpl-3.0 | f9cb9067a905ea3686b67099a8e82c6c | 33.140351 | 96 | 0.613052 | 3.838264 | false | false | false | false |
Litote/kmongo | kmongo-coroutine-core/src/main/kotlin/org/litote/kmongo/coroutine/CoroutineChangeStreamPublisher.kt | 1 | 4729 | /*
* Copyright (C) 2016/2022 Litote
*
* 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.litote.kmongo.coroutine
import com.mongodb.client.model.Collation
import com.mongodb.client.model.changestream.ChangeStreamDocument
import com.mongodb.client.model.changestream.FullDocument
import com.mongodb.reactivestreams.client.ChangeStreamPublisher
import kotlinx.coroutines.reactive.awaitFirstOrNull
import org.bson.BsonDocument
import org.bson.BsonTimestamp
import java.util.concurrent.TimeUnit
/**
* Gets coroutine version of [ChangeStreamPublisher].
*/
val <T: Any> ChangeStreamPublisher<T>.coroutine: CoroutineChangeStreamPublisher<T>
get() = CoroutineChangeStreamPublisher(
this
)
/**
* Coroutine wrapper around [ChangeStreamPublisher].
*/
class CoroutineChangeStreamPublisher<TResult: Any>(override val publisher: ChangeStreamPublisher<TResult>) :
CoroutinePublisher<ChangeStreamDocument<TResult>>(publisher) {
/**
* Sets the fullDocument value.
*
* @param fullDocument the fullDocument
* @return this
*/
fun fullDocument(fullDocument: FullDocument): CoroutineChangeStreamPublisher<TResult> =
publisher.fullDocument(fullDocument).coroutine
/**
* Sets the logical starting point for the new change stream.
*
* @param resumeToken the resume token
* @return this
*/
fun resumeAfter(resumeToken: BsonDocument): CoroutineChangeStreamPublisher<TResult> =
publisher.resumeAfter(resumeToken).coroutine
/**
* The change stream will only provide changes that occurred after the specified timestamp.
*
*
* Any command run against the server will return an operation time that can be used here.
*
* The default value is an operation time obtained from the server before the change stream was created.
*
* @param startAtOperationTime the start at operation time
* @since 1.9
* @return this
* @mongodb.server.release 4.0
* @mongodb.driver.manual reference/method/db.runCommand/
*/
fun startAtOperationTime(startAtOperationTime: BsonTimestamp): CoroutineChangeStreamPublisher<TResult> =
publisher.startAtOperationTime(startAtOperationTime).coroutine
/**
* Sets the maximum await execution time on the server for this operation.
*
* @param maxAwaitTime the max await time. A zero value will be ignored, and indicates that the driver should respect the server's
* default value
* @param timeUnit the time unit, which may not be null
* @return this
*/
fun maxAwaitTime(maxAwaitTime: Long, timeUnit: TimeUnit): CoroutineChangeStreamPublisher<TResult> =
publisher.maxAwaitTime(maxAwaitTime, timeUnit).coroutine
/**
* Sets the collation options
*
*
* A null value represents the server default.
* @param collation the collation options to use
* @return this
*/
fun collation(collation: Collation): CoroutineChangeStreamPublisher<TResult> =
publisher.collation(collation).coroutine
/**
* Returns a list containing the results of the change stream based on the document class provided.
*
* @param <TDocument> the result type
* @return the new Mongo Iterable
*/
suspend inline fun <reified TDocument> withDocumentClass(): List<TDocument> =
publisher.withDocumentClass(TDocument::class.java).toList()
/**
* Sets the number of documents to return per batch.
*
*
* Overrides the [org.reactivestreams.Subscription.request] value for setting the batch size, allowing for fine grained
* control over the underlying cursor.
*
* @param batchSize the batch size
* @return this
* @since 1.8
* @mongodb.driver.manual reference/method/cursor.batchSize/#cursor.batchSize Batch Size
*/
fun batchSize(batchSize: Int): CoroutineChangeStreamPublisher<TResult> =
publisher.batchSize(batchSize).coroutine
/**
* Helper to return a publisher limited to the first result.
*
* @return a single item.
* @since 1.8
*/
suspend fun first(): ChangeStreamDocument<TResult>? = publisher.first().awaitFirstOrNull()
}
| apache-2.0 | 1d6b9baf0b224d93a004fa6c5a3ab881 | 35.376923 | 136 | 0.71495 | 4.534036 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/test/testdata/inspections/unsafeIterators/OrderedMap.kt | 1 | 746 | package main
import com.badlogic.gdx.utils.ObjectMap
import com.badlogic.gdx.utils.OrderedMap
@Suppress("UNUSED_VARIABLE", "UNCHECKED_CAST", "USELESS_CAST")
class OrderedMapT {
var map = OrderedMap<String, Any>()
var map2 = OrderedMap<String, OrderedMap<String, Any>>()
fun test() {
map2.put("abc", map)
for (e in <warning>map2</warning>) {
for (e1 in <warning>e.value</warning>) {
}
}
}
var i1: Iterator<Any> = <warning>map.keys()</warning>
var i2: Iterator<Any> = <warning>map.values()</warning>
var i3: Iterator<Any> = <warning>map.iterator()</warning>
var i4: Iterator<Any> = <warning>map.entries()</warning>
var o: Any = <warning><warning>map2.values()</warning>.next().values()</warning>
}
| apache-2.0 | 59e1601316281c9d1cef3b03a426b2fe | 23.866667 | 82 | 0.659517 | 3.188034 | false | false | false | false |
josegonzalez/kotterknife | src/main/kotlin/butterknife/ButterKnife.kt | 1 | 4918 | package butterknife
import android.app.Activity
import android.app.Dialog
import android.app.Fragment
import android.support.v4.app.Fragment as SupportFragment
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import kotlin.properties.ReadOnlyProperty
public fun <V : View> View.bindView(id: Int)
: ReadOnlyProperty<View, V> = required(id, ::findViewById)
public fun <V : View> Activity.bindView(id: Int)
: ReadOnlyProperty<Activity, V> = required(id, ::findViewById)
public fun <V : View> Dialog.bindView(id: Int)
: ReadOnlyProperty<Dialog, V> = required(id, ::findViewById)
public fun <V : View> Fragment.bindView(id: Int)
: ReadOnlyProperty<Fragment, V> = required(id, ::findViewById)
public fun <V : View> SupportFragment.bindView(id: Int)
: ReadOnlyProperty<SupportFragment, V> = required(id, ::findViewById)
public fun <V : View> ViewHolder.bindView(id: Int)
: ReadOnlyProperty<ViewHolder, V> = required(id, ::findViewById)
public fun <V : View> View.bindOptionalView(id: Int)
: ReadOnlyProperty<View, V?> = optional(id, ::findViewById)
public fun <V : View> Activity.bindOptionalView(id: Int)
: ReadOnlyProperty<Activity, V?> = optional(id, ::findViewById)
public fun <V : View> Dialog.bindOptionalView(id: Int)
: ReadOnlyProperty<Dialog, V?> = optional(id, ::findViewById)
public fun <V : View> Fragment.bindOptionalView(id: Int)
: ReadOnlyProperty<Fragment, V?> = optional(id, ::findViewById)
public fun <V : View> SupportFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<SupportFragment, V?> = optional(id, ::findViewById)
public fun <V : View> ViewHolder.bindOptionalView(id: Int)
: ReadOnlyProperty<ViewHolder, V?> = optional(id, ::findViewById)
public fun <V : View> View.bindViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = required(ids, ::findViewById)
public fun <V : View> Activity.bindViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = required(ids, ::findViewById)
public fun <V : View> Dialog.bindViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = required(ids, ::findViewById)
public fun <V : View> Fragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<Fragment, List<V>> = required(ids, ::findViewById)
public fun <V : View> SupportFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<SupportFragment, List<V>> = required(ids, ::findViewById)
public fun <V : View> ViewHolder.bindViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = required(ids, ::findViewById)
public fun <V : View> View.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = optional(ids, ::findViewById)
public fun <V : View> Activity.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = optional(ids, ::findViewById)
public fun <V : View> Dialog.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = optional(ids, ::findViewById)
public fun <V : View> Fragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Fragment, List<V>> = optional(ids, ::findViewById)
public fun <V : View> SupportFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<SupportFragment, List<V>> = optional(ids, ::findViewById)
public fun <V : View> ViewHolder.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = optional(ids, ::findViewById)
private fun Fragment.findViewById(id: Int): View? = getView().findViewById(id)
private fun SupportFragment.findViewById(id: Int): View? = getView().findViewById(id)
private fun ViewHolder.findViewById(id: Int): View? = itemView.findViewById(id)
private fun viewNotFound(id:Int, desc: PropertyMetadata) =
throw IllegalStateException("View ID $id for '${desc.name}' not found.")
suppress("UNCHECKED_CAST")
private fun required<T, V : View>(id: Int, finder : T.(Int) -> View?)
= Lazy { t : T, desc -> t.finder(id) as V? ?: viewNotFound(id, desc) }
suppress("UNCHECKED_CAST")
private fun optional<T, V : View>(id: Int, finder : T.(Int) -> View?)
= Lazy { t : T, desc -> t.finder(id) as V? }
suppress("UNCHECKED_CAST")
private fun required<T, V : View>(ids: IntArray, finder : T.(Int) -> View?)
= Lazy { t : T, desc -> ids.map { t.finder(it) as V? ?: viewNotFound(it, desc) } }
suppress("UNCHECKED_CAST")
private fun optional<T, V : View>(ids: IntArray, finder : T.(Int) -> View?)
= Lazy { t : T, desc -> ids.map { t.finder(it) as V? }.filterNotNull() }
// Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it
private class Lazy<T, V>(private val initializer : (T, PropertyMetadata) -> V) : ReadOnlyProperty<T, V> {
private object EMPTY
private var value: Any? = EMPTY
override fun get(thisRef: T, desc: PropertyMetadata): V {
if (value == EMPTY) {
value = initializer(thisRef, desc)
}
@suppress("UNCHECKED_CAST")
return value as V
}
}
| apache-2.0 | d518eb7be51a7be7a6bc79725d3f0b2d | 49.183673 | 105 | 0.712688 | 3.731411 | false | false | false | false |
AlekseyZhelo/LBM | LWJGL_APP/src/main/java/com/alekseyzhelo/lbm/gui/lwjgl/render/util/RenderUtil.kt | 1 | 1296 | package com.alekseyzhelo.lbm.gui.lwjgl.render.util
private fun binarySearch(a: FloatArray, key: Float): Int {
var low = 0
var high = a.size - 1
while (low <= high) {
val mid = (low + high).ushr(1)
val midVal = a[mid]
if (midVal < key)
low = mid + 1 // Neither val is NaN, thisVal is smaller
else if (midVal > key)
high = mid - 1 // Neither val is NaN, thisVal is larger
else {
val midBits = java.lang.Float.floatToIntBits(midVal)
val keyBits = java.lang.Float.floatToIntBits(key)
if (midBits == keyBits)
// Values are equal
return if (mid > 0) mid - 1 else mid // Key found
else if (midBits < keyBits)
// (-0.0, 0.0) or (!NaN, NaN)
low = mid + 1
else
// (0.0, -0.0) or (NaN, !NaN)
high = mid - 1
}
}
return low - 1 // key not found.
}
private val x = floatArrayOf(0.0f, 0.15f, 0.4f, 0.5f, 0.65f, 0.8f, 1.0f)
private val r = floatArrayOf(0.0f, 0.0f, 0.0f, 0.56470588f, 1.0f, 1.0f, 0.54509804f)
private val g = floatArrayOf(0.0f, 0.0f, 1.0f, 0.93333333f, 1.0f, 0.0f, 0.0f)
private val b = floatArrayOf(0.54509804f, 1.0f, 1.0f, 0.56470588f, 0.0f, 0.0f, 0.0f) | apache-2.0 | b978ce9fc9778461dec277f747cd8ce4 | 36.057143 | 84 | 0.537809 | 2.886414 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/command/mute/MuteCommand.kt | 1 | 2993 | /*
* Copyright 2021 Ren Binden
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.chat.bukkit.command.mute
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelName
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
/**
* Mute command.
* Mutes a chat channel.
*/
class MuteCommand(private val plugin: RPKChatBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
if (args.isEmpty()) {
sender.sendMessage(plugin.messages["mute-usage"])
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return true
}
val chatChannelService = Services[RPKChatChannelService::class.java]
if (chatChannelService == null) {
sender.sendMessage(plugin.messages["no-chat-channel-service"])
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return true
}
val chatChannel = chatChannelService.getChatChannel(RPKChatChannelName(args[0]))
if (chatChannel == null) {
sender.sendMessage(plugin.messages["mute-invalid-chatchannel"])
return true
}
if (!sender.hasPermission("rpkit.chat.command.mute.${chatChannel.name.value}")) {
sender.sendMessage(plugin.messages["no-permission-mute", mapOf(
"channel" to chatChannel.name.value
)])
return true
}
chatChannel.removeListener(minecraftProfile)
sender.sendMessage(plugin.messages["mute-valid", mapOf(
"channel" to chatChannel.name.value
)])
return true
}
}
| apache-2.0 | c7599bf378573289ddad542b092c6d2d | 38.381579 | 118 | 0.6856 | 4.691223 | false | false | false | false |
ansman/kotshi | tests/src/main/kotlin/se/ansman/kotshi/ClassWithManyProperties.kt | 1 | 1949 | package se.ansman.kotshi
@JsonSerializable
data class ClassWithManyProperties(
val v1: String = "v1",
val v2: String = "v2",
val v3: String = "v3",
val v4: String = "v4",
val v5: String = "v5",
val v6: String = "v6",
val v7: String = "v7",
val v8: String = "v8",
val v9: String = "v9",
val v10: String = "v10",
val v11: String = "v11",
val v12: String = "v12",
val v13: String = "v13",
val v14: String = "v14",
val v15: String = "v15",
val v16: String = "v16",
val v17: String = "v17",
val v18: String = "v18",
val v19: String = "v19",
val v20: String = "v20",
val v21: String = "v21",
val v22: String = "v22",
val v23: String = "v23",
val v24: String = "v24",
val v25: String = "v25",
val v26: String = "v26",
val v27: String = "v27",
val v28: String = "v28",
val v29: String = "v29",
val v30: String = "v30",
val v31: String = "v31",
val v32: String = "v32",
val v33: String = "v33",
val v34: String = "v34",
val v35: String = "v35",
val v36: String = "v36",
val v37: String = "v37",
val v38: String = "v38",
val v39: String = "v39",
val v40: String = "v40",
val v41: String = "v41",
val v42: String = "v42",
val v43: String = "v43",
val v44: String = "v44",
val v45: String = "v45",
val v46: String = "v46",
val v47: String = "v47",
val v48: String = "v48",
val v49: String = "v49",
val v50: String = "v50",
val v51: String = "v51",
val v52: String = "v52",
val v53: String = "v53",
val v54: String = "v54",
val v55: String = "v55",
val v56: String = "v56",
val v57: String = "v57",
val v58: String = "v58",
val v59: String = "v59",
val v60: String = "v60",
val v61: String = "v61",
val v62: String = "v62",
val v63: String = "v63",
val v64: String = "v64",
val v65: String = "v65",
)
| apache-2.0 | 17ad7d0bfe3fa590901abc2374d97f29 | 26.842857 | 35 | 0.526424 | 2.651701 | false | false | false | false |
andrei-heidelbacher/algostorm | algostorm-systems/src/main/kotlin/com/andreihh/algostorm/systems/graphics2d/GraphicsSystem.kt | 1 | 1319 | /*
* Copyright (c) 2017 Andrei Heidelbacher <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.andreihh.algostorm.systems.graphics2d
import com.andreihh.algostorm.systems.EventSystem
abstract class GraphicsSystem : EventSystem() {
companion object {
const val TILE_WIDTH: String = "TILE_WIDTH"
const val TILE_HEIGHT: String = "TILE_HEIGHT"
const val TILE_SET_COLLECTION: String = "TILE_SET_COLLECTION"
const val CAMERA: String = "CAMERA"
const val GRAPHICS_DRIVER: String = "GRAPHICS_DRIVER"
}
protected val tileWidth: Int by context(TILE_WIDTH)
protected val tileHeight: Int by context(TILE_HEIGHT)
protected val tileSetCollection: TileSetCollection
by context(TILE_SET_COLLECTION)
}
| apache-2.0 | ade884d7fd33fdc3bc124b7f153a223b | 37.794118 | 75 | 0.724033 | 4.174051 | false | false | false | false |
mplatvoet/kovenant | projects/core/src/main/kotlin/queue-jvm.kt | 1 | 3602 | /*
* Copyright (c) 2015 Mark Platvoet<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* THE SOFTWARE.
*/
package nl.komponents.kovenant
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicInteger
class NonBlockingWorkQueue<V : Any>() : BlockingSupportWorkQueue<V>() {
private val queue = ConcurrentLinkedQueue<V>()
override fun tryPoll(): V? = queue.poll()
override fun tryOffer(elem: V): Boolean = queue.offer(elem)
override fun size(): Int = queue.size
override fun isEmpty(): Boolean = queue.isEmpty()
override fun isNotEmpty(): Boolean = !isEmpty()
override fun remove(elem: Any?): Boolean = queue.remove(elem)
}
abstract class BlockingSupportWorkQueue<V : Any>() : WorkQueue<V> {
private val waitingThreads = AtomicInteger(0)
//yes I could also use a ReentrantLock with a Condition but
//introduces quite a lot of overhead and the semantics
//are just the same
private val mutex = Object()
abstract fun tryPoll(): V?
abstract fun tryOffer(elem: V): Boolean
override fun offer(elem: V): Boolean {
val added = tryOffer(elem)
if (added && waitingThreads.get() > 0) {
synchronized(mutex) {
//maybe there aren't any threads waiting or
//there isn't anything in the queue anymore
//just notify, we've got this far
mutex.notifyAll()
}
}
return added
}
override fun poll(block: Boolean, timeoutMs: Long): V? {
if (!block) return tryPoll()
val elem = tryPoll()
if (elem != null) return elem
waitingThreads.incrementAndGet()
try {
return if (timeoutMs > -1L) {
blockingPoll(timeoutMs)
} else {
blockingPoll()
}
} finally {
waitingThreads.decrementAndGet()
}
}
private fun blockingPoll(): V? {
synchronized(mutex) {
while (true) {
val retry = tryPoll()
if (retry != null) return retry
mutex.wait()
}
}
throw KovenantException("unreachable")
}
private fun blockingPoll(timeoutMs: Long): V? {
val deadline = System.currentTimeMillis() + timeoutMs
synchronized(mutex) {
while (true) {
val retry = tryPoll()
if (retry != null || System.currentTimeMillis() >= deadline) return retry
mutex.wait(timeoutMs)
}
}
throw KovenantException("unreachable")
}
}
| mit | 9c873f97197dda74a414ac083ca6fedb | 31.745455 | 89 | 0.632149 | 4.690104 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/ui/preferences/components/AppItem.kt | 1 | 3205 | /*
* Copyright 2021, Lawnchair
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.lawnchair.ui.preferences.components
import android.graphics.Bitmap
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import app.lawnchair.util.App
import com.google.accompanist.placeholder.PlaceholderHighlight
import com.google.accompanist.placeholder.material.fade
import com.google.accompanist.placeholder.material.placeholder
@Composable
fun AppItem(
app: App,
onClick: (app: App) -> Unit,
widget: (@Composable () -> Unit)? = null,
) {
AppItem(
label = app.label,
icon = app.icon,
onClick = { onClick(app) },
widget = widget,
)
}
@Composable
fun AppItem(
label: String,
icon: Bitmap,
onClick: () -> Unit,
widget: (@Composable () -> Unit)? = null,
) {
AppItemLayout(
modifier = Modifier
.clickable(onClick = onClick),
widget = widget,
icon = {
Image(
bitmap = icon.asImageBitmap(),
contentDescription = null,
modifier = Modifier.size(30.dp),
)
},
title = { Text(text = label) }
)
}
@Composable
fun AppItemPlaceholder(
widget: (@Composable () -> Unit)? = null,
) {
AppItemLayout(
widget = widget,
icon = {
Spacer(
modifier = Modifier
.size(30.dp)
.placeholder(
visible = true,
highlight = PlaceholderHighlight.fade(),
)
)
}
) {
Spacer(
modifier = Modifier
.width(120.dp)
.height(24.dp)
.placeholder(
visible = true,
highlight = PlaceholderHighlight.fade(),
)
)
}
}
@Composable
private fun AppItemLayout(
modifier: Modifier = Modifier,
widget: (@Composable () -> Unit)? = null,
icon: @Composable () -> Unit,
title: @Composable () -> Unit,
) {
PreferenceTemplate(
title = title,
modifier = modifier,
startWidget = {
widget?.let {
it()
Spacer(modifier = Modifier.requiredWidth(16.dp))
}
icon()
},
verticalPadding = 12.dp
)
}
| gpl-3.0 | 54cc621df2a7e8398766c7c9f17f112b | 26.161017 | 75 | 0.588768 | 4.470014 | false | false | false | false |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/ArenaMetaEntity.kt | 1 | 7464 | @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.BallActionType
import com.github.shynixn.blockball.api.business.enumeration.ParticleType
import com.github.shynixn.blockball.api.business.enumeration.PlaceHolder
import com.github.shynixn.blockball.api.persistence.entity.ArenaMeta
import com.github.shynixn.blockball.api.persistence.entity.HologramMeta
/**
* 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 ArenaMetaEntity : ArenaMeta {
/** Meta data for spectating setting. */
@YamlSerialize(orderNumber = 12, value = "spectator-meta")
override val spectatorMeta: SpectatorMetaEntity = SpectatorMetaEntity()
/** Meta data of the customizing Properties. */
@YamlSerialize(orderNumber = 13, value = "customizing-meta")
override val customizingMeta: CustomizationMetaEntity = CustomizationMetaEntity()
/** Meta data for rewards */
@YamlSerialize(orderNumber = 10, value = "reward-meta")
override val rewardMeta: RewardEntity = RewardEntity()
/** Meta data of all holograms. */
override val hologramMetas: ArrayList<HologramMeta>
get() = this.internalHologramMetas as ArrayList<HologramMeta>
/** Meta data of a generic lobby. */
@YamlSerialize(orderNumber = 1, value = "meta")
override val lobbyMeta: LobbyMetaEntity = LobbyMetaEntity()
/** Meta data of the hub lobby. */
@YamlSerialize(orderNumber = 2, value = "hubgame-meta")
override var hubLobbyMeta: HubLobbyMetaEntity = HubLobbyMetaEntity()
/** Meta data of the minigame lobby. */
@YamlSerialize(orderNumber = 3, value = "minigame-meta")
override val minigameMeta: MinigameLobbyMetaEntity = MinigameLobbyMetaEntity()
/** Meta data of the bungeecord lobby. */
@YamlSerialize(orderNumber = 4, value = "bungeecord-meta")
override val bungeeCordMeta: BungeeCordLobbyMetaEntity = BungeeCordLobbyMetaEntity()
/** Meta data of the doubleJump. */
@YamlSerialize(orderNumber = 8, value = "double-jump")
override val doubleJumpMeta: DoubleJumpMetaEntity = DoubleJumpMetaEntity()
/** Meta data of the bossbar. */
@YamlSerialize(orderNumber = 7, value = "bossbar")
override val bossBarMeta: BossBarMetaEntity = BossBarMetaEntity()
/** Meta data of the scoreboard. */
@YamlSerialize(orderNumber = 6, value = "scoreboard")
override val scoreboardMeta: ScoreboardEntity = ScoreboardEntity()
/** Meta data of proection. */
@YamlSerialize(orderNumber = 5, value = "protection")
override val protectionMeta: ArenaProtectionMetaEntity = ArenaProtectionMetaEntity()
/** Meta data of the ball. */
@YamlSerialize(orderNumber = 4, value = "ball")
override val ballMeta: BallMetaEntity = BallMetaEntity("http://textures.minecraft.net/texture/8e4a70b7bbcd7a8c322d522520491a27ea6b83d60ecf961d2b4efbbf9f605d")
/** Meta data of the blueTeam. */
@YamlSerialize(orderNumber = 3, value = "team-blue")
override val blueTeamMeta: TeamMetaEntity = TeamMetaEntity("Team Blue", "&9", PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.BLUE_GOALS.placeHolder + " : " + PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.RED_GOALS.placeHolder, PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.LASTHITBALL.placeHolder + " scored for " + PlaceHolder.TEAM_BLUE.placeHolder, PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.TEAM_BLUE.placeHolder, PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.TEAM_BLUE.placeHolder + "&a has won the match", PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.TEAM_BLUE.placeHolder, "&eMatch ended in a draw.")
/** Meta data of the redTeam. */
@YamlSerialize(orderNumber = 2, value = "team-red")
override val redTeamMeta: TeamMetaEntity = TeamMetaEntity("Team Red", "&c", PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.RED_GOALS.placeHolder + " : " + PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.BLUE_GOALS.placeHolder, PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.LASTHITBALL.placeHolder + " scored for " + PlaceHolder.TEAM_RED.placeHolder, PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.TEAM_RED.placeHolder, PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.TEAM_RED.placeHolder + "&a has won the match", PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.TEAM_RED.placeHolder, "&eMatch ended in a draw.")
@YamlSerialize(orderNumber = 9, value = "holograms")
private val internalHologramMetas: ArrayList<HologramMetaEntity> = ArrayList()
init {
val partMetaSpawn = ParticleEntity()
partMetaSpawn.typeName = ParticleType.EXPLOSION_NORMAL.name
partMetaSpawn.amount = 10
partMetaSpawn.speed = 0.1
partMetaSpawn.offset.x = 2.0
partMetaSpawn.offset.y = 2.0
partMetaSpawn.offset.z = 2.0
ballMeta.particleEffects[BallActionType.ONSPAWN] = partMetaSpawn
val partMetaInteraction = ParticleEntity()
partMetaInteraction.typeName = ParticleType.CRIT.name
partMetaInteraction.amount = 5
partMetaInteraction.speed = 0.1
partMetaInteraction.offset.x = 2.0
partMetaInteraction.offset.y = 2.0
partMetaInteraction.offset.z = 2.0
ballMeta.particleEffects[BallActionType.ONINTERACTION] = partMetaInteraction
val partMetaKick = ParticleEntity()
partMetaKick.typeName = ParticleType.EXPLOSION_LARGE.name
partMetaKick.amount = 5
partMetaKick.speed = 0.1
partMetaKick.offset.x = 0.2
partMetaKick.offset.y = 0.2
partMetaKick.offset.z = 0.2
ballMeta.particleEffects[BallActionType.ONKICK] = partMetaKick
val partMetaShoot = ParticleEntity()
partMetaShoot.typeName = ParticleType.EXPLOSION_NORMAL.name
partMetaShoot.amount = 5
partMetaShoot.speed = 0.1
partMetaShoot.offset.x = 0.1
partMetaShoot.offset.y = 0.1
partMetaShoot.offset.z = 0.1
ballMeta.particleEffects[BallActionType.ONPASS] = partMetaShoot
val soundMetaKick = SoundEntity()
soundMetaKick.name = "ZOMBIE_WOOD"
soundMetaKick.volume = 10.0
soundMetaKick.pitch = 1.5
ballMeta.soundEffects[BallActionType.ONKICK] = soundMetaKick
}
} | apache-2.0 | 141b48bfcfc85a113b0c981edda5f8a5 | 53.489051 | 630 | 0.733655 | 3.922228 | false | false | false | false |
HerbLuo/shop-api | src/main/java/cn/cloudself/service/impl/OrderServiceImpl.kt | 1 | 9882 | package cn.cloudself.service.impl
import cn.cloudself.components.annotation.ParamChecker
import cn.cloudself.dao.*
import cn.cloudself.exception.http.RequestBadException
import cn.cloudself.exception.http.ServerException
import cn.cloudself.model.*
import cn.cloudself.service.IOrderService
import org.apache.log4j.Logger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.util.Assert
/**
* @author HerbLuo
* @version 1.0.0.d
*/
@Service
@Transactional
open class OrderServiceImpl @Autowired
constructor(
private val orderDao: IOrderDao,
private val itemDao: IItemDao,
private val addressDao: IAddressDao,
private val itemSellingInfoDao: IItemSellingInfoDao,
private val deliverDao: IDeliverDao,
private val orderAShopDao: IOrderAShopDao,
private val messageDao: IMessageDao,
private val logger: Logger,
private val itemCommentDao: IItemCommentDao
) : IOrderService {
/**
* 取得历史订单
*
* @param userId 用户id
* @param page .
* @param aPageSize .
* @return .
*/
@ParamChecker(
greaterThan0 = intArrayOf(0, 2),
greaterOrEqual0 = intArrayOf(1)
)
@Throws(Exception::class)
override fun getOrdersByUser(
userId: Int, page: Int, aPageSize: Int
): Page<OrderEntity> {
return orderDao.findByUserIdAndEnabledTrue(
userId,
PageRequest(page, aPageSize, Sort(Sort.Direction.DESC, "createTime"))
)
}
/**
* 创建订单
*
* @param userId .
* @param orderAShops 订单(分为对个店铺)
* @return 订单id
*/
@ParamChecker(greaterThan0 = intArrayOf(0), notEmpty = intArrayOf(1))
@Throws(Exception::class)
override fun createOrder(userId: Int, orderAShops: List<OrderAShopEntity>): Int? {
// 1. 过滤orderAShop,将id 发货状态 收货状态 是否评论 折扣 设为默认值
// 2. 检查商品与商家是否对应
// 3. 检查收货地址是否为用户名下的收货地址(防止地址信息泄露)
// 4. 过滤orderAnItem 的id值 保证购买的商品数量(quantity)大于0
// 5. 商品库存检查
for (orderAShop in orderAShops) {
/*
* 1 request param to json bean
*/
orderAShop.id = 0
orderAShop.areDeliver = null
orderAShop.areReceive = null
orderAShop.areEvaluate = null
orderAShop.discount = null
orderAShop.userId = userId
/*
* 2
*/
// non-null check
val orderAnItems = orderAShop.orderAnItems
?: throw RequestBadException("items 不能为空")
val shopid = orderAShop.shop?.id ?: throw RequestBadException("shop 不能为空")
// 需要检查的item id
val itemIds = orderAnItems
.map { it.item ?: throw RequestBadException("items 不能为空")}
.map { it.id }
// 数据库中取出来的Item对象
itemDao.findAll(itemIds)
.filter { it.shop?.id != shopid }
.forEach { throw RequestBadException("商品信息与店铺所售不一致") }
/*
* 3
*/
val address = addressDao.findOne(orderAShop.address?.id
?: throw RequestBadException("address不能未空")
)
address.userId != userId &&
throw RequestBadException("地址信息不符要求")
for (orderAnItem in orderAnItems) {
orderAnItem.item == null &&
throw RequestBadException("商品信息不能为空")
/*
* 4
*/
orderAnItem.id = 0
orderAnItem.quantity <= 0 &&
throw RequestBadException("购买的商品数量不能小于0")
/*
* 5
*/
if (!kucunChecker(orderAnItem.item!!.id, orderAnItem.quantity)) {
throw RequestBadException("库存不足")
}
}
}
var order = OrderEntity()
order.userId = userId
order.orderAShops = orderAShops
order = orderDao.save(order)
return order.id
}
/**
* 检查库存预留方法
*
* @return .
*/
private fun kucunChecker(itemId: Int?, quantity: Int?): Boolean {
Assert.notNull(itemId)
Assert.notNull(quantity)
val itemSellingInfo = itemSellingInfoDao.findOne(itemId)
return itemSellingInfo != null &&
itemSellingInfo.inOrdering + quantity!! <= itemSellingInfo.quantity
}
/**
* 生成订单的支付信息
* 计算订单价格
*
* @param orderId .
* @param userId .
* @return .
*/
@ParamChecker(0, 1)
@Throws(Exception::class)
override fun pay(orderId: Int, userId: Int): PayEntity {
val order = orderDao.findOne(orderId)
if (order.areFinished!!) {
throw RequestBadException("订单已完成")
}
if (order.arePaied!!) {
throw RequestBadException("订单已支付")
}
if (order.userId != userId) {
throw RequestBadException("用户信息不符")
}
val orderAShops = order.orderAShops
Assert.notEmpty(orderAShops, "创建了错误的订单?")
/*
* 计算订单价格
*/
var discount = 0.0 //商家给的折扣
var totalCost = 0.0 //商品价格合计
for (orderAShop in orderAShops!!) {
/*
* 计算折扣
*/
val t = orderAShop.discount
discount += t ?: 0.0
val orderAnItems = orderAShop.orderAnItems!!
/*
* 累加商品价格
*/
for ((_, quantity, item) in orderAnItems) {
Assert.notNull(quantity, "商品数量为空?")
if (quantity <= 0) {
throw ServerException("商品数量小于0?")
}
logger.debug(item)
Assert.notNull(item, "商品信息为空?")
val itemPrice = item!!.price
if (itemPrice <= 0) {
throw ServerException("商品价格小于0?")
}
totalCost += itemPrice * quantity
}
}
/*
* 最终价格
*/
var pay = totalCost - discount
if (pay > 200000) {
throw RequestBadException("订单价格不能大于10万元")
}
pay = (pay * 100).toInt() / 100.0
if (pay <= 0) {
throw ServerException("订单价格不能小于0.01元")
}
val payEntity = newPay
payEntity.price = pay
return payEntity
}
private val newPay: PayEntity
get() {
val payEntity = PayEntity()
payEntity.thirdPayUrl = "https://pay.cloudself.cn/"
return payEntity
}
/**
* 发货
*
* @param sellerId 店主id
* @param orderAShopId 单个店铺的订单
* @param delivers 快递对象
*/
@ParamChecker(greaterThan0 = intArrayOf(0, 1), notEmpty = intArrayOf(2))
@Throws(Exception::class)
override fun deliver(
sellerId: Int, orderAShopId: Int, delivers: List<DeliverEntity>
): Iterable<DeliverEntity> {
// 单个店铺,单个订单不允许上传大于10个运单号
if (delivers.size > 10) {
throw RequestBadException("单个订单不允许上传大于10个物流运单号")
} else if (delivers.size > 5) {
logger.warn("运单号过多")
}
// 检测该订单是否属于 该店主
val ordershop = orderAShopDao.findOne(orderAShopId)
?: throw RequestBadException("订单不存在")
if (ordershop.shop!!.sellerId != sellerId) {
throw RequestBadException("店铺信息不符")
}
// 检测订单是否已发货
if (ordershop.areDeliver!!) {
throw RequestBadException("该订单已发货")
}
// 更改所有的id信息
for (deliver in delivers) {
deliver.orderAShopId = orderAShopId
}
val newdelivers = deliverDao.save(delivers)
// 将订单状态设置为已发货
ordershop.areDeliver = true
orderAShopDao.save(ordershop)
// 通知用户已发货
messageDao.save(MessageEntity("您的订单已发货", "发货信息", ordershop.userId!!))
return newdelivers
}
/**
* 收货
*
* @param userId 下单用户id
* @param orderAShopId 订单id(店铺)
* @return 是否执行成功
*/
override fun receiveOne(userId: Int?, orderAShopId: Int?): Boolean? {
return null
}
/**
* 评论
*
* @param itemComments 评论
*/
override fun comment(
itemComments: Iterable<ItemCommentEntity>, userId: Int
): Iterable<ItemCommentEntity> {
for (itemComment in itemComments) {
itemComment.createTime = null
itemComment.id = 0
itemComment.userId = userId
}
return itemCommentDao.save(itemComments)
}
} | mit | c129fec2043f07a24fdd69047fba1c42 | 25.817365 | 86 | 0.548682 | 3.926348 | false | false | false | false |
john9x/jdbi | kotlin/src/main/kotlin/org/jdbi/v3/core/kotlin/Extensions.kt | 2 | 4162 | /*
* 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.jdbi.v3.core.kotlin
import org.jdbi.v3.core.Jdbi
import org.jdbi.v3.core.extension.ExtensionCallback
import org.jdbi.v3.core.extension.ExtensionConsumer
import org.jdbi.v3.core.kotlin.internal.KotlinPropertyArguments
import org.jdbi.v3.core.qualifier.Qualifier
import org.jdbi.v3.core.result.ResultBearing
import org.jdbi.v3.core.result.ResultIterable
import org.jdbi.v3.core.statement.SqlStatement
import org.jdbi.v3.meta.Beta
import kotlin.reflect.KAnnotatedElement
import kotlin.reflect.KClass
import kotlin.reflect.full.findAnnotation
private val metadataFqName = "kotlin.Metadata"
fun Class<*>.isKotlinClass(): Boolean {
return this.annotations.singleOrNull { it.annotationClass.java.name == metadataFqName } != null
}
inline fun <reified T : Any> ResultBearing.mapTo(): ResultIterable<T> {
return this.mapTo(T::class.java)
}
inline fun <O : Any> ResultIterable<O>.useSequence(block: (Sequence<O>) -> Unit) {
this.iterator().use {
block(it.asSequence())
}
}
@Beta
fun <This : SqlStatement<This>> SqlStatement<This>.bindKotlin(name: String, obj: Any): This {
return this.bindNamedArgumentFinder(KotlinPropertyArguments(obj, name))
}
@Beta
fun <This : SqlStatement<This>> SqlStatement<This>.bindKotlin(obj: Any): This {
return this.bindNamedArgumentFinder(KotlinPropertyArguments(obj))
}
/**
* A convenience method which opens an extension of the given type, yields it to a callback, and returns the result
* of the callback. A handle is opened if needed by the extension, and closed before returning to the caller.
*
* @param extensionType the type of extension.
* @param callback a callback which will receive the extension.
* @param <R> the return type
* @param <E> the extension type
* @param <X> the exception type optionally thrown by the callback
* @return the value returned by the callback.
* @throws org.jdbi.v3.core.extension.NoSuchExtensionException if no [org.jdbi.v3.core.extension.ExtensionFactory]
* is registered which supports the given extension type.
* @throws X if thrown by the callback.
*/
fun <E : Any, R, X : Exception> Jdbi.withExtension(extensionType: KClass<E>, callback: ExtensionCallback<R, E, X>): R {
return withExtension(extensionType.java, callback)
}
/**
* A convenience method which opens an extension of the given type, and yields it to a callback. A handle is opened
* if needed by the extention, and closed before returning to the caller.
*
* @param extensionType the type of extension
* @param callback a callback which will receive the extension
* @param <E> the extension type
* @param <X> the exception type optionally thrown by the callback
* @throws org.jdbi.v3.core.extension.NoSuchExtensionException if no [org.jdbi.v3.core.extension.ExtensionFactory]
* is registered which supports the given extension type.
* @throws X if thrown by the callback.
*/
fun <E : Any, X : Exception> Jdbi.useExtension(extensionType: KClass<E>, callback: ExtensionConsumer<E, X>) {
useExtension(extensionType.java, callback)
}
/**
* Returns the set of qualifying annotations on the given Kotlin elements.
* @param elements the annotated element. Null elements are ignored.
* @return the set of qualifying annotations on the given elements.
*/
fun getQualifiers(vararg elements: KAnnotatedElement?): Set<Annotation> {
return elements.filterNotNull()
.flatMap { element -> element.annotations }
.filter { anno -> anno.annotationClass.findAnnotation<Qualifier>() != null }
.toSet()
}
| apache-2.0 | 634fd25ca4d8beecc92084d82fa9cc3f | 41.040404 | 119 | 0.739068 | 3.941288 | false | false | false | false |
jpmoreto/play-with-robots | android/app/src/main/java/jpm/android/ui/common/ZoomAndMoveView.kt | 1 | 3553 | package jpm.android.ui.common
import android.content.Context
import android.util.AttributeSet
import android.view.ScaleGestureDetector
import android.view.View
import android.view.MotionEvent.INVALID_POINTER_ID
import android.view.MotionEvent
/**
* Created by jm on 18/02/17.
*
*/
abstract class ZoomAndMoveView: View {
protected var mPosX = 0f
protected var mPosY = 0f
private var mLastTouchX = 0f
private var mLastTouchY = 0f
// The ‘active pointer’ is the one currently moving our object.
private var mActivePointerId = INVALID_POINTER_ID
private var mScaleDetector: ScaleGestureDetector? = null
protected var mScaleFactor = 1f
private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
mScaleFactor *= detector.scaleFactor
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f))
invalidate()
return true
}
}
private fun init() {
mScaleDetector = ScaleGestureDetector(context, ScaleListener())
}
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
override fun onTouchEvent(ev: MotionEvent): Boolean {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector!!.onTouchEvent(ev)
val action = ev.action
when (action and MotionEvent.ACTION_MASK) {
MotionEvent.ACTION_DOWN -> {
mLastTouchX = ev.x
mLastTouchY = ev.y
mActivePointerId = ev.getPointerId(0)
}
MotionEvent.ACTION_MOVE -> {
val pointerIndex = ev.findPointerIndex(mActivePointerId)
val x = ev.getX(pointerIndex)
val y = ev.getY(pointerIndex)
// Only move if the ScaleGestureDetector isn't processing a gesture.
if (!mScaleDetector!!.isInProgress) {
val dx = x - mLastTouchX
val dy = y - mLastTouchY
mPosX += dx
mPosY += dy
invalidate()
}
mLastTouchX = x
mLastTouchY = y
}
MotionEvent.ACTION_UP -> {
mActivePointerId = INVALID_POINTER_ID
}
MotionEvent.ACTION_CANCEL -> {
mActivePointerId = INVALID_POINTER_ID
}
MotionEvent.ACTION_POINTER_UP -> {
val pointerIndex = ev.action and MotionEvent.ACTION_POINTER_INDEX_MASK shr MotionEvent.ACTION_POINTER_INDEX_SHIFT
val pointerId = ev.getPointerId(pointerIndex)
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
val newPointerIndex = if (pointerIndex == 0) 1 else 0
mLastTouchX = ev.getX(newPointerIndex)
mLastTouchY = ev.getY(newPointerIndex)
mActivePointerId = ev.getPointerId(newPointerIndex)
}
}
}
return true
}
} | mit | f4743fcc207e1015eba71cccfb82b333 | 30.696429 | 129 | 0.586644 | 5.07 | false | false | false | false |
http4k/http4k | http4k-multipart/src/test/kotlin/org/http4k/lens/MultipartFormTest.kt | 1 | 5520 | package org.http4k.lens
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.throws
import org.http4k.core.Body
import org.http4k.core.ContentType
import org.http4k.core.ContentType.Companion
import org.http4k.core.ContentType.Companion.MultipartFormWithBoundary
import org.http4k.core.ContentType.Companion.MultipartMixedWithBoundary
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.with
import org.http4k.lens.Validator.Feedback
import org.http4k.lens.Validator.Strict
import org.http4k.testing.ApprovalTest
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(ApprovalTest::class)
class MultipartFormTest {
private val emptyRequest = Request(GET, "")
private val stringRequiredField = MultipartFormField.string().required("hello")
private val intRequiredField = MultipartFormField.string().int().required("another")
private val fieldWithHeaders = MultipartFormField.required("fieldWithHeaders")
private val requiredFile = MultipartFormFile.required("file")
private val message = javaClass.getResourceAsStream("fullMessage.txt").reader().use { it.readText() }
private fun validFile() = MultipartFormFile("hello.txt", ContentType.TEXT_HTML, "bits".byteInputStream())
private val DEFAULT_BOUNDARY = "hello"
@Test
fun `multipart form serialized into request`() {
val populatedRequest = emptyRequest.with(
multipartFormLens(Strict, ::MultipartMixedWithBoundary) of MultipartForm().with(
stringRequiredField of "world",
intRequiredField of 123,
requiredFile of validFile(),
fieldWithHeaders of MultipartFormField("someValue",
listOf("MyHeader" to "myHeaderValue")
)
)
)
assertThat(populatedRequest.toMessage().replace("\r\n", "\n"), equalTo(message))
}
@Test
fun `multipart form blows up if not correct content type`() {
val request = emptyRequest.with(
multipartFormLens(Strict) of MultipartForm().with(
stringRequiredField of "world",
intRequiredField of 123,
requiredFile of validFile()
)).replaceHeader("Content-Type", "unknown; boundary=hello")
assertThat({
multipartFormLens(Strict)(request)
}, throws(lensFailureWith<Any?>(Unsupported(Header.CONTENT_TYPE.meta), overallType = Failure.Type.Unsupported)))
}
@Test
fun `multipart form extracts ok form values`() {
val request = emptyRequest.with(
multipartFormLens(Strict) of MultipartForm().with(
stringRequiredField of "world",
intRequiredField of 123,
requiredFile of validFile()
)
)
val expected = MultipartForm(
mapOf("hello" to listOf(MultipartFormField("world")),
"another" to listOf(MultipartFormField("123"))),
mapOf("file" to listOf(validFile())))
assertThat(multipartFormLens(Strict)(request), equalTo(expected))
}
@Test
fun `feedback multipart form extracts ok form values and errors`() {
val request = emptyRequest.with(
multipartFormLens(Feedback) of MultipartForm().with(
intRequiredField of 123,
requiredFile of validFile()
)
)
val requiredString = MultipartFormField.string().required("hello")
assertThat(multipartFormLens(Feedback)(request), equalTo(MultipartForm(
mapOf("another" to listOf(MultipartFormField("123"))),
mapOf("file" to listOf(validFile())),
listOf(Missing(requiredString.meta)))))
}
@Test
fun `strict multipart form blows up with invalid form values`() {
val intStringField = MultipartFormField.string().required("another")
val request = emptyRequest.with(
Body.multipartForm(
Strict,
stringRequiredField,
intStringField,
requiredFile,
defaultBoundary = DEFAULT_BOUNDARY,
contentTypeFn = ::MultipartFormWithBoundary
).toLens() of
MultipartForm().with(
stringRequiredField of "hello",
intStringField of "world",
requiredFile of validFile()
)
)
assertThat(
{ multipartFormLens(Strict)(request) },
throws(lensFailureWith<Any?>(Invalid(intRequiredField.meta), overallType = Failure.Type.Invalid))
)
}
@Test
fun `can set multiple values on a form`() {
val stringField = MultipartFormField.string().required("hello")
val intField = MultipartFormField.string().int().required("another")
val populated = MultipartForm()
.with(stringField of "world",
intField of 123)
assertThat(stringField(populated), equalTo("world"))
assertThat(intField(populated), equalTo(123))
}
private fun multipartFormLens(validator: Validator,
contentTypeFn: (String) -> ContentType = Companion::MultipartFormWithBoundary
) = Body.multipartForm(validator, stringRequiredField, intRequiredField, requiredFile, defaultBoundary = DEFAULT_BOUNDARY, contentTypeFn = contentTypeFn).toLens()
}
| apache-2.0 | b4fdfad11043a33058725494fb5937d5 | 38.71223 | 166 | 0.649457 | 4.825175 | false | true | false | false |
kotlin-es/kotlin-JFrame-standalone | 12-start-async-spinner-button-application/src/main/kotlin/components/statusBar/StatusBarImpl.kt | 2 | 1381 | package components.progressBar
import utils.ThreadMain
import java.awt.Dimension
import java.util.concurrent.CompletableFuture
import javax.swing.BoxLayout
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.SwingConstants
import javax.swing.border.BevelBorder
/**
* Created by vicboma on 05/12/16.
*/
class StatusBarImpl internal constructor(private val _width : Int) : JPanel() , StatusBar {
private var statusLabel = JLabel();
companion object {
fun create(_width: Int): StatusBar {
return StatusBarImpl(_width)
}
}
init{
border = BevelBorder(BevelBorder.LOWERED);
preferredSize = Dimension(_width, 19);
layout = BoxLayout(this, BoxLayout.X_AXIS);
statusLabel.horizontalAlignment = SwingConstants.LEFT;
this.add(statusLabel);
}
override fun asyncUI() = asyncSpel(StatusBar.TEXT,1000L,50L)
private fun asyncSpel(str: String, delay: Long, sequence:Long) {
ThreadMain.asyncUI {
CompletableFuture.runAsync {
Thread.sleep(delay)
statusLabel.text = ""
for (i in 0..str.length - 1) {
Thread.sleep(sequence)
statusLabel.text += str[i].toString()
}
}.thenAcceptAsync {
asyncUI()
}
}
}
}
| mit | fb580a017c164b7babb4b4ef74a1e958 | 27.183673 | 91 | 0.616944 | 4.440514 | false | false | false | false |
Nandi/http | src/main/kotlin/com/headlessideas/http/util/UtilityFunction.kt | 1 | 613 | package com.headlessideas.http.util
import com.headlessideas.http.Header
import java.nio.file.Files
import java.nio.file.Path
val Path.contentTypeHeader: Header
get() = getContentType(this)
private fun getContentType(path: Path) = when (path.extension) {
"html", "htm" -> html
"css" -> css
"csv" -> csv
"png" -> png
"jpg", "jpeg" -> jpeg
"gif" -> gif
"js" -> js
"json" -> json
"svg" -> svg
else -> plain
}
fun Path.exists(): Boolean = Files.exists(this)
fun Path.readable(): Boolean = Files.isReadable(this)
val Path.extension: String
get() = toFile().extension | mit | e1c56c9be2286d21bbe2ade3a6f78ba8 | 22.615385 | 64 | 0.644372 | 3.368132 | false | false | false | false |
googlecodelabs/android-paging | advanced/start/app/src/main/java/com/example/android/codelabs/paging/ui/ReposAdapter.kt | 1 | 1686 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.codelabs.paging.ui
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import com.example.android.codelabs.paging.model.Repo
/**
* Adapter for the list of repositories.
*/
class ReposAdapter : ListAdapter<Repo, RepoViewHolder>(REPO_COMPARATOR) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RepoViewHolder {
return RepoViewHolder.create(parent)
}
override fun onBindViewHolder(holder: RepoViewHolder, position: Int) {
val repoItem = getItem(position)
if (repoItem != null) {
holder.bind(repoItem)
}
}
companion object {
private val REPO_COMPARATOR = object : DiffUtil.ItemCallback<Repo>() {
override fun areItemsTheSame(oldItem: Repo, newItem: Repo): Boolean =
oldItem.fullName == newItem.fullName
override fun areContentsTheSame(oldItem: Repo, newItem: Repo): Boolean =
oldItem == newItem
}
}
}
| apache-2.0 | a56bb51902eca147ecc3e8289d29f7fc | 33.408163 | 87 | 0.70344 | 4.520107 | false | false | false | false |
craigjbass/pratura | src/test/kotlin/uk/co/craigbass/pratura/unit/usecase/catalogue/ViewAllProductsSpec.kt | 1 | 1477 | package uk.co.craigbass.pratura.unit.usecase.catalogue
import com.madetech.clean.usecase.execute
import org.amshove.kluent.shouldEqual
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.*
import uk.co.craigbass.pratura.domain.*
import uk.co.craigbass.pratura.unit.testdouble.*
import uk.co.craigbass.pratura.usecase.catalogue.ViewAllProducts
import java.math.BigDecimal.ONE
class ViewAllProductsSpec : Spek({
var products: List<Product> = listOf()
val currency = Currency("GBP", "GB", "en")
val productRetriever = memoized { StubProductRetriever(products) }
val useCase = memoized {
ViewAllProducts(productRetriever(),
StubCurrencyRetriever(currency))
}
given("one product is available") {
beforeEachTest {
products = listOf(
Product(
sku = "sku:90",
price = ONE,
name = "Bottle of Water"
)
)
}
val presentableProducts = memoized { useCase().execute() }
val firstPresentableProduct = memoized { presentableProducts().first() }
it("should return one product") {
presentableProducts().count().shouldEqual(1)
}
it("should have the correct sku") {
firstPresentableProduct().sku.shouldEqual("sku:90")
}
it("should have the correct price") {
firstPresentableProduct().price.shouldEqual("£1.00")
}
it("should have the correct name") {
firstPresentableProduct().name.shouldEqual("Bottle of Water")
}
}
})
| bsd-3-clause | bca080e329b7c4a53092757ff1443eb4 | 28.52 | 76 | 0.686314 | 4.054945 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/test/java/com/ichi2/anki/services/NoteServiceTest.kt | 1 | 12528 | /*
Copyright (c) 2021 Kael Madar <[email protected]>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.services
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.anki.RobolectricTest
import com.ichi2.anki.multimediacard.IMultimediaEditableNote
import com.ichi2.anki.multimediacard.fields.ImageField
import com.ichi2.anki.multimediacard.fields.MediaClipField
import com.ichi2.anki.servicelayer.NoteService
import com.ichi2.libanki.Collection
import com.ichi2.libanki.Consts
import com.ichi2.libanki.Model
import com.ichi2.libanki.Note
import com.ichi2.testutils.createTransientFile
import com.ichi2.utils.KotlinCleanup
import org.hamcrest.CoreMatchers.*
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.io.FileMatchers.*
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import java.io.File
import java.io.FileWriter
import java.io.IOException
@KotlinCleanup("have Model constructor accent @Language('JSON')")
@RunWith(AndroidJUnit4::class)
class NoteServiceTest : RobolectricTest() {
@KotlinCleanup("lateinit")
var testCol: Collection? = null
@Before
fun before() {
testCol = col
}
// temporary directory to test importMediaToDirectory function
@get:Rule
var directory = TemporaryFolder()
@get:Rule
var directory2 = TemporaryFolder()
// tests if the text fields of the notes are the same after calling updateJsonNoteFromMultimediaNote
@Test
fun updateJsonNoteTest() {
val testModel = testCol!!.models.byName("Basic")
val multiMediaNote: IMultimediaEditableNote? = NoteService.createEmptyNote(testModel!!)
multiMediaNote!!.getField(0)!!.text = "foo"
multiMediaNote.getField(1)!!.text = "bar"
val basicNote = Note(testCol!!, testModel).apply {
setField(0, "this should be changed to foo")
setField(1, "this should be changed to bar")
}
NoteService.updateJsonNoteFromMultimediaNote(multiMediaNote, basicNote)
assertEquals(basicNote.fields[0], multiMediaNote.getField(0)!!.text)
assertEquals(basicNote.fields[1], multiMediaNote.getField(1)!!.text)
}
// tests if updateJsonNoteFromMultimediaNote throws a RuntimeException if the ID's of the notes don't match
@Test
fun updateJsonNoteRuntimeErrorTest() {
// model with ID 42
var testModel = Model("{\"flds\": [{\"name\": \"foo bar\", \"ord\": \"1\"}], \"id\": \"42\"}")
val multiMediaNoteWithID42: IMultimediaEditableNote? = NoteService.createEmptyNote(testModel)
// model with ID 45
testModel = Model("{\"flds\": [{\"name\": \"foo bar\", \"ord\": \"1\"}], \"id\": \"45\"}")
val noteWithID45 = Note(testCol!!, testModel)
val expectedException: Throwable = assertThrows(RuntimeException::class.java) { NoteService.updateJsonNoteFromMultimediaNote(multiMediaNoteWithID42, noteWithID45) }
assertEquals(expectedException.message, "Source and Destination Note ID do not match.")
}
@Test
@Throws(IOException::class)
fun importAudioClipToDirectoryTest() {
val fileAudio = directory.newFile("testaudio.wav")
// writes a line in the file so the file's length isn't 0
FileWriter(fileAudio).use { fileWriter -> fileWriter.write("line1") }
val audioField = MediaClipField()
audioField.audioPath = fileAudio.absolutePath
NoteService.importMediaToDirectory(testCol!!, audioField)
val outFile = File(testCol!!.media.dir(), fileAudio.name)
assertThat("path should be equal to new file made in NoteService.importMediaToDirectory", outFile, aFileWithAbsolutePath(equalTo(audioField.audioPath)))
}
// Similar test like above, but with an ImageField instead of a MediaClipField
@Test
@Throws(IOException::class)
fun importImageToDirectoryTest() {
val fileImage = directory.newFile("test_image.png")
// writes a line in the file so the file's length isn't 0
FileWriter(fileImage).use { fileWriter -> fileWriter.write("line1") }
val imgField = ImageField()
imgField.extraImagePathRef = fileImage.absolutePath
NoteService.importMediaToDirectory(testCol!!, imgField)
val outFile = File(testCol!!.media.dir(), fileImage.name)
assertThat("path should be equal to new file made in NoteService.importMediaToDirectory", outFile, aFileWithAbsolutePath(equalTo(imgField.extraImagePathRef)))
}
/**
* Tests if after importing:
*
* * New file keeps its name
* * File with same name, but different content, has its name changed
* * File with same name and content don't have its name changed
*
* @throws IOException if new created files already exist on temp directory
*/
@Test
@Throws(IOException::class)
fun importAudioWithSameNameTest() {
val f1 = directory.newFile("audio.mp3")
val f2 = directory2.newFile("audio.mp3")
// writes a line in the file so the file's length isn't 0
FileWriter(f1).use { fileWriter -> fileWriter.write("1") }
// do the same to the second file, but with different data
FileWriter(f2).use { fileWriter -> fileWriter.write("2") }
val fld1 = MediaClipField()
fld1.audioPath = f1.absolutePath
val fld2 = MediaClipField()
fld2.audioPath = f2.absolutePath
// third field to test if name is kept after reimporting the same file
val fld3 = MediaClipField()
fld3.audioPath = f1.absolutePath
NoteService.importMediaToDirectory(testCol!!, fld1)
val o1 = File(testCol!!.media.dir(), f1.name)
NoteService.importMediaToDirectory(testCol!!, fld2)
val o2 = File(testCol!!.media.dir(), f2.name)
NoteService.importMediaToDirectory(testCol!!, fld3)
// creating a third outfile isn't necessary because it should be equal to the first one
assertThat("path should be equal to new file made in NoteService.importMediaToDirectory", o1, aFileWithAbsolutePath(equalTo(fld1.audioPath)))
assertThat("path should be different to new file made in NoteService.importMediaToDirectory", o2, aFileWithAbsolutePath(not(fld2.audioPath)))
assertThat("path should be equal to new file made in NoteService.importMediaToDirectory", o1, aFileWithAbsolutePath(equalTo(fld3.audioPath)))
}
// Similar test like above, but with an ImageField instead of a MediaClipField
@Test
@Throws(IOException::class)
fun importImageWithSameNameTest() {
val f1 = directory.newFile("img.png")
val f2 = directory2.newFile("img.png")
// write a line in the file so the file's length isn't 0
FileWriter(f1).use { fileWriter -> fileWriter.write("1") }
// do the same to the second file, but with different data
FileWriter(f2).use { fileWriter -> fileWriter.write("2") }
val fld1 = ImageField()
fld1.extraImagePathRef = f1.absolutePath
val fld2 = ImageField()
fld2.extraImagePathRef = f2.absolutePath
// third field to test if name is kept after reimporting the same file
val fld3 = ImageField()
fld3.extraImagePathRef = f1.absolutePath
NoteService.importMediaToDirectory(testCol!!, fld1)
val o1 = File(testCol!!.media.dir(), f1.name)
NoteService.importMediaToDirectory(testCol!!, fld2)
val o2 = File(testCol!!.media.dir(), f2.name)
NoteService.importMediaToDirectory(testCol!!, fld3)
// creating a third outfile isn't necessary because it should be equal to the first one
assertThat("path should be equal to new file made in NoteService.importMediaToDirectory", o1, aFileWithAbsolutePath(equalTo(fld1.extraImagePathRef)))
assertThat("path should be different to new file made in NoteService.importMediaToDirectory", o2, aFileWithAbsolutePath(not(fld2.extraImagePathRef)))
assertThat("path should be equal to new file made in NoteService.importMediaToDirectory", o1, aFileWithAbsolutePath(equalTo(fld3.extraImagePathRef)))
}
/**
* Sometimes media files cannot be imported directly to the media directory,
* so they are copied to cache then imported and deleted.
* This tests if cached media are properly deleted after import.
*/
@Test
fun tempAudioIsDeletedAfterImport() {
val file = createTransientFile("foo")
val field = MediaClipField().apply {
audioPath = file.absolutePath
hasTemporaryMedia = true
}
NoteService.importMediaToDirectory(testCol!!, field)
assertThat("Audio temporary file should have been deleted after importing", file, not(anExistingFile()))
}
// Similar test like above, but with an ImageField instead of a MediaClipField
@Test
fun tempImageIsDeletedAfterImport() {
val file = createTransientFile("foo")
val field = ImageField().apply {
extraImagePathRef = file.absolutePath
hasTemporaryMedia = true
}
NoteService.importMediaToDirectory(testCol!!, field)
assertThat("Image temporary file should have been deleted after importing", file, not(anExistingFile()))
}
@Test
fun testAvgEase() {
// basic case: no cards are new
val note = addNoteUsingModelName("Cloze", "{{c1::Hello}}{{c2::World}}{{c3::foo}}{{c4::bar}}", "extra")
// factor for cards: 3000, 1500, 1000, 750
for ((i, card) in note.cards().withIndex()) {
card.apply {
type = Consts.CARD_TYPE_REV
factor = 3000 / (i + 1)
flush()
}
}
// avg ease = (3000/10 + 1500/10 + 100/10 + 750/10) / 4 = [156.25] = 156
assertEquals(156, NoteService.avgEase(note))
// test case: one card is new
note.cards()[2].apply {
type = Consts.CARD_TYPE_NEW
flush()
}
// avg ease = (3000/10 + 1500/10 + 750/10) / 3 = [175] = 175
assertEquals(175, NoteService.avgEase(note))
// test case: all cards are new
for (card in note.cards()) {
card.type = Consts.CARD_TYPE_NEW
card.flush()
}
// no cards are rev, so avg ease cannot be calculated
assertEquals(null, NoteService.avgEase(note))
}
@Test
fun testAvgInterval() {
// basic case: all cards are relearning or review
val note = addNoteUsingModelName("Cloze", "{{c1::Hello}}{{c2::World}}{{c3::foo}}{{c4::bar}}", "extra")
val reviewOrRelearningList = listOf(Consts.CARD_TYPE_REV, Consts.CARD_TYPE_RELEARNING)
val newOrLearningList = listOf(Consts.CARD_TYPE_NEW, Consts.CARD_TYPE_LRN)
// interval for cards: 3000, 1500, 1000, 750
for ((i, card) in note.cards().withIndex()) {
card.apply {
type = reviewOrRelearningList.shuffled().first()
ivl = 3000 / (i + 1)
flush()
}
}
// avg interval = (3000 + 1500 + 1000 + 750) / 4 = [1562.5] = 1562
assertEquals(1562, NoteService.avgInterval(note))
// case: one card is new or learning
note.cards()[2].apply {
type = newOrLearningList.shuffled().first()
flush()
}
// avg interval = (3000 + 1500 + 750) / 3 = [1750] = 1750
assertEquals(1750, NoteService.avgInterval(note))
// case: all cards are new or learning
for (card in note.cards()) {
card.type = newOrLearningList.shuffled().first()
card.flush()
}
// no cards are rev or relearning, so avg interval cannot be calculated
assertEquals(null, NoteService.avgInterval(note))
}
}
| gpl-3.0 | 75b7403eb1984831a90656ab835f0393 | 39.153846 | 172 | 0.668024 | 4.170439 | false | true | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/multimediacard/fields/AudioField.kt | 1 | 2957 | /****************************************************************************************
* Copyright (c) 2013 Bibek Shrestha <[email protected]> *
* Copyright (c) 2013 Zaur Molotnikov <[email protected]> *
* Copyright (c) 2013 Nicolas Raoul <[email protected]> *
* Copyright (c) 2013 Flavio Lerda <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.multimediacard.fields
import com.ichi2.libanki.Collection
import com.ichi2.utils.KotlinCleanup
import java.io.File
import java.util.regex.Pattern
/**
* Implementation of Audio field types
*/
abstract class AudioField : FieldBase(), IField {
private var mAudioPath: String? = null
override var imagePath: String? = null
override var audioPath: String?
get() = mAudioPath
set(value) {
mAudioPath = value
setThisModified()
}
override var text: String? = null
override var hasTemporaryMedia: Boolean = false
@KotlinCleanup("get() can be simplified with a scope function")
override val formattedValue: String
get() {
if (audioPath == null) {
return ""
}
val file = File(audioPath!!)
return if (file.exists()) "[sound:${file.name}]" else ""
}
override fun setFormattedString(col: Collection, value: String) {
val p = Pattern.compile(PATH_REGEX)
val m = p.matcher(value)
var res = ""
if (m.find()) {
res = m.group(1)!!
}
val mediaDir = col.media.dir() + "/"
audioPath = mediaDir + res
}
companion object {
protected const val PATH_REGEX = "\\[sound:(.*)]"
}
}
| gpl-3.0 | 2b1d3ff8adaea879d0d27143d4449da4 | 41.242857 | 90 | 0.488671 | 4.994932 | false | false | false | false |
apoi/quickbeer-android | app/src/main/java/quickbeer/android/feature/beerdetails/BeerReviewsViewHolder.kt | 2 | 2839 | /**
* This file is part of QuickBeer.
* Copyright (C) 2017 Antti Poikela <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package quickbeer.android.feature.beerdetails
import android.view.View
import androidx.annotation.StringRes
import java.lang.String.valueOf
import quickbeer.android.R
import quickbeer.android.databinding.ReviewListItemBinding
import quickbeer.android.domain.review.Review
import quickbeer.android.ui.adapter.base.ListViewHolder
import quickbeer.android.ui.adapter.review.ReviewListModel
/**
* View holder for reviews in list
*/
class BeerReviewsViewHolder(
private val binding: ReviewListItemBinding
) : ListViewHolder<ReviewListModel>(binding.root) {
override fun bind(item: ReviewListModel) {
val metadata = item.review.userName +
(item.review.country?.let { ", $it" } ?: "") +
"\n" + item.review.timeEntered
binding.user.text = metadata
binding.score.text = String.format("%.1f", item.review.totalScore)
binding.description.text = item.review.comments
if (item.review.appearance != null) {
setDetails(item.review)
binding.detailsRow.visibility = View.VISIBLE
} else {
binding.detailsRow.visibility = View.GONE
}
}
private fun setDetails(review: Review) {
binding.appearance.text = valueOf(review.appearance)
binding.aroma.text = valueOf(review.aroma)
binding.flavor.text = valueOf(review.flavor)
binding.mouthfeel.text = valueOf(review.mouthfeel)
binding.overall.text = valueOf(review.overall)
binding.appearanceColumn.setOnClickListener { showToast(R.string.review_appearance_hint) }
binding.aromaColumn.setOnClickListener { showToast(R.string.review_aroma_hint) }
binding.flavorColumn.setOnClickListener { showToast(R.string.review_flavor_hint) }
binding.mouthfeelColumn.setOnClickListener { showToast(R.string.review_mouthfeel_hint) }
binding.overallColumn.setOnClickListener { showToast(R.string.review_overall_hint) }
}
private fun showToast(@StringRes resource: Int) {
// toastProvider.showCancelableToast(resource, Toast.LENGTH_LONG)
}
}
| gpl-3.0 | b27d6cffe2843b8e90c5c151b34b29c8 | 39.557143 | 98 | 0.720676 | 4.205926 | false | false | false | false |
matkoniecz/StreetComplete | app/src/test/java/de/westnordost/streetcomplete/quests/TestMapDataWithGeometry.kt | 1 | 1145 | package de.westnordost.streetcomplete.quests
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.streetcomplete.data.osm.mapdata.MutableMapData
import de.westnordost.streetcomplete.testutils.bbox
import de.westnordost.streetcomplete.data.osm.geometry.ElementGeometry
import de.westnordost.streetcomplete.data.osm.geometry.ElementPointGeometry
import de.westnordost.streetcomplete.data.osm.mapdata.Element
class TestMapDataWithGeometry(elements: Iterable<Element>) : MutableMapData(), MapDataWithGeometry {
init {
addAll(elements)
boundingBox = bbox()
}
val nodeGeometriesById: MutableMap<Long, ElementPointGeometry?> = mutableMapOf()
val wayGeometriesById: MutableMap<Long, ElementGeometry?> = mutableMapOf()
val relationGeometriesById: MutableMap<Long, ElementGeometry?> = mutableMapOf()
override fun getNodeGeometry(id: Long): ElementPointGeometry? = nodeGeometriesById[id]
override fun getWayGeometry(id: Long): ElementGeometry? = wayGeometriesById[id]
override fun getRelationGeometry(id: Long): ElementGeometry? = relationGeometriesById[id]
}
| gpl-3.0 | 2aec57de29c91f7353239ebddbeda73b | 46.708333 | 100 | 0.804367 | 4.525692 | false | true | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/edithistory/EditHistoryFragment.kt | 1 | 4090 | package de.westnordost.streetcomplete.edithistory
import android.os.Bundle
import android.view.View
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import de.westnordost.streetcomplete.Injector
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.edithistory.Edit
import de.westnordost.streetcomplete.data.edithistory.EditHistorySource
import de.westnordost.streetcomplete.data.edithistory.EditKey
import de.westnordost.streetcomplete.databinding.FragmentEditHistoryListBinding
import de.westnordost.streetcomplete.ktx.viewBinding
import de.westnordost.streetcomplete.ktx.viewLifecycleScope
import de.westnordost.streetcomplete.view.insets_animation.respectSystemInsets
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
/** Shows a list of the edit history */
class EditHistoryFragment : Fragment(R.layout.fragment_edit_history_list) {
@Inject internal lateinit var editHistorySource: EditHistorySource
interface Listener {
/** Called when an edit has been selected and the undo-button appeared */
fun onSelectedEdit(edit: Edit)
/** Called when the edit that was selected has been removed */
fun onDeletedSelectedEdit()
/** Called when the edit history is empty now */
fun onEditHistoryIsEmpty()
}
private val listener: Listener? get() = parentFragment as? Listener ?: activity as? Listener
private val binding by viewBinding(FragmentEditHistoryListBinding::bind)
private val adapter = EditHistoryAdapter(this::onSelected, this::onSelectionDeleted, this::onUndo)
private val editHistoryListener = object : EditHistorySource.Listener {
override fun onAdded(edit: Edit) { viewLifecycleScope.launch { adapter.onAdded(edit) } }
override fun onSynced(edit: Edit) { viewLifecycleScope.launch { adapter.onSynced(edit) } }
override fun onDeleted(edits: List<Edit>) {
viewLifecycleScope.launch {
adapter.onDeleted(edits)
if (editHistorySource.getCount() == 0) {
listener?.onEditHistoryIsEmpty()
}
}
}
override fun onInvalidated() {
viewLifecycleScope.launch {
val edits = withContext(Dispatchers.IO) { editHistorySource.getAll() }
adapter.setEdits(edits)
if (edits.isEmpty()) {
listener?.onEditHistoryIsEmpty()
}
}
}
}
init {
Injector.applicationComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
editHistorySource.addListener(editHistoryListener)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val initialPaddingBottom = binding.editHistoryList.paddingBottom
binding.editHistoryList.respectSystemInsets {
updatePadding(left = it.left, top = it.top, bottom = it.bottom + initialPaddingBottom)
}
viewLifecycleScope.launch {
val edits = withContext(Dispatchers.IO) { editHistorySource.getAll() }
adapter.setEdits(edits)
val first = edits.firstOrNull { it.isUndoable }
if (first != null) {
adapter.select(first)
}
binding.editHistoryList.adapter = adapter
}
}
override fun onDestroy() {
super.onDestroy()
editHistorySource.removeListener(editHistoryListener)
}
fun select(editKey: EditKey) {
val edit = editHistorySource.get(editKey) ?: return
adapter.select(edit)
}
private fun onSelected(edit: Edit) {
listener?.onSelectedEdit(edit)
}
private fun onSelectionDeleted() {
listener?.onDeletedSelectedEdit()
}
private fun onUndo(edit: Edit) {
UndoDialog(requireContext(), edit).show()
}
}
| gpl-3.0 | e1cdb03c68fc6abe219f9f7d56c7e50f | 35.517857 | 102 | 0.686064 | 4.817432 | false | false | false | false |
songzhw/Hello-kotlin | AdvancedJ/src/main/kotlin/basic/io/RandomAccessFileDemo.kt | 1 | 742 | package basic.io
import java.io.RandomAccessFile
fun readFile() {
val stream = RandomAccessFile("build.gradle", "rw")
println("first position = ${stream.filePointer}")
//在最末追回一个注释
val comment = "\n// added by RandomAccessFile demo"
stream.seek(stream.length())
stream.write(comment.toByteArray()) //java中是用"write(comment.getBytes())"
// 要开始读取文件, 就得再移支指针到最开始来
stream.seek(0)
val buff = ByteArray(1024)
var readedCount = stream.read(buff)
while (readedCount > 0) {
println(String(buff, 0, readedCount))
readedCount = stream.read(buff)
}
stream.close()
}
fun main(args: Array<String>) {
readFile()
} | apache-2.0 | f2ce1d90ecd7702699cb8ed51dfcc61f | 19.636364 | 77 | 0.651471 | 3.469388 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/sorter/AverageWeightSorter.kt | 1 | 983 | package com.boardgamegeek.sorter
import android.content.Context
import androidx.annotation.StringRes
import com.boardgamegeek.R
import com.boardgamegeek.entities.CollectionItemEntity
import java.text.DecimalFormat
abstract class AverageWeightSorter(context: Context) : CollectionSorter(context) {
private val defaultValue = context.getString(R.string.text_unknown)
@StringRes
override val descriptionResId = R.string.collection_sort_average_weight
override fun getHeaderText(item: CollectionItemEntity): String {
val averageWeight = item.averageWeight
return if (averageWeight == 0.0) defaultValue else DecimalFormat("#.0").format(averageWeight)
}
override fun getDisplayInfo(item: CollectionItemEntity): String {
val averageWeight = item.averageWeight
val info = if (averageWeight == 0.0) defaultValue else DecimalFormat("0.000").format(averageWeight)
return "${context.getString(R.string.weight)} $info"
}
}
| gpl-3.0 | fd7e7df68c4f328618fb0f0b0ffc92bc | 38.32 | 107 | 0.758901 | 4.550926 | false | false | false | false |
devulex/eventorage | backend/src/com/devulex/eventorage/config/ElasticsearchConfig.kt | 1 | 1543 | package com.devulex.eventorage.config
import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.common.transport.InetSocketTransportAddress
import org.elasticsearch.transport.client.PreBuiltTransportClient
import org.jetbrains.ktor.config.ApplicationConfig
import java.net.InetAddress
import java.net.UnknownHostException
@Throws(UnknownHostException::class)
fun connectElasticsearch(applicationConfig: ApplicationConfig): TransportClient {
val clusterName = applicationConfig.property("elasticsearch.cluster.name")
val settings = Settings.builder()
.put("cluster.name", clusterName.getString())
.put("client.transport.sniff", true)
.build()
val client = PreBuiltTransportClient(settings)
val clusterNodes = applicationConfig.property("elasticsearch.cluster.nodes").getList()
if (clusterNodes.isEmpty()) {
throw NoSuchElementException("List nodes Elasticsearch is empty.")
}
for (node in clusterNodes) {
val nodeSplit = node.split(":")
if (nodeSplit.size != 2) {
throw IllegalArgumentException("Node address should have delimiter \":\" between host and port values.")
}
val host = nodeSplit.first()
val port = nodeSplit.last().toInt()
client.addTransportAddress(InetSocketTransportAddress(InetAddress.getByName(host), port))
}
return client
}
fun disconnectElasticsearch(client: TransportClient) {
client.close();
}
| mit | 90227cccecaa0e6bed44b46766cc28d5 | 35.738095 | 116 | 0.736876 | 4.806854 | false | true | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/registry/type/data/NotePitchRegistry.kt | 1 | 1707 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.registry.type.data
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.key.minecraftKey
import org.lanternpowered.server.catalog.DefaultCatalogType
import org.lanternpowered.server.registry.internalCatalogTypeRegistry
import org.spongepowered.api.data.type.NotePitch
val NotePitchRegistry = internalCatalogTypeRegistry<NotePitch> {
val sortedNotePitches = arrayOf(
"F_SHARP0",
"G0",
"G_SHARP0",
"A1",
"A_SHARP1",
"B1",
"C1",
"C_SHARP1",
"D1",
"D_SHARP1",
"E1",
"F1",
"F_SHARP1",
"G1",
"G_SHARP1",
"A2",
"A_SHARP2",
"B2",
"C2",
"C_SHARP2",
"D2",
"D_SHARP2",
"E2",
"F2",
"F_SHARP2"
)
val entries = sortedNotePitches.mapIndexed { index, name ->
register(index, LanternNotePitch(minecraftKey(name.toLowerCase())))
}
entries.forEachIndexed { index, notePitch -> notePitch.next = entries[(index + 1) % entries.size] }
}
private class LanternNotePitch(key: NamespacedKey) : DefaultCatalogType(key), NotePitch {
lateinit var next: NotePitch
override fun cycleNext(): NotePitch = this.next
}
| mit | a29802996de48933995db46c62fd49f2 | 28.947368 | 103 | 0.592853 | 3.906178 | false | false | false | false |
i7c/cfm | server/mbservice/src/main/kotlin/org/rliz/mbs/release/data/Medium.kt | 1 | 333 | package org.rliz.mbs.release.data
import java.util.Date
class Medium {
val id: Long? = null
// format | integer
// edits_pending | integer
val release: Release? = null
val position: Int? = null
val name: String? = null
val lastUpdated: Date? = null
val trackCount: Int? = null
}
| gpl-3.0 | a193bbb0f89e89df07ac563895f26833 | 14.857143 | 33 | 0.600601 | 3.741573 | false | false | false | false |
GDG-Nantes/devfest-android | app/src/main/kotlin/com/gdgnantes/devfest/android/provider/ScheduleSeed.kt | 1 | 2858 | package com.gdgnantes.devfest.android.provider
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import com.gdgnantes.devfest.android.R
import com.gdgnantes.devfest.android.http.JsonConverters
import com.gdgnantes.devfest.android.json.fromJson
import com.gdgnantes.devfest.android.model.Schedule
import com.gdgnantes.devfest.android.model.toContentValues
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.Reader
internal class ScheduleSeed(val context: Context) {
companion object {
private const val TAG = "ScheduleSeed"
private const val DEBUG_LOG_PERFORMANCE = true
}
fun seed(database: SQLiteDatabase) {
var now: Long = 0
if (DEBUG_LOG_PERFORMANCE) {
now = System.currentTimeMillis()
}
val schedule = parse()
if (DEBUG_LOG_PERFORMANCE) {
Log.i(TAG, "Parsing took: ${System.currentTimeMillis() - now}ms")
now = System.currentTimeMillis()
}
insert(database, schedule)
if (DEBUG_LOG_PERFORMANCE) {
Log.i(TAG, "Insertion took: ${System.currentTimeMillis() - now}ms")
}
}
private fun insert(database: SQLiteDatabase, schedule: Schedule) {
insertRooms(database, schedule)
insertSpeakers(database, schedule)
insertSessions(database, schedule)
}
private fun insertRooms(database: SQLiteDatabase, schedule: Schedule) {
schedule.rooms.forEach {
database.insert(ScheduleDatabase.Tables.ROOMS, null, it.toContentValues())
}
}
private fun insertSpeakers(database: SQLiteDatabase, schedule: Schedule) {
schedule.speakers.forEach {
database.insert(ScheduleDatabase.Tables.SPEAKERS, null, it.toContentValues())
}
}
private fun insertSessions(database: SQLiteDatabase, schedule: Schedule) {
schedule.sessions.forEach { session ->
database.insert(ScheduleDatabase.Tables.SESSIONS, null, session.toContentValues())
session.speakersIds?.forEach { speakerId ->
val values = ContentValues().apply {
put(ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SESSION_ID, session.id)
put(ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SPEAKER_ID, speakerId)
}
database.insert(ScheduleDatabase.Tables.SESSIONS_SPEAKERS, null, values)
}
}
}
private fun parse(): Schedule {
var reader: Reader? = null
try {
reader = BufferedReader(InputStreamReader(context.resources.openRawResource(R.raw.seed)))
return JsonConverters.main.fromJson(reader)
} finally {
reader?.close()
}
}
}
| apache-2.0 | 33a0421b2351fa3b52e71ac809f9fd90 | 33.853659 | 101 | 0.664451 | 4.685246 | false | false | false | false |
c4software/Android-Password-Store | app/src/main/java/com/zeapo/pwdstore/autofill/AutofillRecyclerAdapter.kt | 1 | 6543 | /*
* Copyright © 2014-2019 The Android Password Store Authors. All Rights Reserved.
* SPDX-License-Identifier: GPL-2.0
*/
package com.zeapo.pwdstore.autofill
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SortedList
import androidx.recyclerview.widget.SortedListAdapterCallback
import com.zeapo.pwdstore.R
import com.zeapo.pwdstore.utils.splitLines
import java.util.ArrayList
import java.util.Locale
internal class AutofillRecyclerAdapter(
allApps: List<AppInfo>,
private val activity: AutofillPreferenceActivity
) : RecyclerView.Adapter<AutofillRecyclerAdapter.ViewHolder>() {
private val apps: SortedList<AppInfo>
private val allApps: ArrayList<AppInfo> // for filtering, maintain a list of all
private var browserIcon: Drawable? = null
init {
val callback = object : SortedListAdapterCallback<AppInfo>(this) {
// don't take into account secondary text. This is good enough
// for the limited add/remove usage for websites
override fun compare(o1: AppInfo, o2: AppInfo): Int {
return o1.appName.toLowerCase(Locale.ROOT).compareTo(o2.appName.toLowerCase(Locale.ROOT))
}
override fun areContentsTheSame(oldItem: AppInfo, newItem: AppInfo): Boolean {
return oldItem.appName == newItem.appName
}
override fun areItemsTheSame(item1: AppInfo, item2: AppInfo): Boolean {
return item1.appName == item2.appName
}
}
apps = SortedList(AppInfo::class.java, callback)
apps.addAll(allApps)
this.allApps = ArrayList(allApps)
try {
browserIcon = activity.packageManager.getApplicationIcon("com.android.browser")
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context)
.inflate(R.layout.autofill_row_layout, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val app = apps.get(position)
holder.packageName = app.packageName
holder.appName = app.appName
holder.isWeb = app.isWeb
holder.icon.setImageDrawable(app.icon)
holder.name.text = app.appName
holder.secondary.visibility = View.VISIBLE
val prefs: SharedPreferences
prefs = if (app.appName != app.packageName) {
activity.applicationContext.getSharedPreferences("autofill", Context.MODE_PRIVATE)
} else {
activity.applicationContext.getSharedPreferences("autofill_web", Context.MODE_PRIVATE)
}
when (val preference = prefs.getString(holder.packageName, "")) {
"" -> {
holder.secondary.visibility = View.GONE
holder.view.setBackgroundResource(0)
}
"/first" -> holder.secondary.setText(R.string.autofill_apps_first)
"/never" -> holder.secondary.setText(R.string.autofill_apps_never)
else -> {
holder.secondary.setText(R.string.autofill_apps_match)
holder.secondary.append(" " + preference!!.splitLines()[0])
if (preference.trim { it <= ' ' }.splitLines().size - 1 > 0) {
holder.secondary.append(" and " +
(preference.trim { it <= ' ' }.splitLines().size - 1) + " more")
}
}
}
}
override fun getItemCount(): Int {
return apps.size()
}
fun getPosition(appName: String): Int {
return apps.indexOf(AppInfo(null, appName, false, null))
}
// for websites, URL = packageName == appName
fun addWebsite(packageName: String) {
apps.add(AppInfo(packageName, packageName, true, browserIcon))
allApps.add(AppInfo(packageName, packageName, true, browserIcon))
}
fun removeWebsite(packageName: String) {
apps.remove(AppInfo(null, packageName, false, null))
allApps.remove(AppInfo(null, packageName, false, null)) // compare with equals
}
fun updateWebsite(oldPackageName: String, packageName: String) {
apps.updateItemAt(getPosition(oldPackageName), AppInfo(packageName, packageName, true, browserIcon))
allApps.remove(AppInfo(null, oldPackageName, false, null)) // compare with equals
allApps.add(AppInfo(null, packageName, false, null))
}
fun filter(s: String) {
if (s.isEmpty()) {
apps.addAll(allApps)
return
}
apps.beginBatchedUpdates()
for (app in allApps) {
if (app.appName.toLowerCase(Locale.ROOT).contains(s.toLowerCase(Locale.ROOT))) {
apps.add(app)
} else {
apps.remove(app)
}
}
apps.endBatchedUpdates()
}
internal class AppInfo(var packageName: String?, var appName: String, var isWeb: Boolean, var icon: Drawable?) {
override fun equals(other: Any?): Boolean {
return other is AppInfo && this.appName == other.appName
}
override fun hashCode(): Int {
var result = packageName?.hashCode() ?: 0
result = 31 * result + appName.hashCode()
result = 31 * result + isWeb.hashCode()
result = 31 * result + (icon?.hashCode() ?: 0)
return result
}
}
internal inner class ViewHolder(var view: View) : RecyclerView.ViewHolder(view), View.OnClickListener {
var name: AppCompatTextView = view.findViewById(R.id.app_name)
var icon: AppCompatImageView = view.findViewById(R.id.app_icon)
var secondary: AppCompatTextView = view.findViewById(R.id.secondary_text)
var packageName: String? = null
var appName: String? = null
var isWeb: Boolean = false
init {
view.setOnClickListener(this)
}
override fun onClick(v: View) {
activity.showDialog(packageName, appName, isWeb)
}
}
}
| gpl-3.0 | 9c3c605f79d235b541faa097fd7c518a | 37.034884 | 116 | 0.638795 | 4.610289 | false | false | false | false |
arturbosch/detekt | detekt-gradle-plugin/src/test/kotlin/io/gitlab/arturbosch/detekt/DetektReportMergeSpec.kt | 1 | 8336 | package io.gitlab.arturbosch.detekt
import io.gitlab.arturbosch.detekt.testkit.DslGradleRunner
import io.gitlab.arturbosch.detekt.testkit.DslTestBuilder
import io.gitlab.arturbosch.detekt.testkit.ProjectLayout
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
internal class DetektReportMergeSpec : Spek({
describe("Sarif merge is configured correctly for multi module project") {
val groovy by memoized { DslTestBuilder.groovy() }
val groovyBuildFileContent by memoized {
"""
|${groovy.gradlePlugins}
|
|allprojects {
| ${groovy.gradleRepositories}
|}
|
|task sarifReportMerge(type: io.gitlab.arturbosch.detekt.report.ReportMergeTask) {
| output = project.layout.buildDirectory.file("reports/detekt/merge.sarif")
|}
|
|subprojects {
| ${groovy.gradleSubprojectsApplyPlugins}
|
| detekt {
| reports.sarif.enabled = true
| }
|
| plugins.withType(io.gitlab.arturbosch.detekt.DetektPlugin) {
| tasks.withType(io.gitlab.arturbosch.detekt.Detekt) { detektTask ->
| sarifReportMerge.configure { mergeTask ->
| mergeTask.mustRunAfter(detektTask)
| mergeTask.input.from(detektTask.sarifReportFile)
| }
| }
| }
|}
|""".trimMargin()
}
val kotlin by memoized { DslTestBuilder.kotlin() }
val kotlinBuildFileContent by memoized {
"""
|${kotlin.gradlePlugins}
|
|allprojects {
| ${kotlin.gradleRepositories}
|}
|
|val sarifReportMerge by tasks.registering(io.gitlab.arturbosch.detekt.report.ReportMergeTask::class) {
| output.set(project.layout.buildDirectory.file("reports/detekt/merge.sarif"))
|}
|
|subprojects {
| ${kotlin.gradleSubprojectsApplyPlugins}
|
| detekt {
| reports.sarif.enabled = true
| }
|
| plugins.withType(io.gitlab.arturbosch.detekt.DetektPlugin::class) {
| tasks.withType(io.gitlab.arturbosch.detekt.Detekt::class) detekt@{
| sarifReportMerge.configure {
| this.mustRunAfter(this@detekt)
| input.from([email protected])
| }
| }
| }
|}
|""".trimMargin()
}
it("using Groovy and Kotlin") {
listOf(
groovy to groovyBuildFileContent,
kotlin to kotlinBuildFileContent
).forEach { (builder, mainBuildFileContent) ->
val projectLayout = ProjectLayout(numberOfSourceFilesInRootPerSourceDir = 0).apply {
addSubmodule(
name = "child1",
numberOfSourceFilesPerSourceDir = 2,
numberOfCodeSmells = 2
)
addSubmodule(
name = "child2",
numberOfSourceFilesPerSourceDir = 4,
numberOfCodeSmells = 4
)
}
val gradleRunner = DslGradleRunner(projectLayout, builder.gradleBuildName, mainBuildFileContent)
gradleRunner.setupProject()
gradleRunner.runTasksAndExpectFailure("detekt", "sarifReportMerge", "--continue") { _ ->
assertThat(projectFile("build/reports/detekt/detekt.sarif")).doesNotExist()
assertThat(projectFile("build/reports/detekt/merge.sarif")).exists()
assertThat(projectFile("build/reports/detekt/merge.sarif").readText())
.contains("\"ruleId\": \"detekt.style.MagicNumber\"")
projectLayout.submodules.forEach {
assertThat(projectFile("${it.name}/build/reports/detekt/detekt.sarif")).exists()
}
}
}
}
}
describe("XML merge is configured correctly for multi module project") {
val groovy by memoized { DslTestBuilder.groovy() }
val groovyBuildFileContent by memoized {
"""
|${groovy.gradlePlugins}
|
|allprojects {
| ${groovy.gradleRepositories}
|}
|
|task xmlReportMerge(type: io.gitlab.arturbosch.detekt.report.ReportMergeTask) {
| output = project.layout.buildDirectory.file("reports/detekt/merge.xml")
|}
|
|subprojects {
| ${groovy.gradleSubprojectsApplyPlugins}
|
| detekt {
| reports.xml.enabled = true
| }
|
| plugins.withType(io.gitlab.arturbosch.detekt.DetektPlugin) {
| tasks.withType(io.gitlab.arturbosch.detekt.Detekt) { detektTask ->
| xmlReportMerge.configure { mergeTask ->
| mergeTask.mustRunAfter(detektTask)
| mergeTask.input.from(detektTask.xmlReportFile)
| }
| }
| }
|}
|""".trimMargin()
}
val kotlin by memoized { DslTestBuilder.kotlin() }
val kotlinBuildFileContent by memoized {
"""
|${kotlin.gradlePlugins}
|
|allprojects {
| ${kotlin.gradleRepositories}
|}
|
|val xmlReportMerge by tasks.registering(io.gitlab.arturbosch.detekt.report.ReportMergeTask::class) {
| output.set(project.layout.buildDirectory.file("reports/detekt/merge.xml"))
|}
|
|subprojects {
| ${kotlin.gradleSubprojectsApplyPlugins}
|
| detekt {
| reports.xml.enabled = true
| }
|
| plugins.withType(io.gitlab.arturbosch.detekt.DetektPlugin::class) {
| tasks.withType(io.gitlab.arturbosch.detekt.Detekt::class) detekt@{
| xmlReportMerge.configure {
| this.mustRunAfter(this@detekt)
| input.from([email protected])
| }
| }
| }
|}
|""".trimMargin()
}
it("using Groovy and Kotlin") {
listOf(
groovy to groovyBuildFileContent,
kotlin to kotlinBuildFileContent
).forEach { (builder, mainBuildFileContent) ->
val projectLayout = ProjectLayout(numberOfSourceFilesInRootPerSourceDir = 0).apply {
addSubmodule(
name = "child1",
numberOfSourceFilesPerSourceDir = 2,
numberOfCodeSmells = 2
)
addSubmodule(
name = "child2",
numberOfSourceFilesPerSourceDir = 4,
numberOfCodeSmells = 4
)
}
val gradleRunner = DslGradleRunner(projectLayout, builder.gradleBuildName, mainBuildFileContent)
gradleRunner.setupProject()
gradleRunner.runTasksAndExpectFailure("detekt", "xmlReportMerge", "--continue") { _ ->
assertThat(projectFile("build/reports/detekt/detekt.xml")).doesNotExist()
assertThat(projectFile("build/reports/detekt/merge.xml")).exists()
assertThat(projectFile("build/reports/detekt/merge.xml").readText())
.contains("<error column=\"30\" line=\"4\"")
projectLayout.submodules.forEach {
assertThat(projectFile("${it.name}/build/reports/detekt/detekt.xml")).exists()
}
}
}
}
}
})
| apache-2.0 | e7bb6e008c2358e518e356d0b571ed96 | 39.270531 | 115 | 0.514036 | 5.17764 | false | false | false | false |
calintat/Units | app/src/main/java/com/calintat/units/ui/ListItem.kt | 1 | 1851 | package com.calintat.units.ui
import android.text.TextUtils
import android.util.TypedValue
import android.view.Gravity
import android.view.ViewGroup
import android.widget.LinearLayout
import com.calintat.units.R
import org.jetbrains.anko.*
class ListItem() : AnkoComponent<ViewGroup> {
override fun createView(ui: AnkoContext<ViewGroup>) = with(ui) {
linearLayout {
lparams(width = matchParent, height = wrapContent)
backgroundResource = attr(R.attr.selectableItemBackground)
gravity = Gravity.CENTER_VERTICAL
minimumHeight = dip(72)
orientation = LinearLayout.HORIZONTAL
textView {
id = R.id.list_item_num
ellipsize = TextUtils.TruncateAt.MARQUEE
marqueeRepeatLimit = -1 // repeat indefinitely
maxLines = 1
padding = dip(16)
textAppearance = R.style.TextAppearance_AppCompat_Subhead
}.lparams(width = 0, height = wrapContent, weight = 1f)
verticalLayout {
gravity = Gravity.END
padding = dip(16)
textView {
id = R.id.list_item_str
maxLines = 1
textAppearance = R.style.TextAppearance_AppCompat_Body2
}.lparams(width = wrapContent, height = wrapContent)
textView {
id = R.id.list_item_sym
maxLines = 1
textAppearance = R.style.TextAppearance_AppCompat_Body1
}.lparams(width = wrapContent, height = wrapContent)
}
}
}
internal fun AnkoContext<*>.attr(value: Int): Int {
return TypedValue().let { ctx.theme.resolveAttribute(value, it, true); it.resourceId }
}
} | apache-2.0 | eff97bd7b51a1771fed4469dd036ec32 | 23.368421 | 94 | 0.574284 | 5.085165 | false | false | false | false |
ExMCL/ExMCL | ExMCL API/src/main/kotlin/com/n9mtq4/exmcl/api/tabs/events/TabEvents.kt | 1 | 2075 | /*
* MIT License
*
* Copyright (c) 2016 Will (n9Mtq4) Bresnahan
*
* 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.n9mtq4.exmcl.api.tabs.events
import com.n9mtq4.logwindow.BaseConsole
import com.n9mtq4.logwindow.events.DefaultGenericEvent
import java.awt.Component
/**
* Created by will on 2/27/16 at 3:09 PM.
*
* @author Will "n9Mtq4" Bresnahan
*/
class CreateTabEvent(val title: String, val component: Component, baseConsole: BaseConsole) : DefaultGenericEvent(baseConsole) {
override fun toString() = "${this.javaClass.name}{title=$title, component=$component}"
}
class LowLevelCreateTabEvent(val title: String, val component: Component, baseConsole: BaseConsole) : DefaultGenericEvent(baseConsole) {
override fun toString() = "${this.javaClass.name}{title=$title, component=$component}"
}
class SafeForLowLevelTabCreationEvent(initiatingBaseConsole: BaseConsole) : DefaultGenericEvent(initiatingBaseConsole)
class SafeForTabCreationEvent(initiatingBaseConsole: BaseConsole) : DefaultGenericEvent(initiatingBaseConsole)
| mit | 91bd8a6daf356f2738b8645dfd4e0e70 | 47.255814 | 136 | 0.779277 | 4.243354 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/event/AutoVersioningEventServiceImpl.kt | 1 | 3958 | package net.nemerosa.ontrack.extension.av.event
import net.nemerosa.ontrack.common.getOrNull
import net.nemerosa.ontrack.extension.av.dispatcher.AutoVersioningOrder
import net.nemerosa.ontrack.extension.av.event.AutoVersioningEvents.AUTO_VERSIONING_ERROR
import net.nemerosa.ontrack.extension.av.event.AutoVersioningEvents.AUTO_VERSIONING_PR_MERGE_TIMEOUT_ERROR
import net.nemerosa.ontrack.extension.av.event.AutoVersioningEvents.AUTO_VERSIONING_SUCCESS
import net.nemerosa.ontrack.extension.scm.service.SCMPullRequest
import net.nemerosa.ontrack.model.events.*
import net.nemerosa.ontrack.model.exceptions.ProjectNotFoundException
import net.nemerosa.ontrack.model.structure.StructureService
import net.nemerosa.ontrack.model.support.StartupService
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
class AutoVersioningEventServiceImpl(
private val structureService: StructureService,
private val eventFactory: EventFactory,
private val eventPostService: EventPostService,
) : AutoVersioningEventService, StartupService {
/**
* We do need a separate transaction to send events in case of error
* because the current transaction WILL be cancelled
*/
@Transactional(propagation = Propagation.REQUIRES_NEW)
override fun sendError(order: AutoVersioningOrder, message: String, error: Exception) {
eventPostService.post(
error(order, message, error)
)
}
override fun sendPRMergeTimeoutError(order: AutoVersioningOrder, pr: SCMPullRequest) {
eventPostService.post(
prMergeTimeoutError(order, pr)
)
}
override fun sendSuccess(order: AutoVersioningOrder, message: String, pr: SCMPullRequest) {
eventPostService.post(
success(order, message, pr)
)
}
override fun getName(): String = "Registration of auto versioning events"
override fun startupOrder(): Int = StartupService.JOB_REGISTRATION
override fun start() {
eventFactory.register(AUTO_VERSIONING_SUCCESS)
eventFactory.register(AUTO_VERSIONING_ERROR)
eventFactory.register(AUTO_VERSIONING_PR_MERGE_TIMEOUT_ERROR)
}
internal fun success(
order: AutoVersioningOrder,
message: String,
pr: SCMPullRequest,
): Event =
Event.of(AUTO_VERSIONING_SUCCESS)
.withBranch(order.branch)
.withExtraProject(sourceProject(order))
.with("version", order.targetVersion)
.with("message", close(message))
.with("pr-name", pr.name)
.with("pr-link", pr.link)
.build()
internal fun error(
order: AutoVersioningOrder,
message: String,
error: Exception,
): Event =
Event.of(AUTO_VERSIONING_ERROR)
.withBranch(order.branch)
.withExtraProject(sourceProject(order))
.with("version", order.targetVersion)
.with("message", close(message))
.with("error", close(error.message ?: error::class.java.name))
.build()
internal fun prMergeTimeoutError(
order: AutoVersioningOrder,
pr: SCMPullRequest,
): Event =
Event.of(AUTO_VERSIONING_PR_MERGE_TIMEOUT_ERROR)
.withBranch(order.branch)
.withExtraProject(sourceProject(order))
.with("version", order.targetVersion)
.with("pr-name", pr.name)
.with("pr-link", pr.link)
.build()
private fun sourceProject(order: AutoVersioningOrder) =
structureService.findProjectByName(order.sourceProject)
.getOrNull()
?: throw ProjectNotFoundException(order.sourceProject)
private fun close(message: String) = if (message.endsWith(".")) {
message
} else {
"$message."
}
} | mit | c23d4117902a237ba51b94437c731b83 | 35.657407 | 106 | 0.690248 | 4.482446 | false | false | false | false |
goodwinnk/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/eventLog/FeatureUsageFileEventLogger.kt | 2 | 2589 | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.internal.statistic.eventLog
import com.intellij.openapi.Disposable
import com.intellij.util.ConcurrencyUtil
import java.io.File
import java.util.*
open class FeatureUsageFileEventLogger(private val sessionId: String,
private val build: String,
private val bucket: String,
private val recorderVersion: String,
private val writer: FeatureUsageEventWriter) : FeatureUsageEventLogger, Disposable {
protected val myLogExecutor = ConcurrencyUtil.newSingleThreadExecutor(javaClass.simpleName)
private var lastEvent: LogEvent? = null
private var lastEventTime: Long = 0
private var lastEventCreatedTime: Long = 0
override fun log(recorderId: String, action: String, isState: Boolean) {
log(recorderId, action, Collections.emptyMap(), isState)
}
override fun log(recorderId: String, action: String, data: Map<String, Any>, isState: Boolean) {
val eventTime = System.currentTimeMillis()
myLogExecutor.execute(Runnable {
val creationTime = System.currentTimeMillis()
val event = newLogEvent(sessionId, build, bucket, eventTime, recorderId, recorderVersion, action, isState)
for (datum in data) {
event.event.addData(datum.key, datum.value)
}
log(writer, event, creationTime)
})
}
private fun log(writer: FeatureUsageEventWriter, event: LogEvent, createdTime: Long) {
if (lastEvent != null && event.time - lastEventTime <= 10000 && lastEvent!!.shouldMerge(event)) {
lastEventTime = event.time
lastEvent!!.event.increment()
}
else {
logLastEvent(writer)
lastEvent = event
lastEventTime = event.time
lastEventCreatedTime = createdTime
}
}
private fun logLastEvent(writer: FeatureUsageEventWriter) {
lastEvent?.let {
if (it.event.isEventGroup()) {
it.event.addData("last", lastEventTime)
}
it.event.addData("created", lastEventCreatedTime)
writer.log(LogEventSerializer.toString(it))
}
lastEvent = null
}
override fun getLogFiles(): List<File> {
return writer.getFiles()
}
override fun dispose() {
dispose(writer)
}
private fun dispose(writer: FeatureUsageEventWriter) {
myLogExecutor.execute(Runnable {
logLastEvent(writer)
})
myLogExecutor.shutdown()
}
} | apache-2.0 | 173f1aefb857d2b53f1cdd11bbfceb2e | 32.636364 | 140 | 0.672074 | 4.741758 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/ui/UIRadioButton.kt | 1 | 2521 | package com.soywiz.korge.ui
import com.soywiz.korge.view.*
import com.soywiz.korge.view.ktree.*
import com.soywiz.korim.bitmap.*
class UIRadioButtonGroup {
private var mutableButtons = hashSetOf<UIRadioButton>()
val buttons: Set<UIRadioButton> get() = mutableButtons
var selectedButton: UIRadioButton? = null
internal set(value) {
if (field != value) {
field?.checked = false
field = value
}
}
internal fun addRadio(button: UIRadioButton) {
mutableButtons += button
if (selectedButton == null) {
button.checked = true
}
}
internal fun removeRadio(button: UIRadioButton) {
mutableButtons -= button
}
}
inline fun Container.uiRadioButton(
width: Double = UI_DEFAULT_WIDTH,
height: Double = UI_DEFAULT_HEIGHT,
checked: Boolean = false,
text: String = "Radio Button",
group: UIRadioButtonGroup = UIRadioButtonGroup(),
block: @ViewDslMarker UIRadioButton.() -> Unit = {}
): UIRadioButton = UIRadioButton(width, height, checked, group, text).addTo(this).apply(block)
open class UIRadioButton(
width: Double = UI_DEFAULT_WIDTH,
height: Double = UI_DEFAULT_HEIGHT,
checked: Boolean = false,
group: UIRadioButtonGroup = UIRadioButtonGroup(),
text: String = "Radio Button",
) : UIBaseCheckBox<UIRadioButton>(width, height, checked, text) {
var group: UIRadioButtonGroup = group
set(value) {
if (field !== value) {
field.removeRadio(this)
field = value
value.addRadio(this)
}
}
override var checked: Boolean
get() = super.checked
set(value) {
if (super.checked != value) {
super.checked = value
if (value) group.selectedButton = this
}
}
init {
group.addRadio(this)
if (checked) {
group.selectedButton = this
}
}
override fun onComponentClick() {
checked = true
}
override fun getNinePatch(over: Boolean): NinePatchBmpSlice {
return when {
over -> radioOver
else -> radioNormal
}
}
object Serializer : KTreeSerializerExt<UIRadioButton>("UIRadioButton", UIRadioButton::class, { UIRadioButton() }, {
add(UIRadioButton::text)
add(UIRadioButton::checked)
add(UIRadioButton::width)
add(UIRadioButton::height)
})
}
| apache-2.0 | ff7c88733ed2872feae2acdff80f3d5f | 27.647727 | 119 | 0.596192 | 4.384348 | false | false | false | false |
kiruto/kotlin-android-mahjong | mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/models/collections/Kantsu.kt | 1 | 3728 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.yuriel.kotmahjan.models.collections
import dev.yuriel.kotmahjan.models.Hai
/**
* Created by yuriel on 8/13/16.
*/
/**
* 槓子に関するクラスです
* 暗槓と明槓の両方を扱います
*/
class Kantsu(override var identifierTile: Hai?): Mentsu() {
/**
* 槓子が完成していることを前提にしているため
* 槓子であるかのチェックは伴いません。
* @param isOpen 暗槓の場合false, 明槓の場合はtrueを入れて下さい
* @param identifierTile どの牌の槓子なのか
*/
constructor(isOpen: Boolean, identifierTile: Hai): this(identifierTile) {
this.isOpen = isOpen
this.isMentsu = true
}
/**
* 槓子であるかのチェックも伴います
* すべての牌(t1~4)が同じ場合にisMentsuがtrueになります
* @param isOpen 暗槓の場合false, 明槓の場合はtrueを入れて下さい
* @param tile1 1枚目
* @param tile2 2枚目
* @param tile3 3枚目
* @param tile4 4枚目
*/
constructor(isOpen: Boolean, tile1: Hai, tile2: Hai, tile3: Hai, tile4: Hai): this(tile1) {
this.isOpen = isOpen
this.isMentsu = check(tile1, tile2, tile3, tile4)
if (!isMentsu) {
identifierTile = null
}
}
override val fu: Int by lazy {
var mentsuFu = 8
if (!isOpen) {
mentsuFu *= 2
}
if (identifierTile?.isYaochu() == true) {
mentsuFu *= 2
}
mentsuFu
}
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o !is Kantsu) return false
if (isMentsu !== o.isMentsu) return false
if (isOpen !== o.isOpen) return false
return identifierTile === o.identifierTile
}
override fun hashCode(): Int {
var result: Int = if (null != identifierTile) identifierTile!!.hashCode() else 0
result = 31 * result + if (isMentsu) 1 else 0
result = 31 * result + if (isOpen) 1 else 0
return result
}
companion object {
/**
* t1~4が同一の牌かを調べます
* @param tile1 1枚目
* @param tile2 2枚目
* @param tile3 3枚目
* @param tile4 4枚目
* @return 槓子の場合true 槓子でない場合false
*/
fun check(tile1: Hai, tile2: Hai, tile3: Hai, tile4: Hai): Boolean {
return tile1 sameAs tile2 && tile2 sameAs tile3 && tile3 sameAs tile4
}
}
} | mit | 699034b13a5270bd0d93d31df95e8f15 | 29.627273 | 95 | 0.635095 | 3.361277 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-VDOM-JS/src/main/kotlin/o/katydid/vdom/builders/media/KatydidMediaEmbeddedContentBuilder.kt | 1 | 5008 | //
// (C) Copyright 2019 Martin E. Nordberg III
// Apache 2.0 License
//
package o.katydid.vdom.builders.media
import o.katydid.vdom.builders.KatydidAttributesContentBuilder
import o.katydid.vdom.builders.KatydidEmbeddedContentBuilder
import o.katydid.vdom.types.EDirection
import o.katydid.vdom.types.ETrackKind
import o.katydid.vdom.types.MimeType
//---------------------------------------------------------------------------------------------------------------------
/**
* Builder DSL to create the contents of a media element.
*/
interface KatydidMediaEmbeddedContentBuilder<in Msg>
: KatydidEmbeddedContentBuilder<Msg> {
/**
* Adds a `<source>` element with its attributes as the next child of the element under construction.
* @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class".
* @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element.
* @param accesskey a string specifying the HTML accesskey value.
* @param contenteditable whether the element has editable content.
* @param dir the left-to-right direction of text inside this element.
* @param draggable controls whether or not the element is draggable.
* @param hidden true if the element is to be hidden.
* @param lang the language of text within this element.
* @param media the media descriptor for which the source applies.
* @param sizes image sizes between breakpoints.
* @param spellcheck whether the element is subject to spell checking.
* @param src address of the resource.
* @param srcset images to use in different situations (e.g., high-resolution displays, small monitors, etc).
* @param style a string containing CSS for this element.
* @param tabindex the tab index for the element.
* @param title a tool tip for the element.
* @param translate whether to translate text within this element.
* @param type the MIME type of the source.
* @param defineAttributes a DSL-style lambda that builds any custom attributes of the new element.
*/
fun source(
selector: String? = null,
key: Any? = null,
accesskey: Char? = null,
contenteditable: Boolean? = null,
dir: EDirection? = null,
draggable: Boolean? = null,
hidden: Boolean? = null,
lang: String? = null,
media: String? = null,
sizes: String? = null,
spellcheck: Boolean? = null,
src: String,
srcset: String? = null,
style: String? = null,
tabindex: Int? = null,
title: String? = null,
translate: Boolean? = null,
type: MimeType? = null,
defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit
)
/**
* Adds a `<track>` element with its attributes as the next child of the element under construction.
* @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class".
* @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element.
* @param accesskey a string specifying the HTML accesskey value.
* @param contenteditable whether the element has editable content.
* @param default whether this is the default track to play.
* @param dir the left-to-right direction of text inside this element.
* @param draggable controls whether or not the element is draggable.
* @param hidden true if the element is to be hidden.
* @param kind the purpose of this track.
* @param label user-visible label for the track.
* @param lang the language of text within this element.
* @param spellcheck whether the element is subject to spell checking.
* @param src address of the resource.
* @param srclang the language of the source.
* @param style a string containing CSS for this element.
* @param tabindex the tab index for the element.
* @param title a tool tip for the element.
* @param translate whether to translate text within this element.
* @param defineAttributes a DSL-style lambda that builds any custom attributes of the new element.
*/
fun track(
selector: String? = null,
key: Any? = null,
accesskey: Char? = null,
contenteditable: Boolean? = null,
default: Boolean? = null,
dir: EDirection? = null,
draggable: Boolean? = null,
hidden: Boolean? = null,
kind: ETrackKind? = null,
label: String? = null,
lang: String? = null,
spellcheck: Boolean? = null,
src: String,
srclang: String? = null,
style: String? = null,
tabindex: Int? = null,
title: String? = null,
translate: Boolean? = null,
defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit
)
}
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | 39f971e016ed8b78019aa2fda9bdba1f | 43.318584 | 119 | 0.635982 | 4.602941 | false | false | false | false |
shlusiak/Freebloks-Android | app/src/main/java/de/saschahlusiak/freebloks/preferences/types/ListPreferenceDialogFragment.kt | 1 | 1468 | package de.saschahlusiak.freebloks.preferences.types
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import androidx.preference.ListPreferenceDialogFragmentCompat
import androidx.preference.PreferenceDialogFragmentCompat
import com.google.android.material.dialog.MaterialAlertDialogBuilder
open class ListPreferenceDialogFragment : ListPreferenceDialogFragmentCompat() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// exactly the same as super.onCreateDialog, but uses a MaterialAlertDialogBuilder instead
val context: Context? = activity
val builder = MaterialAlertDialogBuilder(requireContext())
.setTitle(preference.dialogTitle)
.setIcon(preference.dialogIcon)
.setPositiveButton(preference.positiveButtonText, this)
.setNegativeButton(preference.negativeButtonText, this)
val contentView = onCreateDialogView(requireContext())
if (contentView != null) {
onBindDialogView(contentView)
builder.setView(contentView)
} else {
builder.setMessage(preference.dialogMessage)
}
onPrepareDialogBuilder(builder)
return builder.create()
}
fun setKey(key: String): ListPreferenceDialogFragment {
if (arguments == null) arguments = Bundle()
arguments?.putString(PreferenceDialogFragmentCompat.ARG_KEY, key)
return this
}
} | gpl-2.0 | 804757cfb4322ebaa743196f90b11aba | 40.971429 | 98 | 0.730245 | 5.802372 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/AsyncTaskPreference.kt | 1 | 2889 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.preference
import android.content.Context
import android.os.AsyncTask
import android.os.AsyncTask.Status
import android.support.v7.preference.Preference
import android.util.AttributeSet
import org.mariotaku.chameleon.ChameleonUtils
import org.mariotaku.ktextension.dismissDialogFragment
import de.vanita5.twittnuker.activity.iface.IBaseActivity
import de.vanita5.twittnuker.fragment.ProgressDialogFragment
import java.lang.ref.WeakReference
abstract class AsyncTaskPreference(context: Context, attrs: AttributeSet? = null) :
Preference(context, attrs) {
private var task: InternalTask? = null
override fun onClick() {
if (task?.status != Status.RUNNING) {
task = InternalTask(this).apply { execute() }
}
}
protected abstract fun doInBackground()
private class InternalTask(preference: AsyncTaskPreference) : AsyncTask<Any, Any, Unit>() {
private val preferenceRef = WeakReference<AsyncTaskPreference>(preference)
override fun doInBackground(vararg args: Any) {
val preference = preferenceRef.get() ?: return
preference.doInBackground()
}
override fun onPostExecute(result: Unit) {
val context = preferenceRef.get()?.context ?: return
val activity = ChameleonUtils.getActivity(context) as? IBaseActivity<*> ?: return
activity.executeAfterFragmentResumed {
it.supportFragmentManager.dismissDialogFragment(FRAGMENT_TAG)
}
}
override fun onPreExecute() {
val context = preferenceRef.get()?.context ?: return
val activity = ChameleonUtils.getActivity(context) as? IBaseActivity<*> ?: return
activity.executeAfterFragmentResumed {
ProgressDialogFragment.show(it.supportFragmentManager, FRAGMENT_TAG)
}
}
companion object {
private const val FRAGMENT_TAG = "task_progress"
}
}
} | gpl-3.0 | 6fcfb16ed47bcc7d013d13ed72841b6b | 35.582278 | 95 | 0.703704 | 4.689935 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/talk/TalkReplyActivity.kt | 1 | 15060 | package org.wikipedia.talk
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextWatcher
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.util.lruCache
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.BaseActivity
import org.wikipedia.analytics.EditFunnel
import org.wikipedia.analytics.LoginFunnel
import org.wikipedia.analytics.eventplatform.EditAttemptStepEvent
import org.wikipedia.auth.AccountUtil
import org.wikipedia.databinding.ActivityTalkReplyBinding
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.discussiontools.ThreadItem
import org.wikipedia.history.HistoryEntry
import org.wikipedia.login.LoginActivity
import org.wikipedia.notifications.AnonymousNotificationHelper
import org.wikipedia.page.*
import org.wikipedia.page.linkpreview.LinkPreviewDialog
import org.wikipedia.readinglist.AddToReadingListDialog
import org.wikipedia.richtext.RichTextUtil
import org.wikipedia.staticdata.TalkAliasData
import org.wikipedia.util.*
import org.wikipedia.views.UserMentionInputView
class TalkReplyActivity : BaseActivity(), LinkPreviewDialog.Callback, UserMentionInputView.Listener {
private lateinit var binding: ActivityTalkReplyBinding
private lateinit var editFunnel: EditFunnel
private lateinit var linkHandler: TalkLinkHandler
private lateinit var textWatcher: TextWatcher
private val viewModel: TalkReplyViewModel by viewModels { TalkReplyViewModel.Factory(intent.extras!!) }
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
private var userMentionScrolled = false
private var savedSuccess = false
private val linkMovementMethod = LinkMovementMethodExt { url, title, linkText, x, y ->
linkHandler.onUrlClick(url, title, linkText, x, y)
}
private val requestLogin = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == LoginActivity.RESULT_LOGIN_SUCCESS) {
updateEditLicenseText()
editFunnel.logLoginSuccess()
FeedbackUtil.showMessage(this, R.string.login_success_toast)
} else {
editFunnel.logLoginFailure()
}
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityTalkReplyBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.replyToolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
title = ""
linkHandler = TalkLinkHandler(this)
linkHandler.wikiSite = viewModel.pageTitle.wikiSite
textWatcher = binding.replySubjectText.doOnTextChanged { _, _, _, _ ->
binding.replySubjectLayout.error = null
binding.replyInputView.textInputLayout.error = null
setSaveButtonEnabled(!binding.replyInputView.editText.text.isNullOrBlank())
}
binding.replyInputView.editText.addTextChangedListener(textWatcher)
binding.replySaveButton.setOnClickListener {
onSaveClicked()
}
binding.replyInputView.wikiSite = viewModel.pageTitle.wikiSite
binding.replyInputView.listener = this
editFunnel = EditFunnel(WikipediaApp.instance, viewModel.pageTitle)
editFunnel.logStart()
EditAttemptStepEvent.logInit(viewModel.pageTitle)
if (viewModel.topic != null) {
binding.threadItemView.bindItem(viewModel.topic!!, linkMovementMethod, true)
binding.threadItemView.isVisible = true
} else {
binding.threadItemView.isVisible = false
}
viewModel.postReplyData.observe(this) {
if (it is Resource.Success) {
savedSuccess = true
onSaveSuccess(it.data)
} else if (it is Resource.Error) {
onSaveError(it.throwable)
}
}
onInitialLoad()
}
public override fun onDestroy() {
if (!savedSuccess && !binding.replyInputView.editText.text.isNullOrBlank() && viewModel.topic != null) {
draftReplies.put(viewModel.topic!!.id, binding.replyInputView.editText.text!!)
}
binding.replySubjectText.removeTextChangedListener(textWatcher)
binding.replyInputView.editText.removeTextChangedListener(textWatcher)
super.onDestroy()
}
private fun onInitialLoad() {
updateEditLicenseText()
setSaveButtonEnabled(false)
setToolbarTitle(viewModel.pageTitle)
L10nUtil.setConditionalLayoutDirection(binding.talkScrollContainer, viewModel.pageTitle.wikiSite.languageCode)
if (viewModel.topic != null) {
binding.replyInputView.userNameHints = setOf(viewModel.topic!!.author)
}
val savedReplyText = if (viewModel.topic == null) null else draftReplies.get(viewModel.topic?.id)
if (!savedReplyText.isNullOrEmpty()) {
binding.replyInputView.editText.setText(savedReplyText)
binding.replyInputView.editText.setSelection(binding.replyInputView.editText.text.toString().length)
}
binding.progressBar.isVisible = false
binding.replySubjectText.setText(intent.getCharSequenceExtra(EXTRA_SUBJECT))
if (intent.hasExtra(EXTRA_BODY) && binding.replyInputView.editText.text.isNullOrEmpty()) {
binding.replyInputView.editText.setText(intent.getCharSequenceExtra(EXTRA_BODY))
binding.replyInputView.editText.setSelection(binding.replyInputView.editText.text.toString().length)
}
editFunnel.logStart()
EditAttemptStepEvent.logInit(viewModel.pageTitle)
if (viewModel.isNewTopic) {
title = getString(R.string.talk_new_topic)
binding.replyInputView.textInputLayout.hint = getString(R.string.talk_message_hint)
binding.replySubjectLayout.isVisible = true
binding.replySubjectLayout.requestFocus()
} else {
binding.replySubjectLayout.isVisible = false
binding.replyInputView.textInputLayout.hint = getString(R.string.talk_reply_hint)
binding.talkScrollContainer.fullScroll(View.FOCUS_DOWN)
binding.replyInputView.maybePrepopulateUserName(AccountUtil.userName.orEmpty(), viewModel.pageTitle)
binding.talkScrollContainer.post {
if (!isDestroyed) {
binding.replyInputView.editText.requestFocus()
DeviceUtil.showSoftKeyboard(binding.replyInputView.editText)
binding.talkScrollContainer.postDelayed({
binding.talkScrollContainer.smoothScrollTo(0, binding.talkScrollContainer.height * 4)
}, 500)
}
}
}
}
private fun setToolbarTitle(pageTitle: PageTitle) {
binding.toolbarTitle.text = StringUtil.fromHtml(
if (viewModel.isNewTopic) pageTitle.namespace.ifEmpty { TalkAliasData.valueFor(pageTitle.wikiSite.languageCode) } + ": " + "<a href='#'>${StringUtil.removeNamespace(pageTitle.displayText)}</a>"
else intent.getStringExtra(EXTRA_PARENT_SUBJECT).orEmpty()
).trim().ifEmpty { getString(R.string.talk_no_subject) }
binding.toolbarTitle.contentDescription = binding.toolbarTitle.text
binding.toolbarTitle.movementMethod = LinkMovementMethodExt { _ ->
val entry = HistoryEntry(TalkTopicsActivity.getNonTalkPageTitle(pageTitle), HistoryEntry.SOURCE_TALK_TOPIC)
startActivity(PageActivity.newIntentForNewTab(this, entry, entry.title))
}
RichTextUtil.removeUnderlinesFromLinks(binding.toolbarTitle)
FeedbackUtil.setButtonLongPressToast(binding.toolbarTitle)
}
internal inner class TalkLinkHandler internal constructor(context: Context) : LinkHandler(context) {
private var lastX: Int = 0
private var lastY: Int = 0
fun onUrlClick(url: String, title: String?, linkText: String, x: Int, y: Int) {
lastX = x
lastY = y
super.onUrlClick(url, title, linkText)
}
override fun onMediaLinkClicked(title: PageTitle) {
// TODO
}
override fun onDiffLinkClicked(title: PageTitle, revisionId: Long) {
// TODO
}
override lateinit var wikiSite: WikiSite
override fun onPageLinkClicked(anchor: String, linkText: String) {
// TODO
}
override fun onInternalLinkClicked(title: PageTitle) {
UserTalkPopupHelper.show(this@TalkReplyActivity, bottomSheetPresenter, title, false, lastX, lastY,
Constants.InvokeSource.TALK_REPLY_ACTIVITY, HistoryEntry.SOURCE_TALK_TOPIC)
}
}
private fun setSaveButtonEnabled(enabled: Boolean) {
binding.replySaveButton.isEnabled = enabled
binding.replySaveButton.setTextColor(ResourceUtil
.getThemedColor(this, if (enabled) R.attr.colorAccent else R.attr.material_theme_de_emphasised_color))
}
private fun onSaveClicked() {
val subject = binding.replySubjectText.text.toString().trim()
val body = binding.replyInputView.editText.getParsedText(viewModel.pageTitle.wikiSite).trim()
Intent().let {
it.putExtra(EXTRA_SUBJECT, subject)
it.putExtra(EXTRA_BODY, body)
}
editFunnel.logSaveAttempt()
EditAttemptStepEvent.logSaveAttempt(viewModel.pageTitle)
if (viewModel.isNewTopic && subject.isEmpty()) {
binding.replySubjectLayout.error = getString(R.string.talk_subject_empty)
binding.replySubjectLayout.requestFocus()
return
} else if (body.isEmpty()) {
binding.replyInputView.textInputLayout.error = getString(R.string.talk_message_empty)
binding.replyInputView.textInputLayout.requestFocus()
return
}
binding.progressBar.visibility = View.VISIBLE
setSaveButtonEnabled(false)
viewModel.postReply(subject, body)
}
private fun onSaveSuccess(newRevision: Long) {
AnonymousNotificationHelper.onEditSubmitted()
binding.progressBar.visibility = View.GONE
setSaveButtonEnabled(true)
editFunnel.logSaved(newRevision)
EditAttemptStepEvent.logSaveSuccess(viewModel.pageTitle)
Intent().let {
it.putExtra(RESULT_NEW_REVISION_ID, newRevision)
it.putExtra(EXTRA_SUBJECT, binding.replySubjectText.text)
it.putExtra(EXTRA_BODY, binding.replyInputView.editText.text)
if (viewModel.topic != null) {
it.putExtra(EXTRA_TOPIC_ID, viewModel.topic!!.id)
}
setResult(RESULT_EDIT_SUCCESS, it)
if (viewModel.topic != null) {
draftReplies.remove(viewModel.topic?.id)
}
finish()
}
}
private fun onSaveError(t: Throwable) {
editFunnel.logError(t.message)
EditAttemptStepEvent.logSaveFailure(viewModel.pageTitle)
binding.progressBar.visibility = View.GONE
setSaveButtonEnabled(true)
FeedbackUtil.showError(this, t)
}
private fun updateEditLicenseText() {
binding.licenseText.text = StringUtil.fromHtml(getString(if (AccountUtil.isLoggedIn) R.string.edit_save_action_license_logged_in else R.string.edit_save_action_license_anon,
getString(R.string.terms_of_use_url),
getString(R.string.cc_by_sa_3_url)))
binding.licenseText.movementMethod = LinkMovementMethodExt { url: String ->
if (url == "https://#login") {
val loginIntent = LoginActivity.newIntent(this,
LoginFunnel.SOURCE_EDIT, editFunnel.sessionToken)
requestLogin.launch(loginIntent)
} else {
UriUtil.handleExternalLink(this, Uri.parse(url))
}
}
}
override fun onLinkPreviewLoadPage(title: PageTitle, entry: HistoryEntry, inNewTab: Boolean) {
startActivity(if (inNewTab) PageActivity.newIntentForNewTab(this, entry, title) else
PageActivity.newIntentForCurrentTab(this, entry, title, false))
}
override fun onLinkPreviewCopyLink(title: PageTitle) {
ClipboardUtil.setPlainText(this, text = title.uri)
FeedbackUtil.showMessage(this, R.string.address_copied)
}
override fun onLinkPreviewAddToList(title: PageTitle) {
bottomSheetPresenter.show(supportFragmentManager,
AddToReadingListDialog.newInstance(title, Constants.InvokeSource.TALK_REPLY_ACTIVITY))
}
override fun onLinkPreviewShareLink(title: PageTitle) {
ShareUtil.shareText(this, title)
}
override fun onBackPressed() {
setResult(RESULT_BACK_FROM_TOPIC)
super.onBackPressed()
}
override fun onUserMentionListUpdate() {
binding.licenseText.isVisible = false
binding.talkScrollContainer.post {
if (!isDestroyed && !userMentionScrolled) {
binding.talkScrollContainer.smoothScrollTo(0, binding.root.height * 4)
userMentionScrolled = true
}
}
}
override fun onUserMentionComplete() {
userMentionScrolled = false
binding.licenseText.isVisible = true
}
companion object {
const val EXTRA_PAGE_TITLE = "pageTitle"
const val EXTRA_PARENT_SUBJECT = "parentSubject"
const val EXTRA_TOPIC = "topic"
const val EXTRA_TOPIC_ID = "topicId"
const val EXTRA_SUBJECT = "subject"
const val EXTRA_BODY = "body"
const val RESULT_EDIT_SUCCESS = 1
const val RESULT_BACK_FROM_TOPIC = 2
const val RESULT_NEW_REVISION_ID = "newRevisionId"
// TODO: persist in db. But for now, it's fine to store these for the lifetime of the app.
val draftReplies = lruCache<String, CharSequence>(10)
fun newIntent(context: Context,
pageTitle: PageTitle,
parentSubject: String?,
topic: ThreadItem?,
invokeSource: Constants.InvokeSource,
undoSubject: CharSequence? = null,
undoBody: CharSequence? = null): Intent {
return Intent(context, TalkReplyActivity::class.java)
.putExtra(EXTRA_PAGE_TITLE, pageTitle)
.putExtra(EXTRA_PARENT_SUBJECT, parentSubject)
.putExtra(EXTRA_TOPIC, topic)
.putExtra(EXTRA_SUBJECT, undoSubject)
.putExtra(EXTRA_BODY, undoBody)
.putExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE, invokeSource)
}
}
}
| apache-2.0 | 1e3ffe1fd5937b21a635a847343b6d24 | 41.067039 | 205 | 0.676627 | 4.87221 | false | false | false | false |
deskchanproject/DeskChanJava | src/main/kotlin/info/deskchan/groovy_support/GroovyPlugin.kt | 2 | 3292 | package info.deskchan.groovy_support
import groovy.lang.Script
import info.deskchan.core.*
import java.util.*
abstract class GroovyPlugin : Script(), Plugin {
private var pluginProxy: PluginProxyInterface? = null
private val cleanupHandlers = ArrayList<Runnable>()
var pluginDirPath: Path? = null
get() = pluginProxy!!.pluginDirPath
var assetsDirPath: Path? = null
get() = pluginProxy!!.assetsDirPath
var rootDirPath: Path? = null
get() = pluginProxy!!.rootDirPath
val dataDirPath: Path
get() = pluginProxy!!.dataDirPath
val id: String
get() = pluginProxy!!.getId()
val properties: PluginProperties
get() = pluginProxy!!.getProperties()
override fun initialize(pluginProxy: PluginProxyInterface): Boolean {
this.pluginProxy = pluginProxy
try {
run()
} catch (e: Exception) {
pluginProxy.log(e)
return false
}
return true
}
override fun unload() {
for (runnable in cleanupHandlers) {
runnable.run()
}
}
fun sendMessage(tag: String, data: Any?) {
pluginProxy!!.sendMessage(tag, data)
}
fun sendMessage(tag: String, data: Any?, responseListener: ResponseListener) {
pluginProxy!!.sendMessage(tag, data, responseListener)
}
fun sendMessage(tag: String, data: Any?, responseListener: ResponseListener, returnListener: ResponseListener) {
pluginProxy!!.sendMessage(tag, data, responseListener, returnListener)
}
fun addMessageListener(tag: String, listener: MessageListener) {
pluginProxy!!.addMessageListener(tag, listener)
}
fun removeMessageListener(tag: String, listener: MessageListener) {
pluginProxy!!.removeMessageListener(tag, listener)
}
fun setTimer(delay: Long, listener: ResponseListener): Int {
return pluginProxy!!.setTimer(delay, listener)
}
fun setTimer(delay: Long, count: Int, listener: ResponseListener): Int {
return pluginProxy!!.setTimer(delay, count, listener)
}
fun cancelTimer(id: Int) {
pluginProxy!!.cancelTimer(id)
}
fun getString(key: String): String {
return pluginProxy!!.getString(key)
}
fun addCleanupHandler(handler: Runnable) {
cleanupHandlers.add(handler)
}
fun setResourceBundle(path: String) {
pluginProxy!!.setResourceBundle(pluginDirPath!!.resolve(path).toString())
}
fun setConfigField(key: String, value: Any) {
pluginProxy!!.setConfigField(key, value)
}
fun getConfigField(key: String): Any? {
return pluginProxy!!.getConfigField(key)
}
fun log(text: String) {
pluginProxy!!.log(text)
}
fun log(e: Throwable) {
pluginProxy!!.log(e)
}
fun setAlternative(srcTag: String, dstTag: String, priority:Int) {
pluginProxy!!.setAlternative(srcTag, dstTag, priority)
}
fun deleteAlternative(srcTag: String, dstTag: String) {
pluginProxy!!.deleteAlternative(srcTag, dstTag)
}
fun callNextAlternative(sender: String, tag: String, currentAlternative: String, data: Any?) {
pluginProxy!!.callNextAlternative(sender, tag, currentAlternative, data)
}
}
| lgpl-3.0 | 9984b866117864274184d699b9960335 | 26.898305 | 116 | 0.650668 | 4.528198 | false | false | false | false |
kittinunf/Fuel | fuel/src/main/kotlin/com/github/kittinunf/fuel/core/requests/RepeatableBody.kt | 1 | 3166 | package com.github.kittinunf.fuel.core.requests
import com.github.kittinunf.fuel.core.Body
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.io.OutputStream
/**
* A Repeatable Body wraps a body and on the first [writeTo] it keeps the bytes in memory so it can be written again.
*
* Delegation is not possible because the [body] is re-assigned, and the delegation would point to the initial
* assignment.
*/
data class RepeatableBody(
var body: Body
) : Body {
/**
* Writes the body to the [OutputStream].
*
* @note callers are responses for closing the [OutputStream].
* @note implementations may choose to make the [Body] `isConsumed` and can not be written or read from again.
* @note implementations are recommended to buffer the output stream if they can't ensure bulk writing.
*
* @param outputStream [OutputStream] the stream to write to
* @return [Long] the number of bytes written
*/
override fun writeTo(outputStream: OutputStream): Long {
val repeatableBodyStream = ByteArrayInputStream(toByteArray())
return body.writeTo(outputStream)
.also { length -> body = DefaultBody.from({ repeatableBodyStream }, { length }) }
}
/**
* Returns the body as a [ByteArray].
*
* @note Because the body needs to be read into memory anyway, implementations may choose to make the [Body]
* readable once more after calling this method, with the original [InputStream] being closed (and release its
* resources). This also means that if an implementation choose to keep it around, `isConsumed` returns false.
*
* @return the entire body
*/
override fun toByteArray() = body.toByteArray()
/**
* Returns the body as an [InputStream].
*
* @note callers are responsible for closing the returned stream.
* @note implementations may choose to make the [Body] `isConsumed` and can not be written or read from again.
*
* @return the body as input stream
*/
override fun toStream() = body.toStream()
/**
* Returns the body emptiness.
* @return [Boolean] if true, this body is empty
*/
override fun isEmpty() = body.isEmpty()
/**
* Returns if the body is consumed.
* @return [Boolean] if true, `writeTo`, `toStream` and `toByteArray` may throw
*/
override fun isConsumed() = body.isConsumed()
/**
* Represents this body as a string
* @param contentType [String] the type of the content in the body, or null if a guess is necessary
* @return [String] the body as a string or a string that represents the body such as (empty) or (consumed)
*/
override fun asString(contentType: String?) = body.asString(contentType)
/**
* Returns the length of the body in bytes
* @return [Long?] the length in bytes, null if it is unknown
*/
override val length = body.length
/**
* Makes the body repeatable by e.g. loading its contents into memory
* @return [RepeatableBody] the body to be repeated
*/
override fun asRepeatable(): RepeatableBody = this
} | mit | 850fbbfe5a664e27d5e72fa9d334ef0a | 36.702381 | 117 | 0.672773 | 4.446629 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/extractFunction/ExtractFunctionParameterTablePanel.kt | 3 | 3254 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.extractFunction
import com.intellij.refactoring.util.AbstractParameterTablePanel
import com.intellij.refactoring.util.AbstractVariableData
import com.intellij.ui.BooleanTableCellEditor
import com.intellij.ui.BooleanTableCellRenderer
import com.intellij.util.ui.ColumnInfo
class ParameterDataHolder(val parameter: Parameter, val onChange: () -> Unit) : AbstractVariableData() {
fun changeName(name: String) {
parameter.name = name
onChange()
}
fun changeMutability(mutable: Boolean) {
parameter.isMutable = mutable
onChange()
}
}
class ChooseColumn : ColumnInfo<ParameterDataHolder, Boolean>(null) {
override fun valueOf(item: ParameterDataHolder): Boolean =
item.parameter.isSelected
override fun setValue(item: ParameterDataHolder, value: Boolean) {
item.parameter.isSelected = value
}
override fun getColumnClass(): Class<*> = Boolean::class.java
override fun isCellEditable(item: ParameterDataHolder): Boolean = true
}
class NameColumn(private val nameValidator: (String) -> Boolean) : ColumnInfo<ParameterDataHolder, String>("Name") {
override fun valueOf(item: ParameterDataHolder): String =
item.parameter.name
override fun setValue(item: ParameterDataHolder, value: String) {
if (nameValidator(value)) {
item.changeName(value)
}
}
override fun isCellEditable(item: ParameterDataHolder): Boolean = true
}
class TypeColumn : ColumnInfo<ParameterDataHolder, String>("Type") {
override fun valueOf(item: ParameterDataHolder): String =
item.parameter.type?.toString() ?: "_"
}
class MutabilityColumn : ColumnInfo<ParameterDataHolder, Boolean>("Mutable") {
override fun valueOf(item: ParameterDataHolder): Boolean =
item.parameter.isMutable
override fun setValue(item: ParameterDataHolder, value: Boolean) {
item.changeMutability(value)
}
override fun isCellEditable(item: ParameterDataHolder): Boolean = true
override fun getColumnClass(): Class<*> = Boolean::class.java
}
class ExtractFunctionParameterTablePanel(
nameValidator: (String) -> Boolean,
private val config: RsExtractFunctionConfig,
private val onChange: () -> Unit
) : AbstractParameterTablePanel<ParameterDataHolder>(
ChooseColumn(),
NameColumn(nameValidator),
TypeColumn(),
MutabilityColumn()
) {
init {
myTable.setDefaultRenderer(Boolean::class.java, BooleanTableCellRenderer())
myTable.setDefaultEditor(Boolean::class.java, BooleanTableCellEditor())
myTable.columnModel.getColumn(0).preferredWidth = WIDTH
myTable.columnModel.getColumn(0).maxWidth = WIDTH
init(
config.parameters.map {
ParameterDataHolder(it, ::updateSignature)
}.toTypedArray()
)
}
override fun doEnterAction() {}
override fun doCancelAction() {}
override fun updateSignature() {
config.parameters = variableData.map { it.parameter }
onChange()
}
companion object {
private const val WIDTH = 40
}
}
| mit | 9831563af4f315fade1cb78e6e1347f7 | 30.288462 | 116 | 0.702827 | 4.750365 | false | false | false | false |
satamas/fortran-plugin | src/test/kotlin/org/jetbrains/fortran/ide/inspections/FortranNonstandardKindInspectionTest.kt | 1 | 1261 | package org.jetbrains.fortran.ide.inspections
import org.junit.Test
class FortranNonstandardKindInspectionTest() : FortranInspectionsBaseTestCase(FortranNonstandardKindInspection()) {
@Test
fun testReal8() = checkFixByText(
"Nonstandard Kind Selector fix", """program prog1
real<warning descr="Nonstandard Kind Selector">*8<caret></warning> :: a
end
""", """program prog1
real(kind=8) :: a
end
""", true)
@Test
fun testComplex16() = checkFixByText("Nonstandard Kind Selector fix","""program prog1
complex<warning descr="Nonstandard Kind Selector">*16<caret></warning> :: a
end
""", """program prog1
complex(kind=8) :: a
end
""", true)
@Test
fun testRealN() = checkFixByText("Nonstandard Kind Selector fix","""program prog1
real<warning descr="Nonstandard Kind Selector">*N<caret></warning> :: a
end
""", """program prog1
real(kind=N) :: a
end
""", true)
@Test
fun testComplexN() = checkFixByText("Nonstandard Kind Selector fix","""program prog1
complex<warning descr="Nonstandard Kind Selector">*N<caret></warning> :: a
end
""", """program prog1
complex(kind=(N)/2) :: a
end
""", true)
} | apache-2.0 | 542c0a7257656b0a24c6db0df8bb2910 | 28.348837 | 115 | 0.629659 | 4.203333 | false | true | false | false |
google/dokka | core/src/main/kotlin/Formats/PackageListService.kt | 2 | 2456 | package org.jetbrains.dokka
import com.google.inject.Inject
interface PackageListService {
fun formatPackageList(module: DocumentationModule): String
}
class DefaultPackageListService @Inject constructor(
val generator: NodeLocationAwareGenerator,
val formatService: FormatService
) : PackageListService {
override fun formatPackageList(module: DocumentationModule): String {
val packages = mutableSetOf<String>()
val nonStandardLocations = mutableMapOf<String, String>()
fun visit(node: DocumentationNode, relocated: Boolean = false) {
val nodeKind = node.kind
when (nodeKind) {
NodeKind.Package -> {
packages.add(node.qualifiedName())
node.members.forEach { visit(it) }
}
NodeKind.Signature -> {
if (relocated)
nonStandardLocations[node.name] = generator.relativePathToLocation(module, node.owner!!)
}
NodeKind.ExternalClass -> {
node.members.forEach { visit(it, relocated = true) }
}
NodeKind.GroupNode -> {
//only children of top-level GN records interesting for us, since link to top-level ones should point to GN
node.members.forEach { it.members.forEach { visit(it, relocated = true) } }
//record signature of GN as signature of type alias and class merged to GN, so link to it should point to GN
node.detailOrNull(NodeKind.Signature)?.let { visit(it, relocated = true) }
}
else -> {
if (nodeKind in NodeKind.classLike || nodeKind in NodeKind.memberLike) {
node.details(NodeKind.Signature).forEach { visit(it, relocated) }
node.members.forEach { visit(it, relocated) }
}
}
}
}
module.members.forEach { visit(it) }
return buildString {
appendln("\$dokka.linkExtension:${formatService.linkExtension}")
nonStandardLocations.map { (signature, location) -> "\$dokka.location:$signature\u001f$location" }
.sorted().joinTo(this, separator = "\n", postfix = "\n")
packages.sorted().joinTo(this, separator = "\n", postfix = "\n")
}
}
}
| apache-2.0 | a4575e33d59905df8f7940997ea2ba2d | 37.984127 | 128 | 0.567997 | 4.97166 | false | false | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/studyroom/model/StudyRoom.kt | 1 | 1984 | package de.tum.`in`.tumcampusapp.component.ui.studyroom.model
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import android.arch.persistence.room.RoomWarnings
import com.google.gson.annotations.SerializedName
import org.joda.time.DateTime
/**
* Representation of a study room.
*/
@Entity(tableName = "study_rooms")
@SuppressWarnings(RoomWarnings.DEFAULT_CONSTRUCTOR)
data class StudyRoom(
@PrimaryKey
@SerializedName("room_id")
var id: Int = -1,
@SerializedName("room_code")
var code: String = "",
@SerializedName("room_name")
var name: String = "",
@ColumnInfo(name = "building_name")
@SerializedName("building_name")
var buildingName: String = "",
@ColumnInfo(name = "group_id")
@SerializedName("group_id")
var studyRoomGroup: Int = -1,
@ColumnInfo(name = "occupied_until")
@SerializedName("occupied_until")
var occupiedUntil: DateTime? = null,
@ColumnInfo(name = "free_until")
@SerializedName("free_until")
var freeUntil: DateTime? = null
) : Comparable<StudyRoom> {
override fun compareTo(other: StudyRoom): Int {
// We use the following sorting order:
// 1. Rooms that are currently free and don't have a reservation coming up (freeUntil == null)
// 2. Rooms that are currently free but have a reservation coming up (sorted descending by
// the amount of free time remaining)
// 3. Rooms that are currently occupied but will be free soon (sorted ascending by the
// amount of occupied time remaining)
// 4. The remaining rooms
return compareBy<StudyRoom> { it.freeUntil?.millis?.times(-1) }
.thenBy { it.occupiedUntil }
.thenBy { it.name }
.compare(this, other)
}
override fun toString() = code
}
| gpl-3.0 | ecc4fa2912abaeb531b8095f40d0a4b1 | 36.433962 | 102 | 0.647681 | 4.294372 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems | advanced/exercise-solutions/card-game/part-02/cards-dto/src/main/kotlin/org/tsdes/advanced/exercises/cardgame/cards/dto/CardDto.kt | 1 | 621 | package org.tsdes.advanced.exercises.cardgame.cards.dto
import io.swagger.annotations.ApiModelProperty
class CardDto(
@get:ApiModelProperty("The id of the card")
var cardId : String? = null,
@get:ApiModelProperty("The name of this card")
var name : String? = null,
@get:ApiModelProperty("A description of the card effects")
var description: String? = null,
@get:ApiModelProperty("The rarity of the card")
var rarity: Rarity? = null,
@get:ApiModelProperty("The id of the image associated with this card")
var imageId: String? = null
) | lgpl-3.0 | d3d2ef5fd466cf94e81ba57df655bd8b | 27.272727 | 78 | 0.660225 | 4.404255 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/inspections/ElmLocalInspection.kt | 1 | 1864 | package org.elm.ide.inspections
import com.intellij.codeInsight.intention.PriorityAction
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import org.elm.lang.core.psi.ElmPsiElement
abstract class ElmLocalInspection : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : PsiElementVisitor() {
override fun visitElement(element: PsiElement) {
super.visitElement(element)
if (element is ElmPsiElement) {
visitElement(element, holder, isOnTheFly)
}
}
}
abstract fun visitElement(element: ElmPsiElement, holder: ProblemsHolder, isOnTheFly: Boolean)
}
/**
* A [LocalQuickFix] base class that takes care of some of the boilerplate
*
* Note: [LocalQuickFix] implementations should never store a reference to a [PsiElement], since the
* PSI may change between the time that they're created and called, causing the elements to be
* invalid or leak memory.
*
* If you really need a reference to an element other than the one this fix is shown on, you can implement
* [LocalQuickFixOnPsiElement], which holds a weak reference to an element.
*/
abstract class NamedQuickFix(
private val fixName: String,
private val fixPriority: PriorityAction.Priority = PriorityAction.Priority.NORMAL
) : LocalQuickFix, PriorityAction {
override fun getName(): String = fixName
override fun getFamilyName(): String = name
override fun getPriority(): PriorityAction.Priority = fixPriority
final override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
this.applyFix(descriptor.psiElement ?: return, project)
}
abstract fun applyFix(element: PsiElement, project: Project)
}
| mit | 381a53c3f0cd70d979b76dae8bd12d69 | 40.422222 | 107 | 0.743026 | 4.892388 | false | false | false | false |
danwallach/CalWatch | app/src/main/kotlin/org/dwallach/calwatch2/Constants.kt | 1 | 883 | /*
* CalWatch / CalWatch2
* Copyright © 2014-2022 by Dan S. Wallach
* Home page: http://www.cs.rice.edu/~dwallach/calwatch/
* Licensing: http://www.cs.rice.edu/~dwallach/calwatch/licensing.html
*/
package org.dwallach.calwatch2
import org.dwallach.complications.ComplicationLocation.BOTTOM
import org.dwallach.complications.ComplicationLocation.RIGHT
import org.dwallach.complications.ComplicationLocation.TOP
object Constants {
const val PREFS_KEY = "org.dwallach.calwatch2.prefs"
const val DATA_KEY = "org.dwallach.calwatch2.data"
const val SETTINGS_PATH = "/settings"
const val DEFAULT_WATCHFACE = ClockState.FACE_TOOL
const val DEFAULT_SHOW_SECONDS = true
const val DEFAULT_SHOW_DAY_DATE = true
const val POWER_WARN_LOW_LEVEL = 0.33f
const val POWER_WARN_CRITICAL_LEVEL = 0.1f
val COMPLICATION_LOCATIONS = listOf(RIGHT, TOP, BOTTOM)
}
| gpl-3.0 | beabefb9318028f63e5bfdf06c10fab2 | 37.347826 | 70 | 0.751701 | 3.528 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/users/dto/UsersCareer.kt | 1 | 2396 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.users.dto
import com.google.gson.annotations.SerializedName
import com.vk.dto.common.id.UserId
import kotlin.Int
import kotlin.String
/**
* @param cityId - City ID
* @param cityName - City name
* @param company - Company name
* @param countryId - Country ID
* @param from - From year
* @param groupId - Community ID
* @param id - Career ID
* @param position - Position
* @param until - Till year
*/
data class UsersCareer(
@SerializedName("city_id")
val cityId: Int? = null,
@SerializedName("city_name")
val cityName: String? = null,
@SerializedName("company")
val company: String? = null,
@SerializedName("country_id")
val countryId: Int? = null,
@SerializedName("from")
val from: Int? = null,
@SerializedName("group_id")
val groupId: UserId? = null,
@SerializedName("id")
val id: Int? = null,
@SerializedName("position")
val position: String? = null,
@SerializedName("until")
val until: Int? = null
)
| mit | e77620b449a9a105f53c5ea464551dc3 | 35.861538 | 81 | 0.669449 | 4.233216 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/parser/ParsedDataTypes.kt | 1 | 9404 | package org.jetbrains.haskell.debugger.parser
import java.util.ArrayList
import org.json.simple.JSONObject
import java.io.File
/**
* This file contains data types for holding parsed information
*
* @author Habibullin Marat
*/
public open class ParseResult
public class BreakpointCommandResult(public val breakpointNumber: Int,
public val position: HsFilePosition) : ParseResult() {
override fun equals(other: Any?): Boolean {
if (other identityEquals this) return true
if (other == null || other.javaClass != this.javaClass) return false
val othCasted = other as BreakpointCommandResult
return breakpointNumber == othCasted.breakpointNumber && position.equals(othCasted.position)
}
override fun hashCode(): Int {
val prime = 31;
var result = 1;
result = prime * result + breakpointNumber
result = prime * result + position.hashCode()
return result
}
}
public class HsFilePosition(public val filePath: String,
public val rawStartLine: Int,
public val rawStartSymbol: Int,
public val rawEndLine: Int,
public val rawEndSymbol: Int)
: ParseResult() {
// zero based start line number
public val normalizedStartLine: Int = rawStartLine - 1
public val normalizedStartSymbol: Int = rawStartSymbol
// zero based end line number
public val normalizedEndLine: Int = rawEndLine - 1
// ghci returns value for end symbol that is less for 1 than idea uses. so normalizedEndSymbol contains corrected one
public val normalizedEndSymbol: Int = rawEndSymbol + 1
public val simplePath: String = filePath.substring(if (filePath.contains("/")) filePath.lastIndexOf('/') + 1 else 0)
public fun spanToString(): String {
if (rawStartLine == rawEndLine) {
if (rawStartSymbol == rawEndSymbol) {
return "$rawStartLine:$rawStartSymbol"
} else {
return "$rawStartLine:$rawStartSymbol-$rawEndSymbol"
}
} else {
return "($rawStartLine,$rawStartSymbol)-($rawEndLine,$rawEndSymbol)"
}
}
public fun getFileName(): String = File(filePath).getName()
override fun toString(): String = "${getFileName()}:${spanToString()}"
override fun equals(other: Any?): Boolean {
if (other identityEquals this) return true
if (other == null || other.javaClass != this.javaClass) return false
val othCasted = other as HsFilePosition
return filePath.equals(othCasted.filePath) && rawStartLine == othCasted.rawStartLine &&
rawEndLine == othCasted.rawEndLine && rawStartSymbol == othCasted.rawStartSymbol &&
rawEndSymbol == othCasted.rawEndSymbol
}
override fun hashCode(): Int {
val prime = 31;
var result = 1;
result = prime * result + filePath.hashCode()
result = prime * result + rawStartLine
result = prime * result + rawEndLine
result = prime * result + rawStartSymbol
result = prime * result + rawEndSymbol
return result
}
}
public class BreakInfo(public val breakIndex: Int, public val srcSpan: HsFilePosition) : ParseResult()
public class BreakInfoList(public val list: ArrayList<BreakInfo>) : ParseResult()
public class ExceptionResult(public val message: String) : ParseResult()
//public class CallInfo(public val index: Int, public val function: String, public val position: FilePosition): ParseResult()
//public class HistoryResult(public val list: ArrayList<CallInfo>) : ParseResult()
public class LocalBinding(var name: String?,
var typeName: String?,
var value: String?) : ParseResult() {
override fun equals(other: Any?): Boolean {
if (other identityEquals this) return true
if (other == null || other.javaClass != this.javaClass) return false
val othCasted = other as LocalBinding
return name == othCasted.name && typeName == othCasted.typeName && value == othCasted.value
}
override fun hashCode(): Int {
val prime = 31;
var result = 1;
result = prime * result + (name?.hashCode() ?: 0)
result = prime * result + (typeName?.hashCode() ?: 0)
result = prime * result + (value?.hashCode() ?: 0)
return result
}
}
public class LocalBindingList(public val list: ArrayList<LocalBinding>) : ParseResult() {
override fun equals(other: Any?): Boolean {
if (other identityEquals this) return true
if (other == null || other.javaClass != this.javaClass) return false
val othCasted = other as LocalBindingList
var bindingsAreEq = true
if (list.size() != othCasted.list.size()) {
bindingsAreEq = false
} else {
for (i in 0..list.size() - 1) {
if (list.get(i) != othCasted.list.get(i)) {
bindingsAreEq = false
break
}
}
}
return bindingsAreEq
}
}
public open class HsStackFrameInfo(val filePosition: HsFilePosition?,
var bindings: ArrayList<LocalBinding>?,
val functionName: String?) : ParseResult() {
override fun equals(other: Any?): Boolean {
if (other identityEquals this) return true
if (other == null || other.javaClass != this.javaClass) return false
val othCasted = other as HsStackFrameInfo
var bindingsAreEq = true
if (bindings != null && othCasted.bindings != null && bindings!!.size() != othCasted.bindings!!.size()) {
bindingsAreEq = false
} else {
for (i in 0..bindings!!.size() - 1) {
if (bindings!!.get(i) != othCasted.bindings!!.get(i)) {
bindingsAreEq = false
break
}
}
}
return bindingsAreEq && filePosition == othCasted.filePosition && functionName == othCasted.functionName
}
}
public class HsHistoryFrameInfo(public val index: Int,
public val function: String?,
public val filePosition: HsFilePosition?) : ParseResult() {
override fun toString(): String {
return if (function != null) "$function : $filePosition" else filePosition.toString()
}
override fun equals(other: Any?): Boolean {
if (other identityEquals this) return true
if (other == null || other.javaClass != this.javaClass) return false
val othCasted = other as HsHistoryFrameInfo
return index == othCasted.index && function == othCasted.function && filePosition == othCasted.filePosition
}
override fun hashCode(): Int {
val prime = 31;
var result = 1;
result = prime * result + index
result = prime * result + (function?.hashCode() ?: 0)
result = prime * result + (filePosition?.hashCode() ?: 0)
return result
}
}
public class ExpressionType(public val expression: String,
public val expressionType: String) : ParseResult() {
override fun equals(other: Any?): Boolean {
if (other identityEquals this) return true
if (other == null || other.javaClass != this.javaClass) return false
val othCasted = other as ExpressionType
return expression == othCasted.expression && expressionType == othCasted.expressionType
}
override fun hashCode(): Int {
val prime = 31;
var result = 1;
result = prime * result + expression.hashCode()
result = prime * result + expressionType.hashCode()
return result
}
}
public class EvalResult(public val expressionType: String,
public val expressionValue: String) : ParseResult()
public class ShowOutput(public val output: String) : ParseResult()
public class MoveHistResult(public val filePosition: HsFilePosition?,
public val bindingList: LocalBindingList) : ParseResult() {
override fun equals(other: Any?): Boolean {
if (other identityEquals this) return true
if (other == null || other.javaClass != this.javaClass) return false
val othCasted = other as MoveHistResult
return filePosition == othCasted.filePosition && bindingList == othCasted.bindingList
}
}
public class HistoryResult(public val frames: ArrayList<HsHistoryFrameInfo>,
public val full: Boolean) : ParseResult() {
override fun equals(other: Any?): Boolean {
if (other identityEquals this) return true
if (other == null || other.javaClass != this.javaClass) return false
val othCasted = other as HistoryResult
var framesAreEq = true
if (frames.size() != othCasted.frames.size()) {
framesAreEq = false
} else {
for (i in 0..frames.size() - 1) {
if (frames.get(i) != othCasted.frames.get(i)) {
framesAreEq = false
break
}
}
}
return framesAreEq && full == othCasted.full
}
}
public class JSONResult(public val json: JSONObject) : ParseResult()
| apache-2.0 | 6f926aabe206b14e4d342e9725be0655 | 39.534483 | 125 | 0.612718 | 4.618861 | false | false | false | false |
Gnar-Team/Gnar-bot | src/main/kotlin/xyz/gnarbot/gnar/utils/response/ResponseBuilder.kt | 1 | 3549 | package xyz.gnarbot.gnar.utils.response
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.MessageChannel
import net.dv8tion.jda.api.requests.RestAction
import org.apache.commons.lang3.exception.ExceptionUtils
import xyz.gnarbot.gnar.utils.EmbedProxy
import xyz.gnarbot.gnar.utils.Utils
import java.awt.Color
import javax.annotation.CheckReturnValue
open class ResponseBuilder(private val channel: MessageChannel) {
/**
* Quick-reply to a message.
*
* @param text The text to send.
* @return The Message created by this function.
*/
open fun text(text: String): RestAction<Message> {
return channel.sendMessage(text)
}
/**
* Send a standard info message.
*
* @param msg The text to send.
* @return The Message created by this function.
*/
open fun info(msg: String): RestAction<Message> {
return embed {
desc { msg }
}.action()
}
/**
* Send a standard error message.
*
* @param msg The text to send.
* @return The Message created by this function.
*/
open fun error(msg: String): RestAction<Message> {
return embed {
title { "Error" }
desc { msg }
color { Color.RED }
}.action()
}
/**
* Send a standard exception message.
*
* @return The Message created by this function.
*/
open fun exception(exception: Exception): RestAction<Message> {
if (exception.toString().contains("decoding")) {
return embed {
title { "Exception" }
desc {
buildString {
append("```\n")
append(exception.toString())
append("```\n")
val link = Utils.hasteBin(ExceptionUtils.getStackTrace(exception))
if (link != null) {
append("[Full stack trace.](").append("Probably a music error tbh").append(')')
} else {
append("HasteBin down.")
}
}
}
color { Color.RED }
}.action()
}
return embed {
title { "Exception" }
desc {
buildString {
append("For some reason this track causes errors, ignore this.")
}
}
color { Color.RED }
}.action()
}
/**
* Creates an EmbedBuilder to be used to creates an embed to send.
*/
open fun embed(): ResponseEmbedBuilder = embed(null)
/**
* Creates an EmbedBuilder to be used to creates an embed to send.
*
* @param title Title of the embed.
*/
open fun embed(title: String?): ResponseEmbedBuilder = ResponseEmbedBuilder().apply {
title { title }
}
/**
* Creates an EmbedBuilder to be used to creates an embed to send.
* This builder can use [ResponseEmbedBuilder.action] to quickly send the built embed.
*
* @param title Title of the embed.
*/
inline fun embed(title: String? = null, value: ResponseEmbedBuilder.() -> Unit): ResponseEmbedBuilder {
return embed(title).apply(value)
}
inner class ResponseEmbedBuilder : EmbedProxy<ResponseEmbedBuilder>() {
@CheckReturnValue
fun action(): RestAction<Message> {
return channel.sendMessage(build())
}
}
} | mit | 21a341685351e68c0389b41c9defb020 | 29.869565 | 107 | 0.55255 | 4.776581 | false | false | false | false |
why168/AndroidProjects | KotlinLearning/app/src/main/java/com/github/why168/kotlinlearn/Constants.kt | 1 | 795 | package com.github.why168.kotlinlearn
/**
*
*
* @author Edwin.Wu
* @version 2018/2/23 上午11:31
* @since JDK1.8
*/
class Constants {
companion object {
const val BASE_URL = "http://baobab.kaiyanapp.com/api/"
const val ERROR_NETWORK_1: String = " 网络不给力 "
const val ERROR_NETWORK_2: String = "网络异常,请检查你的网络!"
const val HTTP_STATUS_0: Int = 0
const val HTTP_STATUS_1: Int = 1
const val HTTP_STATUS_2: Int = 2
const val HTTP_STATUS_3: Int = 3
const val HTTP_STATUS_4: Int = 4
const val HTTP_STATUS_5: Int = 5
const val HTTP_STATUS_6: Int = 6
const val HTTP_STATUS_7: Int = 7
const val HTTP_STATUS_8: Int = 8
const val HTTP_STATUS_9: Int = 9
}
} | mit | 949687a6c282f339a4b921a8621c5c20 | 27.148148 | 63 | 0.586298 | 3.097959 | false | false | false | false |
ZieIony/Carbon | samples/src/main/java/tk/zielony/carbonsamples/component/AvatarTextRatingSubtextDateListItemActivity.kt | 1 | 4165 | package tk.zielony.carbonsamples.component
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import carbon.component.AvatarTextRatingSubtextDateRow
import carbon.component.DefaultAvatarTextRatingSubtextDateItem
import carbon.component.DefaultHeaderItem
import carbon.component.PaddedHeaderRow
import carbon.recycler.RowListAdapter
import carbon.recycler.ViewItemDecoration
import kotlinx.android.synthetic.main.activity_listcomponent.*
import tk.zielony.carbonsamples.R
import tk.zielony.carbonsamples.SampleAnnotation
import tk.zielony.carbonsamples.ThemedActivity
import tk.zielony.randomdata.RandomData
import tk.zielony.randomdata.Target
import tk.zielony.randomdata.common.DateGenerator
import tk.zielony.randomdata.common.IntegerGenerator
import tk.zielony.randomdata.common.TextGenerator
import tk.zielony.randomdata.person.DrawableAvatarGenerator
import tk.zielony.randomdata.person.StringNameGenerator
import tk.zielony.randomdata.transformer.DateToStringTransformer
import java.io.Serializable
@SampleAnnotation(layoutId = R.layout.activity_listcomponent, titleId = R.string.avatarTextRatingSubtextDateListItemActivity_title)
class AvatarTextRatingSubtextDateListItemActivity : ThemedActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initToolbar()
val randomData = RandomData().apply {
addGenerator(Drawable::class.java, DrawableAvatarGenerator(this@AvatarTextRatingSubtextDateListItemActivity))
addGenerator(String::class.java, StringNameGenerator().withMatcher { f: Target -> f.name == "text" && f.declaringClass == DefaultAvatarTextRatingSubtextDateItem::class.java })
addGenerator(Int::class.java, IntegerGenerator(0, 5).withMatcher { f: Target -> f.name == "rating" })
addGenerator(String::class.java, TextGenerator().withMatcher { f: Target -> f.name == "subtext" })
addGenerator(String::class.java, DateGenerator().withTransformer(DateToStringTransformer()).withMatcher { f: Target -> f.name == "date" })
}
val adapter = RowListAdapter<Serializable>().apply {
putFactory(DefaultAvatarTextRatingSubtextDateItem::class.java, { AvatarTextRatingSubtextDateRow(it) })
putFactory(DefaultHeaderItem::class.java, { PaddedHeaderRow(it) })
}
adapter.items = listOf(
DefaultHeaderItem("Header"),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java),
DefaultHeaderItem("Header"),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java),
DefaultHeaderItem("Header"),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java),
DefaultHeaderItem("Header"),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java),
randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java))
recycler.layoutManager = LinearLayoutManager(this)
recycler.adapter = adapter
val paddingItemDecoration = ViewItemDecoration(this, R.layout.carbon_row_padding)
paddingItemDecoration.setDrawBefore { it == 0 }
paddingItemDecoration.setDrawAfter { it == adapter.itemCount - 1 }
recycler.addItemDecoration(paddingItemDecoration)
}
} | apache-2.0 | a03bb9e906e94d3a8c6caaf7b4478267 | 56.861111 | 187 | 0.753181 | 4.706215 | false | false | false | false |
JavaEden/Orchid | plugins/OrchidForms/src/main/kotlin/com/eden/orchid/forms/model/FormFieldList.kt | 2 | 1407 | package com.eden.orchid.forms.model
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.theme.components.ModularPageList
import java.util.function.Function
import javax.inject.Provider
import javax.inject.Inject
class FormFieldList : ModularPageList<FormFieldList, FormField>(Function { getFieldInputTypes(it) }) {
private var extraFields = mutableMapOf<String, Boolean>()
override fun getItemClass(): Class<FormField> {
return FormField::class.java
}
fun addExtraField(extraFieldKey: String, fieldName: String, fieldValue: String) {
if(!extraFields.containsKey(extraFieldKey)) {
add(mapOf(
"type" to "hidden",
"key" to fieldName,
"value" to fieldValue,
"order" to Integer.MAX_VALUE
))
extraFields[extraFieldKey] = true
}
}
companion object {
fun getFieldInputTypes(context: OrchidContext): Map<String, Class<FormField>> {
val fieldTypes = HashMap<String, Class<FormField>>()
val itemTypes = context.resolveSet(FormField::class.java)
for (itemType in itemTypes) {
for (itemTypeAtKey in itemType.inputTypes) {
fieldTypes[itemTypeAtKey] = itemType.javaClass
}
}
return fieldTypes
}
}
}
| lgpl-3.0 | 8da4aac8dd2c6f43e34ac2ec8d19a49c | 29.586957 | 102 | 0.617626 | 4.69 | false | false | false | false |
Jire/Arrowhead | src/main/kotlin/org/jire/arrowhead/ProcessBy.kt | 1 | 1849 | /*
* Copyright 2016 Thomas Nappo
*
* 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("ProcessBy")
package org.jire.arrowhead
import com.sun.jna.Platform
import com.sun.jna.platform.win32.WinNT
import org.jire.arrowhead.linux.LinuxProcess
import org.jire.arrowhead.windows.Windows
import java.util.*
/**
* Attempts to open a process of the specified process ID.
*
* @param processID The ID of the process to open.
*/
@JvmOverloads
fun processByID(processID: Int, accessFlags: Int = WinNT.PROCESS_ALL_ACCESS): Process? = when {
Platform.isWindows() || Platform.isWindowsCE() -> Windows.openProcess(processID, accessFlags)
Platform.isLinux() -> LinuxProcess(processID)
else -> null
}
/**
* Attempts to open a process of the specified process name.
*
* @param processName The name of the process to open.
*/
@JvmOverloads
fun processByName(processName: String, accessFlags: Int = WinNT.PROCESS_ALL_ACCESS): Process? = when {
Platform.isWindows() || Platform.isWindowsCE() -> Windows.openProcess(processName, accessFlags)
Platform.isLinux() -> {
val search = Runtime.getRuntime().exec(arrayOf("bash", "-c",
"ps -A | grep -m1 \"$processName\" | awk '{print $1}'"))
val scanner = Scanner(search.inputStream)
val processID = scanner.nextInt()
scanner.close()
processByID(processID)
}
else -> null
} | apache-2.0 | 43f037cbefcce66bf172f91c83f5966d | 32.035714 | 102 | 0.731747 | 3.675944 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/recycling_glass/DetermineRecyclingGlass.kt | 1 | 1620 | package de.westnordost.streetcomplete.quests.recycling_glass
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.quest.AllCountriesExcept
import de.westnordost.streetcomplete.quests.recycling_glass.RecyclingGlass.*
class DetermineRecyclingGlass : OsmFilterQuestType<RecyclingGlass>() {
override val elementFilter = """
nodes with amenity = recycling and recycling_type = container
and recycling:glass = yes and !recycling:glass_bottles
"""
override val commitMessage = "Determine whether any glass or just glass bottles can be recycled here"
override val wikiLink = "Key:recycling"
override val icon = R.drawable.ic_quest_recycling_glass
// see isUsuallyAnyGlassRecycleableInContainers.yml
override val enabledInCountries = AllCountriesExcept("CZ")
override val isDeleteElementEnabled = true
override fun getTitle(tags: Map<String, String>) = R.string.quest_recycling_glass_title
override fun createForm() = DetermineRecyclingGlassForm()
override fun applyAnswerTo(answer: RecyclingGlass, changes: StringMapChangesBuilder) {
when(answer) {
ANY -> {
// to mark that it has been checked
changes.add("recycling:glass_bottles", "yes")
}
BOTTLES -> {
changes.add("recycling:glass_bottles", "yes")
changes.modify("recycling:glass", "no")
}
}
}
}
| gpl-3.0 | e4c26aca4aac0c70bfb2fca9c636d960 | 41.631579 | 105 | 0.712346 | 4.615385 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/shops/PurchaseDialogCustomizationSetContent.kt | 1 | 1648 | package com.habitrpg.android.habitica.ui.views.shops
import android.content.Context
import android.widget.TextView
import com.google.android.flexbox.FlexboxLayout
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.DialogPurchaseCustomizationsetBinding
import com.habitrpg.android.habitica.models.shops.ShopItem
import com.habitrpg.common.habitica.extensions.dpToPx
import com.habitrpg.common.habitica.extensions.layoutInflater
import com.habitrpg.common.habitica.extensions.loadImage
import com.habitrpg.common.habitica.views.PixelArtView
class PurchaseDialogCustomizationSetContent(context: Context) : PurchaseDialogContent(context) {
val binding = DialogPurchaseCustomizationsetBinding.inflate(context.layoutInflater, this)
override val imageView: PixelArtView
get() = PixelArtView(context)
override val titleTextView: TextView
get() = binding.titleTextView
override fun setItem(item: ShopItem) {
titleTextView.text = item.text
binding.imageViewWrapper.removeAllViews()
item.setImageNames.forEach {
val imageView = PixelArtView(context)
imageView.setBackgroundResource(R.drawable.layout_rounded_bg_window)
imageView.loadImage(it)
imageView.layoutParams = FlexboxLayout.LayoutParams(76.dpToPx(context), 76.dpToPx(context))
binding.imageViewWrapper.addView(imageView)
}
if (item.key == "facialHair") {
binding.notesTextView.text = context.getString(R.string.facial_hair_notes)
} else {
binding.notesTextView.text = item.notes
}
}
}
| gpl-3.0 | be081dcc7e8837adeae9029f53c0712f | 43.540541 | 103 | 0.750607 | 4.565097 | false | true | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/presentation/comment/CommentsPresenter.kt | 1 | 12408 | package org.stepik.android.presentation.comment
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.rxkotlin.Singles
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.subjects.PublishSubject
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import ru.nobird.android.domain.rx.emptyOnErrorStub
import org.stepik.android.domain.comment.interactor.CommentInteractor
import org.stepik.android.domain.comment.interactor.ComposeCommentInteractor
import org.stepik.android.domain.comment.model.CommentsData
import org.stepik.android.domain.discussion_proxy.interactor.DiscussionProxyInteractor
import org.stepik.android.domain.discussion_proxy.model.DiscussionOrder
import org.stepik.android.domain.profile.interactor.ProfileGuestInteractor
import org.stepik.android.model.Step
import org.stepik.android.model.Submission
import org.stepik.android.model.comments.Comment
import org.stepik.android.model.comments.DiscussionProxy
import org.stepik.android.model.comments.Vote
import org.stepik.android.presentation.base.PresenterBase
import org.stepik.android.presentation.comment.mapper.CommentsStateMapper
import org.stepik.android.presentation.comment.model.CommentItem
import org.stepik.android.view.injection.step.StepDiscussionBus
import ru.nobird.android.core.model.PaginationDirection
import javax.inject.Inject
class CommentsPresenter
@Inject
constructor(
private val commentInteractor: CommentInteractor,
private val composeCommentInteractor: ComposeCommentInteractor,
private val discussionProxyInteractor: DiscussionProxyInteractor,
private val profileGuestInteractor: ProfileGuestInteractor,
private val commentsStateMapper: CommentsStateMapper,
@StepDiscussionBus
private val stepDiscussionSubject: PublishSubject<Long>,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler
) : PresenterBase<CommentsView>() {
private var state: CommentsView.State = CommentsView.State.Idle
set(value) {
field = value
view?.setState(value)
}
override fun attachView(view: CommentsView) {
super.attachView(view)
view.setState(state)
}
/**
* Data initialization variants
*/
fun onDiscussion(discussionProxyId: String, discussionId: Long?, forceUpdate: Boolean = false) {
if (state != CommentsView.State.Idle &&
!((state == CommentsView.State.NetworkError || state is CommentsView.State.DiscussionLoaded) && forceUpdate)
) {
return
}
val discussionOrderSource = (state as? CommentsView.State.DiscussionLoaded)
?.discussionOrder
?.let { Single.just(it) }
?: discussionProxyInteractor.getDiscussionOrder()
compositeDisposable.clear()
state = CommentsView.State.Loading
compositeDisposable += Singles
.zip(
profileGuestInteractor.isGuest(),
discussionProxyInteractor.getDiscussionProxy(discussionProxyId),
discussionOrderSource
)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onSuccess = { (isGuest, discussionProxy, discussionOrder) ->
fetchComments(isGuest, discussionProxy, discussionOrder, discussionId)
},
onError = { state = CommentsView.State.NetworkError }
)
}
private fun fetchComments(
isGuest: Boolean,
discussionProxy: DiscussionProxy,
discussionOrder: DiscussionOrder,
discussionId: Long?,
keepCachedComments: Boolean = false
) {
if (discussionProxy.discussions.isEmpty()) {
state = CommentsView.State.DiscussionLoaded(isGuest, discussionProxy, discussionOrder, discussionId, CommentsView.CommentsState.EmptyComments)
} else {
val cachedComments: List<CommentItem.Data> = ((state as? CommentsView.State.DiscussionLoaded)
?.commentsState as? CommentsView.CommentsState.Loaded)
?.commentDataItems
?.takeIf { keepCachedComments }
?: emptyList()
val newState = CommentsView.State.DiscussionLoaded(isGuest, discussionProxy, discussionOrder, discussionId, CommentsView.CommentsState.Loading)
state = newState
compositeDisposable += commentInteractor
.getComments(discussionProxy, discussionOrder, discussionId, cachedComments)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onSuccess = {
state = newState.copy(commentsState = CommentsView.CommentsState.Loaded(it, commentsStateMapper.mapCommentDataItemsToRawItems(it)))
if (discussionId != null) {
view?.focusDiscussion(discussionId)
}
},
onError = { state = CommentsView.State.NetworkError }
)
}
}
/**
* Discussion ordering
*/
fun changeDiscussionOrder(discussionOrder: DiscussionOrder) {
val oldState = (state as? CommentsView.State.DiscussionLoaded)
?: return
compositeDisposable += discussionProxyInteractor
.saveDiscussionOrder(discussionOrder)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(onError = emptyOnErrorStub)
fetchComments(oldState.isGuest, oldState.discussionProxy, discussionOrder, oldState.discussionId, keepCachedComments = true)
}
/**
* Load more logic in both directions
*/
fun onLoadMore(direction: PaginationDirection) {
val oldState = (state as? CommentsView.State.DiscussionLoaded)
?: return
val commentsState = (oldState.commentsState as? CommentsView.CommentsState.Loaded)
?: return
val commentDataItems =
commentsState.commentDataItems
val lastCommentId =
when (direction) {
PaginationDirection.PREV ->
commentDataItems
.takeIf { it.hasPrev }
.takeIf { commentsState.commentItems.first() !is CommentItem.Placeholder }
?.first()
?.id
?: return
PaginationDirection.NEXT ->
commentDataItems
.takeIf { it.hasNext }
.takeIf { commentsState.commentItems.last() !is CommentItem.Placeholder }
?.last { it.comment.parent == null }
?.id
?: return
}
state = oldState.copy(commentsState = commentsStateMapper.mapToLoadMoreState(commentsState, direction))
compositeDisposable += commentInteractor
.getMoreComments(oldState.discussionProxy, oldState.discussionOrder, direction, lastCommentId)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onSuccess = { state = commentsStateMapper.mapFromLoadMoreToSuccess(state, it, direction) },
onError = { state = commentsStateMapper.mapFromLoadMoreToError(state, direction); view?.showNetworkError() }
)
}
/**
* Load more comments logic
*/
fun onLoadMoreReplies(loadMoreReplies: CommentItem.LoadMoreReplies) {
val oldState = (state as? CommentsView.State.DiscussionLoaded)
?: return
val commentsState = (oldState.commentsState as? CommentsView.CommentsState.Loaded)
?: return
state = oldState.copy(commentsState = commentsStateMapper.mapToLoadMoreRepliesState(commentsState, loadMoreReplies))
compositeDisposable += commentInteractor
.getMoreReplies(loadMoreReplies.parentComment, loadMoreReplies.lastCommentId)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onSuccess = { state = commentsStateMapper.mapFromLoadMoreRepliesToSuccess(state, it, loadMoreReplies) },
onError = { state = commentsStateMapper.mapFromLoadMoreRepliesToError(state, loadMoreReplies); view?.showNetworkError() }
)
}
/**
* Vote logic
*
* if [voteValue] is equal to current value new value will be null
*/
fun onChangeVote(commentDataItem: CommentItem.Data, voteValue: Vote.Value) {
if (commentDataItem.voteStatus !is CommentItem.Data.VoteStatus.Resolved ||
commentDataItem.comment.actions?.vote != true) {
return
}
val oldState = (state as? CommentsView.State.DiscussionLoaded)
?: return
val commentsState = (oldState.commentsState as? CommentsView.CommentsState.Loaded)
?: return
val newVote = commentDataItem.voteStatus.vote
.copy(value = voteValue.takeIf { it != commentDataItem.voteStatus.vote.value })
state = oldState.copy(commentsState = commentsStateMapper.mapToVotePending(commentsState, commentDataItem))
compositeDisposable += commentInteractor
.changeCommentVote(commentDataItem.id, newVote)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onSuccess = { state = commentsStateMapper.mapFromVotePendingToSuccess(state, it) },
onError = { state = commentsStateMapper.mapFromVotePendingToError(state, commentDataItem.voteStatus.vote); view?.showNetworkError() }
)
}
fun onComposeCommentClicked(step: Step, parent: Long? = null, comment: Comment? = null, submission: Submission? = null) {
val oldState = (state as? CommentsView.State.DiscussionLoaded)
?: return
if (oldState.isGuest) {
view?.showAuthRequired()
} else {
view?.showCommentComposeDialog(step, parent, comment, submission)
}
}
/**
* Edit logic
*/
fun onCommentCreated(commentsData: CommentsData) {
val commentDataItem = commentInteractor
.mapCommentsDataToCommentItem(commentsData)
?: return
state =
if (commentDataItem.comment.parent != null) {
commentsStateMapper.insertCommentReply(state, commentDataItem)
} else {
stepDiscussionSubject.onNext(commentDataItem.comment.target)
commentsStateMapper.insertComment(state, commentDataItem)
}
view?.focusDiscussion(commentDataItem.id)
}
fun onCommentUpdated(commentsData: CommentsData) {
val commentDataItem = commentInteractor
.mapCommentsDataToCommentItem(commentsData)
?: return
state = commentsStateMapper.mapFromVotePendingToSuccess(state, commentDataItem)
}
fun removeComment(commentId: Long) {
val oldState = (state as? CommentsView.State.DiscussionLoaded)
?: return
val commentsState = (oldState.commentsState as? CommentsView.CommentsState.Loaded)
?: return
val commentDataItem = commentsState.commentDataItems.find { it.id == commentId }
?: return
state = oldState.copy(commentsState = commentsStateMapper.mapToRemovePending(commentsState, commentDataItem))
compositeDisposable += composeCommentInteractor
.removeComment(commentDataItem.id)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.doOnComplete {
if (commentDataItem.comment.parent == null) {
stepDiscussionSubject.onNext(commentDataItem.comment.target)
}
}
.subscribeBy(
onComplete = { state = commentsStateMapper.mapFromRemovePendingToSuccess(state, commentId) },
onError = { state = commentsStateMapper.mapFromRemovePendingToError(state, commentDataItem); view?.showNetworkError() }
)
}
} | apache-2.0 | 0df4e2b02c9f01cb124edba91ff3d405 | 40.64094 | 155 | 0.657398 | 5.629764 | false | false | false | false |
robfletcher/orca | orca-sql/src/main/kotlin/com/netflix/spinnaker/orca/sql/pipeline/persistence/ExecutionMapper.kt | 3 | 3114 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.sql.pipeline.persistence
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import java.sql.ResultSet
import org.jooq.DSLContext
import org.slf4j.LoggerFactory
/**
* Converts a SQL [ResultSet] into an Execution.
*
* When retrieving an Execution from SQL, we lazily load its stages on-demand
* in this mapper as well.
*/
class ExecutionMapper(
private val mapper: ObjectMapper,
private val stageBatchSize: Int
) {
private val log = LoggerFactory.getLogger(javaClass)
fun map(rs: ResultSet, context: DSLContext): Collection<PipelineExecution> {
val results = mutableListOf<PipelineExecution>()
val executionMap = mutableMapOf<String, PipelineExecution>()
val legacyMap = mutableMapOf<String, String>()
while (rs.next()) {
mapper.readValue<PipelineExecution>(rs.getString("body"))
.also {
execution ->
results.add(execution)
execution.partition = rs.getString("partition")
if (rs.getString("id") != execution.id) {
// Map legacyId executions to their current ULID
legacyMap[execution.id] = rs.getString("id")
executionMap[rs.getString("id")] = execution
} else {
executionMap[execution.id] = execution
}
}
}
if (results.isNotEmpty()) {
val type = results[0].type
results.chunked(stageBatchSize) { executions ->
val executionIds: List<String> = executions.map {
if (legacyMap.containsKey(it.id)) {
legacyMap[it.id]!!
} else {
it.id
}
}
context.selectExecutionStages(type, executionIds).let { stageResultSet ->
while (stageResultSet.next()) {
mapStage(stageResultSet, executionMap)
}
}
executions.forEach { execution ->
execution.stages.sortBy { it.refId }
}
}
}
return results
}
private fun mapStage(rs: ResultSet, executions: Map<String, PipelineExecution>) {
val executionId = rs.getString("execution_id")
executions.getValue(executionId)
.stages
.add(
mapper.readValue<StageExecution>(rs.getString("body"))
.apply {
execution = executions.getValue(executionId)
}
)
}
}
| apache-2.0 | 1a4549a87ea79a34de51805cbe34b049 | 30.454545 | 83 | 0.663455 | 4.385915 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/increment/postfixNullableClassIncrement.kt | 3 | 221 | class MyClass
operator fun MyClass?.inc(): MyClass? = null
public fun box() : String {
var i : MyClass?
i = MyClass()
val j = i++
return if (j is MyClass && null == i) "OK" else "fail i = $i j = $j"
}
| apache-2.0 | eea081f95577c1571c6d0d14083add36 | 19.090909 | 72 | 0.556561 | 3.157143 | false | false | false | false |
anrelic/Anci-OSS | logging/src/main/kotlin/su/jfdev/anci/logging/CatchingUtil.kt | 1 | 2023 | package su.jfdev.anci.logging
import su.jfdev.anci.logging.LogLevel.*
infix inline fun <R> Logger.unchecked(block: () -> R): R? = unchecked(ERROR, block)
infix inline fun <R> Logger.exception(block: () -> R): R? = exception(ERROR, block)
infix inline fun <R> Logger.throwable(block: () -> R): R? = throwable(ERROR, block)
inline fun <R> Logger.unchecked(level: LogLevel, block: () -> R): R? = catching<R, RuntimeException>(level, block)
inline fun <R> Logger.exception(level: LogLevel, block: () -> R): R? = catching<R, Exception>(level, block)
inline fun <R> Logger.throwable(level: LogLevel, block: () -> R): R? = catching<R, Throwable>(level, block)
inline fun <R, reified T: Throwable> Logger.catching(level: LogLevel, block: () -> R): R? {
doOrCatch<T>(level, { return block() }) {
return null
}
error("should exit by doOrCatch")
}
infix inline fun Logger.unchecked(block: () -> Unit): Unit = catch<RuntimeException>(block)
infix inline fun Logger.exception(block: () -> Unit): Unit = catch<Exception>(block)
infix inline fun Logger.throwable(block: () -> Unit): Unit = catch<Throwable>(block)
inline fun Logger.unchecked(level: LogLevel, block: () -> Unit): Unit = catch<RuntimeException>(level, block)
inline fun Logger.exception(level: LogLevel, block: () -> Unit): Unit = catch<Exception>(level, block)
inline fun Logger.throwable(level: LogLevel, block: () -> Unit): Unit = catch<Throwable>(level, block)
infix inline fun <reified T: Throwable> Logger.catch(block: () -> Unit): Unit = catch<T>(ERROR, block)
inline fun <reified T: Throwable> Logger.catch(level: LogLevel, block: () -> Unit): Unit = doOrCatch<T>(level, block) {
}
inline fun <reified T: Throwable> Logger.doOrCatch(level: LogLevel, block: () -> Unit, or: () -> Unit) = tryCatch<T>(block) {
log(level, it)
or()
}
inline fun <reified T: Throwable> tryCatch(`try`: () -> Unit, catch: (T) -> Unit) = try {
`try`()
} catch (e: Throwable) {
when (e) {
is T -> catch(e)
else -> throw e
}
} | mit | 505d177d43579790487eae2675470578 | 45 | 125 | 0.661394 | 3.377295 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/autotune/data/PreppedGlucose.kt | 1 | 4184 | package info.nightscout.androidaps.plugins.general.autotune.data
import info.nightscout.androidaps.utils.DateUtil
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.*
class PreppedGlucose {
var crData: List<CRDatum> = ArrayList()
var csfGlucoseData: List<BGDatum> = ArrayList()
var isfGlucoseData: List<BGDatum> = ArrayList()
var basalGlucoseData: List<BGDatum> = ArrayList()
var diaDeviations: List<DiaDeviation> = ArrayList()
var peakDeviations: List<PeakDeviation> = ArrayList()
var from: Long = 0
lateinit var dateUtil: DateUtil
// to generate same king of json string than oref0-autotune-prep
override fun toString(): String {
return toString(0)
}
constructor(from: Long, crData: List<CRDatum>, csfGlucoseData: List<BGDatum>, isfGlucoseData: List<BGDatum>, basalGlucoseData: List<BGDatum>, dateUtil: DateUtil) {
this.from = from
this.crData = crData
this.csfGlucoseData = csfGlucoseData
this.isfGlucoseData = isfGlucoseData
this.basalGlucoseData = basalGlucoseData
this.dateUtil = dateUtil
}
constructor(json: JSONObject?, dateUtil: DateUtil) {
if (json == null) return
this.dateUtil = dateUtil
crData = ArrayList()
csfGlucoseData = ArrayList()
isfGlucoseData = ArrayList()
basalGlucoseData = ArrayList()
try {
crData = JsonCRDataToList(json.getJSONArray("CRData"))
csfGlucoseData = JsonGlucoseDataToList(json.getJSONArray("CSFGlucoseData"))
isfGlucoseData = JsonGlucoseDataToList(json.getJSONArray("ISFGlucoseData"))
basalGlucoseData = JsonGlucoseDataToList(json.getJSONArray("basalGlucoseData"))
} catch (e: JSONException) {
}
}
private fun JsonGlucoseDataToList(array: JSONArray): List<BGDatum> {
val bgData: MutableList<BGDatum> = ArrayList()
for (index in 0 until array.length()) {
try {
val o = array.getJSONObject(index)
bgData.add(BGDatum(o, dateUtil))
} catch (e: Exception) {
}
}
return bgData
}
private fun JsonCRDataToList(array: JSONArray): List<CRDatum> {
val crData: MutableList<CRDatum> = ArrayList()
for (index in 0 until array.length()) {
try {
val o = array.getJSONObject(index)
crData.add(CRDatum(o, dateUtil))
} catch (e: Exception) {
}
}
return crData
}
fun toString(indent: Int): String {
var jsonString = ""
val json = JSONObject()
try {
val crjson = JSONArray()
for (crd in crData) {
crjson.put(crd.toJSON())
}
val csfjson = JSONArray()
for (bgd in csfGlucoseData) {
csfjson.put(bgd.toJSON(true))
}
val isfjson = JSONArray()
for (bgd in isfGlucoseData) {
isfjson.put(bgd.toJSON(false))
}
val basaljson = JSONArray()
for (bgd in basalGlucoseData) {
basaljson.put(bgd.toJSON(false))
}
val diajson = JSONArray()
val peakjson = JSONArray()
if (diaDeviations.size > 0 || peakDeviations.size > 0) {
for (diad in diaDeviations) {
diajson.put(diad.toJSON())
}
for (peakd in peakDeviations) {
peakjson.put(peakd.toJSON())
}
}
json.put("CRData", crjson)
json.put("CSFGlucoseData", csfjson)
json.put("ISFGlucoseData", isfjson)
json.put("basalGlucoseData", basaljson)
if (diaDeviations.size > 0 || peakDeviations.size > 0) {
json.put("diaDeviations", diajson)
json.put("peakDeviations", peakjson)
}
jsonString = if (indent != 0) json.toString(indent) else json.toString()
} catch (e: JSONException) {
}
return jsonString
}
} | agpl-3.0 | c597c7fb4c3f365930fd76cde2e817ee | 34.769231 | 167 | 0.580067 | 4.436903 | false | false | false | false |
elsiff/MoreFish | src/main/kotlin/me/elsiff/morefish/configuration/loader/PrizeMapLoader.kt | 1 | 1023 | package me.elsiff.morefish.configuration.loader
import me.elsiff.morefish.configuration.ConfigurationValueAccessor
import me.elsiff.morefish.configuration.translated
import me.elsiff.morefish.fishing.competition.Prize
/**
* Created by elsiff on 2019-01-20.
*/
class PrizeMapLoader : CustomLoader<Map<IntRange, Prize>> {
override fun loadFrom(section: ConfigurationValueAccessor, path: String): Map<IntRange, Prize> {
return section[path].children.map {
val range = intRangeFrom(it.name)
val commands = it.strings("commands").translated()
range to Prize(commands)
}.toMap()
}
private fun intRangeFrom(string: String): IntRange {
val tokens = string.split("~")
val start = tokens[0].toInt()
val end = if (tokens.size > 1) {
if (tokens[1].isEmpty())
Int.MAX_VALUE
else
tokens[1].toInt()
} else {
start
}
return IntRange(start, end)
}
} | mit | bce7af5dd0ff8cb21629b781bc26ba0f | 29.117647 | 100 | 0.620723 | 4.209877 | false | true | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/quickfixUtil.kt | 2 | 2770 | // 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.util
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoAfter
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.ifEmpty
inline fun <reified T : PsiElement> Diagnostic.createIntentionForFirstParentOfType(
factory: (T) -> KotlinQuickFixAction<T>?
) = psiElement.getNonStrictParentOfType<T>()?.let(factory)
fun createIntentionFactory(
factory: (Diagnostic) -> IntentionAction?
) = object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic) = factory(diagnostic)
}
fun KtPrimaryConstructor.addConstructorKeyword(): PsiElement? {
val modifierList = this.modifierList ?: return null
val psiFactory = KtPsiFactory(this)
val constructor = if (valueParameterList == null) {
psiFactory.createPrimaryConstructor("constructor()")
} else {
psiFactory.createConstructorKeyword()
}
return addAfter(constructor, modifierList)
}
fun getDataFlowAwareTypes(
expression: KtExpression,
bindingContext: BindingContext = expression.analyze(),
originalType: KotlinType? = bindingContext.getType(expression)
): Collection<KotlinType> {
if (originalType == null) return emptyList()
val dataFlowInfo = bindingContext.getDataFlowInfoAfter(expression)
val dataFlowValueFactory = expression.getResolutionFacade().dataFlowValueFactory
val expressionType = bindingContext.getType(expression) ?: return listOf(originalType)
val dataFlowValue = dataFlowValueFactory.createDataFlowValue(
expression, expressionType, bindingContext, expression.getResolutionFacade().moduleDescriptor
)
return dataFlowInfo.getCollectedTypes(dataFlowValue, expression.languageVersionSettings).ifEmpty { listOf(originalType) }
}
| apache-2.0 | 02fa1b0fe367d691847379aa07c323d8 | 45.949153 | 158 | 0.810108 | 5.091912 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/newapi/IjVimInjector.kt | 1 | 8720 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.newapi
import com.intellij.openapi.components.service
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.api.EngineEditorHelper
import com.maddyhome.idea.vim.api.ExEntryPanel
import com.maddyhome.idea.vim.api.ExecutionContextManager
import com.maddyhome.idea.vim.api.NativeActionManager
import com.maddyhome.idea.vim.api.SystemInfoService
import com.maddyhome.idea.vim.api.VimActionExecutor
import com.maddyhome.idea.vim.api.VimApplication
import com.maddyhome.idea.vim.api.VimChangeGroup
import com.maddyhome.idea.vim.api.VimClipboardManager
import com.maddyhome.idea.vim.api.VimCommandGroup
import com.maddyhome.idea.vim.api.VimDigraphGroup
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimEditorGroup
import com.maddyhome.idea.vim.api.VimEnabler
import com.maddyhome.idea.vim.api.VimExOutputPanel
import com.maddyhome.idea.vim.api.VimExOutputPanelService
import com.maddyhome.idea.vim.api.VimExtensionRegistrator
import com.maddyhome.idea.vim.api.VimFile
import com.maddyhome.idea.vim.api.VimInjectorBase
import com.maddyhome.idea.vim.api.VimKeyGroup
import com.maddyhome.idea.vim.api.VimLookupManager
import com.maddyhome.idea.vim.api.VimMessages
import com.maddyhome.idea.vim.api.VimMotionGroup
import com.maddyhome.idea.vim.api.VimProcessGroup
import com.maddyhome.idea.vim.api.VimRegexpService
import com.maddyhome.idea.vim.api.VimSearchGroup
import com.maddyhome.idea.vim.api.VimSearchHelper
import com.maddyhome.idea.vim.api.VimStatistics
import com.maddyhome.idea.vim.api.VimStorageService
import com.maddyhome.idea.vim.api.VimStringParser
import com.maddyhome.idea.vim.api.VimTemplateManager
import com.maddyhome.idea.vim.api.VimVisualMotionGroup
import com.maddyhome.idea.vim.api.VimrcFileState
import com.maddyhome.idea.vim.api.VimscriptExecutor
import com.maddyhome.idea.vim.api.VimscriptFunctionService
import com.maddyhome.idea.vim.api.VimscriptParser
import com.maddyhome.idea.vim.command.VimStateMachine
import com.maddyhome.idea.vim.common.VimMachine
import com.maddyhome.idea.vim.diagnostic.VimLogger
import com.maddyhome.idea.vim.ex.ExOutputModel
import com.maddyhome.idea.vim.extension.VimExtensionRegistrar
import com.maddyhome.idea.vim.group.CommandGroup
import com.maddyhome.idea.vim.group.EditorGroup
import com.maddyhome.idea.vim.group.FileGroup
import com.maddyhome.idea.vim.group.HistoryGroup
import com.maddyhome.idea.vim.group.MacroGroup
import com.maddyhome.idea.vim.group.MarkGroup
import com.maddyhome.idea.vim.group.MotionGroup
import com.maddyhome.idea.vim.group.SearchGroup
import com.maddyhome.idea.vim.group.TabService
import com.maddyhome.idea.vim.group.VimWindowGroup
import com.maddyhome.idea.vim.group.WindowGroup
import com.maddyhome.idea.vim.group.copy.PutGroup
import com.maddyhome.idea.vim.helper.CommandLineHelper
import com.maddyhome.idea.vim.helper.IjActionExecutor
import com.maddyhome.idea.vim.helper.IjEditorHelper
import com.maddyhome.idea.vim.helper.IjVimStringParser
import com.maddyhome.idea.vim.helper.UndoRedoHelper
import com.maddyhome.idea.vim.helper.VimCommandLineHelper
import com.maddyhome.idea.vim.helper.vimStateMachine
import com.maddyhome.idea.vim.history.VimHistory
import com.maddyhome.idea.vim.macro.VimMacro
import com.maddyhome.idea.vim.mark.VimMarkGroup
import com.maddyhome.idea.vim.put.VimPut
import com.maddyhome.idea.vim.register.VimRegisterGroup
import com.maddyhome.idea.vim.ui.VimRcFileState
import com.maddyhome.idea.vim.undo.VimUndoRedo
import com.maddyhome.idea.vim.vimscript.Executor
import com.maddyhome.idea.vim.vimscript.services.FunctionStorage
import com.maddyhome.idea.vim.vimscript.services.OptionService
import com.maddyhome.idea.vim.vimscript.services.PatternService
import com.maddyhome.idea.vim.vimscript.services.VariableService
import com.maddyhome.idea.vim.yank.VimYankGroup
import com.maddyhome.idea.vim.yank.YankGroupBase
class IjVimInjector : VimInjectorBase() {
override fun <T : Any> getLogger(clazz: Class<T>): VimLogger = IjVimLogger(Logger.getInstance(clazz::class.java))
override val actionExecutor: VimActionExecutor
get() = service<IjActionExecutor>()
override val exEntryPanel: ExEntryPanel
get() = service<IjExEntryPanel>()
override val exOutputPanel: VimExOutputPanelService
get() = object : VimExOutputPanelService {
override fun getPanel(editor: VimEditor): VimExOutputPanel {
return ExOutputModel.getInstance(editor.ij)
}
}
override val historyGroup: VimHistory
get() = service<HistoryGroup>()
override val extensionRegistrator: VimExtensionRegistrator
get() = VimExtensionRegistrar
override val tabService: TabService
get() = service()
override val regexpService: VimRegexpService
get() = PatternService
override val clipboardManager: VimClipboardManager
get() = service<IjClipboardManager>()
override val searchHelper: VimSearchHelper
get() = service<IjVimSearchHelper>()
override val motion: VimMotionGroup
get() = service<MotionGroup>()
override val lookupManager: VimLookupManager
get() = service<IjVimLookupManager>()
override val templateManager: VimTemplateManager
get() = service<IjTemplateManager>()
override val searchGroup: VimSearchGroup
get() = service<SearchGroup>()
override val put: VimPut
get() = service<PutGroup>()
override val window: VimWindowGroup
get() = service<WindowGroup>()
override val yank: VimYankGroup
get() = service<YankGroupBase>()
override val file: VimFile
get() = service<FileGroup>()
override val macro: VimMacro
get() = service<MacroGroup>()
override val undo: VimUndoRedo
get() = service<UndoRedoHelper>()
override val commandLineHelper: VimCommandLineHelper
get() = service<CommandLineHelper>()
override val nativeActionManager: NativeActionManager
get() = service<IjNativeActionManager>()
override val messages: VimMessages
get() = service<IjVimMessages>()
override val registerGroup: VimRegisterGroup
get() = service()
override val registerGroupIfCreated: VimRegisterGroup?
get() = serviceIfCreated()
override val changeGroup: VimChangeGroup
get() = service()
override val processGroup: VimProcessGroup
get() = service()
override val keyGroup: VimKeyGroup
get() = service()
override val markGroup: VimMarkGroup
get() = service<MarkGroup>()
override val application: VimApplication
get() = service<IjVimApplication>()
override val executionContextManager: ExecutionContextManager
get() = service<IjExecutionContextManager>()
override val vimMachine: VimMachine
get() = service<VimMachineImpl>()
override val enabler: VimEnabler
get() = service<IjVimEnabler>()
override val digraphGroup: VimDigraphGroup
get() = service()
override val visualMotionGroup: VimVisualMotionGroup
get() = service()
override val statisticsService: VimStatistics
get() = service()
override val commandGroup: VimCommandGroup
get() = service<CommandGroup>()
override val functionService: VimscriptFunctionService
get() = FunctionStorage
override val variableService: VariableService
get() = service()
override val vimrcFileState: VimrcFileState
get() = VimRcFileState
override val vimscriptExecutor: VimscriptExecutor
get() = service<Executor>()
override val vimscriptParser: VimscriptParser
get() = com.maddyhome.idea.vim.vimscript.parser.VimscriptParser
override val optionService: OptionService
get() = service()
override val parser: VimStringParser
get() = service<IjVimStringParser>()
override val systemInfoService: SystemInfoService
get() = service()
override val vimStorageService: VimStorageService
get() = service()
override fun commandStateFor(editor: VimEditor): VimStateMachine {
var res = editor.ij.vimStateMachine
if (res == null) {
res = VimStateMachine(editor)
editor.ij.vimStateMachine = res
}
return res
}
override fun commandStateFor(editor: Any): VimStateMachine {
return when (editor) {
is VimEditor -> this.commandStateFor(editor)
is Editor -> this.commandStateFor(IjVimEditor(editor))
else -> error("Unexpected type: $editor")
}
}
override val engineEditorHelper: EngineEditorHelper
get() = service<IjEditorHelper>()
override val editorGroup: VimEditorGroup
get() = service<EditorGroup>()
}
| mit | 70c7aebffbaffd7984b07605b0338487 | 40.132075 | 115 | 0.791284 | 4.053928 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.