repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
googlemaps/android-samples | snippets/app/src/gms/java/com/google/maps/example/kotlin/Shapes.kt | 1 | 6771 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.maps.example.kotlin
import android.graphics.Color
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.*
import com.google.maps.example.R
internal class Shapes {
private lateinit var map: GoogleMap
private fun polylines() {
// [START maps_android_shapes_polylines_polylineoptions]
// Instantiates a new Polyline object and adds points to define a rectangle
val polylineOptions = PolylineOptions()
.add(LatLng(37.35, -122.0))
.add(LatLng(37.45, -122.0)) // North of the previous point, but at the same longitude
.add(LatLng(37.45, -122.2)) // Same latitude, and 30km to the west
.add(LatLng(37.35, -122.2)) // Same longitude, and 16km to the south
.add(LatLng(37.35, -122.0)) // Closes the polyline.
// Get back the mutable Polyline
val polyline = map.addPolyline(polylineOptions)
// [END maps_android_shapes_polylines_polylineoptions]
}
private fun polygons() {
// [START maps_android_shapes_polygons_polygonoptions]
// Instantiates a new Polygon object and adds points to define a rectangle
val rectOptions = PolygonOptions()
.add(
LatLng(37.35, -122.0),
LatLng(37.45, -122.0),
LatLng(37.45, -122.2),
LatLng(37.35, -122.2),
LatLng(37.35, -122.0)
)
// Get back the mutable Polygon
val polygon = map.addPolygon(rectOptions)
// [END maps_android_shapes_polygons_polygonoptions]
}
private fun polygonAutocompletion() {
// [START maps_android_shapes_polygons_autocompletion]
val polygon1 = map.addPolygon(
PolygonOptions()
.add(
LatLng(0.0, 0.0),
LatLng(0.0, 5.0),
LatLng(3.0, 5.0),
LatLng(0.0, 0.0)
)
.strokeColor(Color.RED)
.fillColor(Color.BLUE)
)
val polygon2 = map.addPolygon(
PolygonOptions()
.add(
LatLng(0.0, 0.0),
LatLng(0.0, 5.0),
LatLng(3.0, 5.0)
)
.strokeColor(Color.RED)
.fillColor(Color.BLUE)
)
// [END maps_android_shapes_polygons_autocompletion]
}
private fun polygonHollow() {
// [START maps_android_shapes_polygons_hollow]
val hole = listOf(
LatLng(1.0, 1.0),
LatLng(1.0, 2.0),
LatLng(2.0, 2.0),
LatLng(2.0, 1.0),
LatLng(1.0, 1.0)
)
val hollowPolygon = map.addPolygon(
PolygonOptions()
.add(
LatLng(0.0, 0.0),
LatLng(0.0, 5.0),
LatLng(3.0, 5.0),
LatLng(3.0, 0.0),
LatLng(0.0, 0.0)
)
.addHole(hole)
.fillColor(Color.BLUE)
)
// [END maps_android_shapes_polygons_hollow]
}
private fun circles() {
// [START maps_android_shapes_circles_circleoptions]
// Instantiates a new CircleOptions object and defines the center and radius
val circleOptions = CircleOptions()
.center(LatLng(37.4, -122.1))
.radius(1000.0) // In meters
// Get back the mutable Circle
val circle = map.addCircle(circleOptions)
// [END maps_android_shapes_circles_circleoptions]
}
private fun circlesEvents() {
// [START maps_android_shapes_circles_events]
val circle = map.addCircle(
CircleOptions()
.center(LatLng(37.4, -122.1))
.radius(1000.0)
.strokeWidth(10f)
.strokeColor(Color.GREEN)
.fillColor(Color.argb(128, 255, 0, 0))
.clickable(true)
)
map.setOnCircleClickListener {
// Flip the r, g and b components of the circle's stroke color.
val strokeColor = it.strokeColor xor 0x00ffffff
it.strokeColor = strokeColor
}
// [END maps_android_shapes_circles_events]
}
private fun customAppearances() {
// [START maps_android_shapes_custom_appearances]
val polyline = map.addPolyline(
PolylineOptions()
.add(LatLng(-37.81319, 144.96298), LatLng(-31.95285, 115.85734))
.width(25f)
.color(Color.BLUE)
.geodesic(true)
)
// [END maps_android_shapes_custom_appearances]
// [START maps_android_shapes_custom_appearances_stroke_pattern]
val pattern = listOf(
Dot(), Gap(20F), Dash(30F), Gap(20F)
)
polyline.pattern = pattern
// [END maps_android_shapes_custom_appearances_stroke_pattern]
// [START maps_android_shapes_custom_appearances_joint_type]
polyline.jointType = JointType.ROUND
// [END maps_android_shapes_custom_appearances_joint_type]
// [START maps_android_shapes_custom_appearances_start_cap]
polyline.startCap = RoundCap()
// [END maps_android_shapes_custom_appearances_start_cap]
// [START maps_android_shapes_custom_appearances_end_cap]
polyline.endCap = CustomCap(BitmapDescriptorFactory.fromResource(R.drawable.arrow), 16F)
// [END maps_android_shapes_custom_appearances_end_cap]
}
private fun associateData() {
// [START maps_android_shapes_associate_data]
val polyline = map.addPolyline(
PolylineOptions()
.clickable(true)
.add(
LatLng(-35.016, 143.321),
LatLng(-34.747, 145.592),
LatLng(-34.364, 147.891),
LatLng(-33.501, 150.217),
LatLng(-32.306, 149.248),
LatLng(-32.491, 147.309)
)
)
polyline.tag = "A"
// [END maps_android_shapes_associate_data]
}
} | apache-2.0 | 47bdf36f9b26ade72d07723d47746200 | 35.213904 | 97 | 0.556048 | 4.069111 | false | false | false | false |
brunordg/ctanywhere | app/src/main/java/br/com/codeteam/ctanywhere/ext/LogExt.kt | 1 | 2267 | package br.com.codeteam.ctanywhere.ext
import android.util.Log
/**
* Created by Bruno Rodrigues e Rodrigues on 17/05/2018.
*/
//--------------β--------------β--------------β--------------β--------------β
// Logger
//--------------β--------------β--------------β--------------β--------------β
fun Any.logVerbose(message: String) = Log.v(if (this::class.java.simpleName.length <= 23) this::class.java.simpleName else this::class.java.simpleName.substring(23), message)
fun Any.logDebug(message: String) = Log.d(if (this::class.java.simpleName.length <= 23) this::class.java.simpleName else this::class.java.simpleName.substring(23), message)
fun Any.logError(message: String) = Log.e(if (this::class.java.simpleName.length <= 23) this::class.java.simpleName else this::class.java.simpleName.substring(23), message)
fun Any.logInfo(message: String) = Log.i(if (this::class.java.simpleName.length <= 23) this::class.java.simpleName else this::class.java.simpleName.substring(23), message)
fun Any.logWarn(message: String) = Log.w(if (this::class.java.simpleName.length <= 23) this::class.java.simpleName else this::class.java.simpleName.substring(23), message)
//--------------β--------------β--------------β--------------β--------------β
// Log Self
//--------------β--------------β--------------β--------------β--------------β
@Suppress("unused")
fun String.logSelfVerbose() = Log.v(if (this::class.java.simpleName.length <= 23) this::class.java.simpleName else this::class.java.simpleName.substring(23), this)
fun String.logSelfDebug() = Log.d(if (this::class.java.simpleName.length <= 23) this::class.java.simpleName else this::class.java.simpleName.substring(23), this)
@Suppress("unused")
fun String.logSelfError() = Log.e(if (this::class.java.simpleName.length <= 23) this::class.java.simpleName else this::class.java.simpleName.substring(23), this)
@Suppress("unused")
fun String.logSelfInfo() = Log.i(if (this::class.java.simpleName.length <= 23) this::class.java.simpleName else this::class.java.simpleName.substring(23), this)
@Suppress("unused")
fun String.logSelfWarn() = Log.w(if (this::class.java.simpleName.length <= 23) this::class.java.simpleName else this::class.java.simpleName.substring(23), this) | mit | ed42c9a5ec60fe6c7836a5ad62177403 | 60.888889 | 174 | 0.64661 | 3.529319 | false | false | false | false |
angryziber/picasa-gallery | src/photos/LocalContent.kt | 1 | 1365 | package photos
import org.commonmark.parser.Parser
import org.commonmark.renderer.html.HtmlRenderer
import java.io.File
import javax.servlet.ServletContext
class LocalContent(path: String?) {
constructor(servletContext: ServletContext): this(servletContext.getRealPath("content"))
private val mdParser = Parser.builder().build()
private val mdRenderer = HtmlRenderer.builder().build()
private val albums: Map<String, AlbumContent> = path?.let { loadFilesFrom(it) } ?: emptyMap()
private fun loadFilesFrom(path: String) = File(path).listFiles { file -> file.name.endsWith(".md") }
?.associate { file -> file.name.substringBefore('.') to loadContentFrom(file) }
private fun loadContentFrom(file: File): AlbumContent {
var source = file.readText().trim()
val coords = if (source.startsWith(".coords")) {
val parts = source.split("\n", limit = 2)
source = parts[1]
GeoLocation(parts[0].substringAfter(".coords "))
} else null
return AlbumContent(markdown2Html(source), coords)
}
private fun markdown2Html(source: String): String {
val document = mdParser.parse(source)
return mdRenderer.render(document)
}
fun contains(albumName: String?) = albums.contains(albumName)
fun forAlbum(albumName: String?) = albums[albumName]
}
data class AlbumContent(val content: String?, val geo: GeoLocation?) | gpl-3.0 | 978ba019463dc19706bb6053bebd6396 | 35.918919 | 102 | 0.723077 | 4.038462 | false | false | false | false |
ebi-uniprot/QuickGOBE | annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/model/AnnotationRequestBody.kt | 1 | 5054 | package uk.ac.ebi.quickgo.annotation.model
import uk.ac.ebi.quickgo.annotation.model.AnnotationRequest.DEFAULT_GO_USAGE
import uk.ac.ebi.quickgo.annotation.model.AnnotationRequest.USAGE_RELATIONSHIP_PARAM
import uk.ac.ebi.quickgo.rest.controller.request.ArrayPattern
import uk.ac.ebi.quickgo.rest.controller.request.ArrayPattern.Flag.CASE_INSENSITIVE
import javax.validation.Valid
import javax.validation.constraints.Pattern
/**
* This class is a simple data class with builders having jvm overloads, written using kotlin.
* Before that we decided to use loombok, but we think for data object/clear code kotlin is more useful
* Look into git history AnnotationRequestBody.java with loombok annotation deleted (for reference)
* Might be is future we decide to not use kotlin when java will introduce data objects (release 14 or 15)
*
* This class could be lot smaller and simpler but as all test expecting builders, i decided to not make any change at all
* in other parts of application, that is how we can be sure about the seamless interoperability of kotlin with java
*
* For onwards we can simply use data object with jvmoverloads and copy constructor from kotlin to have clean code and easy to test
*/
data class AnnotationRequestBody @JvmOverloads constructor(@field:Valid var and: GoDescription? = null,
@field:Valid var not: GoDescription? = null) {
companion object {
@JvmStatic
fun builder() = AnnotationRequestBody.Builder()
@JvmStatic
fun putDefaultValuesIfAbsent(requestBody: AnnotationRequestBody?) {
if (requestBody == null)
return
if (requestBody.and == null) {
requestBody.and = AnnotationRequestBody.GoDescription()
}
requestBody.and?.let { fillDefaultGoDescriptionIfNotPresent(it) }
if (requestBody.not == null) {
requestBody.not = AnnotationRequestBody.GoDescription()
}
requestBody.not?.let { fillDefaultGoDescriptionIfNotPresent(it) }
}
private fun fillDefaultGoDescriptionIfNotPresent(goDescription: AnnotationRequestBody.GoDescription) {
val goUsage = goDescription.goUsage
if (goUsage == null || goUsage.trim().isEmpty()) {
goDescription.goUsage = DEFAULT_GO_USAGE
}
val goUsageRelationships = goDescription.goUsageRelationships
if (goUsageRelationships == null || goUsageRelationships.isEmpty()) {
goDescription.setGoUsageRelationships(AnnotationRequest.DEFAULT_GO_USAGE_RELATIONSHIPS)
}
}
}
data class Builder(
var and: GoDescription? = null,
var not: GoDescription? = null) {
fun and(and: GoDescription) = apply { this.and = and }
fun not(not: GoDescription) = apply { this.not = not }
fun build() = AnnotationRequestBody(and, not)
}
class GoDescription {
@JvmOverloads
constructor (goTerms: Array<String> = emptyArray(),
goUsageRelationships: Array<String>? = null,
goUsage: String? = null) {
this.goTerms = goTerms
this.goUsageRelationships = goUsageRelationships
this.goUsage = goUsage
}
companion object {
@JvmStatic
fun builder() = GoDescription.Builder()
}
@get:ArrayPattern(regexp = "^GO:[0-9]{7}$", flags = [CASE_INSENSITIVE], paramName = "goTerms")
var goTerms: Array<String>
@get:Pattern(regexp = "^descendants|exact$", flags = [Pattern.Flag.CASE_INSENSITIVE], message = "Invalid goUsage: \${validatedValue}")
var goUsage: String?
set(goUsage) {
field = goUsage?.toLowerCase()
}
@get:ArrayPattern(regexp = "^is_a|part_of|occurs_in|regulates$", flags = [CASE_INSENSITIVE], paramName = USAGE_RELATIONSHIP_PARAM)
var goUsageRelationships: Array<String>?
private set
fun setGoUsageRelationships(goUsageRelationships: String?) {
this.goUsageRelationships = goUsageRelationships.orEmpty().split(",")
.filter { it.isNotBlank() }
.map { it.toLowerCase() }
.toTypedArray()
}
class Builder {
private var goTerms: Array<String> = emptyArray()
private var goUsage: String? = null
private var goUsageRelationships: Array<String>? = null
fun goUsageRelationships(vararg goUsageRelationships: String) =
apply { this.goUsageRelationships = goUsageRelationships.map { it.toLowerCase() }.toTypedArray(); }
fun goUsage(goUsage: String?) = apply { this.goUsage = goUsage?.toLowerCase() }
fun goTerms(goTerms: Array<String>) = apply { this.goTerms = goTerms }
fun build() = GoDescription(goTerms, goUsageRelationships, goUsage)
}
}
} | apache-2.0 | 8b0327d86d2a560f9e85a956c25d4150 | 42.577586 | 142 | 0.642264 | 4.645221 | false | false | false | false |
Kotlin/dokka | runners/gradle-plugin/src/main/kotlin/org/jetbrains/dokka/gradle/DokkaPlugin.kt | 1 | 3840 | package org.jetbrains.dokka.gradle
import org.gradle.api.DefaultTask
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.kotlin.dsl.register
import org.gradle.util.GradleVersion
open class DokkaPlugin : Plugin<Project> {
override fun apply(project: Project) {
if (GradleVersion.version(project.gradle.gradleVersion) < GradleVersion.version("5.6")) {
project.logger.warn("Dokka: Build is using unsupported gradle version, expected at least 5.6 but got ${project.gradle.gradleVersion}. This may result in strange errors")
}
project.setupDokkaTasks("dokkaHtml") {
description = "Generates documentation in 'html' format"
}
project.setupDokkaTasks(
name = "dokkaJavadoc",
multiModuleTaskSupported = false
) {
plugins.dependencies.add(project.dokkaArtifacts.javadocPlugin)
description = "Generates documentation in 'javadoc' format"
}
project.setupDokkaTasks("dokkaGfm", allModulesPageAndTemplateProcessing = project.dokkaArtifacts.gfmTemplateProcessing) {
plugins.dependencies.add(project.dokkaArtifacts.gfmPlugin)
description = "Generates documentation in GitHub flavored markdown format"
}
project.setupDokkaTasks("dokkaJekyll", allModulesPageAndTemplateProcessing = project.dokkaArtifacts.jekyllTemplateProcessing) {
plugins.dependencies.add(project.dokkaArtifacts.jekyllPlugin)
description = "Generates documentation in Jekyll flavored markdown format"
}
}
/**
* Creates [DokkaTask], [DokkaMultiModuleTask] for the given
* name and configuration.
*/
private fun Project.setupDokkaTasks(
name: String,
multiModuleTaskSupported: Boolean = true,
allModulesPageAndTemplateProcessing: Dependency = project.dokkaArtifacts.allModulesPage,
configuration: AbstractDokkaTask.() -> Unit = {}
) {
project.maybeCreateDokkaPluginConfiguration(name)
project.maybeCreateDokkaRuntimeConfiguration(name)
project.tasks.register<DokkaTask>(name) {
configuration()
}
if (project.parent != null) {
val partialName = "${name}Partial"
project.maybeCreateDokkaPluginConfiguration(partialName)
project.maybeCreateDokkaRuntimeConfiguration(partialName)
project.tasks.register<DokkaTaskPartial>(partialName) {
configuration()
}
}
if (project.subprojects.isNotEmpty()) {
if (multiModuleTaskSupported) {
val multiModuleName = "${name}MultiModule"
project.maybeCreateDokkaPluginConfiguration(multiModuleName, setOf(allModulesPageAndTemplateProcessing))
project.maybeCreateDokkaRuntimeConfiguration(multiModuleName)
project.tasks.register<DokkaMultiModuleTask>(multiModuleName) {
addSubprojectChildTasks("${name}Partial")
configuration()
description = "Runs all subprojects '$name' tasks and generates module navigation page"
}
project.tasks.register<DefaultTask>("${name}Multimodule") {
dependsOn(multiModuleName)
doLast {
logger.warn("'Multimodule' is deprecated. Use 'MultiModule' instead")
}
}
}
project.tasks.register<DokkaCollectorTask>("${name}Collector") {
addSubprojectChildTasks(name)
description =
"Generates documentation merging all subprojects '$name' tasks into one virtual module"
}
}
}
}
| apache-2.0 | ba90d2f0a00c3d8f8df4a4df218d0d3f | 41.197802 | 181 | 0.648958 | 5.303867 | false | true | false | false |
dkhmelenko/miband-android | app/src/main/java/com/khmelenko/lab/mibanddemo/MainActivity.kt | 2 | 10546 | package com.khmelenko.lab.mibanddemo
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import butterknife.ButterKnife
import butterknife.OnClick
import com.khmelenko.lab.miband.MiBand
import com.khmelenko.lab.miband.listeners.HeartRateNotifyListener
import com.khmelenko.lab.miband.listeners.RealtimeStepsNotifyListener
import com.khmelenko.lab.miband.model.UserInfo
import com.khmelenko.lab.miband.model.VibrationMode
import io.reactivex.disposables.CompositeDisposable
import timber.log.Timber
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* Main application activity
*
* @author Dmytro Khmelenko
*/
class MainActivity : AppCompatActivity(), LocationListener {
private var miBand: MiBand = MiBand(this)
private val locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
private val provider: String = LocationManager.GPS_PROVIDER
private val disposables = CompositeDisposable()
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
ButterKnife.bind(this)
checkLocationPermission()
}
override fun onDestroy() {
disposables.clear()
super.onDestroy()
}
@OnClick(R.id.action_connect)
fun actionConnect() {
val device = intent.getParcelableExtra<BluetoothDevice>("device")
val d = miBand.connect(device!!)
.subscribe({ result ->
Timber.d("Connect onNext: $result")
}, { throwable ->
throwable.printStackTrace()
Timber.e(throwable)
})
disposables.add(d)
}
@OnClick(R.id.action_pair)
fun actionPair() {
val d = miBand.pair().subscribe(
{ Timber.d("Pairing successful") },
{ throwable -> Timber.e(throwable, "Pairing failed") })
disposables.add(d)
}
@OnClick(R.id.action_show_services)
fun actionShowServices() {
// TODO miband.showServicesAndCharacteristics();
}
@OnClick(R.id.action_read_rssi)
fun actionReadRssi() {
val d = miBand.readRssi()
.subscribe({ rssi -> Timber.d("rssi:$rssi") },
{ throwable -> Timber.e(throwable, "readRssi fail") },
{ Timber.d("Rssi onCompleted") })
disposables.add(d)
}
@OnClick(R.id.action_battery_info)
fun actionBatteryInfo() {
val d = miBand.batteryInfo
.subscribe({ batteryInfo -> Timber.d(batteryInfo.toString()) },
{ throwable -> Timber.e(throwable, "getBatteryInfo fail") })
disposables.add(d)
}
@OnClick(R.id.action_set_user_info)
fun actionSetUserInfo() {
val userInfo = UserInfo(20271234, 1.toByte(), 32.toByte(), 160.toByte(), 40.toByte(), "alias", 0.toByte())
Timber.d("setUserInfo: $userInfo data: ${userInfo.getBytes(miBand.device!!.address).contentToString()}")
val d = miBand.setUserInfo(userInfo)
.subscribe({ Timber.d("setUserInfo success") },
{ throwable -> Timber.e(throwable, "setUserInfo failed") })
disposables.add(d)
}
@OnClick(R.id.action_set_heart_rate_notify_listener)
fun actionSetHeartRateNotifyListener() {
miBand.setHeartRateScanListener(object : HeartRateNotifyListener {
override fun onNotify(heartRate: Int) {
Timber.d("heart rate: $heartRate") }
})
}
@OnClick(R.id.action_start_heart_rate_scan)
fun actionStartHeartRateScan() {
val d = miBand.startHeartRateScan().subscribe()
disposables.add(d)
}
@OnClick(R.id.action_start_vibro_with_led)
fun actionStartVibroWithLed() {
val d = miBand.startVibration(VibrationMode.VIBRATION_WITH_LED)
.subscribe { Timber.d("Vibration started") }
disposables.add(d)
}
@OnClick(R.id.action_start_vibro)
fun actionStartVibro() {
val d = miBand.startVibration(VibrationMode.VIBRATION_WITHOUT_LED)
.subscribe { Timber.d("Vibration started") }
disposables.add(d)
}
@OnClick(R.id.action_start_vibro_with_led_time)
fun actionStartVibroWithLedAndTime() {
val d = miBand.startVibration(VibrationMode.VIBRATION_10_TIMES_WITH_LED)
.subscribe { Timber.d("Vibration started") }
disposables.add(d)
}
@OnClick(R.id.action_stop_vibro)
fun actionStopVibration() {
val d = miBand.stopVibration()
.subscribe { Timber.d("Vibration stopped") }
disposables.add(d)
}
@OnClick(R.id.action_set_notify_listener)
fun actionSetNotifyListener() {
miBand.setNormalNotifyListener { data ->
Timber.d("NormalNotifyListener: ${data.contentToString()}")
}
}
@OnClick(R.id.action_set_realtime_notify_listener)
fun actionSetRealtimeNotifyListener() {
miBand.setRealtimeStepsNotifyListener(object : RealtimeStepsNotifyListener{
override fun onNotify(steps: Int) {
Timber.d("RealtimeStepsNotifyListener:$steps") }
})
}
@OnClick(R.id.action_enable_realtime_steps_notify)
fun actionEnableRealtimeStepsNotify() {
val d = miBand.enableRealtimeStepsNotify().subscribe()
disposables.add(d)
}
@OnClick(R.id.action_disable_realtime_steps_notify)
fun actionDisableRealtimeStepsNotify() {
val d = miBand.disableRealtimeStepsNotify().subscribe()
disposables.add(d) }
@OnClick(R.id.action_set_sensor_data_notify_listener)
fun actionSetSensorDataNotifyListener() {
miBand.setSensorDataNotifyListener { data ->
ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN)
var i = 0
val index = data[i++].toInt() and 0xFF or (data[i++].toInt() and 0xFF shl 8)
val d1 = data[i++].toInt() and 0xFF or (data[i++].toInt() and 0xFF shl 8)
val d2 = data[i++].toInt() and 0xFF or (data[i++].toInt() and 0xFF shl 8)
val d3 = data[i++].toInt() and 0xFF or (data[i++].toInt() and 0xFF shl 8)
val logMsg = "$index , $d1 , $d2 , $d3"
Timber.d(logMsg)
}
}
@OnClick(R.id.action_enable_sensor_data_notify)
fun actionEnableSensorDataNotify() {
val d = miBand.enableSensorDataNotify().subscribe()
disposables.add(d)
}
@OnClick(R.id.action_disable_sensor_data_notify)
fun actionDisableSensorDataNotify() {
val d = miBand.disableSensorDataNotify().subscribe()
disposables.add(d)
}
private fun checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
AlertDialog.Builder(this)
.setTitle("Location permission")
.setMessage("Mi Band needs to access your location in order to continue working.")
.setPositiveButton("OK") { _, i ->
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this@MainActivity,
arrayOf(ACCESS_FINE_LOCATION), PERMISSIONS_REQUEST_LOCATION)
}
.create()
.show()
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
arrayOf(ACCESS_FINE_LOCATION), PERMISSIONS_REQUEST_LOCATION)
}
}
}
@SuppressLint("MissingPermission")
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PERMISSIONS_REQUEST_LOCATION -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Location permission granted", Toast.LENGTH_SHORT).show()
locationManager.requestLocationUpdates(provider, 400, 1f, this)
} else {
Toast.makeText(this, "Location permission denied. Please grant location permission.",
Toast.LENGTH_SHORT).show()
}
}
}
}
override fun onResume() {
super.onResume()
if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(provider, 400, 1f, this)
}
}
override fun onPause() {
super.onPause()
if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.removeUpdates(this)
}
}
override fun onLocationChanged(location: Location) {
val lat = location.latitude
val lng = location.longitude
Timber.i("Location info: Lat $lat")
Timber.i("Location info: Lng $lng")
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
// do nothing
}
override fun onProviderEnabled(provider: String) {
// do nothing
}
override fun onProviderDisabled(provider: String) {
// do nothing
}
companion object {
const val PERMISSIONS_REQUEST_LOCATION = 99
}
}
| apache-2.0 | 31d1f9e62b96b6c5093f6b9f52fc8ff9 | 35.874126 | 115 | 0.628674 | 4.453547 | false | false | false | false |
SimpleTimeTracking/StandaloneClient | src/main/kotlin/org/stt/gui/jfx/TimeTrackingItemNodes.kt | 1 | 4869 | package org.stt.gui.jfx
import javafx.beans.binding.DoubleBinding
import javafx.collections.ObservableList
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.control.Control
import javafx.scene.control.Label
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.layout.*
import javafx.scene.paint.Color
import javafx.scene.text.Font
import javafx.scene.text.Text
import javafx.scene.text.TextFlow
import org.controlsfx.validation.decoration.GraphicValidationDecoration
import org.stt.gui.UIMain
import org.stt.gui.jfx.Glyph.Companion.GLYPH_SIZE_MEDIUM
import org.stt.gui.jfx.Glyph.Companion.glyph
import org.stt.model.TimeTrackingItem
import org.stt.time.DateTimes
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.stream.Stream
import kotlin.streams.toList
/**
* Created by dante on 01.07.17.
*/
class TimeTrackingItemNodes(private val labelToNodeMapper: @JvmSuppressWildcards ActivityTextDisplayProcessor,
private val dateTimeFormatter: DateTimeFormatter,
fontAwesome: Font,
labelAreaWidth: Int,
timePaneWidth: Int,
private val localization: ResourceBundle) {
private val labelForComment = TextFlow()
private val timePane = HBox()
private val labelForStart = Label()
private val labelForEnd = Label()
private val startToFinishActivityGraphics: Node
private val ongoingActivityGraphics: Control
private val space: Pane
private val labelArea: Pane
init {
startToFinishActivityGraphics = glyph(fontAwesome, Glyph.FAST_FORWARD, GLYPH_SIZE_MEDIUM)
ongoingActivityGraphics = glyph(fontAwesome, Glyph.FORWARD, GLYPH_SIZE_MEDIUM)
labelArea = StackPaneWithoutResize(labelForComment)
StackPane.setAlignment(labelForComment, Pos.CENTER_LEFT)
HBox.setHgrow(labelArea, Priority.ALWAYS)
labelArea.maxWidth = labelAreaWidth.toDouble()
space = Pane()
HBox.setHgrow(space, Priority.SOMETIMES)
timePane.prefWidth = timePaneWidth.toDouble()
timePane.spacing = 10.0
timePane.alignment = Pos.CENTER_LEFT
if (UIMain.DEBUG_UI) {
labelArea.border = Border(BorderStroke(Color.RED, BorderStrokeStyle.DASHED, CornerRadii.EMPTY, BorderStroke.MEDIUM))
labelForComment.border = Border(BorderStroke(Color.GREEN, BorderStrokeStyle.DASHED, CornerRadii.EMPTY, BorderStroke.MEDIUM))
}
}
private fun applyLabelForComment(activity: String) {
val textNodes = labelToNodeMapper(Stream.of(activity))
.map<Node> {
if (it is String) {
return@map Text(it)
}
if (it is Node) {
return@map it
}
throw IllegalArgumentException(String.format("Unsupported element: %s", it))
}.toList()
labelForComment.children.setAll(textNodes)
}
fun appendNodesTo(parent: ObservableList<Node>) {
parent.addAll(labelArea, space, timePane)
}
fun appendNodesTo(timePaneContainer: Pane, timePaneOpacity: DoubleBinding, parent: ObservableList<Node>) {
timePane.opacityProperty().bind(timePaneOpacity)
timePaneContainer.children.add(timePane)
parent.addAll(labelArea, space, timePaneContainer)
}
fun setItem(item: TimeTrackingItem) {
applyLabelForComment(item.activity)
setupTimePane(item)
}
private fun setupTimePane(item: TimeTrackingItem) {
labelForStart.text = dateTimeFormatter.format(item.start)
val end = item.end
if (end != null) {
labelForEnd.text = dateTimeFormatter.format(end)
timePane.children.setAll(labelForStart, startToFinishActivityGraphics, labelForEnd)
} else {
if (!DateTimes.isOnSameDay(item.start, LocalDateTime.now())) {
val stackPane = StackPane(ongoingActivityGraphics)
val ongoingActivityWarning = ImageView(WARNING_IMAGE)
Tooltips.install(stackPane, localization.getString("ongoingActivityDidntStartToday"))
stackPane.children.add(ongoingActivityWarning)
StackPane.setAlignment(ongoingActivityWarning, Pos.TOP_RIGHT)
timePane.children.setAll(labelForStart, stackPane)
} else {
timePane.children.setAll(labelForStart, ongoingActivityGraphics)
}
}
}
companion object {
private val WARNING_IMAGE = Image(GraphicValidationDecoration::class.java.getResource("/impl/org/controlsfx/control/validation/decoration-warning.png").toExternalForm()) //$NON-NLS-1$
}
}
| gpl-3.0 | 8dfc2d2b95b664f37a70c334680b9d5e | 37.952 | 191 | 0.680838 | 4.525093 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/data/models/BracketSource.kt | 1 | 1014 | package com.garpr.android.data.models
import android.os.Parcel
import android.os.Parcelable
import com.garpr.android.extensions.createParcel
import com.garpr.android.extensions.toJavaUri
import com.squareup.moshi.Json
enum class BracketSource(
private val host: String
) : Parcelable {
@Json(name = "challonge")
CHALLONGE("challonge.com"),
@Json(name = "smash_gg")
SMASH_GG("smash.gg");
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(ordinal)
}
companion object {
@JvmField
val CREATOR = createParcel { values()[it.readInt()] }
fun fromUrl(url: String?): BracketSource? {
val host = url.toJavaUri()?.host
return if (host.isNullOrBlank()) {
null
} else {
values().firstOrNull { value ->
host.endsWith(value.host, ignoreCase = true)
}
}
}
}
}
| unlicense | 811229546b0506bf627224e4bdca26b1 | 23.142857 | 64 | 0.594675 | 4.17284 | false | false | false | false |
RyotaMurohoshi/KotLinq | src/test/kotlin/com/muhron/kotlinq/default_methods/AssociateTest.kt | 1 | 1846 | package com.muhron.kotlinq.default_methods
import org.junit.Assert
import org.junit.Test
class AssociateTest {
data class Person(val id: Long, val name: String, val teamId: Long)
val person000 = Person(id = 0L, name = "Taro", teamId = 0L)
val person001 = Person(id = 1L, name = "Jiro", teamId = 0L)
val person002 = Person(id = 2L, name = "Saburo", teamId = 0L)
val person003 = Person(id = 3L, name = "Matsuko", teamId = 1L)
val person004 = Person(id = 4L, name = "Takeko", teamId = 1L)
val person005 = Person(id = 5L, name = "Umeko", teamId = 1L)
val person006 = Person(id = 6L, name = "Hanako", teamId = 2L)
val personList = listOf(
person000,
person001,
person002,
person003,
person004,
person005,
person006
)
@Test
fun test0() {
val result = listOf(1, 2, 3).associateBy { it }
Assert.assertEquals(result, mapOf(1 to 1, 2 to 2, 3 to 3));
}
@Test
fun test1() {
val result = listOf(1, 2, 3, 1).associateBy { it }
Assert.assertEquals(result, mapOf(1 to 1, 2 to 2, 3 to 3));
}
@Test
fun test2() {
val result = personList.associateBy { it.id }
val expected = mapOf(
0L to person000,
1L to person001,
2L to person002,
3L to person003,
4L to person004,
5L to person005,
6L to person006
)
Assert.assertEquals(expected, result)
}
@Test
fun test3() {
val result = personList.associateBy { it.teamId }
val expected = mapOf(
0L to person002,
1L to person005,
2L to person006
)
Assert.assertEquals(expected, result)
}
}
| mit | 91acbffd5aaf76b14f7f1549d28a6393 | 27.4 | 71 | 0.537378 | 3.662698 | false | true | false | false |
square/duktape-android | zipline/src/jsMain/kotlin/app/cash/zipline/GlobalBridge.kt | 1 | 3743 | /*
* Copyright (C) 2022 Block, 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 app.cash.zipline
import app.cash.zipline.internal.JsPlatform
import app.cash.zipline.internal.bridge.CallChannel
import app.cash.zipline.internal.bridge.inboundChannelName
/**
* JS-global bindings for implementing a complete JS platform (setTimeout, console), and receiving
* calls from the host platform (inboundChannel).
*
* Creating this has the side effect of setting variables on `globalThis`, so we can initialize the
* host platform and JS platform in any order.
*/
internal object GlobalBridge : JsPlatform, CallChannel {
private var nextTimeoutId = 1
private val jobs = mutableMapOf<Int, Job>()
private val zipline: Zipline
get() = THE_ONLY_ZIPLINE ?: error("Zipline isn't ready: did you call Zipline.get() yet?")
private val inboundChannel: CallChannel
get() = zipline.endpoint.inboundChannel
init {
@Suppress("UNUSED_VARIABLE") // Used in raw JS code below.
val globalBridge = this
js(
"""
globalThis.$inboundChannelName = globalBridge;
globalThis.setTimeout = function(handler, delay) {
return globalBridge.setTimeout(handler, delay, arguments);
};
globalThis.clearTimeout = function(timeoutID) {
return globalBridge.clearTimeout(timeoutID);
};
globalThis.console = {
error: function() { globalBridge.consoleMessage('error', arguments) },
info: function() { globalBridge.consoleMessage('info', arguments) },
log: function() { globalBridge.consoleMessage('log', arguments) },
warn: function() { globalBridge.consoleMessage('warn', arguments) },
};
"""
)
}
override fun serviceNamesArray() = inboundChannel.serviceNamesArray()
override fun call(callJson: String) = inboundChannel.call(callJson)
override fun disconnect(instanceName: String) = inboundChannel.disconnect(instanceName)
override fun runJob(timeoutId: Int) {
val job = jobs.remove(timeoutId) ?: return
job.handler.apply(null, job.arguments)
}
override fun close() {
}
@JsName("setTimeout")
fun setTimeout(handler: dynamic, timeout: Int, vararg arguments: Any?): Int {
val timeoutId = nextTimeoutId++
jobs[timeoutId] = Job(handler, arguments)
zipline.eventLoop.setTimeout(timeoutId, timeout)
return timeoutId
}
@JsName("clearTimeout")
fun clearTimeout(timeoutId: Int) {
jobs.remove(timeoutId)
zipline.eventLoop.clearTimeout(timeoutId)
}
/**
* Note that this doesn't currently implement `%o`, `%d`, `%s`, etc.
* https://developer.mozilla.org/en-US/docs/Web/API/console#outputting_text_to_the_console
*/
@JsName("consoleMessage")
fun consoleMessage(level: String, vararg arguments: Any?) {
var throwable: Throwable? = null
val argumentsList = mutableListOf<Any?>()
for (argument in arguments) {
if (throwable == null && argument is Throwable) {
throwable = argument
} else {
argumentsList += argument
}
}
zipline.console.log(level, argumentsList.joinToString(separator = " "), throwable)
}
private class Job(
val handler: dynamic,
val arguments: Array<out Any?>
)
}
| apache-2.0 | e197f71a7f37d49746a884dc42324f72 | 32.419643 | 99 | 0.698103 | 4.122247 | false | false | false | false |
facebook/react-native | packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GenerateCodegenArtifactsTaskTest.kt | 2 | 6038 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.tasks
import com.facebook.react.tests.OS
import com.facebook.react.tests.OsRule
import com.facebook.react.tests.WithOs
import com.facebook.react.tests.createTestTask
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class GenerateCodegenArtifactsTaskTest {
@get:Rule val tempFolder = TemporaryFolder()
@get:Rule val osRule = OsRule()
@Test
fun generateCodegenSchema_inputFiles_areSetCorrectly() {
val codegenDir = tempFolder.newFolder("codegen")
val outputDir = tempFolder.newFolder("output")
val task =
createTestTask<GenerateCodegenArtifactsTask> {
it.codegenDir.set(codegenDir)
it.generatedSrcDir.set(outputDir)
}
assertEquals(
File(codegenDir, "lib/cli/combine/combine-js-to-schema-cli.js"),
task.combineJsToSchemaCli.get().asFile)
assertEquals(File(outputDir, "schema.json"), task.generatedSchemaFile.get().asFile)
}
@Test
fun generateCodegenSchema_outputFile_isSetCorrectly() {
val codegenDir = tempFolder.newFolder("codegen")
val outputDir = tempFolder.newFolder("output")
val task =
createTestTask<GenerateCodegenArtifactsTask> {
it.codegenDir.set(codegenDir)
it.generatedSrcDir.set(outputDir)
}
assertEquals(File(outputDir, "java"), task.generatedJavaFiles.get().asFile)
assertEquals(File(outputDir, "jni"), task.generatedJniFiles.get().asFile)
}
@Test
fun generateCodegenSchema_simpleProperties_areInsideInput() {
val packageJsonFile = tempFolder.newFile("package.json")
val task =
createTestTask<GenerateCodegenArtifactsTask> {
it.nodeExecutableAndArgs.set(listOf("npm", "help"))
it.codegenJavaPackageName.set("com.example.test")
it.libraryName.set("example-test")
it.packageJsonFile.set(packageJsonFile)
}
assertEquals(listOf("npm", "help"), task.nodeExecutableAndArgs.get())
assertEquals("com.example.test", task.codegenJavaPackageName.get())
assertEquals("example-test", task.libraryName.get())
assertTrue(task.inputs.properties.containsKey("nodeExecutableAndArgs"))
assertTrue(task.inputs.properties.containsKey("codegenJavaPackageName"))
assertTrue(task.inputs.properties.containsKey("libraryName"))
}
@Test
@WithOs(OS.LINUX)
fun setupCommandLine_willSetupCorrectly() {
val reactNativeDir = tempFolder.newFolder("node_modules/react-native/")
val codegenDir = tempFolder.newFolder("codegen")
val outputDir = tempFolder.newFolder("output")
val task =
createTestTask<GenerateCodegenArtifactsTask> {
it.reactNativeDir.set(reactNativeDir)
it.codegenDir.set(codegenDir)
it.generatedSrcDir.set(outputDir)
it.nodeExecutableAndArgs.set(listOf("--verbose"))
}
task.setupCommandLine("example-test", "com.example.test")
assertEquals(
listOf(
"--verbose",
File(reactNativeDir, "scripts/generate-specs-cli.js").toString(),
"--platform",
"android",
"--schemaPath",
File(outputDir, "schema.json").toString(),
"--outputDir",
outputDir.toString(),
"--libraryName",
"example-test",
"--javaPackageName",
"com.example.test",
),
task.commandLine.toMutableList())
}
@Test
fun resolveTaskParameters_withConfigInPackageJson_usesIt() {
val packageJsonFile =
tempFolder.newFile("package.json").apply {
// language=JSON
writeText(
"""
{
"name": "@a/libray",
"codegenConfig": {
"name": "an-awesome-library",
"android": {
"javaPackageName": "com.awesome.package"
}
}
}
"""
.trimIndent())
}
val task =
createTestTask<GenerateCodegenArtifactsTask> {
it.packageJsonFile.set(packageJsonFile)
it.codegenJavaPackageName.set("com.example.ignored")
it.libraryName.set("a-library-name-that-is-ignored")
}
val (libraryName, javaPackageName) = task.resolveTaskParameters()
assertEquals("an-awesome-library", libraryName)
assertEquals("com.awesome.package", javaPackageName)
}
@Test
fun resolveTaskParameters_withConfigMissingInPackageJson_usesGradleOne() {
val packageJsonFile =
tempFolder.newFile("package.json").apply {
// language=JSON
writeText(
"""
{
"name": "@a/libray",
"codegenConfig": {
}
}
"""
.trimIndent())
}
val task =
createTestTask<GenerateCodegenArtifactsTask> {
it.packageJsonFile.set(packageJsonFile)
it.codegenJavaPackageName.set("com.example.test")
it.libraryName.set("a-library-name-from-gradle")
}
val (libraryName, javaPackageName) = task.resolveTaskParameters()
assertEquals("a-library-name-from-gradle", libraryName)
assertEquals("com.example.test", javaPackageName)
}
@Test
fun resolveTaskParameters_withMissingPackageJson_usesGradleOne() {
val task =
createTestTask<GenerateCodegenArtifactsTask> {
it.packageJsonFile.set(File(tempFolder.root, "package.json"))
it.codegenJavaPackageName.set("com.example.test")
it.libraryName.set("a-library-name-from-gradle")
}
val (libraryName, javaPackageName) = task.resolveTaskParameters()
assertEquals("a-library-name-from-gradle", libraryName)
assertEquals("com.example.test", javaPackageName)
}
}
| mit | 28531cd4ccdcd6a106be4a7bda44ed4d | 30.778947 | 87 | 0.652203 | 4.436444 | false | true | false | false |
tipsy/javalin | javalin/src/test/kotlin/io/javalin/examples/HelloWorldGson.kt | 1 | 717 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Γ
se
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.examples
import com.google.gson.GsonBuilder
import io.javalin.Javalin
import io.javalin.plugin.json.JsonMapper
import java.util.*
fun main() {
val gson = GsonBuilder().create()
val gsonMapper = object : JsonMapper {
override fun <T> fromJsonString(json: String, targetClass: Class<T>): T = gson.fromJson(json, targetClass)
override fun toJsonString(obj: Any) = gson.toJson(obj)
}
val app = Javalin.create { it.jsonMapper(gsonMapper) }.start(7070)
app.get("/") { it.json(Arrays.asList("a", "b", "c")) }
}
| apache-2.0 | b03ff0f6c9e37f1c69e4dd69c96af2ba | 26.538462 | 114 | 0.685754 | 3.527094 | false | false | false | false |
WijayaPrinting/wp-javafx | openpss-server/src/com/hendraanggrian/openpss/route/PaymentsRouting.kt | 1 | 2102 | package com.hendraanggrian.openpss.route
import com.hendraanggrian.openpss.R
import com.hendraanggrian.openpss.Server
import com.hendraanggrian.openpss.nosql.transaction
import com.hendraanggrian.openpss.schema.Invoices
import com.hendraanggrian.openpss.schema.Log
import com.hendraanggrian.openpss.schema.Logs
import com.hendraanggrian.openpss.schema.Payment
import com.hendraanggrian.openpss.schema.Payments
import io.ktor.application.call
import io.ktor.http.HttpStatusCode
import io.ktor.request.receive
import io.ktor.response.respond
import io.ktor.routing.Routing
import io.ktor.routing.delete
import io.ktor.routing.get
import io.ktor.routing.post
import io.ktor.routing.route
import kotlinx.nosql.equal
fun Routing.payment() {
route(Payments.schemaName) {
get {
call.respond(transaction {
Payments { dateTime.matches(call.parameters["dateTime"]!!) }.toList()
})
}
post {
val payment = call.receive<Payment>()
payment.id = transaction { Payments.insert(payment) }
call.respond(payment)
}
delete {
val payment = call.receive<Payment>()
transaction {
val invoiceNo = Invoices[payment.invoiceId].single().no
Payments -= payment.id
Logs += Log.new(
Server.getString(R.string.payment_delete).format(
payment.value,
invoiceNo
),
call.getString("login")
)
}
call.respond(HttpStatusCode.OK)
}
route("{invoiceId}") {
get {
call.respond(transaction {
Payments { invoiceId.equal(call.getString("invoiceId")) }.toList()
})
}
get("due") {
call.respond(transaction {
Payments { invoiceId.equal(call.getString("invoiceId")) }
.sumByDouble { it.value }
})
}
}
}
}
| apache-2.0 | a472c32deaa811818008c25332e9a09d | 32.365079 | 86 | 0.580875 | 4.799087 | false | false | false | false |
songzhw/Hello-kotlin | KotlinPlayground/src/main/kotlin/ca/six/rxjava/IntervalTrap.kt | 1 | 820 | package ca.six.rxjava
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit
fun main(args: Array<String>) {
/*
Nothing hapens
Observable.interval(1, TimeUnit.SECONDS)
.subscribe { println("$it") }
*/
/*
Solution 01
Observable.interval(1, TimeUnit.SECONDS)
.subscribe {
println("$it ${Thread.currentThread().name}")
}
Thread.sleep(2000)
*/
// =================== 1. interval ε ===================
Observable.interval(1500, TimeUnit.MILLISECONDS, Schedulers.trampoline())
.subscribe { println("$it ${Thread.currentThread().name}") } //=> 0 main; 1 main; ...
// Schdulers.immediate() is okay too, just not recommended for this type of work(interval)
} | apache-2.0 | e060fa94827fa4e5156a7efa3a2dda9f | 21.75 | 97 | 0.603912 | 4.305263 | false | false | false | false |
hubme/WorkHelperApp | applib/src/main/java/com/king/applib/ui/recyclerview/ItemClickSupport.kt | 1 | 4269 | import androidx.annotation.IdRes
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import com.king.applib.R
import org.jetbrains.annotations.NotNull
/**
* RecyclerView Item ηΉε»δΊδ»Άε·₯ε
·η±»γ
*
* @author VanceKing
* @since 2019/11/13.
*/
class ItemClickSupport private constructor(private val mRecyclerView: androidx.recyclerview.widget.RecyclerView) {
private var mOnItemClickListener: OnItemClickListener? = null
private var mOnItemLongClickListener: OnItemLongClickListener? = null
private val childListenerMap = hashMapOf<Int, OnChildClickListener>()
private val mAttachListener = object : androidx.recyclerview.widget.RecyclerView.OnChildAttachStateChangeListener {
override fun onChildViewAttachedToWindow(view: View) {
mOnItemClickListener?.let {
view.setOnClickListener {
val holder = mRecyclerView.findContainingViewHolder(it)
if (holder != null && holder.adapterPosition != -1) {
mOnItemClickListener?.onItemClicked(mRecyclerView, holder.adapterPosition, it)
}
}
}
if (childListenerMap.isNotEmpty()) {
for (key in childListenerMap.keys) {
view.findViewById<View>(key)?.setOnClickListener {
val holder = mRecyclerView.findContainingViewHolder(it)
if (holder != null && holder.adapterPosition != -1) {
childListenerMap[key]?.onChildClicked(mRecyclerView, holder.adapterPosition, it)
}
}
}
}
mOnItemLongClickListener?.let {
view.setOnLongClickListener(View.OnLongClickListener {
if (mOnItemLongClickListener != null) {
val holder = mRecyclerView.getChildViewHolder(it)
return@OnLongClickListener mOnItemLongClickListener!!.onItemLongClicked(mRecyclerView, holder.adapterPosition, it)
}
false
})
}
}
override fun onChildViewDetachedFromWindow(view: View) {
}
}
init {
mRecyclerView.setTag(R.id.item_click_support, this)
mRecyclerView.addOnChildAttachStateChangeListener(mAttachListener)
}
fun addOnChildClickListener(@IdRes resId: Int, @NotNull listener: OnChildClickListener): ItemClickSupport {
childListenerMap[resId] = listener
return this
}
fun addOnItemClickListener(@NotNull listener: OnItemClickListener): ItemClickSupport {
mOnItemClickListener = listener
return this
}
fun addOnItemLongClickListener(@NotNull listener: OnItemLongClickListener): ItemClickSupport {
mOnItemLongClickListener = listener
return this
}
private fun detach(view: androidx.recyclerview.widget.RecyclerView) {
view.removeOnChildAttachStateChangeListener(mAttachListener)
view.setTag(R.id.item_click_support, null)
}
// ε ViewηΉε»ζ₯ε£
interface OnChildClickListener {
fun onChildClicked(recyclerView: androidx.recyclerview.widget.RecyclerView, position: Int, v: View)
}
// ηΉε»ζ₯ε£
interface OnItemClickListener {
fun onItemClicked(recyclerView: androidx.recyclerview.widget.RecyclerView, position: Int, v: View)
}
// ιΏζζ₯ε£
interface OnItemLongClickListener {
fun onItemLongClicked(recyclerView: androidx.recyclerview.widget.RecyclerView, position: Int, v: View): Boolean
}
companion object {
fun addTo(view: androidx.recyclerview.widget.RecyclerView): ItemClickSupport {
var support: ItemClickSupport? = view.getTag(R.id.item_click_support) as ItemClickSupport?
if (support == null) {
support = ItemClickSupport(view)
}
return support
}
fun removeFrom(view: androidx.recyclerview.widget.RecyclerView): ItemClickSupport? {
val support = view.getTag(R.id.item_click_support) as ItemClickSupport
support.detach(view)
return support
}
}
} | apache-2.0 | c0be32b9ba73c9f9d26a77288a3b90bf | 35.765217 | 138 | 0.643482 | 5.426187 | false | false | false | false |
adamahrens/AndroidExploration | ListMaker/app/src/main/java/com/appsbyahrens/listmaker/ListSelectionRecyclerViewAdapter.kt | 1 | 1293 | package com.appsbyahrens.listmaker
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
class ListSelectionRecyclerViewAdapter(val taskLists: ArrayList<TaskList>, val clickListener: ListSelectionRecyclerViewClickListener): RecyclerView.Adapter<ListSelectionViewHolder>() {
interface ListSelectionRecyclerViewClickListener {
fun listItemClicked(list: TaskList)
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ListSelectionViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.list_selection_view_holder, parent,false)
return ListSelectionViewHolder(view)
}
override fun getItemCount(): Int {
return taskLists.size
}
override fun onBindViewHolder(holder: ListSelectionViewHolder?, position: Int) {
if (holder != null) {
val item = taskLists[position]
holder.listTitle?.text = item.name
holder.listPosition?.text = (position + 1).toString()
holder.itemView.setOnClickListener { _ ->
clickListener.listItemClicked(item)
}
}
}
fun addTaskList(list: TaskList) {
taskLists.add(list)
notifyDataSetChanged()
}
} | mit | c178c7b8b7e965bbbc71624f89001eb4 | 33.972973 | 184 | 0.699149 | 4.992278 | false | false | false | false |
sabi0/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/IconsClassGenerator.kt | 1 | 13309 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.intellij.build.images
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.LineSeparator
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.diff.Diff
import org.jetbrains.jps.model.JpsSimpleElement
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.util.JpsPathUtil
import java.io.File
import java.util.*
class IconsClassGenerator(val projectHome: File, val util: JpsModule, val writeChangesToDisk: Boolean = true) {
private var processedClasses = 0
private var processedIcons = 0
private var processedPhantom = 0
private var modifiedClasses = ArrayList<Triple<JpsModule, File, String>>()
fun processModule(module: JpsModule) {
val customLoad: Boolean
val packageName: String
val className: String
val outFile: File
if ("intellij.platform.icons" == module.name) {
customLoad = false
packageName = "com.intellij.icons"
className = "AllIcons"
val dir = util.getSourceRoots(JavaSourceRootType.SOURCE).first().file.absolutePath + "/com/intellij/icons"
outFile = File(dir, "AllIcons.java")
}
else {
customLoad = true
packageName = "icons"
val firstRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).firstOrNull()
if (firstRoot == null) return
val generatedRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).find { it.properties.isForGeneratedSources }
val targetRoot = File((generatedRoot ?: firstRoot).file, "icons")
val firstRootDir = File(firstRoot.file, "icons")
if (firstRootDir.isDirectory && firstRootDir.list().isEmpty()) {
//this is added to remove unneeded empty directories created by previous version of this script
println("deleting empty directory ${firstRootDir.absolutePath}")
firstRootDir.delete()
}
var oldClassName = findIconClass(firstRootDir)
if (generatedRoot != null && oldClassName != null) {
val oldFile = File(firstRootDir, "${oldClassName}.java")
println("deleting $oldFile from source root which isn't marked as 'generated'")
oldFile.delete()
}
if (oldClassName == null) {
oldClassName = findIconClass(targetRoot)
}
className = oldClassName ?: directoryName(module) + "Icons"
outFile = File(targetRoot, "${className}.java")
}
val oldText = if (outFile.exists()) outFile.readText() else null
val copyrightComment = getCopyrightComment(oldText)
val separator = getSeparators(oldText)
val newText = generate(module, className, packageName, customLoad, copyrightComment)
val oldLines = oldText?.lines() ?: emptyList()
val newLines = newText?.lines() ?: emptyList()
if (newLines.isNotEmpty()) {
processedClasses++
if (oldLines != newLines) {
if (writeChangesToDisk) {
outFile.parentFile.mkdirs()
outFile.writeText(newLines.joinToString(separator = separator.separatorString))
println("Updated icons class: ${outFile.name}")
}
else {
val sb = StringBuilder()
var ch = Diff.buildChanges(oldLines.toTypedArray(), newLines.toTypedArray())
while (ch != null) {
val deleted = oldLines.subList(ch.line0, ch.line0 + ch.deleted)
val inserted = newLines.subList(ch.line1, ch.line1 + ch.inserted)
if (sb.isNotEmpty()) sb.append("=".repeat(20)).append("\n")
deleted.forEach { sb.append("-").append(it).append("\n") }
inserted.forEach { sb.append("+").append(it).append("\n") }
ch = ch.link
}
modifiedClasses.add(Triple(module, outFile, sb.toString()))
}
}
}
}
fun printStats() {
println()
println("Generated classes: $processedClasses. Processed icons: $processedIcons. Phantom icons: $processedPhantom")
}
fun getModifiedClasses(): List<Triple<JpsModule, File, String>> = modifiedClasses
private fun findIconClass(dir: File): String? {
var className: String? = null
dir.children.forEach {
if (it.name.endsWith("Icons.java")) {
className = it.name.substring(0, it.name.length - ".java".length)
}
}
return className
}
private fun getCopyrightComment(text: String?): String {
if (text == null) return ""
val i = text.indexOf("package ")
if (i == -1) return ""
val comment = text.substring(0, i)
return if (comment.trim().endsWith("*/") || comment.trim().startsWith("//")) comment else ""
}
private fun getSeparators(text: String?): LineSeparator {
if (text == null) return LineSeparator.LF
return StringUtil.detectSeparators(text) ?: LineSeparator.LF
}
private fun generate(module: JpsModule, className: String, packageName: String, customLoad: Boolean, copyrightComment: String): String? {
val imageCollector = ImageCollector(projectHome, true)
val images = imageCollector.collect(module, true)
imageCollector.printUsedIconRobots()
val answer = StringBuilder()
answer.append(copyrightComment)
append(answer, "package $packageName;\n", 0)
append(answer, "import com.intellij.openapi.util.IconLoader;", 0)
append(answer, "", 0)
append(answer, "import javax.swing.*;", 0)
append(answer, "", 0)
// IconsGeneratedSourcesFilter depends on following comment, if you going to change the text
// please do corresponding changes in IconsGeneratedSourcesFilter as well
append(answer, "/**", 0)
append(answer, " * NOTE THIS FILE IS AUTO-GENERATED", 0)
append(answer, " * DO NOT EDIT IT BY HAND, run \"Generate icon classes\" configuration instead", 0)
append(answer, " */", 0)
append(answer, "public class $className {", 0)
if (customLoad) {
append(answer, "private static Icon load(String path) {", 1)
append(answer, "return IconLoader.getIcon(path, ${className}.class);", 2)
append(answer, "}", 1)
append(answer, "", 0)
val customExternalLoad = images.any { it.deprecation?.replacementContextClazz != null }
if (customExternalLoad) {
append(answer, "private static Icon load(String path, Class<?> clazz) {", 1)
append(answer, "return IconLoader.getIcon(path, clazz);", 2)
append(answer, "}", 1)
append(answer, "", 0)
}
}
val inners = StringBuilder()
processIcons(images, inners, customLoad, 0)
if (inners.isEmpty()) return null
answer.append(inners)
append(answer, "}", 0)
return answer.toString()
}
private fun processIcons(images: List<ImagePaths>, answer: StringBuilder, customLoad: Boolean, depth: Int) {
val level = depth + 1
val (nodes, leafs) = images.partition { getImageId(it, depth).contains('/') }
val nodeMap = nodes.groupBy { getImageId(it, depth).substringBefore('/') }
val leafMap = ContainerUtil.newMapFromValues(leafs.iterator(), { getImageId(it, depth) })
val sortedKeys = (nodeMap.keys + leafMap.keys).sortedWith(NAME_COMPARATOR)
sortedKeys.forEach { key ->
val group = nodeMap[key]
val image = leafMap[key]
if (group != null) {
val inners = StringBuilder()
processIcons(group, inners, customLoad, depth + 1)
if (inners.isNotEmpty()) {
append(answer, "", level)
append(answer, "public static class " + className(key) + " {", level)
append(answer, inners.toString(), 0)
append(answer, "}", level)
}
}
if (image != null) {
appendImage(image, answer, level, customLoad)
}
}
}
private fun appendImage(image: ImagePaths,
answer: StringBuilder,
level: Int,
customLoad: Boolean) {
val file = image.file
if (file == null) return
if (!image.phantom && !isIcon(file)) return
val iconName = iconName(file)
val used = image.used
val deprecated = image.deprecated
val deprecationComment = image.deprecation?.comment
val deprecationReplacement = image.deprecation?.replacement
val deprecationReplacementContextClazz = image.deprecation?.replacementContextClazz
processedIcons++
if (image.phantom) processedPhantom++
if (used || deprecated) {
append(answer, "", level)
if (deprecationComment != null) {
append(answer, "/** @deprecated $deprecationComment */", level)
}
append(answer, "@SuppressWarnings(\"unused\")", level)
}
if (deprecated) {
append(answer, "@Deprecated", level)
}
val sourceRoot = image.sourceRoot
var root_prefix = ""
if (sourceRoot.rootType == JavaSourceRootType.SOURCE) {
@Suppress("UNCHECKED_CAST")
val packagePrefix = (sourceRoot.properties as JpsSimpleElement<JavaSourceRootProperties>).data.packagePrefix
if (!packagePrefix.isEmpty()) root_prefix = "/" + packagePrefix.replace('.', '/')
}
if (deprecationReplacementContextClazz == null) {
val imageFile: File
if (deprecationReplacement != null) {
imageFile = File(sourceRoot.file, deprecationReplacement)
assert(isIcon(imageFile), { "Overriding icon should be valid: $iconName - ${imageFile.path}" })
}
else {
imageFile = file
}
val size = if (imageFile.exists()) imageSize(imageFile) else null
val comment: String
if (size != null) {
comment = " // ${size.width}x${size.height}"
}
else if (image.phantom) {
comment = ""
}
else {
error("Can't get icon size: $imageFile")
}
val method = if (customLoad) "load" else "IconLoader.getIcon"
val relativePath = root_prefix + "/" + FileUtil.getRelativePath(sourceRoot.file, imageFile)!!.replace('\\', '/')
append(answer,
"public static final Icon $iconName = $method(\"$relativePath\");$comment",
level)
}
else {
val method = if (customLoad) "load" else "IconLoader.getIcon"
val relativePath = deprecationReplacement
append(answer,
"public static final Icon $iconName = $method(\"$relativePath\", ${deprecationReplacementContextClazz}.class);",
level)
}
}
private fun append(answer: StringBuilder, text: String, level: Int) {
if (text.isNotBlank()) answer.append(" ".repeat(level))
answer.append(text).append("\n")
}
private fun getImageId(image: ImagePaths, depth: Int): String {
val path = StringUtil.trimStart(image.id, "/").split("/")
if (path.size < depth) throw IllegalArgumentException("Can't get image ID - ${image.id}, $depth")
return path.drop(depth).joinToString("/")
}
private fun directoryName(module: JpsModule): String {
return directoryNameFromConfig(module) ?: className(module.name)
}
private fun directoryNameFromConfig(module: JpsModule): String? {
val rootUrl = getFirstContentRootUrl(module) ?: return null
val rootDir = File(JpsPathUtil.urlToPath(rootUrl))
if (!rootDir.isDirectory) return null
val file = File(rootDir, ImageCollector.ROBOTS_FILE_NAME)
if (!file.exists()) return null
val prefix = "name:"
var moduleName: String? = null
file.forEachLine {
if (it.startsWith(prefix)) {
val name = it.substring(prefix.length).trim()
if (name.isNotEmpty()) moduleName = name
}
}
return moduleName
}
private fun getFirstContentRootUrl(module: JpsModule): String? {
return module.contentRootsList.urls.firstOrNull()
}
private fun className(name: String): String {
val answer = StringBuilder()
name.removePrefix("intellij.").split("-", "_", ".").forEach {
answer.append(capitalize(it))
}
return toJavaIdentifier(answer.toString())
}
private fun iconName(file: File): String {
val name = capitalize(file.name.substringBeforeLast('.'))
return toJavaIdentifier(name)
}
private fun toJavaIdentifier(id: String): String {
val sb = StringBuilder()
id.forEach {
if (Character.isJavaIdentifierPart(it)) {
sb.append(it)
}
else {
sb.append('_')
}
}
if (Character.isJavaIdentifierStart(sb.first())) {
return sb.toString()
}
else {
return "_" + sb.toString()
}
}
private fun capitalize(name: String): String {
if (name.length == 2) return name.toUpperCase()
return name.capitalize()
}
// legacy ordering
private val NAME_COMPARATOR: Comparator<String> = compareBy { it.toLowerCase() + "." }
}
| apache-2.0 | 56fbf38173e921cc5b5ecf2b61cf44c1 | 34.302387 | 139 | 0.655647 | 4.380843 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/service/api/v2alpha/CertificatesService.kt | 1 | 21341 | // Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.service.api.v2alpha
import io.grpc.Status
import io.grpc.StatusException
import org.wfanet.measurement.api.v2alpha.Certificate
import org.wfanet.measurement.api.v2alpha.Certificate.RevocationState
import org.wfanet.measurement.api.v2alpha.CertificateParentKey
import org.wfanet.measurement.api.v2alpha.CertificatesGrpcKt.CertificatesCoroutineImplBase
import org.wfanet.measurement.api.v2alpha.CreateCertificateRequest
import org.wfanet.measurement.api.v2alpha.DataProviderCertificateKey
import org.wfanet.measurement.api.v2alpha.DataProviderKey
import org.wfanet.measurement.api.v2alpha.DataProviderPrincipal
import org.wfanet.measurement.api.v2alpha.DuchyCertificateKey
import org.wfanet.measurement.api.v2alpha.DuchyKey
import org.wfanet.measurement.api.v2alpha.DuchyPrincipal
import org.wfanet.measurement.api.v2alpha.GetCertificateRequest
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerCertificateKey
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerKey
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerPrincipal
import org.wfanet.measurement.api.v2alpha.MeasurementPrincipal
import org.wfanet.measurement.api.v2alpha.ModelProviderCertificateKey
import org.wfanet.measurement.api.v2alpha.ModelProviderKey
import org.wfanet.measurement.api.v2alpha.ModelProviderPrincipal
import org.wfanet.measurement.api.v2alpha.ReleaseCertificateHoldRequest
import org.wfanet.measurement.api.v2alpha.RevokeCertificateRequest
import org.wfanet.measurement.api.v2alpha.certificate
import org.wfanet.measurement.api.v2alpha.makeDataProviderCertificateName
import org.wfanet.measurement.api.v2alpha.makeDuchyCertificateName
import org.wfanet.measurement.api.v2alpha.makeMeasurementConsumerCertificateName
import org.wfanet.measurement.api.v2alpha.makeModelProviderCertificateName
import org.wfanet.measurement.api.v2alpha.principalFromCurrentContext
import org.wfanet.measurement.common.api.ResourceKey
import org.wfanet.measurement.common.grpc.failGrpc
import org.wfanet.measurement.common.grpc.grpcRequire
import org.wfanet.measurement.common.grpc.grpcRequireNotNull
import org.wfanet.measurement.common.identity.apiIdToExternalId
import org.wfanet.measurement.common.identity.externalIdToApiId
import org.wfanet.measurement.internal.kingdom.Certificate as InternalCertificate
import org.wfanet.measurement.internal.kingdom.Certificate.RevocationState as InternalRevocationState
import org.wfanet.measurement.internal.kingdom.CertificatesGrpcKt.CertificatesCoroutineStub
import org.wfanet.measurement.internal.kingdom.certificate as internalCertificate
import org.wfanet.measurement.internal.kingdom.getCertificateRequest
import org.wfanet.measurement.internal.kingdom.releaseCertificateHoldRequest
import org.wfanet.measurement.internal.kingdom.revokeCertificateRequest
class CertificatesService(private val internalCertificatesStub: CertificatesCoroutineStub) :
CertificatesCoroutineImplBase() {
override suspend fun getCertificate(request: GetCertificateRequest): Certificate {
val key =
grpcRequireNotNull(createResourceKey(request.name)) { "Resource name unspecified or invalid" }
val principal: MeasurementPrincipal = principalFromCurrentContext
val internalGetCertificateRequest = getCertificateRequest {
externalCertificateId = apiIdToExternalId(key.certificateId)
when (key) {
is DataProviderCertificateKey -> {
externalDataProviderId = apiIdToExternalId(key.dataProviderId)
when (principal) {
is DataProviderPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.dataProviderId) != externalDataProviderId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot get another DataProvider's Certificate"
}
}
}
is MeasurementConsumerPrincipal -> {}
is ModelProviderPrincipal -> {}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to get a DataProvider's Certificate"
}
}
}
}
is DuchyCertificateKey -> externalDuchyId = key.duchyId
is MeasurementConsumerCertificateKey -> {
externalMeasurementConsumerId = apiIdToExternalId(key.measurementConsumerId)
when (principal) {
is DataProviderPrincipal -> {}
is MeasurementConsumerPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.measurementConsumerId) !=
externalMeasurementConsumerId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot get another MeasurementConsumer's Certificate"
}
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to get a MeasurementConsumer's Certificate"
}
}
}
}
is ModelProviderCertificateKey ->
externalModelProviderId = apiIdToExternalId(key.modelProviderId)
else -> failGrpc(Status.INTERNAL) { "Unsupported parent: ${key.toName()}" }
}
}
val internalCertificate =
try {
internalCertificatesStub.getCertificate(internalGetCertificateRequest)
} catch (ex: StatusException) {
when (ex.status.code) {
Status.Code.INVALID_ARGUMENT ->
failGrpc(Status.INVALID_ARGUMENT, ex) { "Required field unspecified or invalid." }
else -> failGrpc(Status.UNKNOWN, ex) { "Unknown exception." }
}
}
return internalCertificate.toCertificate()
}
override suspend fun createCertificate(request: CreateCertificateRequest): Certificate {
val dataProviderKey = DataProviderKey.fromName(request.parent)
val duchyKey = DuchyKey.fromName(request.parent)
val measurementConsumerKey = MeasurementConsumerKey.fromName(request.parent)
val modelProviderKey = ModelProviderKey.fromName(request.parent)
val principal: MeasurementPrincipal = principalFromCurrentContext
val internalCertificate = internalCertificate {
fillCertificateFromDer(request.certificate.x509Der)
when {
dataProviderKey != null -> {
externalDataProviderId = apiIdToExternalId(dataProviderKey.dataProviderId)
when (principal) {
is DataProviderPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.dataProviderId) != externalDataProviderId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot create another DataProvider's Certificate"
}
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to create a DataProvider's Certificate"
}
}
}
}
duchyKey != null -> {
externalDuchyId = duchyKey.duchyId
when (principal) {
is DuchyPrincipal -> {
if (principal.resourceKey.duchyId != externalDuchyId) {
failGrpc(Status.PERMISSION_DENIED) { "Cannot create another Duchy's Certificate" }
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to create a Duchy's Certificate"
}
}
}
}
measurementConsumerKey != null -> {
externalMeasurementConsumerId =
apiIdToExternalId(measurementConsumerKey.measurementConsumerId)
when (principal) {
is MeasurementConsumerPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.measurementConsumerId) !=
externalMeasurementConsumerId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot create another MeasurementConsumer's Certificate"
}
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to create a MeasurementConsumer's Certificate"
}
}
}
}
modelProviderKey != null -> {
externalModelProviderId = apiIdToExternalId(modelProviderKey.modelProviderId)
when (principal) {
is ModelProviderPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.modelProviderId) != externalModelProviderId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot create another ModelProvider's Certificate"
}
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to create a ModelProvider's Certificate"
}
}
}
}
else -> failGrpc(Status.INVALID_ARGUMENT) { "Parent unspecified or invalid" }
}
}
val response =
try {
internalCertificatesStub.createCertificate(internalCertificate)
} catch (ex: StatusException) {
when (ex.status.code) {
Status.Code.NOT_FOUND -> failGrpc(Status.NOT_FOUND, ex) { ex.message ?: "Not found" }
Status.Code.ALREADY_EXISTS ->
failGrpc(Status.ALREADY_EXISTS, ex) {
"Certificate with the subject key identifier (SKID) already exists."
}
Status.Code.INVALID_ARGUMENT ->
failGrpc(Status.INVALID_ARGUMENT, ex) { "Required field unspecified or invalid." }
else -> failGrpc(Status.UNKNOWN, ex) { "Unknown exception." }
}
}
return response.toCertificate()
}
override suspend fun revokeCertificate(request: RevokeCertificateRequest): Certificate {
val principal: MeasurementPrincipal = principalFromCurrentContext
val key =
grpcRequireNotNull(createResourceKey(request.name)) { "Resource name unspecified or invalid" }
grpcRequire(request.revocationState != RevocationState.REVOCATION_STATE_UNSPECIFIED) {
"Revocation State unspecified"
}
val internalRevokeCertificateRequest = revokeCertificateRequest {
when (key) {
is DataProviderCertificateKey -> {
externalDataProviderId = apiIdToExternalId(key.dataProviderId)
externalCertificateId = apiIdToExternalId(key.certificateId)
when (principal) {
is DataProviderPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.dataProviderId) != externalDataProviderId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot revoke another DataProvider's Certificate"
}
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to revoke a DataProvider's Certificate"
}
}
}
}
is DuchyCertificateKey -> {
externalDuchyId = key.duchyId
externalCertificateId = apiIdToExternalId(key.certificateId)
when (principal) {
is DuchyPrincipal -> {
if (principal.resourceKey.duchyId != externalDuchyId) {
failGrpc(Status.PERMISSION_DENIED) { "Cannot revoke another Duchy's Certificate" }
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to revoke a Duchy's Certificate"
}
}
}
}
is MeasurementConsumerCertificateKey -> {
externalMeasurementConsumerId = apiIdToExternalId(key.measurementConsumerId)
externalCertificateId = apiIdToExternalId(key.certificateId)
when (principal) {
is MeasurementConsumerPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.measurementConsumerId) !=
externalMeasurementConsumerId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot revoke another MeasurementConsumer's Certificate"
}
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to revoke a MeasurementConsumer's Certificate"
}
}
}
}
is ModelProviderCertificateKey -> {
externalModelProviderId = apiIdToExternalId(key.modelProviderId)
externalCertificateId = apiIdToExternalId(key.certificateId)
when (principal) {
is ModelProviderPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.modelProviderId) != externalModelProviderId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot revoke another ModelProvider's Certificate"
}
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to revoke a ModelProvider's Certificate"
}
}
}
}
else -> failGrpc(Status.INVALID_ARGUMENT) { "Parent unspecified or invalid" }
}
revocationState = request.revocationState.toInternal()
}
val internalCertificate =
try {
internalCertificatesStub.revokeCertificate(internalRevokeCertificateRequest)
} catch (ex: StatusException) {
when (ex.status.code) {
Status.Code.NOT_FOUND -> failGrpc(Status.NOT_FOUND, ex) { ex.message ?: "Not found" }
Status.Code.FAILED_PRECONDITION ->
failGrpc(Status.FAILED_PRECONDITION, ex) { "Certificate is in wrong State." }
else -> failGrpc(Status.UNKNOWN, ex) { "Unknown exception." }
}
}
return internalCertificate.toCertificate()
}
override suspend fun releaseCertificateHold(request: ReleaseCertificateHoldRequest): Certificate {
val principal: MeasurementPrincipal = principalFromCurrentContext
val key =
grpcRequireNotNull(createResourceKey(request.name)) { "Resource name unspecified or invalid" }
val internalReleaseCertificateHoldRequest = releaseCertificateHoldRequest {
externalCertificateId = apiIdToExternalId(key.certificateId)
when (key) {
is DataProviderCertificateKey -> {
externalDataProviderId = apiIdToExternalId(key.dataProviderId)
when (principal) {
is DataProviderPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.dataProviderId) != externalDataProviderId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot release another DataProvider's Certificate"
}
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to release a DataProvider's Certificate"
}
}
}
}
is DuchyCertificateKey -> {
externalDuchyId = key.duchyId
when (principal) {
is DuchyPrincipal -> {
if (principal.resourceKey.duchyId != externalDuchyId) {
failGrpc(Status.PERMISSION_DENIED) { "Cannot release another Duchy's Certificate" }
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to release a Duchy's Certificate"
}
}
}
}
is MeasurementConsumerCertificateKey -> {
externalMeasurementConsumerId = apiIdToExternalId(key.measurementConsumerId)
when (principal) {
is MeasurementConsumerPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.measurementConsumerId) !=
externalMeasurementConsumerId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot release another MeasurementConsumer's Certificate"
}
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to release a MeasurementConsumer's Certificate"
}
}
}
}
is ModelProviderCertificateKey -> {
externalModelProviderId = apiIdToExternalId(key.modelProviderId)
when (principal) {
is ModelProviderPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.modelProviderId) != externalModelProviderId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot release another ModelProvider's Certificate"
}
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to release a ModelProvider's Certificate"
}
}
}
}
}
}
val internalCertificate =
try {
internalCertificatesStub.releaseCertificateHold(internalReleaseCertificateHoldRequest)
} catch (ex: StatusException) {
when (ex.status.code) {
Status.Code.NOT_FOUND -> failGrpc(Status.NOT_FOUND, ex) { ex.message ?: "Not found" }
Status.Code.FAILED_PRECONDITION ->
failGrpc(Status.FAILED_PRECONDITION, ex) { "Certificate is in wrong State." }
else -> failGrpc(Status.UNKNOWN, ex) { "Unknown exception." }
}
}
return internalCertificate.toCertificate()
}
}
/** Converts an internal [InternalCertificate] to a public [Certificate]. */
private fun InternalCertificate.toCertificate(): Certificate {
val certificateApiId = externalIdToApiId(externalCertificateId)
val name =
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA")
when (parentCase) {
InternalCertificate.ParentCase.EXTERNAL_MEASUREMENT_CONSUMER_ID ->
makeMeasurementConsumerCertificateName(
externalIdToApiId(externalMeasurementConsumerId),
certificateApiId
)
InternalCertificate.ParentCase.EXTERNAL_DATA_PROVIDER_ID ->
makeDataProviderCertificateName(externalIdToApiId(externalDataProviderId), certificateApiId)
InternalCertificate.ParentCase.EXTERNAL_DUCHY_ID ->
makeDuchyCertificateName(externalDuchyId, certificateApiId)
InternalCertificate.ParentCase.EXTERNAL_MODEL_PROVIDER_ID ->
makeModelProviderCertificateName(
externalIdToApiId(externalModelProviderId),
certificateApiId
)
InternalCertificate.ParentCase.PARENT_NOT_SET ->
failGrpc(Status.INTERNAL) { "Parent missing" }
}
return certificate {
this.name = name
x509Der = [email protected]
revocationState = [email protected]()
}
}
/** Converts an internal [InternalRevocationState] to a public [RevocationState]. */
private fun InternalRevocationState.toRevocationState(): RevocationState =
when (this) {
InternalRevocationState.REVOKED -> RevocationState.REVOKED
InternalRevocationState.HOLD -> RevocationState.HOLD
InternalRevocationState.UNRECOGNIZED,
InternalRevocationState.REVOCATION_STATE_UNSPECIFIED ->
RevocationState.REVOCATION_STATE_UNSPECIFIED
}
/** Converts a public [RevocationState] to an internal [InternalRevocationState]. */
private fun RevocationState.toInternal(): InternalRevocationState =
when (this) {
RevocationState.REVOKED -> InternalRevocationState.REVOKED
RevocationState.HOLD -> InternalRevocationState.HOLD
RevocationState.UNRECOGNIZED,
RevocationState.REVOCATION_STATE_UNSPECIFIED ->
InternalRevocationState.REVOCATION_STATE_UNSPECIFIED
}
private val CERTIFICATE_PARENT_KEY_PARSERS: List<(String) -> CertificateParentKey?> =
listOf(
DataProviderCertificateKey::fromName,
DuchyCertificateKey::fromName,
MeasurementConsumerCertificateKey::fromName,
ModelProviderCertificateKey::fromName
)
/** Checks the resource name against multiple certificate [ResourceKey]s to find the right one. */
private fun createResourceKey(name: String): CertificateParentKey? {
for (parse in CERTIFICATE_PARENT_KEY_PARSERS) {
return parse(name) ?: continue
}
return null
}
| apache-2.0 | bfcdd02c21627295d3768d2ba0ce1889 | 39.342155 | 101 | 0.64997 | 5.226794 | false | false | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/view/activity/ReplyActivity.kt | 1 | 2911 | package me.ykrank.s1next.view.activity
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import me.ykrank.s1next.R
import me.ykrank.s1next.view.fragment.ReplyFragment
import org.apache.commons.lang3.StringUtils
/**
* An Activity which used to send a reply.
*/
class ReplyActivity : BaseActivity() {
private lateinit var mReplyFragment: ReplyFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_base_with_ime_panel)
setupNavCrossIcon()
val intent = intent
val threadId = intent.getStringExtra(ARG_THREAD_ID)
val quotePostId = intent.getStringExtra(ARG_QUOTE_POST_ID)
leavePageMsg("ReplyActivity##threadId:$threadId,quotePostId:$quotePostId")
val titlePrefix = if (TextUtils.isEmpty(quotePostId))
getString(R.string.reply_activity_title_prefix)
else
getString(R.string.reply_activity_quote_title_prefix,
intent.getStringExtra(ARG_QUOTE_POST_COUNT))
title = titlePrefix + StringUtils.defaultString(intent.getStringExtra(ARG_THREAD_TITLE),
StringUtils.EMPTY)
val fragmentManager = supportFragmentManager
val fragment = fragmentManager.findFragmentByTag(ReplyFragment.TAG)
if (fragment == null) {
mReplyFragment = ReplyFragment.newInstance(threadId!!,
quotePostId)
fragmentManager.beginTransaction().add(R.id.frame_layout, mReplyFragment,
ReplyFragment.TAG).commit()
} else {
mReplyFragment = fragment as ReplyFragment
}
}
/**
* Show [android.support.v7.app.AlertDialog] when reply content is not empty.
*/
override fun onBackPressed() {
if (mReplyFragment.isToolsKeyboardShowing) {
mReplyFragment.hideToolsKeyboard()
} else {
super.onBackPressed()
}
}
companion object {
private const val ARG_THREAD_ID = "thread_id"
private const val ARG_THREAD_TITLE = "thread_title"
private const val ARG_QUOTE_POST_ID = "quote_post_id"
private const val ARG_QUOTE_POST_COUNT = "quote_post_count"
fun startReplyActivityForResultMessage(activity: Activity, threadId: String, threadTitle: String?,
quotePostId: String?, quotePostCount: String?) {
val intent = Intent(activity, ReplyActivity::class.java)
intent.putExtra(ARG_THREAD_ID, threadId)
intent.putExtra(ARG_THREAD_TITLE, threadTitle)
intent.putExtra(ARG_QUOTE_POST_ID, quotePostId)
intent.putExtra(ARG_QUOTE_POST_COUNT, quotePostCount)
BaseActivity.startActivityForResultMessage(activity, intent)
}
}
}
| apache-2.0 | b5b87b534df51055d15954fb6c0a24c7 | 35.3875 | 106 | 0.661285 | 4.506192 | false | false | false | false |
PaulWoitaschek/Voice | sleepTimer/src/main/kotlin/voice/sleepTimer/SleepTimer.kt | 1 | 3663 | package voice.sleepTimer
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import de.paulwoitaschek.flowpref.Pref
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import voice.common.pref.PrefKeys
import voice.logging.core.Logger
import voice.playback.PlayerController
import voice.playback.playstate.PlayStateManager
import voice.playback.playstate.PlayStateManager.PlayState.Playing
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
@Singleton
class SleepTimer
@Inject constructor(
private val playStateManager: PlayStateManager,
private val shakeDetector: ShakeDetector,
@Named(PrefKeys.SLEEP_TIME)
private val sleepTimePref: Pref<Int>,
private val playerController: PlayerController,
) {
private val scope = MainScope()
private val sleepTime: Duration get() = sleepTimePref.value.minutes
private val fadeOutDuration = 10.seconds
private val _leftSleepTime = MutableStateFlow(Duration.ZERO)
private var leftSleepTime: Duration
get() = _leftSleepTime.value
set(value) {
_leftSleepTime.value = value
}
val leftSleepTimeFlow: Flow<Duration> get() = _leftSleepTime
fun sleepTimerActive(): Boolean = sleepJob?.isActive == true && leftSleepTime > Duration.ZERO
private var sleepJob: Job? = null
fun setActive(enable: Boolean) {
Logger.i("enable=$enable")
if (enable) {
start()
} else {
cancel()
}
}
private fun start() {
Logger.i("Starting sleepTimer. Pause in $sleepTime.")
leftSleepTime = sleepTime
playerController.setVolume(1F)
sleepJob?.cancel()
sleepJob = scope.launch {
startSleepTimerCountdown()
val shakeToResetTime = 30.seconds
Logger.d("Wait for $shakeToResetTime for a shake")
withTimeout(shakeToResetTime) {
shakeDetector.detect()
Logger.i("Shake detected. Reset sleep time")
playerController.play()
start()
}
Logger.i("exiting")
}
}
private suspend fun startSleepTimerCountdown() {
var interval = 500.milliseconds
while (leftSleepTime > Duration.ZERO) {
suspendUntilPlaying()
if (leftSleepTime < fadeOutDuration) {
interval = 200.milliseconds
updateVolumeForSleepTime()
}
delay(interval)
leftSleepTime = (leftSleepTime - interval).coerceAtLeast(Duration.ZERO)
}
playerController.pauseWithRewind(fadeOutDuration)
playerController.setVolume(1F)
}
private fun updateVolumeForSleepTime() {
val percentageOfTimeLeft = if (leftSleepTime == Duration.ZERO) {
0F
} else {
(leftSleepTime / fadeOutDuration).toFloat()
}.coerceIn(0F, 1F)
val volume = 1 - FastOutSlowInInterpolator().getInterpolation(1 - percentageOfTimeLeft)
playerController.setVolume(volume)
}
private suspend fun suspendUntilPlaying() {
if (playStateManager.playState != Playing) {
Logger.i("Not playing. Wait for Playback to continue.")
playStateManager.flow
.filter { it == Playing }
.first()
Logger.i("Playback continued.")
}
}
private fun cancel() {
sleepJob?.cancel()
leftSleepTime = Duration.ZERO
playerController.setVolume(1F)
}
}
| gpl-3.0 | e6f79882d82cc54484b3f2e7aa92f396 | 29.02459 | 95 | 0.731368 | 4.299296 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/RecommendationsService.kt | 1 | 4751 | /*****************************************************************************
* RecommendationsService.kt
*
* Copyright Β© 2014-2018 VLC authors, VideoLAN and VideoLabs
* Author: Geoffrey MΓ©tais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*/
package org.videolan.vlc
import android.annotation.TargetApi
import android.app.IntentService
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import kotlinx.coroutines.*
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.resources.*
import org.videolan.tools.getContextWithLocale
import org.videolan.vlc.gui.helpers.BitmapUtil
import org.videolan.vlc.gui.video.VideoPlayerActivity
import org.videolan.vlc.util.getAppSystemService
private const val TAG = "VLC/RecommendationsService"
private const val MAX_RECOMMENDATIONS = 3
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
class RecommendationsService : IntentService("RecommendationService"), CoroutineScope by MainScope() {
private lateinit var mNotificationManager: NotificationManager
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(newBase?.getContextWithLocale(AppContextProvider.locale))
}
override fun getApplicationContext(): Context {
return super.getApplicationContext().getContextWithLocale(AppContextProvider.locale)
}
override fun onCreate() {
super.onCreate()
mNotificationManager = getAppSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
override fun onHandleIntent(intent: Intent?) {
doRecommendations()
}
private fun buildRecommendation(mw: MediaWrapper?, id: Int, priority: Int) {
if (mw == null) return
// build the recommendation as a Notification object
val notification = NotificationCompat.BigPictureStyle(
NotificationCompat.Builder(this@RecommendationsService, "vlc_recommendations")
.setContentTitle(mw.title)
.setContentText(mw.description)
.setContentInfo(getString(R.string.app_name))
.setPriority(priority)
.setLocalOnly(true)
.setOngoing(true)
.setColor(ContextCompat.getColor(this, R.color.orange800))
.setCategory(Notification.CATEGORY_RECOMMENDATION)
.setLargeIcon(BitmapUtil.getPicture(mw))
.setSmallIcon(R.drawable.icon)
.setContentIntent(buildPendingIntent(mw, id))
).build()
// post the recommendation to the NotificationManager
mNotificationManager.notify(id, notification)
}
private fun buildPendingIntent(mw: MediaWrapper, id: Int): PendingIntent {
val intent = Intent(this@RecommendationsService, VideoPlayerActivity::class.java)
intent.action = PLAY_FROM_VIDEOGRID
intent.putExtra(PLAY_EXTRA_ITEM_LOCATION, mw.uri)
intent.putExtra(PLAY_EXTRA_ITEM_TITLE, mw.title)
intent.putExtra(PLAY_EXTRA_FROM_START, false)
return PendingIntent.getActivity(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
private fun doRecommendations() = launch {
mNotificationManager.cancelAll()
val videoList = withContext(Dispatchers.IO) { Medialibrary.getInstance().recentVideos }
if (videoList.isNullOrEmpty()) return@launch
for ((id, mediaWrapper) in videoList.withIndex()) {
buildRecommendation(mediaWrapper, id, NotificationManagerCompat.IMPORTANCE_DEFAULT)
if (id == MAX_RECOMMENDATIONS) break
}
}
override fun onDestroy() {
cancel()
super.onDestroy()
}
}
| gpl-2.0 | a47fcee360560f30480993d8a573e6d3 | 41.401786 | 103 | 0.702043 | 4.972775 | false | false | false | false |
square/sqlbrite | sqlbrite-kotlin/src/main/java/com/squareup/sqlbrite3/extensions.kt | 2 | 4059 | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE") // Extensions provided for intentional convenience.
package com.squareup.sqlbrite3
import android.database.Cursor
import android.support.annotation.RequiresApi
import com.squareup.sqlbrite3.BriteDatabase.Transaction
import com.squareup.sqlbrite3.SqlBrite.Query
import io.reactivex.Observable
import java.util.Optional
typealias Mapper<T> = (Cursor) -> T
/**
* Transforms an observable of single-row [Query] to an observable of `T` using `mapper`.
*
* It is an error for a query to pass through this operator with more than 1 row in its result set.
* Use `LIMIT 1` on the underlying SQL query to prevent this. Result sets with 0 rows do not emit
* an item.
*
* This operator ignores null cursors returned from [Query.run].
*
* @param mapper Maps the current [Cursor] row to `T`. May not return null.
*/
inline fun <T> Observable<Query>.mapToOne(noinline mapper: Mapper<T>): Observable<T>
= lift(Query.mapToOne(mapper))
/**
* Transforms an observable of single-row [Query] to an observable of `T` using `mapper`
*
* It is an error for a query to pass through this operator with more than 1 row in its result set.
* Use `LIMIT 1` on the underlying SQL query to prevent this. Result sets with 0 rows emit
* `default`.
*
* This operator emits `defaultValue` if null is returned from [Query.run].
*
* @param mapper Maps the current [Cursor] row to `T`. May not return null.
* @param default Value returned if result set is empty
*/
inline fun <T> Observable<Query>.mapToOneOrDefault(default: T, noinline mapper: Mapper<T>): Observable<T>
= lift(Query.mapToOneOrDefault(mapper, default))
/**
* Transforms an observable of single-row [Query] to an observable of `T` using `mapper.
*
* It is an error for a query to pass through this operator with more than 1 row in its result set.
* Use `LIMIT 1` on the underlying SQL query to prevent this. Result sets with 0 rows emit
* `default`.
*
* This operator ignores null cursors returned from [Query.run].
*
* @param mapper Maps the current [Cursor] row to `T`. May not return null.
*/
@RequiresApi(24)
inline fun <T> Observable<Query>.mapToOptional(noinline mapper: Mapper<T>): Observable<Optional<T>>
= lift(Query.mapToOptional(mapper))
/**
* Transforms an observable of [Query] to `List<T>` using `mapper` for each row.
*
* Be careful using this operator as it will always consume the entire cursor and create objects
* for each row, every time this observable emits a new query. On tables whose queries update
* frequently or very large result sets this can result in the creation of many objects.
*
* This operator ignores null cursors returned from [Query.run].
*
* @param mapper Maps the current [Cursor] row to `T`. May not return null.
*/
inline fun <T> Observable<Query>.mapToList(noinline mapper: Mapper<T>): Observable<List<T>>
= lift(Query.mapToList(mapper))
/**
* Run the database interactions in `body` inside of a transaction.
*
* @param exclusive Uses [BriteDatabase.newTransaction] if true, otherwise
* [BriteDatabase.newNonExclusiveTransaction].
*/
inline fun <T> BriteDatabase.inTransaction(
exclusive: Boolean = true,
body: BriteDatabase.(Transaction) -> T
): T {
val transaction = if (exclusive) newTransaction() else newNonExclusiveTransaction()
try {
val result = body(transaction)
transaction.markSuccessful()
return result
} finally {
transaction.end()
}
}
| apache-2.0 | 066001c908f5d2e1a1e7ae03fe987d6a | 37.657143 | 105 | 0.731707 | 3.952288 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/network/MRLAdapter.kt | 1 | 6850 | /*****************************************************************************
* MRLAdapter.java
*
* Copyright Β© 2014-2015 VLC authors and VideoLAN
* Author: Geoffrey MΓ©tais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*/
package org.videolan.vlc.gui.network
import android.net.Uri
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.channels.SendChannel
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.tools.Settings
import org.videolan.vlc.R
import org.videolan.vlc.databinding.MrlCardItemBinding
import org.videolan.vlc.databinding.MrlDummyItemBinding
import org.videolan.vlc.databinding.MrlItemBinding
import org.videolan.vlc.gui.DiffUtilAdapter
import org.videolan.vlc.gui.helpers.MarqueeViewHolder
import org.videolan.vlc.gui.helpers.enableMarqueeEffect
private const val TYPE_LIST = 0
private const val TYPE_CARD = 1
private const val TYPE_DUMMY = 2
internal class MRLAdapter(private val eventActor: SendChannel<MrlAction>, private val inCards: Boolean = false) : DiffUtilAdapter<MediaWrapper, RecyclerView.ViewHolder>() {
private var dummyClickListener: (() -> Unit)? = null
private val handler by lazy(LazyThreadSafetyMode.NONE) { Handler() }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return when (viewType) {
TYPE_CARD -> CardViewHolder(DataBindingUtil.inflate(inflater, R.layout.mrl_card_item, parent, false))
TYPE_LIST -> ListViewHolder(DataBindingUtil.inflate(inflater, R.layout.mrl_item, parent, false))
else -> DummyViewHolder(DataBindingUtil.inflate(inflater, R.layout.mrl_dummy_item, parent, false))
}
}
override fun getItemViewType(position: Int) = when {
dataset[position].id < 0 -> TYPE_DUMMY
inCards -> TYPE_CARD
else -> TYPE_LIST
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val item = dataset[position]
when (holder) {
is ListViewHolder -> {
holder.binding.mrlItemUri.text = Uri.decode(item.location)
holder.binding.mrlItemTitle.text = Uri.decode(item.title)
}
is CardViewHolder -> {
holder.binding.mrlItemUri.text = Uri.decode(item.location)
holder.binding.mrlItemTitle.text = Uri.decode(item.title)
}
}
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
if (Settings.listTitleEllipsize == 4) enableMarqueeEffect(recyclerView, handler)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
if (Settings.listTitleEllipsize == 4) handler.removeCallbacksAndMessages(null)
super.onDetachedFromRecyclerView(recyclerView)
}
override fun onViewRecycled(holder: RecyclerView.ViewHolder) {
if (Settings.listTitleEllipsize == 4) handler.removeCallbacksAndMessages(null)
when (holder) {
is ListViewHolder -> holder.recycle()
is CardViewHolder -> holder.recycle()
}
super.onViewRecycled(holder)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: MutableList<Any>) {
if (payloads.isNullOrEmpty()) {
onBindViewHolder(holder, position)
return
}
for (payload in payloads) {
if (payload is String) when (holder) {
is ListViewHolder -> holder.binding.mrlItemTitle.text = payload
is CardViewHolder -> holder.binding.mrlItemTitle.text = payload
}
}
}
inner class DummyViewHolder(val binding: MrlDummyItemBinding) : RecyclerView.ViewHolder(binding.root) {
init {
binding.container.setOnClickListener {
dummyClickListener?.invoke()
}
}
fun recycle() {}
}
inner class ListViewHolder(val binding: MrlItemBinding) : RecyclerView.ViewHolder(binding.root), View.OnClickListener {
init {
itemView.setOnClickListener(this)
itemView.setOnLongClickListener { eventActor.offer(ShowContext(layoutPosition)) }
binding.mrlCtx.setOnClickListener { eventActor.offer(ShowContext(layoutPosition)) }
}
override fun onClick(v: View) {
dataset[layoutPosition].let { eventActor.offer(Playmedia(it)) }
}
fun recycle() {}
}
inner class CardViewHolder(val binding: MrlCardItemBinding) : RecyclerView.ViewHolder(binding.root), View.OnClickListener, MarqueeViewHolder {
init {
binding.container.setOnClickListener(this)
binding.container.setOnLongClickListener { eventActor.offer(ShowContext(layoutPosition)) }
binding.mrlCtx.setOnClickListener { eventActor.offer(ShowContext(layoutPosition)) }
}
override fun onClick(v: View) {
dataset[layoutPosition].let { eventActor.offer(Playmedia(it)) }
}
fun recycle() {
binding.mrlItemTitle.isSelected = false
}
override val titleView = binding.mrlItemTitle
}
override fun createCB() = object : DiffCallback<MediaWrapper>() {
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
&& oldList[oldItemPosition].title == newList[newItemPosition].title
}
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int) = newList[newItemPosition].title
}
fun setOnDummyClickListener(dummyClickLisener: () -> Unit) {
this.dummyClickListener = dummyClickLisener
}
}
sealed class MrlAction
class Playmedia(val media: MediaWrapper) : MrlAction()
class ShowContext(val position: Int) : MrlAction()
| gpl-2.0 | c5c03887f5dd5589b2d25f9a2ab748c9 | 38.813953 | 172 | 0.686916 | 4.713008 | false | false | false | false |
ademar111190/Studies | Template/app/src/main/java/ademar/study/template/view/base/BaseActivity.kt | 1 | 2638 | package ademar.study.template.view.base
import ademar.study.template.App
import ademar.study.template.R
import ademar.study.template.injection.DaggerLifeCycleComponent
import ademar.study.template.injection.LifeCycleComponent
import ademar.study.template.injection.LifeCycleModule
import ademar.study.template.model.ErrorViewModel
import ademar.study.template.presenter.LoadDataView
import android.app.ActivityManager
import android.graphics.Bitmap
import android.graphics.Canvas
import android.support.v4.app.NavUtils
import android.support.v4.app.TaskStackBuilder
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
abstract class BaseActivity : AppCompatActivity(), LoadDataView {
protected val component: LifeCycleComponent by lazy {
DaggerLifeCycleComponent.builder()
.coreComponent(getApp().coreComponent)
.lifeCycleModule(makeLifeCycleModule())
.build()
}
protected open fun makeLifeCycleModule() = LifeCycleModule(this)
protected fun prepareTaskDescription(
label: String = getString(R.string.app_name),
icon: Int = R.drawable.ic_task,
colorPrimary: Int = ContextCompat.getColor(this, R.color.primary)
) {
val drawable = ContextCompat.getDrawable(this, icon)
if (drawable != null) {
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
setTaskDescription(ActivityManager.TaskDescription(label, bitmap, colorPrimary))
}
}
fun getApp() = applicationContext as App
override fun getBaseActivity() = this
override fun showLoading() {
}
override fun showRetry() {
}
override fun showContent() {
}
override fun showError(viewModel: ErrorViewModel) = AlertDialog
.Builder(this, R.style.AppAlertDialog)
.setMessage(viewModel.message)
.setPositiveButton(R.string.app_ok, null)
.create()
.show()
fun back() {
val upIntent = NavUtils.getParentActivityIntent(this) ?: intent
if (NavUtils.shouldUpRecreateTask(this, upIntent) || isTaskRoot) {
TaskStackBuilder.create(this)
.addNextIntentWithParentStack(upIntent)
.startActivities()
} else {
NavUtils.navigateUpTo(this, upIntent)
}
}
}
| mit | 943a39e7da3316c25a0eefe87b762489 | 33.710526 | 120 | 0.689538 | 4.69395 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-stale/src/main/java/net/nemerosa/ontrack/extension/stale/StalePropertyMutationProvider.kt | 1 | 1389 | package net.nemerosa.ontrack.extension.stale
import graphql.schema.GraphQLInputObjectField
import net.nemerosa.ontrack.graphql.schema.*
import net.nemerosa.ontrack.model.structure.ProjectEntity
import net.nemerosa.ontrack.model.structure.PropertyType
import org.springframework.stereotype.Component
import kotlin.reflect.KClass
@Component
class StalePropertyMutationProvider : PropertyMutationProvider<StaleProperty> {
override val propertyType: KClass<out PropertyType<StaleProperty>> = StalePropertyType::class
override val mutationNameFragment: String = "Stale"
override val inputFields: List<GraphQLInputObjectField> = listOf(
intInputField(StaleProperty::disablingDuration),
intInputField(StaleProperty::deletingDuration),
stringListInputField(StaleProperty::promotionsToKeep),
stringInputField(StaleProperty::includes),
stringInputField(StaleProperty::excludes),
)
override fun readInput(entity: ProjectEntity, input: MutationInput) = StaleProperty(
disablingDuration = input.getRequiredInt(StaleProperty::disablingDuration),
deletingDuration = input.getInt(StaleProperty::deletingDuration),
promotionsToKeep = input.getStringList(StaleProperty::promotionsToKeep),
includes = input.getString(StaleProperty::includes),
excludes = input.getString(StaleProperty::excludes),
)
} | mit | 9d40877d085a36d2f6649f79d26c5282 | 43.83871 | 97 | 0.786177 | 5.01444 | false | false | false | false |
alpha-cross/ararat | library/src/main/java/org/akop/ararat/util/HtmlUtility.kt | 1 | 11626 | // Copyright (c) Akop Karapetyan
//
// 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 org.akop.ararat.util
/**
* Provides common HTML-related functionality.
*/
object HtmlUtility {
// Almost certainly not exhaustive
private val entities = listOf(
Entity("amp", 38),
Entity("lt", 60),
Entity("gt", 62),
Entity("quot", 34),
Entity("apos", 39),
Entity("Agrave", 192),
Entity("Aacute", 193),
Entity("Acirc", 194),
Entity("Atilde", 195),
Entity("Auml", 196),
Entity("Aring", 197),
Entity("AElig", 198),
Entity("Ccedil", 199),
Entity("Egrave", 200),
Entity("Eacute", 201),
Entity("Ecirc", 202),
Entity("Euml", 203),
Entity("Igrave", 204),
Entity("Iacute", 205),
Entity("Icirc", 206),
Entity("Iuml", 207),
Entity("ETH", 208),
Entity("Ntilde", 209),
Entity("Ograve", 210),
Entity("Oacute", 211),
Entity("Ocirc", 212),
Entity("Otilde", 213),
Entity("Ouml", 214),
Entity("Oslash", 216),
Entity("Ugrave", 217),
Entity("Uacute", 218),
Entity("Ucirc", 219),
Entity("Uuml", 220),
Entity("Yacute", 221),
Entity("THORN", 222),
Entity("szlig", 223),
Entity("agrave", 224),
Entity("aacute", 225),
Entity("acirc", 226),
Entity("atilde", 227),
Entity("auml", 228),
Entity("aring", 229),
Entity("aelig", 230),
Entity("ccedil", 231),
Entity("egrave", 232),
Entity("eacute", 233),
Entity("ecirc", 234),
Entity("euml", 235),
Entity("igrave", 236),
Entity("iacute", 237),
Entity("icirc", 238),
Entity("iuml", 239),
Entity("eth", 240),
Entity("ntilde", 241),
Entity("ograve", 242),
Entity("oacute", 243),
Entity("ocirc", 244),
Entity("otilde", 245),
Entity("ouml", 246),
Entity("oslash", 248),
Entity("ugrave", 249),
Entity("uacute", 250),
Entity("ucirc", 251),
Entity("uuml", 252),
Entity("yacute", 253),
Entity("thorn", 254),
Entity("yuml", 255),
Entity("nbsp", 160),
Entity("iexcl", 161),
Entity("cent", 162),
Entity("pound", 163),
Entity("curren", 164),
Entity("yen", 165),
Entity("brvbar", 166),
Entity("sect", 167),
Entity("uml", 168),
Entity("copy", 169),
Entity("ordf", 170),
Entity("laquo", 171),
Entity("not", 172),
Entity("shy", 173),
Entity("reg", 174),
Entity("macr", 175),
Entity("deg", 176),
Entity("plusmn", 177),
Entity("sup2", 178),
Entity("sup3", 179),
Entity("acute", 180),
Entity("micro", 181),
Entity("para", 182),
Entity("cedil", 184),
Entity("sup1", 185),
Entity("ordm", 186),
Entity("raquo", 187),
Entity("frac14", 188),
Entity("frac12", 189),
Entity("frac34", 190),
Entity("iquest", 191),
Entity("times", 215),
Entity("divide", 247),
Entity("forall", 8704),
Entity("part", 8706),
Entity("exist", 8707),
Entity("empty", 8709),
Entity("nabla", 8711),
Entity("isin", 8712),
Entity("notin", 8713),
Entity("ni", 8715),
Entity("prod", 8719),
Entity("sum", 8721),
Entity("minus", 8722),
Entity("lowast", 8727),
Entity("radic", 8730),
Entity("prop", 8733),
Entity("infin", 8734),
Entity("ang", 8736),
Entity("and", 8743),
Entity("or", 8744),
Entity("cap", 8745),
Entity("cup", 8746),
Entity("int", 8747),
Entity("there4", 8756),
Entity("sim", 8764),
Entity("cong", 8773),
Entity("asymp", 8776),
Entity("ne", 8800),
Entity("equiv", 8801),
Entity("le", 8804),
Entity("ge", 8805),
Entity("sub", 8834),
Entity("sup", 8835),
Entity("nsub", 8836),
Entity("sube", 8838),
Entity("supe", 8839),
Entity("oplus", 8853),
Entity("otimes", 8855),
Entity("perp", 8869),
Entity("sdot", 8901),
Entity("Alpha", 913),
Entity("Beta", 914),
Entity("Gamma", 915),
Entity("Delta", 916),
Entity("Epsilon", 917),
Entity("Zeta", 918),
Entity("Eta", 919),
Entity("Theta", 920),
Entity("Iota", 921),
Entity("Kappa", 922),
Entity("Lambda", 923),
Entity("Mu", 924),
Entity("Nu", 925),
Entity("Xi", 926),
Entity("Omicron", 927),
Entity("Pi", 928),
Entity("Rho", 929),
Entity("Sigma", 931),
Entity("Tau", 932),
Entity("Upsilon", 933),
Entity("Phi", 934),
Entity("Chi", 935),
Entity("Psi", 936),
Entity("Omega", 937),
Entity("alpha", 945),
Entity("beta", 946),
Entity("gamma", 947),
Entity("delta", 948),
Entity("epsilon", 949),
Entity("zeta", 950),
Entity("eta", 951),
Entity("theta", 952),
Entity("iota", 953),
Entity("kappa", 954),
Entity("lambda", 955),
Entity("mu", 956),
Entity("nu", 957),
Entity("xi", 958),
Entity("omicron", 959),
Entity("pi", 960),
Entity("rho", 961),
Entity("sigmaf", 962),
Entity("sigma", 963),
Entity("tau", 964),
Entity("upsilon", 965),
Entity("phi", 966),
Entity("chi", 967),
Entity("psi", 968),
Entity("omega", 969),
Entity("thetasym", 977),
Entity("upsih", 978),
Entity("piv", 982),
Entity("OElig", 338),
Entity("oelig", 339),
Entity("Scaron", 352),
Entity("scaron", 353),
Entity("Yuml", 376),
Entity("fnof", 402),
Entity("circ", 710),
Entity("tilde", 732),
Entity("ensp", 8194),
Entity("emsp", 8195),
Entity("thinsp", 8201),
Entity("zwnj", 8204),
Entity("zwj", 8205),
Entity("lrm", 8206),
Entity("rlm", 8207),
Entity("ndash", 8211),
Entity("mdash", 8212),
Entity("lsquo", 8216),
Entity("rsquo", 8217),
Entity("sbquo", 8218),
Entity("ldquo", 8220),
Entity("rdquo", 8221),
Entity("bdquo", 8222),
Entity("dagger", 8224),
Entity("Dagger", 8225),
Entity("bull", 8226),
Entity("hellip", 8230),
Entity("permil", 8240),
Entity("prime", 8242),
Entity("Prime", 8243),
Entity("lsaquo", 8249),
Entity("rsaquo", 8250),
Entity("oline", 8254),
Entity("euro", 8364),
Entity("trade", 8482),
Entity("larr", 8592),
Entity("uarr", 8593),
Entity("rarr", 8594),
Entity("darr", 8595),
Entity("harr", 8596),
Entity("crarr", 8629),
Entity("lceil", 8968),
Entity("rceil", 8969),
Entity("lfloor", 8970),
Entity("rfloor", 8971),
Entity("loz", 9674),
Entity("spades", 9824),
Entity("clubs", 9827),
Entity("hearts", 9829),
Entity("diams", 9830)
).sortedBy { it.name }
/**
* Strips named and numeric HTML entities from a string, replacing with
* Unicode equivalents where possible, removing where no known match.
* Badly formatted entities (e.g. "&") are not modified.
*
* As dictated by HTML, entity names are case-sensitive.
*/
fun stripEntities(s: String): String {
val out = CharArray(s.length)
var r = -1
var w = 0
outer@while (++r < s.length) {
val ch = s[r]
if (ch == '&') {
if (r + 1 < s.length && s[r + 1] == '#') {
// Potential numeric entity
var j = r + 1
inner@while (++j < s.length) when (s[j]) {
';' -> {
if (r + 2 < j)
out[w++] = s.substring(r + 2 until j).toInt().toChar()
r = j
continue@outer
}
in '0'..'9' -> {}
else -> break@inner
}
} else {
// Potential named entity
var j = r
inner@while (++j < s.length) when (s[j]) {
';' -> {
// potential valid entity name
val name = s.substring(r + 1 until j)
val p = entities.binarySearchBy(name) { it.name }
if (p >= 0)
out[w++] = entities[p].code.toChar()
r = j
continue@outer
}
in 'a'..'z', in 'A'..'Z', in '0'..'9' -> {}
else -> break@inner
}
}
}
out[w++] = ch
}
return String(out, 0, w)
}
private class Entity(val name: String,
val code: Int)
}
/**
* Extension method for [HtmlUtility.stripEntities].
*/
fun String.stripHtmlEntities(): String = HtmlUtility.stripEntities(this)
| mit | 4f5b1f3f15af825279564833bcad53fb | 33.808383 | 86 | 0.44151 | 4.328369 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/etm/pages/EtmBackgroundJobsFragment.kt | 1 | 5851 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz <[email protected]>
* Copyright (C) 2020 Chris Narkiewicz
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.etm.pages
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.nextcloud.client.etm.EtmBaseFragment
import com.nextcloud.client.jobs.JobInfo
import com.owncloud.android.R
import java.text.SimpleDateFormat
import java.util.Locale
class EtmBackgroundJobsFragment : EtmBaseFragment() {
class Adapter(private val inflater: LayoutInflater) : RecyclerView.Adapter<Adapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val uuid = view.findViewById<TextView>(R.id.etm_background_job_uuid)
val name = view.findViewById<TextView>(R.id.etm_background_job_name)
val user = view.findViewById<TextView>(R.id.etm_background_job_user)
val state = view.findViewById<TextView>(R.id.etm_background_job_state)
val started = view.findViewById<TextView>(R.id.etm_background_job_started)
val progress = view.findViewById<TextView>(R.id.etm_background_job_progress)
private val progressRow = view.findViewById<View>(R.id.etm_background_job_progress_row)
var progressEnabled: Boolean = progressRow.visibility == View.VISIBLE
get() {
return progressRow.visibility == View.VISIBLE
}
set(value) {
field = value
progressRow.visibility = if (value) {
View.VISIBLE
} else {
View.GONE
}
}
}
private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:MM:ssZ", Locale.getDefault())
var backgroundJobs: List<JobInfo> = emptyList()
set(value) {
field = value
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = inflater.inflate(R.layout.etm_background_job_list_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return backgroundJobs.size
}
override fun onBindViewHolder(vh: ViewHolder, position: Int) {
val info = backgroundJobs[position]
vh.uuid.text = info.id.toString()
vh.name.text = info.name
vh.user.text = info.user
vh.state.text = info.state
vh.started.text = dateFormat.format(info.started)
if (info.progress >= 0) {
vh.progressEnabled = true
vh.progress.text = info.progress.toString()
} else {
vh.progressEnabled = false
}
}
}
private lateinit var list: RecyclerView
private lateinit var adapter: Adapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_etm_background_jobs, container, false)
adapter = Adapter(inflater)
list = view.findViewById(R.id.etm_background_jobs_list)
list.layoutManager = LinearLayoutManager(context)
list.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
list.adapter = adapter
vm.backgroundJobs.observe(viewLifecycleOwner, Observer { onBackgroundJobsUpdated(it) })
return view
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_etm_background_jobs, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.etm_background_jobs_cancel -> {
vm.cancelAllJobs(); true
}
R.id.etm_background_jobs_prune -> {
vm.pruneJobs(); true
}
R.id.etm_background_jobs_start_test -> {
vm.startTestJob(periodic = false); true
}
R.id.etm_background_jobs_schedule_test -> {
vm.startTestJob(periodic = true); true
}
R.id.etm_background_jobs_cancel_test -> {
vm.cancelTestJob(); true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun onBackgroundJobsUpdated(backgroundJobs: List<JobInfo>) {
adapter.backgroundJobs = backgroundJobs
}
}
| gpl-2.0 | 81836e713387e33b4595c8ae146f4b99 | 38.533784 | 116 | 0.647923 | 4.654733 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/main/DateListFragment.kt | 1 | 2520 | package de.xikolo.controllers.main
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import de.xikolo.R
import de.xikolo.controllers.course.CourseActivityAutoBundle
import de.xikolo.extensions.observe
import de.xikolo.managers.UserManager
import de.xikolo.models.CourseDate
import de.xikolo.viewmodels.main.DateListViewModel
class DateListFragment : MainFragment<DateListViewModel>() {
companion object {
val TAG: String = DateListFragment::class.java.simpleName
}
@BindView(R.id.content_view)
lateinit var recyclerView: RecyclerView
private lateinit var adapter: DateListAdapter
override val layoutResource: Int = R.layout.fragment_date_list
override fun createViewModel(): DateListViewModel {
return DateListViewModel()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onStart() {
super.onStart()
activityCallback?.onFragmentAttached(R.id.navigation_dates)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
adapter = DateListAdapter(object : DateListAdapter.OnDateClickListener {
override fun onCourseClicked(courseId: String?) {
startActivity(
CourseActivityAutoBundle.builder().courseId(courseId).build(activity!!)
)
}
})
recyclerView.layoutManager = LinearLayoutManager(activity)
recyclerView.setHasFixedSize(true)
recyclerView.adapter = adapter
viewModel.dates
.observe(viewLifecycleOwner) {
showDateList(it)
}
}
private fun showDateList(list: List<CourseDate>) {
if (!UserManager.isAuthorized) {
hideContent()
showLoginRequired()
} else if (list.isEmpty()) {
hideContent()
showEmptyMessage(R.string.empty_message_dates)
} else {
adapter.update(viewModel.sectionedDateList)
showContent()
}
}
override fun onLoginStateChange(isLoggedIn: Boolean) {
super.onLoginStateChange(isLoggedIn)
// refreshing itself does not trigger a change of the dates, so it is done manually
showDateList(listOf())
}
}
| bsd-3-clause | 015a7c3d929ccc0661838fac43caf2cf | 29 | 91 | 0.680159 | 5.142857 | false | false | false | false |
Orchextra/orchextra-android-sdk | core/src/main/java/com/gigigo/orchextra/core/utils/FileLogging.kt | 1 | 3862 | /*
* Created by Orchextra
*
* Copyright (C) 2017 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.core.utils
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.util.Log
import com.gigigo.orchextra.core.Orchextra
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class FileLogging(private val context: Context) {
fun log(priority: Int, tag: String, message: String, t: Throwable? = null) {
val fileNameTimeStamp = SimpleDateFormat("dd-MM-yyyy", Locale.US).format(Date())
val logFile = File("sdcard/ox_log_$fileNameTimeStamp.md")
if (!logFile.exists()) {
try {
logFile.createNewFile()
writeHeader(logFile)
} catch (e: IOException) {
Log.e("FileLogging", e.message ?: "no message")
}
}
writeLog(context, logFile, priority, tag, message)
}
private fun writeHeader(file: File) {
try {
val buf = BufferedWriter(FileWriter(file, true))
buf.append("# Ox log")
buf.newLine()
buf.append("Time | Battery | Status | Priority | Tag | Log")
buf.newLine()
buf.append(":---:|:---:|:---:")
buf.newLine()
buf.close()
} catch (e: IOException) {
Log.e("", e.message ?: "no message")
}
}
private fun writeLog(
context: Context,
file: File,
priority: Int,
tag: String,
message: String
) {
try {
val logTimeStamp =
SimpleDateFormat("E MMM dd yyyy 'at' hh:mm:ss:SSS aaa", Locale.US).format(
Date()
)
val batteryLevel = getBatteryLevel(context)
val status = if (Orchextra.isActivityRunning()) {
"foreground"
} else {
"background"
}
val buf = BufferedWriter(FileWriter(file, true))
buf.append(
"$logTimeStamp | $batteryLevel % | $status | ${getPriority(priority)} | $tag | $message"
)
buf.newLine()
buf.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
fun getBatteryLevel(context: Context): Float {
val batteryIntent =
context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
val level = batteryIntent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
val scale = batteryIntent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1
// Error checking that probably isn't needed but I added just in case.
return if (level == -1 || scale == -1) {
50.0f
} else level.toFloat() / scale.toFloat() * 100.0f
}
private fun getPriority(priority: Int) = when (priority) {
2 -> "VERBOSE"
3 -> "DEBUG"
4 -> "INFO"
5 -> "WARN"
6 -> "ERROR"
7 -> "ASSERT"
else -> "UNKNOWN"
}
companion object {
private val TAG = FileLogging::class.java.simpleName
}
} | apache-2.0 | 2e0c91a50c0a8a3d93e7436fac93d28f | 29.179688 | 104 | 0.584671 | 4.339326 | false | false | false | false |
Kotlin/kotlin-coroutines | examples/channel/channel-example-boring.kt | 1 | 794 | package channel.boring
import channel.*
import delay.*
import java.util.*
// https://talks.golang.org/2012/concurrency.slide#25
suspend fun boring(msg: String): ReceiveChannel<String> { // returns receive-only channel of strings
val c = Channel<String>()
val rnd = Random()
go {
var i = 0
while (true) {
c.send("$msg $i")
delay(rnd.nextInt(1000).toLong())
i++
}
}
return c // return the channel to the caller
}
// https://talks.golang.org/2012/concurrency.slide#26
fun main(args: Array<String>) = mainBlocking {
val joe = boring("Joe")
val ann = boring("Ann")
for (i in 0..4) {
println(joe.receive())
println(ann.receive())
}
println("Your're both boring; I'm leaving.")
}
| apache-2.0 | fe9fcc50f6dc597c9050cc5be4888e95 | 23.060606 | 100 | 0.593199 | 3.59276 | false | false | false | false |
thatJavaNerd/JRAW | lib/src/test/kotlin/net/dean/jraw/test/integration/EmojiReferenceTest.kt | 1 | 1998 | package net.dean.jraw.test.integration
import com.winterbe.expekt.should
import net.dean.jraw.ApiException
import net.dean.jraw.test.CredentialsUtil.moderationSubreddit
import net.dean.jraw.test.TestConfig.reddit
import net.dean.jraw.test.expectException
import net.dean.jraw.test.randomName
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import java.io.File
class EmojiReferenceTest : Spek({
describe("list") {
it("should provide a list of emojis") {
reddit.subreddit("pics").emoji().list().should.have.size.above(0)
}
}
describe("upload/delete") {
it("should make the emoji available to the subreddit") {
val testEmoji = File(EmojiReferenceTest::class.java.getResource("/emoji.png").file)
val emojiName = randomName()
val sr = reddit.subreddit(moderationSubreddit)
val ref = sr.emoji()
val expectedNamespace = sr.about().fullName
/** Query the emojis and find the one that we've uploaded */
fun findEmoji() = ref.list().find { it.namespace == expectedNamespace && it.name == emojiName }
// Sanity check
testEmoji.isFile.should.be.`true`
// Upload the emoji
ref.upload(testEmoji, emojiName)
// Give reddit some time to work
Thread.sleep(3000)
// Make sure it's here
val uploadedEmoji = findEmoji()!!
// Test delete() and clean up the emoji at the same time
ref.delete(uploadedEmoji.name)
// Make sure it was deleted
findEmoji().should.be.`null`
}
}
describe("delete") {
it("should throw an ApiException when trying to delete an emoji that doesn\'t exist") {
expectException(ApiException::class) {
reddit.subreddit(moderationSubreddit).emoji().delete("foo")
}
}
}
})
| mit | 3ea2faa7a1c6ca847f1c8f6a0e07006b | 32.864407 | 107 | 0.625626 | 4.343478 | false | true | false | false |
Andr3Carvalh0/mGBA | app/src/main/java/io/mgba/base/BaseActivity.kt | 1 | 2960 | package io.mgba.base
import android.os.Bundle
import android.view.View
import android.app.Activity
import android.os.Build
import android.os.Build.VERSION_CODES.M
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import com.google.android.material.snackbar.Snackbar
import io.mgba.R
import io.mgba.utilities.device.ResourcesManager
import io.mgba.widgets.MaterialSnackbar
abstract class BaseActivity<T : ViewModel> : AppCompatActivity() {
lateinit var vm: T
override fun onCreate(savedInstanceState: Bundle?){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO)
super.onCreate(savedInstanceState)
setContentView(getLayout())
vm = ViewModelProviders.of(this).get(getViewModel())
colorizeStatusbar()
onCreate()
}
private fun colorizeStatusbar() {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = ResourcesManager.getColor(R.color.statusbarColor)
}
open fun onCreate(){}
abstract fun getLayout(): Int
abstract fun getViewModel(): Class<T>
open fun close() { finish() }
fun showSnackbarAlert(view: View, text: String) {
MaterialSnackbar.notify(view)
.title(text)
.build()
.show()
}
fun showSnackbarAlert(view: View, text: String, onClickText: String, onClick: (View) -> Unit, onDismiss: () -> Unit) {
MaterialSnackbar.notify(view)
.title(text)
.onClick(onClickText, onClick)
.build()
.also {
it.addCallback(object: Snackbar.Callback() {
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
super.onDismissed(transientBottomBar, event)
if(event == DISMISS_EVENT_TIMEOUT) {
onDismiss.invoke()
}
}
})
}
.show()
}
fun setThemeLightMode() {
delegate.setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
fun setThemeDarkMode() {
delegate.setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
fun setThemeAutoMode() {
delegate.setLocalNightMode(AppCompatDelegate.MODE_NIGHT_AUTO)
}
fun hideKeyboard(view: View) {
val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
}
| mpl-2.0 | 0b0e87b38af406d8e98aade391f6d39b | 31.173913 | 122 | 0.655068 | 5 | false | false | false | false |
apixandru/intellij-community | update-server-mock/src/main/java/com/intellij/updater/mock/Generator.kt | 16 | 1545 | /*
* Copyright (c) 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.updater.mock
class Generator {
private val patch = this.javaClass.classLoader.getResourceAsStream("patch/patch.jar").use { it.readBytes() }
fun generateXml(productCode: String, buildId: String, eap: Boolean): String {
val status = if (eap) "eap" else "release"
return """
<!DOCTYPE products SYSTEM "updates.dtd">
<products>
<product name="Mock Product">
<code>$productCode</code>
<channel id="MOCK" status="$status" licensing="$status">
<build number="9999.0.0" version="Mock">
<message><![CDATA[A mock update. For testing purposes only.]]></message>
<button name="Download" url="https://www.jetbrains.com/" download="true"/>
<patch from="$buildId" size="from 0 to β"/>
</build>
</channel>
</product>
</products>""".trimIndent()
}
fun generatePatch(): ByteArray = patch
} | apache-2.0 | d11630c12f90a58f03a00ba9918859da | 37.6 | 110 | 0.655217 | 4.15903 | false | false | false | false |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/ide/inspections/fixes/SubstituteTextFix.kt | 1 | 2368 | package org.jetbrains.fortran.ide.inspections.fixes
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.SmartPsiElementPointer
/**
* Fix that removes the given range from the document and places a text onto its place.
* @param text The text that will be placed starting from `range.startOffset`. If `null`, no text will be inserted.
* @param fixName The name to use for the fix instead of the default one to better fit the inspection.
*/
class SubstituteTextFix : LocalQuickFix {
private val startRangeElementPointer: SmartPsiElementPointer<PsiElement>
private val endRangeElementPointer: SmartPsiElementPointer<PsiElement>
private val text: String?
private val fixName: String
constructor(startRangeElementPointer: SmartPsiElementPointer<PsiElement>,
endRangeElementPointer: SmartPsiElementPointer<PsiElement>,
text: String?, fixName: String
) {
this.startRangeElementPointer = startRangeElementPointer
this.endRangeElementPointer = endRangeElementPointer
this.text = text
this.fixName = fixName
}
constructor(rangeElementPointer: SmartPsiElementPointer<PsiElement>,
text: String?, fixName: String
) {
this.startRangeElementPointer = rangeElementPointer
this.endRangeElementPointer = rangeElementPointer
this.text = text
this.fixName = fixName
}
override fun getName() = fixName
override fun getFamilyName() = "Substitute one text to another"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val startRangeElement = startRangeElementPointer.element
val endRangeElement = endRangeElementPointer.element
if (startRangeElement == null || endRangeElement == null) return
val file = descriptor.psiElement.containingFile
val document = PsiDocumentManager.getInstance(project).getDocument(file)
document?.deleteString(startRangeElement.textOffset, endRangeElement.textOffset + endRangeElement.textLength)
if (text == null || document == null) return
document.insertString(startRangeElement.textOffset, text)
}
}
| apache-2.0 | 480e4a5a1a2ceba53a9dd01f434dcf23 | 43.679245 | 117 | 0.746199 | 5.049041 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/stdext/Concurrency.kt | 3 | 3792 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.stdext
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.util.ProgressIndicatorUtils
import java.util.*
import java.util.concurrent.*
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.Lock
import kotlin.reflect.KProperty
/**
* A container for an immutable value, which allows
* reading and updating value safely concurrently.
* [AsyncValue] is similar to Clojure's atom.
*
* [updateAsync] method is used to schedule a modification
* of the form `(T) -> Promise<T>`. It is guaranteed that
* all updates are serialized.
*/
class AsyncValue<T>(initial: T) {
@Volatile
private var current: T = initial
private val updates: Queue<(T) -> CompletableFuture<Unit>> = ConcurrentLinkedQueue()
private var running: Boolean = false
val currentState: T get() = current
fun updateAsync(updater: (T) -> CompletableFuture<T>): CompletableFuture<T> {
val result = CompletableFuture<T>()
updates.add { current ->
updater(current)
.handle { next, err ->
if (err == null) {
this.current = next
result.complete(next)
} else {
// Do not log `ProcessCanceledException`
if (!(err is ProcessCanceledException || err is CompletionException && err.cause is ProcessCanceledException)) {
LOG.error(err)
}
result.completeExceptionally(err)
}
Unit
}
}
startUpdateProcessing()
return result
}
fun updateSync(updater: (T) -> T): CompletableFuture<T> =
updateAsync { CompletableFuture.completedFuture(updater(it)) }
@Synchronized
private fun startUpdateProcessing() {
if (running || updates.isEmpty()) return
val nextUpdate = updates.remove()
running = true
nextUpdate(current)
.whenComplete { _, _ ->
stopUpdateProcessing()
startUpdateProcessing()
}
}
@Synchronized
private fun stopUpdateProcessing() {
check(running)
running = false
}
companion object {
private val LOG: Logger = logger<AsyncValue<*>>()
}
}
class ThreadLocalDelegate<T>(initializer: () -> T) {
private val tl: ThreadLocal<T> = ThreadLocal.withInitial(initializer)
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return tl.get()
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
tl.set(value)
}
}
@Throws(TimeoutException::class, ExecutionException::class, InterruptedException::class)
fun <V> Future<V>.getWithCheckCanceled(timeoutMillis: Long): V {
val deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis)
while (true) {
try {
return get(10, TimeUnit.MILLISECONDS)
} catch (e: TimeoutException) {
ProgressManager.checkCanceled()
if (System.nanoTime() >= deadline) {
throw e
}
}
}
}
fun <T> Lock.withLockAndCheckingCancelled(action: () -> T): T =
ProgressIndicatorUtils.computeWithLockAndCheckingCanceled<T, Exception>(this, 10, TimeUnit.MILLISECONDS, action)
fun Condition.awaitWithCheckCancelled() {
ProgressIndicatorUtils.awaitWithCheckCanceled(this)
}
| mit | 1680828263a79c1e59b4291e25f93864 | 31.135593 | 136 | 0.627637 | 4.734082 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/ui/simple/SimpleEventLogger.kt | 1 | 7733 | /*
Copyright 2017-2020 Charles Korn.
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 batect.ui.simple
import batect.config.BuildImage
import batect.config.Container
import batect.config.PullImage
import batect.config.SetupCommand
import batect.execution.RunOptions
import batect.execution.model.events.ContainerBecameHealthyEvent
import batect.execution.model.events.ContainerStartedEvent
import batect.execution.model.events.ImageBuiltEvent
import batect.execution.model.events.ImagePulledEvent
import batect.execution.model.events.RunningSetupCommandEvent
import batect.execution.model.events.SetupCommandsCompletedEvent
import batect.execution.model.events.StepStartingEvent
import batect.execution.model.events.TaskEvent
import batect.execution.model.events.TaskFailedEvent
import batect.execution.model.steps.BuildImageStep
import batect.execution.model.steps.CleanupStep
import batect.execution.model.steps.CreateContainerStep
import batect.execution.model.steps.PullImageStep
import batect.execution.model.steps.RunContainerStep
import batect.execution.model.steps.TaskStep
import batect.os.Command
import batect.ui.Console
import batect.ui.EventLogger
import batect.ui.FailureErrorMessageFormatter
import batect.ui.containerio.TaskContainerOnlyIOStreamingOptions
import batect.ui.humanise
import batect.ui.text.Text
import batect.ui.text.TextRun
import java.time.Duration
class SimpleEventLogger(
val containers: Set<Container>,
val taskContainer: Container,
val failureErrorMessageFormatter: FailureErrorMessageFormatter,
val runOptions: RunOptions,
val console: Console,
val errorConsole: Console,
override val ioStreamingOptions: TaskContainerOnlyIOStreamingOptions
) : EventLogger {
private val commands = mutableMapOf<Container, Command?>()
private var haveStartedCleanUp = false
private val lock = Object()
override fun postEvent(event: TaskEvent) {
synchronized(lock) {
when (event) {
is TaskFailedEvent -> logTaskFailure(failureErrorMessageFormatter.formatErrorMessage(event, runOptions))
is ImageBuiltEvent -> logImageBuilt(event.source)
is ImagePulledEvent -> logImagePulled(event.source)
is ContainerStartedEvent -> logContainerStarted(event.container)
is ContainerBecameHealthyEvent -> logContainerBecameHealthy(event.container)
is RunningSetupCommandEvent -> logRunningSetupCommand(event.container, event.command, event.commandIndex)
is SetupCommandsCompletedEvent -> logSetupCommandsCompleted(event.container)
is StepStartingEvent -> logStepStarting(event.step)
}
}
}
private fun logTaskFailure(message: TextRun) {
errorConsole.println()
errorConsole.println(message)
}
private fun logStepStarting(step: TaskStep) {
when (step) {
is BuildImageStep -> logImageBuildStarting(step.source)
is PullImageStep -> logImagePullStarting(step.source)
is RunContainerStep -> logContainerRunning(step.container)
is CreateContainerStep -> commands[step.container] = step.config.command
is CleanupStep -> logCleanUpStarting()
}
}
private fun logImageBuildStarting(source: BuildImage) {
containers
.filter { it.imageSource == source }
.forEach {
console.println(Text.white(Text("Building ") + Text.bold(it.name) + Text("...")))
}
}
private fun logImageBuilt(source: BuildImage) {
containers
.filter { it.imageSource == source }
.forEach {
console.println(Text.white(Text("Built ") + Text.bold(it.name) + Text(".")))
}
}
private fun logImagePullStarting(source: PullImage) {
console.println(Text.white(Text("Pulling ") + Text.bold(source.imageName) + Text("...")))
}
private fun logImagePulled(source: PullImage) {
console.println(Text.white(Text("Pulled ") + Text.bold(source.imageName) + Text(".")))
}
private fun logContainerRunning(container: Container) {
if (container == taskContainer) {
logTaskContainerRunning(container, commands[container])
} else {
logDependencyContainerStarting(container)
}
}
private fun logTaskContainerRunning(container: Container, command: Command?) {
val commandText = if (command != null) {
Text.bold(command.originalCommand) + Text(" in ")
} else {
TextRun()
}
console.println(Text.white(Text("Running ") + commandText + Text.bold(container.name) + Text("...")))
}
private fun logDependencyContainerStarting(container: Container) {
console.println(Text.white(Text("Starting ") + Text.bold(container.name) + Text("...")))
}
private fun logContainerStarted(container: Container) {
if (container == taskContainer) {
return
}
console.println(Text.white(Text("Started ") + Text.bold(container.name) + Text(".")))
}
private fun logContainerBecameHealthy(container: Container) {
if (container == taskContainer) {
return
}
console.println(Text.white(Text.bold(container.name) + Text(" has become healthy.")))
}
private fun logRunningSetupCommand(container: Container, command: SetupCommand, index: Int) {
if (container == taskContainer) {
return
}
console.println(Text.white(Text("Running setup command ") + Text.bold(command.command.originalCommand) + Text(" (${index + 1} of ${container.setupCommands.size}) in ") + Text.bold(container.name) + Text("...")))
}
private fun logSetupCommandsCompleted(container: Container) {
if (container == taskContainer) {
return
}
console.println(Text.white(Text.bold(container.name) + Text(" has completed all setup commands.")))
}
private fun logCleanUpStarting() {
if (haveStartedCleanUp) {
return
}
console.println()
console.println(Text.white("Cleaning up..."))
haveStartedCleanUp = true
}
override fun onTaskFailed(taskName: String, manualCleanupInstructions: TextRun) {
if (manualCleanupInstructions != TextRun()) {
errorConsole.println()
errorConsole.println(manualCleanupInstructions)
}
errorConsole.println()
errorConsole.println(Text.red(Text("The task ") + Text.bold(taskName) + Text(" failed. See above for details.")))
}
override fun onTaskStarting(taskName: String) {
console.println(Text.white(Text("Running ") + Text.bold(taskName) + Text("...")))
}
override fun onTaskFinished(taskName: String, exitCode: Int, duration: Duration) {
console.println(Text.white(Text.bold(taskName) + Text(" finished with exit code $exitCode in ${duration.humanise()}.")))
}
override fun onTaskFinishedWithCleanupDisabled(manualCleanupInstructions: TextRun) {
errorConsole.println()
errorConsole.println(manualCleanupInstructions)
}
}
| apache-2.0 | 9d329634947e2bd647771164f5adf145 | 37.093596 | 219 | 0.688349 | 4.715244 | false | false | false | false |
rejasupotaro/octodroid | app/src/main/kotlin/com/example/octodroid/activities/LoginActivity.kt | 1 | 3053 | package com.example.octodroid.activities
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.view.MenuItem
import android.widget.EditText
import butterknife.bindView
import com.example.octodroid.R
import com.example.octodroid.data.GitHub
import com.example.octodroid.data.prefs.SessionPrefs
import com.example.octodroid.views.helpers.ProgressDialogHelper
import com.example.octodroid.views.helpers.ToastHelper
import rx.subscriptions.Subscriptions
class LoginActivity : AppCompatActivity() {
val usernameEditText: EditText by bindView(R.id.username_edit_text)
val passwordEditText: EditText by bindView(R.id.password_edit_text)
private var subscription = Subscriptions.empty()
private var progressDialogHelper: ProgressDialogHelper? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
setupActionBar()
setupViews()
}
override fun onDestroy() {
subscription.unsubscribe()
super.onDestroy()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
private fun setupActionBar() {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
}
private fun login(username: String, password: String) {
progressDialogHelper?.show()
GitHub.client().authorization(username, password)
subscription = GitHub.client().user().subscribe({ r ->
progressDialogHelper?.dismiss()
if (r.isSuccessful) {
loginSucceeded(username, password)
} else {
ToastHelper.showLoginFailed(this)
}
})
}
private fun loginSucceeded(username: String, password: String) {
val prefs = SessionPrefs.get(this)
prefs.username = username
prefs.password = password
MainActivity.launch(this)
finish()
}
private fun setupViews() {
progressDialogHelper = ProgressDialogHelper(this)
findViewById(R.id.login_button).setOnClickListener {
val username = usernameEditText.text.toString()
val password = passwordEditText.text.toString()
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
return@setOnClickListener
}
login(username, password)
}
}
companion object {
fun launch(context: Context) {
val intent = Intent(context, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
context.startActivity(intent)
}
}
}
| mit | ef014186877a304616d193b271019bdd | 30.802083 | 91 | 0.666557 | 4.892628 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/custom/RoundedTransformation.kt | 1 | 1132 | package com.sedsoftware.yaptalker.presentation.custom
import android.graphics.Bitmap
import android.graphics.Bitmap.Config
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Shader
import com.squareup.picasso.Transformation
class RoundedTransformation(private val radius: Float? = null, private val margin: Float = 0f) : Transformation {
override fun transform(source: Bitmap): Bitmap {
val paint = Paint().apply {
isAntiAlias = true
shader = BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
}
val output = Bitmap.createBitmap(source.width, source.height, Config.ARGB_8888)
Canvas(output).drawRoundRect(
margin, margin, source.width - margin, source.height - margin,
radius ?: source.width.toFloat() / 2, radius ?: source.height.toFloat() / 2,
paint
)
if (source != output) {
source.recycle()
}
return output
}
override fun key(): String =
"rounded(radius=$radius, margin=$margin)"
}
| apache-2.0 | 76b21925a5480084ad432ce4272589fb | 35.516129 | 113 | 0.673145 | 4.50996 | false | true | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/psi/parser/LuaExpressionParser.kt | 2 | 11866 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.psi.parser
import com.intellij.lang.PsiBuilder
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import com.tang.intellij.lua.psi.LuaParserUtil.MY_LEFT_COMMENT_BINDER
import com.tang.intellij.lua.psi.LuaParserUtil.MY_RIGHT_COMMENT_BINDER
import com.tang.intellij.lua.psi.LuaTypes.*
object LuaExpressionParser {
enum class ExprType(val ops: TokenSet) {
// or
T_OR(TokenSet.create(OR)),
// and
T_AND(TokenSet.create(AND)),
// < > <= >= ~= ==
T_CONDITION(TokenSet.create(GT, LT, GE, LE, NE, EQ)),
// |
T_BIT_OR(TokenSet.create(BIT_OR)),
// ~
T_BIT_TILDE(TokenSet.create(BIT_TILDE)),
// &
T_BIT_AND(TokenSet.create(BIT_AND)),
// << >>
T_BIT_SHIFT(TokenSet.create(BIT_LTLT, BIT_RTRT)),
// ..
T_CONCAT(TokenSet.create(CONCAT)),
// + -
T_ADDITIVE(TokenSet.create(PLUS, MINUS)),
// * / // %
T_MULTIPLICATIVE(TokenSet.create(MULT, DIV, DOUBLE_DIV, MOD)),
// not # - ~
T_UNARY(TokenSet.create(NOT, GETN, MINUS, BIT_TILDE)),
// ^
T_EXP(TokenSet.create(EXP)),
// value expr
T_VALUE(TokenSet.EMPTY)
}
fun parseExpr(builder: PsiBuilder, l:Int): PsiBuilder.Marker? {
return parseExpr(builder, ExprType.T_OR, l)
}
private fun parseExpr(builder: PsiBuilder, type: ExprType, l:Int): PsiBuilder.Marker? = when (type) {
ExprType.T_OR -> parseBinary(builder, type.ops, ExprType.T_AND, l)
ExprType.T_AND -> parseBinary(builder, type.ops, ExprType.T_CONDITION, l)
ExprType.T_CONDITION -> parseBinary(builder, type.ops, ExprType.T_BIT_OR, l)
ExprType.T_BIT_OR -> parseBinary(builder, type.ops, ExprType.T_BIT_TILDE, l)
ExprType.T_BIT_TILDE -> parseBinary(builder, type.ops, ExprType.T_BIT_AND, l)
ExprType.T_BIT_AND -> parseBinary(builder, type.ops, ExprType.T_BIT_SHIFT, l)
ExprType.T_BIT_SHIFT -> parseBinary(builder, type.ops, ExprType.T_CONCAT, l)
ExprType.T_CONCAT -> parseBinary(builder, type.ops, ExprType.T_ADDITIVE, l)
ExprType.T_ADDITIVE -> parseBinary(builder, type.ops, ExprType.T_MULTIPLICATIVE, l)
ExprType.T_MULTIPLICATIVE -> parseBinary(builder, type.ops, ExprType.T_EXP, l)
ExprType.T_EXP -> parseBinary(builder, type.ops, ExprType.T_UNARY, l)
ExprType.T_UNARY -> parseUnary(builder, type.ops, ExprType.T_VALUE, l)
ExprType.T_VALUE -> parseValue(builder, l)
}
private fun parseBinary(builder: PsiBuilder, ops: TokenSet, next: ExprType, l:Int): PsiBuilder.Marker? {
var result = parseExpr(builder, next, l + 1) ?: return null
while (true) {
if (ops.contains(builder.tokenType)) {
val opMarker = builder.mark()
builder.advanceLexer()
opMarker.done(BINARY_OP)
val right = parseExpr(builder, next, l + 1)
if (right == null) error(builder, "Expression expected")
//save
result = result.precede()
result.done(BINARY_EXPR)
if (right == null) break
} else break
}
return result
}
private fun parseUnary(b: PsiBuilder, ops: TokenSet, next: ExprType, l: Int): PsiBuilder.Marker? {
val isUnary = ops.contains(b.tokenType)
if (isUnary) {
val m = b.mark()
val opMarker = b.mark()
b.advanceLexer()
opMarker.done(UNARY_OP)
val right = parseUnary(b, ops, next, l)
if (right == null) {
error(b, "Expression expected")
}
m.done(UNARY_EXPR)
return m
}
return parseExpr(b, next, l)
}
private fun parseValue(b: PsiBuilder, l: Int): PsiBuilder.Marker? {
val pri = parsePrimaryExpr(b, l + 1)
if (pri != null)
return pri
return parseClosureExpr(b, l + 1)
}
private fun parsePrimaryExpr(b: PsiBuilder, l: Int): PsiBuilder.Marker? {
val pair = parsePrefixExpr(b, l + 1)
val prefixType = pair?.second
var prefix = pair?.first
val validatePrefixForCall = prefixType != TABLE_EXPR && prefixType != LITERAL_EXPR
/**
* ok:
* {
* ({}){},
* ("")""
* }
* not ok:
* {
* {}{},
* """",
* {}""
* }
*/
while (prefix != null) {
var suffix = parseIndexExpr(prefix, b, l + 1)
if (suffix == null && validatePrefixForCall) {
suffix = parseCallExpr(prefix, b, l + 1)
}
if (suffix == null) break
else prefix = suffix
}
return prefix
}
private fun parseClosureExpr(b: PsiBuilder, l: Int): PsiBuilder.Marker? {
if (b.tokenType == FUNCTION) {
val m = b.mark()
b.advanceLexer()
LuaStatementParser.parseFuncBody(b, l + 1)
m.done(CLOSURE_EXPR)
return m
}
return null
}
private fun parseIndexExpr(prefix: PsiBuilder.Marker, b: PsiBuilder, l: Int): PsiBuilder.Marker? {
when (b.tokenType) {
DOT, COLON -> { // left indexExpr ::= '[' expr ']' | '.' ID | ':' ID
b.advanceLexer() // . or :
expectError(b, ID) { "ID" }
val m = prefix.precede()
m.done(INDEX_EXPR)
return m
}
LBRACK -> {
b.advanceLexer() // [
expectExpr(b, l + 1) // expr
expectError(b, RBRACK) { "']'" } // ]
val m = prefix.precede()
m.done(INDEX_EXPR)
return m
}
}
return null
}
private fun parseCallExpr(prefix: PsiBuilder.Marker, b: PsiBuilder, l: Int): PsiBuilder.Marker? {
when (b.tokenType) {
LPAREN -> { // listArgs ::= '(' (arg_expr_list)? ')'
val listArgs = b.mark()
b.advanceLexer() // (
parseExprList(b, l + 1)
expectError(b, RPAREN) { "')'" }
listArgs.done(LIST_ARGS)
val m = prefix.precede()
m.done(CALL_EXPR)
return m
}
STRING -> { // singleArg ::= tableExpr | stringExpr
val stringExpr = b.mark()
b.advanceLexer()
stringExpr.done(LITERAL_EXPR)
stringExpr.precede().done(SINGLE_ARG)
val m = prefix.precede()
m.done(CALL_EXPR)
return m
}
LCURLY -> {
val tableExpr = parseTableExpr(b, l)
tableExpr?.precede()?.done(SINGLE_ARG)
val m = prefix.precede()
m.done(CALL_EXPR)
return m
}
else -> return null
}
}
private fun parsePrefixExpr(b: PsiBuilder, l: Int): Pair<PsiBuilder.Marker, IElementType>? {
when (b.tokenType) {
LPAREN -> { // parenExpr ::= '(' expr ')'
val m = b.mark()
b.advanceLexer() // (
expectExpr(b, l + 1) // expr
expectError(b, RPAREN) { "')'" } // )
m.done(PAREN_EXPR)
return Pair(m, PAREN_EXPR)
}
ID -> { // nameExpr ::= ID
val m = b.mark()
b.advanceLexer()
m.done(NAME_EXPR)
return Pair(m, NAME_EXPR)
}
NUMBER, STRING, NIL, TRUE, FALSE, ELLIPSIS -> { //literalExpr ::= nil | false | true | NUMBER | STRING | "..."
val m = b.mark()
b.advanceLexer()
m.done(LITERAL_EXPR)
return Pair(m, LITERAL_EXPR)
}
LCURLY -> { // table expr
val tableExpr = parseTableExpr(b, l)
return if (tableExpr != null)
Pair(tableExpr, LITERAL_EXPR)
else null
}
}
return null
}
private fun parseTableExpr(b: PsiBuilder, l: Int): PsiBuilder.Marker? {
if (b.tokenType == LCURLY) {
val m = b.mark()
b.advanceLexer()
parseTableFieldList(b, l)
expectError(b, RCURLY) { "'}'" }
m.done(TABLE_EXPR)
return m
}
return null
}
private fun parseTableFieldList(b: PsiBuilder, l: Int): Boolean {
val result = parseTableField(b, l)
while (result != null) {
val sep = parseTableSep(b)
val sepError = if (sep == null) b.mark() else null
sepError?.error(", or ; expected")
val nextField = parseTableField(b, l)
if (nextField == null)
sepError?.drop()
nextField ?: break
}
return true
}
private fun parseTableSep(b: PsiBuilder): PsiBuilder.Marker? {
when (b.tokenType) {
SEMI, COMMA -> {
val mark = b.mark()
b.advanceLexer()
mark.done(TABLE_FIELD_SEP)
return mark
}
}
return null
}
private fun parseTableField(b: PsiBuilder, l: Int): PsiBuilder.Marker? {
when (b.tokenType) {
LBRACK -> { // '[' expr ']' '=' expr
val m = b.mark()
b.advanceLexer()
expectExpr(b, l + 1) // expr
expectError(b, RBRACK) { "']'" }
expectError(b, ASSIGN) { "'='" }
expectExpr(b, l + 1) // expr
m.done(TABLE_FIELD)
m.setCustomEdgeTokenBinders(MY_LEFT_COMMENT_BINDER, MY_RIGHT_COMMENT_BINDER)
return m
}
ID -> { // ID '=' expr
val m = b.mark()
b.advanceLexer()
if (b.tokenType == ASSIGN) {
b.advanceLexer() // =
expectExpr(b, l + 1) // expr
m.done(TABLE_FIELD)
m.setCustomEdgeTokenBinders(MY_LEFT_COMMENT_BINDER, MY_RIGHT_COMMENT_BINDER)
return m
}
m.rollbackTo()
}
}
// expr
val expr = LuaExpressionParser.parseExpr(b, l + 1)
if (expr != null) {
val m = expr.precede()
m.done(TABLE_FIELD)
m.setCustomEdgeTokenBinders(MY_LEFT_COMMENT_BINDER, MY_RIGHT_COMMENT_BINDER)
return m
}
return null
}
fun parseExprList(b: PsiBuilder, l: Int): PsiBuilder.Marker? {
val expr = parseExpr(b, l)
while (expr != null) {
if (b.tokenType == COMMA) {
b.advanceLexer() // ,
expectExpr(b, l + 1) // expr
} else break
}
return expr
}
private fun error(builder: PsiBuilder, message: String) {
builder.mark().error(message)
}
} | apache-2.0 | 0edf2227b3df0115f72146f411dc4412 | 32.148045 | 122 | 0.506236 | 4.040177 | false | false | false | false |
TakuSemba/DribbbleKotlinApp | app/src/main/java/com/takusemba/dribbblesampleapp/screen/MainActivity.kt | 2 | 1124 | package com.takusemba.dribbblesampleapp.screen
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import com.takusemba.dribbblesampleapp.R
import com.takusemba.dribbblesampleapp.adapter.SectionsPagerAdapter
/**
* Created by takusemba on 15/11/09.
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
var mViewPager: ViewPager = findViewById(R.id.pager) as ViewPager
var mTabLayout: TabLayout = findViewById(R.id.tabs) as TabLayout
var mSectionsPagerAdapter: SectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)
mViewPager.adapter = mSectionsPagerAdapter
mViewPager.offscreenPageLimit = mSectionsPagerAdapter.count
mTabLayout.setupWithViewPager(mViewPager)
}
}
| apache-2.0 | 2306eec6919b04eb6546cc4eeea748e4 | 34.125 | 102 | 0.773132 | 4.550607 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/housenumber/AddHousenumberForm.kt | 1 | 13075 | package de.westnordost.streetcomplete.quests.housenumber
import android.content.res.ColorStateList
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import android.text.InputType
import android.text.method.DigitsKeyListener
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import androidx.core.content.getSystemService
import androidx.core.view.isInvisible
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment
import de.westnordost.streetcomplete.quests.OtherAnswer
import de.westnordost.streetcomplete.quests.building_type.BuildingType
import de.westnordost.streetcomplete.quests.building_type.asItem
import de.westnordost.streetcomplete.util.TextChangedWatcher
import de.westnordost.streetcomplete.view.image_select.ItemViewHolder
class AddHousenumberForm : AbstractQuestFormAnswerFragment<HousenumberAnswer>() {
override val otherAnswers = listOf(
OtherAnswer(R.string.quest_address_answer_no_housenumber) { onNoHouseNumber() },
OtherAnswer(R.string.quest_address_answer_house_name) { switchToHouseName() },
OtherAnswer(R.string.quest_housenumber_multiple_numbers) { showMultipleNumbersHint() }
)
private var houseNumberInput: EditText? = null
private var houseNameInput: EditText? = null
private var conscriptionNumberInput: EditText? = null
private var streetNumberInput: EditText? = null
private var blockNumberInput: EditText? = null
private var toggleKeyboardButton: Button? = null
private var addButton: View? = null
private var subtractButton: View? = null
private var isHousename: Boolean = false
private var houseNumberInputTextColors: ColorStateList? = null
private val isShowingHouseNumberHint: Boolean get() = houseNumberInputTextColors != null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = super.onCreateView(inflater, container, savedInstanceState)
isHousename = savedInstanceState?.getBoolean(IS_HOUSENAME) ?: false
setLayout(if(isHousename) R.layout.quest_housename else R.layout.quest_housenumber)
return view
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(IS_HOUSENAME, isHousename)
}
override fun onClickOk() {
createAnswer()?.let { answer ->
confirmHousenumber(answer.looksInvalid(countryInfo.additionalValidHousenumberRegex)) {
applyAnswer(answer)
if (answer.isRealHouseNumberAnswer) lastRealHousenumberAnswer = answer
}
}
}
override fun isFormComplete() = (!isShowingHouseNumberHint || isHousename) && createAnswer() != null
/* ------------------------------------- Other answers -------------------------------------- */
private fun switchToHouseName() {
isHousename = true
setLayout(R.layout.quest_housename)
}
private fun showMultipleNumbersHint() {
activity?.let { AlertDialog.Builder(it)
.setMessage(R.string.quest_housenumber_multiple_numbers_description)
.setPositiveButton(android.R.string.ok, null)
.show()
}
}
private fun onNoHouseNumber() {
val buildingValue = osmElement!!.tags["building"]!!
val buildingType = BuildingType.getByTag("building", buildingValue)
if (buildingType != null) {
showNoHousenumberDialog(buildingType)
} else {
// fallback in case the type of building is known by Housenumber quest but not by
// building type quest
onClickCantSay()
}
}
private fun showNoHousenumberDialog(buildingType: BuildingType) {
val inflater = LayoutInflater.from(requireContext())
val inner = inflater.inflate(R.layout.dialog_quest_address_no_housenumber, null, false)
ItemViewHolder(inner.findViewById(R.id.item_view)).bind(buildingType.asItem())
AlertDialog.Builder(requireContext())
.setView(inner)
.setPositiveButton(R.string.quest_generic_hasFeature_yes) { _, _ -> applyAnswer(NoHouseNumber) }
.setNegativeButton(R.string.quest_generic_hasFeature_no_leave_note) { _, _ -> composeNote() }
.show()
}
/* -------------------------- Set (different) housenumber layout --------------------------- */
private fun setLayout(layoutResourceId: Int) {
val view = setContentView(layoutResourceId)
toggleKeyboardButton = view.findViewById(R.id.toggleKeyboardButton)
houseNumberInput = view.findViewById(R.id.houseNumberInput)
houseNameInput = view.findViewById(R.id.houseNameInput)
conscriptionNumberInput = view.findViewById(R.id.conscriptionNumberInput)
streetNumberInput = view.findViewById(R.id.streetNumberInput)
blockNumberInput = view.findViewById(R.id.blockNumberInput)
addButton = view.findViewById(R.id.addButton)
subtractButton = view.findViewById(R.id.subtractButton)
addButton?.setOnClickListener { addToHouseNumberInput(+1) }
subtractButton?.setOnClickListener { addToHouseNumberInput(-1) }
// must be called before registering the text changed watchers because it changes the text
prefillBlockNumber()
initKeyboardButton()
// must be after initKeyboardButton because it re-sets the onFocusListener
showHouseNumberHint()
val onChanged = TextChangedWatcher { checkIsFormComplete() }
houseNumberInput?.addTextChangedListener(onChanged)
houseNameInput?.addTextChangedListener(onChanged)
conscriptionNumberInput?.addTextChangedListener(onChanged)
streetNumberInput?.addTextChangedListener(onChanged)
blockNumberInput?.addTextChangedListener(onChanged)
}
private fun prefillBlockNumber() {
/* the block number likely does not change from one input to the other, so let's prefill it
with the last selected value */
val input = blockNumberInput ?: return
val blockNumberAnswer = lastRealHousenumberAnswer as? HouseAndBlockNumber ?: return
input.setText(blockNumberAnswer.blockNumber)
}
private fun showHouseNumberHint() {
val input = houseNumberInput ?: return
val prev = lastRealHousenumberAnswer?.realHouseNumber ?: return
/* The Auto fit layout does not work with hints, so we workaround this by setting the "real"
* text instead and make it look like it is a hint. This little hack is much less effort
* than to fork and fix the external dependency. We need to revert back the color both on
* focus and on text changed (tapping on +/- button) */
houseNumberInputTextColors = input.textColors
input.setTextColor(input.hintTextColors)
input.setText(prev)
input.addTextChangedListener(TextChangedWatcher {
val colors = houseNumberInputTextColors
if (colors != null) input.setTextColor(colors)
houseNumberInputTextColors = null
})
input.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
updateKeyboardButtonVisibility()
if (hasFocus) showKeyboard(input)
val colors = houseNumberInputTextColors
if (hasFocus && colors != null) {
input.text = null
input.setTextColor(colors)
houseNumberInputTextColors = null
}
}
}
private fun addToHouseNumberInput(add: Int) {
val input = houseNumberInput ?: return
val prev = if (input.text.isEmpty()) {
lastRealHousenumberAnswer?.realHouseNumber
} else {
input.text.toString()
} ?: return
val newHouseNumber = prev.addToHouseNumber(add) ?: return
input.setText(newHouseNumber)
input.setSelection(newHouseNumber.length)
}
private fun initKeyboardButton() {
toggleKeyboardButton?.text = "abc"
toggleKeyboardButton?.setOnClickListener {
val focus = requireActivity().currentFocus
if (focus != null && focus is EditText) {
val start = focus.selectionStart
val end = focus.selectionEnd
if (focus.inputType and InputType.TYPE_CLASS_NUMBER != 0) {
focus.inputType = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
toggleKeyboardButton?.text = "123"
} else {
focus.inputType = InputType.TYPE_CLASS_NUMBER
focus.keyListener = DigitsKeyListener.getInstance("0123456789.,- /")
toggleKeyboardButton?.text = "abc"
}
// for some reason, the cursor position gets lost first time the input type is set (#1093)
focus.setSelection(start, end)
showKeyboard(focus)
}
}
updateKeyboardButtonVisibility()
val onFocusChange = View.OnFocusChangeListener { v, hasFocus ->
updateKeyboardButtonVisibility()
if (hasFocus) showKeyboard(v)
}
houseNumberInput?.onFocusChangeListener = onFocusChange
streetNumberInput?.onFocusChangeListener = onFocusChange
blockNumberInput?.onFocusChangeListener = onFocusChange
}
private fun showKeyboard(focus: View) {
val imm = activity?.getSystemService<InputMethodManager>()
imm?.showSoftInput(focus, InputMethodManager.SHOW_IMPLICIT)
}
private fun updateKeyboardButtonVisibility() {
toggleKeyboardButton?.isInvisible = !(
houseNumberInput?.hasFocus() == true ||
streetNumberInput?.hasFocus() == true ||
blockNumberInput?.hasFocus() == true
)
}
private fun confirmHousenumber(isUnusual: Boolean, onConfirmed: () -> Unit) {
if (isUnusual) {
AlertDialog.Builder(requireContext())
.setTitle(R.string.quest_generic_confirmation_title)
.setMessage(R.string.quest_address_unusualHousenumber_confirmation_description)
.setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> onConfirmed() }
.setNegativeButton(R.string.quest_generic_confirmation_no, null)
.show()
} else {
onConfirmed()
}
}
private fun createAnswer(): HousenumberAnswer? =
if (houseNameInput != null) {
houseNameInput?.nonEmptyInput?.let { HouseName(it) }
}
else if (conscriptionNumberInput != null && streetNumberInput != null) {
conscriptionNumberInput?.nonEmptyInput?.let { conscriptionNumber ->
val streetNumber = streetNumberInput?.nonEmptyInput // streetNumber is optional
ConscriptionNumber(conscriptionNumber, streetNumber)
}
}
else if (blockNumberInput != null && houseNumberInput != null) {
blockNumberInput?.nonEmptyInput?.let { blockNumber ->
houseNumberInput?.nonEmptyInput?.let { houseNumber ->
HouseAndBlockNumber(houseNumber, blockNumber)
}
}
}
else if (houseNumberInput != null) {
houseNumberInput?.nonEmptyInput?.let { HouseNumber(it) }
}
else null
private val EditText.nonEmptyInput:String? get() {
val input = text.toString().trim()
return if(input.isNotEmpty()) input else null
}
companion object {
private var lastRealHousenumberAnswer: HousenumberAnswer? = null
private const val IS_HOUSENAME = "is_housename"
}
}
private val HousenumberAnswer.isRealHouseNumberAnswer: Boolean get() = when(this) {
is HouseNumber -> true
is HouseAndBlockNumber -> true
else -> false
}
private val HousenumberAnswer.realHouseNumber: String? get() = when(this) {
is HouseNumber -> number
is HouseAndBlockNumber -> houseNumber
else -> null
}
private fun String.addToHouseNumber(add: Int): String? {
val parsed = parseHouseNumber(this) ?: return null
when {
add == 0 -> return this
add > 0 -> {
val last = when (val it = parsed.list.last()) {
is HouseNumbersPartsRange -> it.end
is SingleHouseNumbersPart -> it.single
}
return (last.number + add).toString()
}
add < 0 -> {
val first = when (val it = parsed.list.first()) {
is HouseNumbersPartsRange -> it.start
is SingleHouseNumbersPart -> it.single
}
val result = first.number + add
return if (result < 1) null else result.toString()
}
else -> return null
}
}
| gpl-3.0 | c444b18d7c7263412295f23e3fe8db81 | 39.987461 | 116 | 0.656138 | 5.352026 | false | false | false | false |
CoEValencia/fwk | src/main/java/body/core/lifecycle/LifecycleAsyncImpl.kt | 1 | 1388 | package body.core.lifecycle
import body.core.lifecycleState.LifecycleState
import java.util.concurrent.CompletableFuture
import java.util.function.Function
class LifecycleAsyncImpl<T> internal constructor(private val obj: T, private var state: String) : LifecycleAsync<T> {
init {
this.state = LifecycleState.CONSTRUCTOR
}
companion object {
fun <H> create(obj: H): LifecycleAsync<H> = LifecycleAsyncImpl(obj, LifecycleState.NO_STATE)
}
override fun getObject() = this.obj
override fun getState() = this.state
override fun isInitialize() = (this.state === LifecycleState.INITIALIZE)
override fun isPreDestroy() = (this.state === LifecycleState.DESTROY)
override fun isPostConstructor() = (this.state === LifecycleState.CONSTRUCTOR)
override fun isResume() = (this.state === LifecycleState.RESUME)
override fun isNotState() = (this.state === LifecycleState.NO_STATE)
override fun <H, T> initialize(`fun`: Function<H, T>): CompletableFuture<T>? {
return null
}
override fun <H, T> preDestroy(`fun`: Function<H, T>): CompletableFuture<T>? {
return null
}
override fun <H, T> postConstructor(`fun`: Function<H, T>): CompletableFuture<T>? {
return null
}
override fun <H, T> resume(`fun`: Function<H, T>): CompletableFuture<T>? {
return null
}
}
| gpl-3.0 | 53c08f678c4e2161478457e704438bb2 | 25.692308 | 117 | 0.674352 | 4.143284 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/user/Preferences.kt | 1 | 1684 | package com.habitrpg.android.habitica.models.user
import com.google.gson.annotations.SerializedName
import com.habitrpg.android.habitica.models.BaseObject
import com.habitrpg.shared.habitica.models.AvatarPreferences
import io.realm.RealmObject
import io.realm.annotations.RealmClass
@RealmClass(embedded = true)
open class Preferences : RealmObject(), AvatarPreferences, BaseObject {
override var hair: Hair? = null
var suppressModals: SuppressedModals? = null
override var costume: Boolean = false
@SerializedName("disableClasses")
override var disableClasses: Boolean = false
@SerializedName("sleep")
override var sleep: Boolean = false
var dailyDueDefaultView: Boolean = false
var automaticAllocation: Boolean = false
var allocationMode: String? = null
override var shirt: String? = null
override var skin: String? = null
override var size: String? = null
override var background: String? = null
override var chair: String? = null
get() {
return if (field != null && field != "none") {
if (field?.contains("chair_") == true) {
field
} else {
"chair_" + field!!
}
} else null
}
var language: String? = null
var sound: String? = null
var dayStart: Int = 0
var timezoneOffset: Int = 0
var timezoneOffsetAtLastCron: Int = 0
var pushNotifications: PushNotificationsPreference? = null
var emailNotifications: EmailNotificationsPreference? = null
var autoEquip: Boolean = true
var tasks: UserTaskPreferences? = null
}
| gpl-3.0 | a79a3b05bc5f8bddbf2229a1361dba1b | 36.272727 | 71 | 0.6538 | 4.651934 | false | false | false | false |
InsertKoinIO/koin | android/koin-android/src/main/java/org/koin/androidx/viewmodel/factory/KoinViewModelFactory.kt | 1 | 1578 | package org.koin.androidx.viewmodel.factory
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.createSavedStateHandle
import androidx.lifecycle.viewmodel.CreationExtras
import org.koin.androidx.viewmodel.needSavedStateHandle
import org.koin.core.annotation.KoinInternalApi
import org.koin.core.parameter.ParametersDefinition
import org.koin.core.parameter.parametersOf
import org.koin.core.qualifier.Qualifier
import org.koin.core.scope.Scope
import kotlin.reflect.KClass
/**
* ViewModelProvider.Factory for Koin instances resolution
* @see ViewModelProvider.Factory
*/
class KoinViewModelFactory(
private val kClass: KClass<out ViewModel>,
private val scope: Scope,
private val qualifier: Qualifier? = null,
private val params: ParametersDefinition? = null
) : ViewModelProvider.Factory {
@OptIn(KoinInternalApi::class)
private val needSSH: Boolean = kClass.java.needSavedStateHandle()
override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T {
val parameters: ParametersDefinition? = if (needSSH) {
val ssh = extras.createSavedStateHandle()
params?.addSSH(ssh) ?: { parametersOf(ssh) }
} else params
return scope.get(kClass, qualifier, parameters)
}
//TODO Avoid such insertion - need to see with internal core resolution
private fun ParametersDefinition.addSSH(ssh: SavedStateHandle): ParametersDefinition {
return { invoke().add(ssh) }
}
} | apache-2.0 | eea804dd7a133f7ec322eed51fbbea26 | 35.72093 | 90 | 0.762357 | 4.696429 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/starred/StarredFragment.kt | 1 | 7891 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.starred
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.*
import android.widget.Toast
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration
import es.dmoral.toasty.Toasty
import giuliolodi.gitnav.R
import giuliolodi.gitnav.ui.adapters.StarredAdapter
import giuliolodi.gitnav.ui.base.BaseFragment
import giuliolodi.gitnav.ui.option.OptionActivity
import giuliolodi.gitnav.ui.repository.RepoActivity
import giuliolodi.gitnav.ui.user.UserActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.starred_fragment.*
import org.eclipse.egit.github.core.Repository
import javax.inject.Inject
/**
* Created by giulio on 20/06/2017.
*/
class StarredFragment : BaseFragment(), StarredContract.View {
@Inject lateinit var mPresenter: StarredContract.Presenter<StarredContract.View>
private var mMenuItem: Int? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
getActivityComponent()?.inject(this)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.starred_fragment, container, false)
}
override fun initLayout(view: View?, savedInstanceState: Bundle?) {
mPresenter.onAttach(this)
setHasOptionsMenu(true)
activity?.title = getString(R.string.starred)
val llm = LinearLayoutManager(context)
llm.orientation = LinearLayoutManager.VERTICAL
starred_fragment_rv.layoutManager = llm
starred_fragment_rv.addItemDecoration(HorizontalDividerItemDecoration.Builder(context).showLastDivider().build())
starred_fragment_rv.itemAnimator = DefaultItemAnimator()
starred_fragment_rv.adapter = StarredAdapter()
(starred_fragment_rv.adapter as StarredAdapter).getImageClicks()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { username -> mPresenter.onUserClick(username) }
(starred_fragment_rv.adapter as StarredAdapter).getRepoClicks()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { repo -> mPresenter.onRepoClick(repo.owner.login, repo.name) }
val mScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
val visibleItemCount = (starred_fragment_rv.layoutManager as LinearLayoutManager).childCount
val totalItemCount = (starred_fragment_rv.layoutManager as LinearLayoutManager).itemCount
val pastVisibleItems = (starred_fragment_rv.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
if (pastVisibleItems + visibleItemCount >= totalItemCount) {
mPresenter.onLastItemVisible(isNetworkAvailable(), dy)
}
}
}
starred_fragment_rv.setOnScrollListener(mScrollListener)
starred_fragment_swipe.setColorSchemeColors(Color.parseColor("#448AFF"))
starred_fragment_swipe.setOnRefreshListener { mPresenter.onSwipeToRefresh(isNetworkAvailable()) }
mPresenter.subscribe(isNetworkAvailable())
}
override fun showRepos(repoList: List<Repository>) {
(starred_fragment_rv.adapter as StarredAdapter).addRepos(repoList)
}
override fun showLoading() {
starred_fragment_progress_bar.visibility = View.VISIBLE
}
override fun hideLoading() {
starred_fragment_progress_bar.visibility = View.GONE
starred_fragment_swipe.isRefreshing = false
}
override fun showNoRepo() {
starred_fragment_no_repo.visibility = View.VISIBLE
}
override fun hideNoRepo() {
starred_fragment_no_repo.visibility = View.GONE
}
override fun showListLoading() {
(starred_fragment_rv.adapter as StarredAdapter).showLoading()
}
override fun hideListLoading() {
(starred_fragment_rv.adapter as StarredAdapter).hideLoading()
}
override fun clearAdapter() {
(starred_fragment_rv.adapter as StarredAdapter).clear()
}
override fun setFilter(filter: HashMap<String, String>) {
(starred_fragment_rv.adapter as StarredAdapter).setFilter(filter)
}
override fun showError(error: String) {
Toasty.error(context, error, Toast.LENGTH_LONG).show()
}
override fun showNoConnectionError() {
Toasty.warning(context, getString(R.string.network_error), Toast.LENGTH_LONG).show()
}
override fun intentToUserActivity(username: String) {
startActivity(UserActivity.getIntent(context).putExtra("username", username))
activity.overridePendingTransition(0,0)
}
override fun intentToRepoActivity(repoOwner: String, repoName: String) {
startActivity(RepoActivity.getIntent(context).putExtra("owner", repoOwner).putExtra("name", repoName))
activity.overridePendingTransition(0,0)
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.starred_sort_menu, menu)
mMenuItem?.let { menu?.findItem(it)?.isChecked = true }
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == R.id.action_options) {
startActivity(OptionActivity.getIntent(context))
activity.overridePendingTransition(0,0)
}
if (isNetworkAvailable()) {
mMenuItem = item?.itemId
when (item?.itemId) {
R.id.starred_sort_starred -> {
item.isChecked = true
mPresenter.onSortStarredClick(isNetworkAvailable())
}
R.id.starred_sort_updated -> {
item.isChecked = true
mPresenter.onSortUpdatedClick(isNetworkAvailable())
}
R.id.starred_sort_pushed -> {
item.isChecked = true
mPresenter.onSortPushedClick(isNetworkAvailable())
}
R.id.starred_sort_alphabetical -> {
item.isChecked = true
mPresenter.onSortAlphabeticalClick(isNetworkAvailable())
}
R.id.starred_sort_stars -> {
item.isChecked = true
mPresenter.onSortStarsClick(isNetworkAvailable())
}
}
}
else
Toasty.warning(context, getString(R.string.network_error), Toast.LENGTH_LONG).show()
return super.onOptionsItemSelected(item)
}
override fun onDestroyView() {
mPresenter.onDetachView()
super.onDestroyView()
}
override fun onDestroy() {
mPresenter.onDetach()
super.onDestroy()
}
} | apache-2.0 | ab1b69f20bdbb2942d823c2c96cc3023 | 37.876847 | 128 | 0.677481 | 4.892126 | false | false | false | false |
da1z/intellij-community | uast/uast-common/src/org/jetbrains/uast/evaluation/MapBasedEvaluationContext.kt | 4 | 3554 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.evaluation
import com.intellij.openapi.progress.ProcessCanceledException
import org.jetbrains.uast.*
import org.jetbrains.uast.values.UUndeterminedValue
import org.jetbrains.uast.visitor.UastVisitor
import java.lang.ref.SoftReference
import java.util.*
class MapBasedEvaluationContext(
override val uastContext: UastContext,
override val extensions: List<UEvaluatorExtension>
) : UEvaluationContext {
data class UEvaluatorWithStamp(val evaluator: UEvaluator, val stamp: Long)
private val evaluators = WeakHashMap<UDeclaration, SoftReference<UEvaluatorWithStamp>>()
override fun analyzeAll(file: UFile, state: UEvaluationState): UEvaluationContext {
file.accept(object : UastVisitor {
override fun visitElement(node: UElement) = false
override fun visitMethod(node: UMethod): Boolean {
analyze(node, state)
return true
}
override fun visitVariable(node: UVariable): Boolean {
if (node is UField) {
analyze(node, state)
return true
}
else return false
}
})
return this
}
@Throws(ProcessCanceledException::class)
private fun getOrCreateEvaluator(declaration: UDeclaration, state: UEvaluationState? = null): UEvaluator {
val containingFile = declaration.getContainingUFile()
val modificationStamp = containingFile?.psi?.modificationStamp ?: -1L
val evaluatorWithStamp = evaluators[declaration]?.get()
if (evaluatorWithStamp != null && evaluatorWithStamp.stamp == modificationStamp) {
return evaluatorWithStamp.evaluator
}
return createEvaluator(uastContext, extensions).apply {
when (declaration) {
is UMethod -> this.analyze(declaration, state ?: declaration.createEmptyState())
is UField -> this.analyze(declaration, state ?: declaration.createEmptyState())
}
evaluators[declaration] = SoftReference(UEvaluatorWithStamp(this, modificationStamp))
}
}
override fun analyze(declaration: UDeclaration, state: UEvaluationState) = getOrCreateEvaluator(declaration, state)
override fun getEvaluator(declaration: UDeclaration) = getOrCreateEvaluator(declaration)
private fun getEvaluator(expression: UExpression): UEvaluator? {
var containingElement = expression.uastParent
while (containingElement != null) {
if (containingElement is UDeclaration) {
val evaluator = evaluators[containingElement]?.get()?.evaluator
if (evaluator != null) {
return evaluator
}
}
containingElement = containingElement.uastParent
}
return null
}
fun cachedValueOf(expression: UExpression) =
(getEvaluator(expression) as? TreeBasedEvaluator)?.getCached(expression)
override fun valueOf(expression: UExpression) =
valueOfIfAny(expression) ?: UUndeterminedValue
override fun valueOfIfAny(expression: UExpression) =
getEvaluator(expression)?.evaluate(expression)
} | apache-2.0 | f0bac69c7f4ea6e59ffd87742ecea145 | 35.649485 | 117 | 0.734384 | 4.875171 | false | false | false | false |
Heiner1/AndroidAPS | diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseSettingResponsePacket.kt | 1 | 1427 | package info.nightscout.androidaps.diaconn.packet
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.diaconn.DiaconnG8Pump
import info.nightscout.shared.logging.LTag
import javax.inject.Inject
/**
* BasalPauseSettingResponsePacket
*/
class BasalPauseSettingResponsePacket(
injector: HasAndroidInjector
) : DiaconnG8Packet(injector ) {
@Inject lateinit var diaconnG8Pump: DiaconnG8Pump
var result = 0
init {
msgType = 0x83.toByte()
aapsLogger.debug(LTag.PUMPCOMM, "BasalPauseSettingResponsePacket Init")
}
override fun handleMessage(data: ByteArray?) {
val defectCheck = defect(data)
if (defectCheck != 0) {
aapsLogger.debug(LTag.PUMPCOMM, "BasalPauseSettingResponsePacket Got some Error")
failed = true
return
} else failed = false
val bufferData = prefixDecode(data)
result = getByteToInt(bufferData)
if(!isSuccSettingResponseResult(result)) {
diaconnG8Pump.resultErrorCode = result
failed = true
return
}
diaconnG8Pump.otpNumber = getIntToInt(bufferData)
aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${result}")
aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}")
}
override fun getFriendlyName(): String {
return "PUMP_BASAL_PAUSE_SETTING_RESPONSE"
}
} | agpl-3.0 | 3d0461c1d6c7b22a44f5b2418617c001 | 28.75 | 93 | 0.678346 | 4.633117 | false | false | false | false |
rey5137/bootstrap | app/src/main/kotlin/com/rey/common/extensions/Context.kt | 1 | 2212 | package com.rey.common.extensions
import android.content.Context
import android.content.res.Resources
import android.support.annotation.StringRes
import android.support.v4.app.Fragment
import android.support.v4.content.res.ResourcesCompat
import android.support.v7.widget.RecyclerView
import android.util.TypedValue
import android.widget.Toast
import com.rey.dependency.HasComponent
/**
* Created by Rey on 12/1/16.
*/
inline fun <reified T> Context.getComponent(): T {
if (this !is HasComponent<*>)
throw IllegalArgumentException("context must be instance of HasComponent.")
@Suppress("UNCHECKED_CAST")
return component as T
}
fun Context.showToast(@StringRes resId: Int, duration: Int) {
Toast.makeText(this, resId, duration).show()
}
fun Context.showToast(message: CharSequence, duration: Int) {
Toast.makeText(this, message, duration).show()
}
fun Context.getColor(id: Int, theme: Resources.Theme? = null): Int
= ResourcesCompat.getColor(resources, id, theme)
fun Context.getDimen(id: Int): Int
= resources.getDimensionPixelSize(id)
fun Context.dpToPx(value: Int): Int
= (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value.toFloat(), resources.displayMetrics) + 0.5F).toInt()
fun Fragment.showToast(@StringRes resId: Int, duration: Int) {
context.showToast(resId, duration)
}
fun Fragment.showToast(message: CharSequence, duration: Int) {
context.showToast(message, duration)
}
fun Fragment.getColor(id: Int, theme: Resources.Theme? = null): Int
= ResourcesCompat.getColor(context.resources, id, theme)
fun Fragment.getDimen(id: Int): Int
= context.resources.getDimensionPixelSize(id)
fun RecyclerView.ViewHolder.getColor(id: Int, theme: Resources.Theme? = null): Int
= ResourcesCompat.getColor(itemView.context.resources, id, theme)
fun RecyclerView.ViewHolder.getDimen(id: Int): Int
= itemView.context.resources.getDimensionPixelSize(id)
fun RecyclerView.ViewHolder.getString(id: Int): CharSequence
= itemView.context.resources.getString(id)
fun RecyclerView.ViewHolder.getString(id: Int, vararg data : Any): CharSequence
= itemView.context.resources.getString(id, data) | apache-2.0 | 3670a634b7cd0e6d423eb0a4e8dd85bf | 33.046154 | 124 | 0.748644 | 3.935943 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/sharing/SharingModule.kt | 2 | 4837 | package abi43_0_0.expo.modules.sharing
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import androidx.core.content.FileProvider
import abi43_0_0.expo.modules.core.ExportedModule
import abi43_0_0.expo.modules.core.ModuleRegistry
import abi43_0_0.expo.modules.core.ModuleRegistryDelegate
import abi43_0_0.expo.modules.core.Promise
import abi43_0_0.expo.modules.core.arguments.ReadableArguments
import abi43_0_0.expo.modules.core.errors.InvalidArgumentException
import abi43_0_0.expo.modules.core.interfaces.ActivityEventListener
import abi43_0_0.expo.modules.core.interfaces.ActivityProvider
import abi43_0_0.expo.modules.core.interfaces.ExpoMethod
import abi43_0_0.expo.modules.core.interfaces.services.UIManager
import abi43_0_0.expo.modules.interfaces.filesystem.FilePermissionModuleInterface
import abi43_0_0.expo.modules.interfaces.filesystem.Permission
import java.io.File
import java.net.URLConnection
class SharingModule(
context: Context,
private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate()
) : ExportedModule(context), ActivityEventListener {
private var pendingPromise: Promise? = null
private val uiManager: UIManager by moduleRegistry()
override fun getName() = "ExpoSharing"
private inline fun <reified T> moduleRegistry() =
moduleRegistryDelegate.getFromModuleRegistry<T>()
override fun onCreate(moduleRegistry: ModuleRegistry) {
moduleRegistryDelegate.onCreate(moduleRegistry)
uiManager.registerActivityEventListener(this)
}
override fun onDestroy() {
uiManager.unregisterActivityEventListener(this)
}
@ExpoMethod
fun shareAsync(url: String?, params: ReadableArguments, promise: Promise) {
if (pendingPromise != null) {
promise.reject("ERR_SHARING_MUL", "Another share request is being processed now.")
return
}
try {
val fileToShare = getLocalFileFoUrl(url)
val contentUri = FileProvider.getUriForFile(
context,
context.applicationInfo.packageName + ".SharingFileProvider",
fileToShare
)
val mimeType = params.getString(MIME_TYPE_OPTIONS_KEY)
?: URLConnection.guessContentTypeFromName(fileToShare.name)
?: "*/*"
val intent = Intent.createChooser(
createSharingIntent(contentUri, mimeType),
params.getString(DIALOG_TITLE_OPTIONS_KEY)
)
val resInfoList = context.packageManager.queryIntentActivities(
intent,
PackageManager.MATCH_DEFAULT_ONLY
)
resInfoList.forEach {
val packageName = it.activityInfo.packageName
context.grantUriPermission(packageName, contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
val activityProvider: ActivityProvider by moduleRegistry()
activityProvider.currentActivity.startActivityForResult(intent, REQUEST_CODE)
pendingPromise = promise
} catch (e: InvalidArgumentException) {
promise.reject("ERR_SHARING_URL", e.message, e)
} catch (e: Exception) {
promise.reject("ERR_SHARING", "Failed to share the file: " + e.message, e)
}
}
@Throws(InvalidArgumentException::class)
private fun getLocalFileFoUrl(url: String?): File {
if (url == null) {
throw InvalidArgumentException("URL to share cannot be null.")
}
val uri = Uri.parse(url)
if ("file" != uri.scheme) {
throw InvalidArgumentException("Only local file URLs are supported (expected scheme to be 'file', got '" + uri.scheme + "'.")
}
val path = uri.path
?: throw InvalidArgumentException("Path component of the URL to share cannot be null.")
if (!isAllowedToRead(path)) {
throw InvalidArgumentException("Not allowed to read file under given URL.")
}
return File(path)
}
private fun isAllowedToRead(url: String?): Boolean {
val permissionModuleInterface: FilePermissionModuleInterface by moduleRegistry()
return permissionModuleInterface.getPathPermissions(context, url).contains(Permission.READ)
}
private fun createSharingIntent(uri: Uri, mimeType: String?) =
Intent(Intent.ACTION_SEND).apply {
putExtra(Intent.EXTRA_STREAM, uri)
setTypeAndNormalize(mimeType)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE && pendingPromise != null) {
pendingPromise?.resolve(Bundle.EMPTY)
pendingPromise = null
}
}
override fun onNewIntent(intent: Intent) = Unit
companion object {
private const val REQUEST_CODE = 8524
private const val MIME_TYPE_OPTIONS_KEY = "mimeType"
private const val DIALOG_TITLE_OPTIONS_KEY = "dialogTitle"
}
}
| bsd-3-clause | 346c298adbaa01f6a22178fef6cf48e4 | 37.388889 | 131 | 0.739094 | 4.361587 | false | false | false | false |
notsyncing/lightfur | lightfur-testing/src/main/kotlin/io/github/notsyncing/lightfur/testing/LightfurTestingEnvironment.kt | 1 | 2549 | package io.github.notsyncing.lightfur.testing
import io.github.notsyncing.lightfur.DataSession
import io.github.notsyncing.lightfur.DatabaseManager
import io.github.notsyncing.lightfur.common.LightfurConfigBuilder
import io.github.notsyncing.lightfur.entity.EntityGlobal
import io.github.notsyncing.lightfur.integration.jdbc.JdbcDataSession
import io.github.notsyncing.lightfur.integration.jdbc.JdbcPostgreSQLDriver
import io.github.notsyncing.lightfur.integration.jdbc.entity.JdbcEntityDataMapper
import io.github.notsyncing.lightfur.integration.jdbc.entity.JdbcEntityQueryExecutor
import io.github.notsyncing.lightfur.integration.jdbc.ql.JdbcRawQueryProcessor
import io.github.notsyncing.lightfur.ql.QueryExecutor
object LightfurTestingEnvironment {
private var currentDatabaseName = "lightfur_test_${Math.abs(this.hashCode())}"
init {
DatabaseManager.setDriver(JdbcPostgreSQLDriver())
DataSession.setCreator { JdbcDataSession(JdbcEntityDataMapper(), it) as DataSession<Any, Any, Any> }
EntityGlobal.setQueryExecutor(JdbcEntityQueryExecutor())
QueryExecutor.setRawQueryProcessor { JdbcRawQueryProcessor() }
}
fun create() {
val conf = LightfurConfigBuilder()
.database(currentDatabaseName)
.databaseVersioning(true)
.host("localhost")
.port(5432)
.maxPoolSize(10)
.username("postgres")
.password("")
.build()
val db = DatabaseManager.getInstance()
db.init(conf).get()
val conn = JdbcDataSession()
try {
conn.updateWithoutPreparing("""
CREATE OR REPLACE FUNCTION truncate_tables() RETURNS void AS \$\$
DECLARE
statements CURSOR FOR
SELECT tablename FROM pg_tables
WHERE schemaname NOT IN ('pg_catalog', 'information_schema');
BEGIN
FOR stmt IN statements LOOP
EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.tablename) || ' RESTART IDENTITY CASCADE;';
END LOOP;
END;
\$\$ LANGUAGE plpgsql;
""").get()
} finally {
conn.end().get()
}
}
fun prepare() {
val conn = JdbcDataSession()
try {
conn.updateWithoutPreparing("SELECT truncate_tables();").get()
} finally {
conn.end().get()
}
}
fun destroy() {
val db = DatabaseManager.getInstance()
db.setDatabase("postgres").get()
db.dropDatabase(currentDatabaseName).get()
db.close().get()
}
} | gpl-3.0 | 95ea711b0ead52fec3e3e69471d1d206 | 33 | 108 | 0.667713 | 4.559928 | false | false | false | false |
Maccimo/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/IgnoredSettingsPanel.kt | 2 | 5521 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.options.SearchableConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.VcsApplicationSettings
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.changes.ignore.IgnoreConfigurationProperty.ASKED_MANAGE_IGNORE_FILES_PROPERTY
import com.intellij.openapi.vcs.changes.ignore.IgnoreConfigurationProperty.MANAGE_IGNORE_FILES_PROPERTY
import com.intellij.openapi.vcs.changes.ui.IgnoredSettingsPanel.ManageIgnoredOption.*
import com.intellij.ui.components.Label
import com.intellij.ui.layout.*
import javax.swing.DefaultComboBoxModel
internal class IgnoredSettingsPanel(private val project: Project) : BoundConfigurable(message("ignored.file.tab.title"),
"project.propVCSSupport.Ignored.Files"), SearchableConfigurable {
internal var selectedManageIgnoreOption = getIgnoredOption()
internal var settings = VcsApplicationSettings.getInstance()
internal var projectSettings = VcsConfiguration.getInstance(project)
override fun apply() {
val modified = isModified
super.apply()
if (modified) {
updateIgnoredOption(selectedManageIgnoreOption)
}
}
override fun createPanel() =
panel {
titledRow(message("ignored.file.general.settings.title")) {
row {
cell {
Label(message("ignored.file.manage.policy.label"))()
comboBox(
DefaultComboBoxModel(arrayOf(AlwaysAsk,
AllProjectsManage,
CurrentProjectManage,
DoNotManageForCurrentProject,
DoNotManageForAllProject)),
::selectedManageIgnoreOption
).growPolicy(GrowPolicy.MEDIUM_TEXT)
}
}
}
titledRow(message("ignored.file.excluded.settings.title")) {
row {
checkBox(message("ignored.file.excluded.to.ignored.label"), settings::MARK_EXCLUDED_AS_IGNORED)
}
row {
checkBox(message("ignored.file.ignored.to.excluded.label"), projectSettings::MARK_IGNORED_AS_EXCLUDED)
}
}
}
private fun updateIgnoredOption(option: ManageIgnoredOption) {
val applicationSettings = VcsApplicationSettings.getInstance()
val propertiesComponent = PropertiesComponent.getInstance(project)
when (option) {
DoNotManageForAllProject -> {
propertiesComponent.setValue(MANAGE_IGNORE_FILES_PROPERTY, false)
propertiesComponent.setValue(ASKED_MANAGE_IGNORE_FILES_PROPERTY, true)
applicationSettings.MANAGE_IGNORE_FILES = false
applicationSettings.DISABLE_MANAGE_IGNORE_FILES = true
}
AllProjectsManage -> {
propertiesComponent.setValue(MANAGE_IGNORE_FILES_PROPERTY, true)
propertiesComponent.setValue(ASKED_MANAGE_IGNORE_FILES_PROPERTY, true)
applicationSettings.MANAGE_IGNORE_FILES = true
applicationSettings.DISABLE_MANAGE_IGNORE_FILES = false
}
CurrentProjectManage -> {
propertiesComponent.setValue(MANAGE_IGNORE_FILES_PROPERTY, true)
propertiesComponent.setValue(ASKED_MANAGE_IGNORE_FILES_PROPERTY, true)
applicationSettings.MANAGE_IGNORE_FILES = false
applicationSettings.DISABLE_MANAGE_IGNORE_FILES = false
}
DoNotManageForCurrentProject -> {
propertiesComponent.setValue(MANAGE_IGNORE_FILES_PROPERTY, false)
propertiesComponent.setValue(ASKED_MANAGE_IGNORE_FILES_PROPERTY, true)
applicationSettings.MANAGE_IGNORE_FILES = false
applicationSettings.DISABLE_MANAGE_IGNORE_FILES = false
}
AlwaysAsk -> {
propertiesComponent.setValue(MANAGE_IGNORE_FILES_PROPERTY, false)
propertiesComponent.setValue(ASKED_MANAGE_IGNORE_FILES_PROPERTY, false)
applicationSettings.MANAGE_IGNORE_FILES = false
applicationSettings.DISABLE_MANAGE_IGNORE_FILES = false
}
}
}
private fun getIgnoredOption(): ManageIgnoredOption {
val applicationSettings = VcsApplicationSettings.getInstance()
val propertiesComponent = PropertiesComponent.getInstance(project)
return when {
applicationSettings.DISABLE_MANAGE_IGNORE_FILES -> DoNotManageForAllProject
applicationSettings.MANAGE_IGNORE_FILES -> AllProjectsManage
propertiesComponent.getBoolean(MANAGE_IGNORE_FILES_PROPERTY, false) -> CurrentProjectManage
propertiesComponent.getBoolean(ASKED_MANAGE_IGNORE_FILES_PROPERTY, false) -> DoNotManageForCurrentProject
else -> AlwaysAsk
}
}
enum class ManageIgnoredOption(val displayName: String) {
AlwaysAsk(message("ignored.file.manage.always.ask.option")),
AllProjectsManage(message("ignored.file.manage.all.projects.option")),
CurrentProjectManage(message("ignored.file.manage.this.project.option")),
DoNotManageForCurrentProject(message("ignored.file.not.manage.this.project.option")),
DoNotManageForAllProject(message("ignored.file.not.manage.option"));
override fun toString() = displayName
}
override fun getId() = helpTopic!!
}
| apache-2.0 | ac6fe866ce24bbf25b2686a4cbe8fa89 | 44.628099 | 151 | 0.712371 | 4.956014 | false | true | false | false |
ihmcrobotics/ihmc-build | src/test/kotlin/us/ihmc/build/ContinuousIntegrationTest.kt | 1 | 2011 | package us.ihmc.build
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
/**
* Must be run from ihmc-build directory!
*/
class ContinuousIntegrationTest
{
@Disabled
@Test
fun testGenerateTestSuitesSucceeds()
{
var output = runGradleTask("test", "generateTestSuitesTest")
assertTrue(output.contains(Regex("BUILD SUCCESSFUL")))
output = runGradleTask("generateTestSuites", "generateTestSuitesTest")
assertTrue(output.contains(Regex("YourProjectAFast")))
assertTrue(output.contains(Regex("BUILD SUCCESSFUL")))
}
@Disabled
@Test
fun testPublishSnapshotLocal()
{
var output: String
output = runGradleTask("publish -PsnapshotMode=true -PpublishUrl=local", "generateTestSuitesTest")
assertTrue(output.contains(Regex("BUILD SUCCESSFUL")))
val nexusUsername = ""
val nexusPassword = ""
output = runGradleTask("publish -PsnapshotMode=true -PpublishUrl=ihmcSnapshots " +
"-PnexusUsername=$nexusUsername -PnexusPassword=$nexusPassword", "generateTestSuitesTest")
assertTrue(output.contains(Regex("BUILD SUCCESSFUL")))
}
@Disabled
@Test
fun testResolveSnapshotLocal()
{
// var output: String
//
// output = runGradleTask("publish -PsnapshotMode=true -PpublishUrl=local", "generateTestSuitesTest")
//
// assertTrue(output.contains(Regex("BUILD SUCCESSFUL")))
//
// val credentials = EncryptedPropertyManager.loadEncryptedCredentials()
// val nexusUsername = credentials.get("nexusUsername")
// val nexusPassword = credentials.get("nexusPassword")
//
// output = runGradleTask("publish -PsnapshotMode=true -PpublishUrl=ihmcSnapshots " +
// "-PnexusUsername=$nexusUsername -PnexusPassword=$nexusPassword", "generateTestSuitesTest")
// assertTrue(output.contains(Regex("BUILD SUCCESSFUL")))
}
} | apache-2.0 | a3ea01b77e3d079526523f15d8927612 | 30.4375 | 127 | 0.681253 | 4.429515 | false | true | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/CompositeChildAbstractEntityImpl.kt | 2 | 13941 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class CompositeChildAbstractEntityImpl: CompositeChildAbstractEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTINLIST_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositeAbstractEntity::class.java, SimpleAbstractEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, false)
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositeAbstractEntity::class.java, SimpleAbstractEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, false)
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentChainEntity::class.java, CompositeAbstractEntity::class.java, ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true)
val connections = listOf<ConnectionId>(
PARENTINLIST_CONNECTION_ID,
CHILDREN_CONNECTION_ID,
PARENTENTITY_CONNECTION_ID,
)
}
override val parentInList: CompositeAbstractEntity
get() = snapshot.extractOneToAbstractManyParent(PARENTINLIST_CONNECTION_ID, this)!!
override val children: List<SimpleAbstractEntity>
get() = snapshot.extractOneToAbstractManyChildren<SimpleAbstractEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override val parentEntity: ParentChainEntity?
get() = snapshot.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: CompositeChildAbstractEntityData?): ModifiableWorkspaceEntityBase<CompositeChildAbstractEntity>(), CompositeChildAbstractEntity.Builder {
constructor(): this(CompositeChildAbstractEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity CompositeChildAbstractEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (_diff != null) {
if (_diff.extractOneToAbstractManyParent<WorkspaceEntityBase>(PARENTINLIST_CONNECTION_ID, this) == null) {
error("Field SimpleAbstractEntity#parentInList should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTINLIST_CONNECTION_ID)] == null) {
error("Field SimpleAbstractEntity#parentInList should be initialized")
}
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field CompositeAbstractEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field CompositeAbstractEntity#children should be initialized")
}
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field CompositeAbstractEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var parentInList: CompositeAbstractEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyParent(PARENTINLIST_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTINLIST_CONNECTION_ID)]!! as CompositeAbstractEntity
} else {
this.entityLinks[EntityLink(false, PARENTINLIST_CONNECTION_ID)]!! as CompositeAbstractEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTINLIST_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTINLIST_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractManyParentOfChild(PARENTINLIST_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTINLIST_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTINLIST_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTINLIST_CONNECTION_ID)] = value
}
changedProperty.add("parentInList")
}
override var children: List<SimpleAbstractEntity>
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyChildren<SimpleAbstractEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<SimpleAbstractEntity> ?: emptyList())
} else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<SimpleAbstractEntity> ?: emptyList()
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToAbstractManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value.asSequence())
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: ParentChainEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? ParentChainEntity
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? ParentChainEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): CompositeChildAbstractEntityData = result ?: super.getEntityData() as CompositeChildAbstractEntityData
override fun getEntityClass(): Class<CompositeChildAbstractEntity> = CompositeChildAbstractEntity::class.java
}
}
class CompositeChildAbstractEntityData : WorkspaceEntityData<CompositeChildAbstractEntity>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<CompositeChildAbstractEntity> {
val modifiable = CompositeChildAbstractEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): CompositeChildAbstractEntity {
val entity = CompositeChildAbstractEntityImpl()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return CompositeChildAbstractEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as CompositeChildAbstractEntityData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as CompositeChildAbstractEntityData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
} | apache-2.0 | 0f4c6e382c2c91efbab0cf3f1a1bc003 | 47.409722 | 234 | 0.616455 | 5.909708 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/helper/ModeExtensions.kt | 1 | 2892 | /*
* 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.
*/
@file:JvmName("ModeHelper")
package com.maddyhome.idea.vim.helper
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.getLineEndForOffset
import com.maddyhome.idea.vim.api.getLineStartForOffset
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.command.VimStateMachine
import com.maddyhome.idea.vim.listener.SelectionVimListenerSuppressor
import com.maddyhome.idea.vim.newapi.IjExecutionContext
import com.maddyhome.idea.vim.newapi.IjVimCaret
import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.vim
/**
* Pop all modes, but leave editor state. E.g. editor selection is not removed.
*/
fun Editor.popAllModes() {
val commandState = this.vim.vimStateMachine
while (commandState.mode != VimStateMachine.Mode.COMMAND) {
commandState.popModes()
}
}
/** [adjustCaretPosition] - if true, caret will be moved one char left if it's on the line end */
fun Editor.exitSelectMode(adjustCaretPosition: Boolean) {
if (!this.inSelectMode) return
this.vim.vimStateMachine.popModes()
SelectionVimListenerSuppressor.lock().use {
this.caretModel.allCarets.forEach {
it.removeSelection()
it.vimSelectionStartClear()
if (adjustCaretPosition) {
val lineEnd = IjVimEditor(this).getLineEndForOffset(it.offset)
val lineStart = IjVimEditor(this).getLineStartForOffset(it.offset)
if (it.offset == lineEnd && it.offset != lineStart) {
it.moveToInlayAwareOffset(it.offset - 1)
}
}
}
}
}
/** [adjustCaretPosition] - if true, caret will be moved one char left if it's on the line end */
fun VimEditor.exitSelectMode(adjustCaretPosition: Boolean) {
if (!this.inSelectMode) return
this.vimStateMachine.popModes()
SelectionVimListenerSuppressor.lock().use {
this.carets().forEach { vimCaret ->
val caret = (vimCaret as IjVimCaret).caret
caret.removeSelection()
caret.vimSelectionStartClear()
if (adjustCaretPosition) {
val lineEnd = IjVimEditor((this as IjVimEditor).editor).getLineEndForOffset(caret.offset)
val lineStart = IjVimEditor(this.editor).getLineStartForOffset(caret.offset)
if (caret.offset == lineEnd && caret.offset != lineStart) {
caret.moveToInlayAwareOffset(caret.offset - 1)
}
}
}
}
}
fun Editor.exitInsertMode(context: DataContext, operatorArguments: OperatorArguments) {
VimPlugin.getChange().processEscape(IjVimEditor(this), IjExecutionContext(context), operatorArguments)
}
| mit | 50e3cebf37132ee1431ce4f6ce611a18 | 35.15 | 104 | 0.743776 | 4.203488 | false | false | false | false |
randombyte-developer/server-tours | src/main/kotlin/de/randombyte/servertours/config/Serialization.kt | 1 | 1937 | package de.randombyte.servertours.config
import com.flowpowered.math.vector.Vector3i
import de.randombyte.servertours.Tour
import de.randombyte.servertours.Waypoint
import ninja.leaping.configurate.ConfigurationNode
import ninja.leaping.configurate.SimpleConfigurationNode
import org.spongepowered.api.text.Text
import org.spongepowered.api.text.serializer.TextSerializers
import org.spongepowered.api.world.Location
import org.spongepowered.api.world.World
object Serialization {
fun serialize(tour: Tour, node: ConfigurationNode) {
node.getNode(ConfigManager.NAME_NODE).value = serializeText(tour.name)
node.getNode(ConfigManager.WAYPOINTS_NODE).value = tour.waypoints.map { serializeWaypoint(it, SimpleConfigurationNode.root()) }
node.getNode(ConfigManager.COMPLETION_COMMAND_NODE).value = tour.completionCommand
}
private fun serializeWaypoint(waypoint: Waypoint, node: ConfigurationNode): ConfigurationNode {
serializeLocation(waypoint.location, node.getNode(ConfigManager.LOCATION_NODE))
node.getNode(ConfigManager.HEAD_ROTATION_NODE).value = serializeVector3i(waypoint.headRotation.toInt())
node.getNode(ConfigManager.INFO_TEXT_NODE).value = serializeText(waypoint.infoText)
node.getNode(ConfigManager.INFO_TEXT_PLACEMENT_NODE).value = waypoint.infoTextPlacement
node.getNode(ConfigManager.FREEZE_PLAYER_NODE).value = waypoint.freezePlayer
return node
}
private fun serializeLocation(location: Location<World>, node: ConfigurationNode) {
node.getNode(ConfigManager.WORLD_UUID_NODE).value = location.extent.uniqueId.toString()
node.getNode(ConfigManager.POSITION_NODE).value = serializeVector3i(location.blockPosition)
}
private fun serializeVector3i(vector3i: Vector3i) = listOf(vector3i.x, vector3i.y, vector3i.z)
private fun serializeText(text: Text) = TextSerializers.FORMATTING_CODE.serialize(text)
} | gpl-2.0 | ac98ab81763d6075ad063c28adefbe37 | 51.378378 | 135 | 0.785235 | 4.183585 | false | true | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/repository/TrackRepositoryImpl.kt | 1 | 2390 | package com.kelsos.mbrc.repository
import com.kelsos.mbrc.data.library.Track
import com.kelsos.mbrc.di.modules.AppDispatchers
import com.kelsos.mbrc.repository.data.LocalTrackDataSource
import com.kelsos.mbrc.repository.data.RemoteTrackDataSource
import com.raizlabs.android.dbflow.list.FlowCursorList
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.withContext
import org.threeten.bp.Instant
import javax.inject.Inject
class TrackRepositoryImpl
@Inject constructor(
private val localDataSource: LocalTrackDataSource,
private val remoteDataSource: RemoteTrackDataSource,
private val dispatchers: AppDispatchers
) : TrackRepository {
override suspend fun getAllCursor(): FlowCursorList<Track> = localDataSource.loadAllCursor()
override suspend fun getAlbumTracks(album: String, artist: String): FlowCursorList<Track> =
localDataSource.getAlbumTracks(album, artist)
override suspend fun getNonAlbumTracks(artist: String): FlowCursorList<Track> =
localDataSource.getNonAlbumTracks(artist)
override suspend fun getAndSaveRemote(): FlowCursorList<Track> {
getRemote()
return localDataSource.loadAllCursor()
}
override suspend fun getRemote() {
val epoch = Instant.now().epochSecond
withContext(dispatchers.io) {
remoteDataSource.fetch()
.onCompletion {
localDataSource.removePreviousEntries(epoch)
}
.collect { tracks ->
val data = tracks.map {
it.apply {
dateAdded = epoch
}
}
localDataSource.saveAll(data)
}
}
}
override suspend fun search(term: String): FlowCursorList<Track> {
return localDataSource.search(term)
}
override suspend fun getGenreTrackPaths(genre: String): List<String> {
return localDataSource.getGenreTrackPaths(genre)
}
override suspend fun getArtistTrackPaths(artist: String): List<String> =
localDataSource.getArtistTrackPaths(artist)
override suspend fun getAlbumTrackPaths(album: String, artist: String): List<String> =
localDataSource.getAlbumTrackPaths(album, artist)
override suspend fun getAllTrackPaths(): List<String> = localDataSource.getAllTrackPaths()
override suspend fun cacheIsEmpty(): Boolean = localDataSource.isEmpty()
override suspend fun count(): Long = localDataSource.count()
}
| gpl-3.0 | e4e9d297ba979ee21723c460673287fb | 32.661972 | 94 | 0.753138 | 4.622824 | false | false | false | false |
Major-/Vicis | modern/src/main/kotlin/rs/emulate/modern/codec/Archive.kt | 1 | 3707 | package rs.emulate.modern.codec
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import java.util.TreeMap
class Archive {
private val entries = TreeMap<Int, ByteBuf>()
val size: Int
get() = entries.size
operator fun contains(id: Int): Boolean {
return id in entries
}
/* returns an immutable buffer (each call returns a new slice) */
operator fun get(id: Int): ByteBuf? {
return entries[id]?.slice()
}
/* accepts an immutable buffer */
operator fun set(id: Int, buf: ByteBuf) {
entries[id] = buf
}
fun removeEntry(id: Int) {
entries.remove(id)
}
/* returns an immutable buffer */
fun write(): ByteBuf {
val size = entries.size
check(size > 0) { "Size must at least 1" }
if (size == 1) {
val firstEntry = entries.values.iterator().next()
return firstEntry.slice()
}
val trailerLen = size * 4 + 1
val trailer = Unpooled.buffer(trailerLen, trailerLen)
var last = 0
for (entry in entries.values) {
val len = entry.readableBytes()
val delta = len - last
trailer.writeInt(delta)
last = len
}
trailer.writeByte(1)
val buf = Unpooled.compositeBuffer(size + 1)
for (entry in entries.values) {
buf.addComponent(entry)
buf.writerIndex(buf.writerIndex() + entry.readableBytes())
}
buf.addComponent(trailer)
buf.writerIndex(buf.writerIndex() + trailer.readableBytes())
return buf.asReadOnly()
}
companion object {
/* accepts an immutable buffer, returns an Archive containing a collection of immutable buffers */
fun ByteBuf.readArchive(entry: ReferenceTable.Entry): Archive {
val size = entry.size
val childIds = entry.childIds
require(size > 0) { "Size must at least 1" }
if (size == 1) {
val archive = Archive()
val id = childIds[0]
archive.entries[id] = this
return archive
}
/* mark the start of the file and calculate length */
val start = readerIndex()
val len = readableBytes()
/* read trailer */
readerIndex(start + len - 1)
val stripes = readUnsignedByte().toInt()
require(stripes > 0) { "Stripes must at least 1" }
/* read entry sizes */
readerIndex(start + len - 1 - stripes * size * 4)
val stripeSizes = Array(stripes) { IntArray(size) }
val sizes = IntArray(size)
repeat(stripes) {
var accumulator = 0
for (i in 0 until size) {
val delta = readInt()
accumulator += delta
stripeSizes[it][i] = accumulator
sizes[i] += accumulator
}
}
/* allocate entry buffers */
val entries = (0 until size).map {
Unpooled.buffer(sizes[it], sizes[it])
}
/* read entries */
readerIndex(start)
repeat(stripes) { stripe ->
repeat(size) { index ->
val slice = readSlice(stripeSizes[stripe][index])
entries[index].writeBytes(slice)
}
}
val archive = Archive()
for ((index, id) in childIds.withIndex()) {
archive.entries[id] = entries[index].asReadOnly()
}
return archive
}
}
}
| isc | 85ede51c2410663aab215c871e339a84 | 25.669065 | 106 | 0.519018 | 4.716285 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-9/app-code/app/src/main/java/dev/mfazio/abl/standings/StandingsAdapter.kt | 5 | 4610 | package dev.mfazio.abl.standings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import dev.mfazio.abl.NavGraphDirections
import dev.mfazio.abl.databinding.StandingsHeaderBinding
import dev.mfazio.abl.databinding.StandingsTeamItemBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.ClassCastException
class StandingsAdapter :
ListAdapter<StandingsListItem, RecyclerView.ViewHolder>(StandingsDiffCallback()) {
fun addHeadersAndBuildStandings(uiTeamStandings: List<UITeamStanding>) = CoroutineScope(
Dispatchers.Default
).launch {
val items = uiTeamStandings
.sortedWith(compareBy({ it.teamStanding.division }, { -it.teamStanding.wins }))
.groupBy { it.teamStanding.division }
.map { (division, teams) ->
listOf(StandingsListItem.Header(division)) +
teams.map { team -> StandingsListItem.TeamItem(team) }
}.flatten()
withContext(Dispatchers.Main) {
submitList(items)
}
}
override fun getItemViewType(position: Int) = when (getItem(position)) {
is StandingsListItem.Header -> STANDINGS_ITEM_VIEW_TYPE_HEADER
is StandingsListItem.TeamItem -> STANDINGS_ITEM_VIEW_TYPE_TEAM
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
when (viewType) {
STANDINGS_ITEM_VIEW_TYPE_HEADER ->
StandingsListHeaderViewHolder.from(parent)
STANDINGS_ITEM_VIEW_TYPE_TEAM ->
StandingsListTeamViewHolder.from(parent)
else -> throw ClassCastException("Unknown view type [$viewType]")
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is StandingsListTeamViewHolder -> {
(getItem(position) as? StandingsListItem.TeamItem)?.let { teamItem ->
holder.bind(teamItem)
}
}
is StandingsListHeaderViewHolder -> {
(getItem(position) as? StandingsListItem.Header)?.let { teamItem ->
holder.bind(teamItem)
}
}
}
}
class StandingsListTeamViewHolder(private val binding: StandingsTeamItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(standingsTeamItem: StandingsListItem.TeamItem) {
binding.uiTeamStanding = standingsTeamItem.uiTeamStanding
binding.clickListener = View.OnClickListener { view ->
val action = NavGraphDirections.actionGoToTeam(
standingsTeamItem.uiTeamStanding.teamId,
standingsTeamItem.uiTeamStanding.teamName
)
view.findNavController().navigate(action)
}
}
companion object {
fun from(parent: ViewGroup): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = StandingsTeamItemBinding.inflate(inflater, parent, false)
return StandingsListTeamViewHolder(binding)
}
}
}
class StandingsListHeaderViewHolder(private val binding: StandingsHeaderBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(standingsHeaderItem: StandingsListItem.Header) {
binding.divisionName = standingsHeaderItem.division.name
}
companion object {
fun from(parent: ViewGroup): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = StandingsHeaderBinding.inflate(inflater, parent, false)
return StandingsListHeaderViewHolder(binding)
}
}
}
companion object {
private const val STANDINGS_ITEM_VIEW_TYPE_HEADER = 0
private const val STANDINGS_ITEM_VIEW_TYPE_TEAM = 1
}
}
class StandingsDiffCallback : DiffUtil.ItemCallback<StandingsListItem>() {
override fun areItemsTheSame(oldItem: StandingsListItem, newItem: StandingsListItem) =
oldItem == newItem
override fun areContentsTheSame(
oldItem: StandingsListItem,
newItem: StandingsListItem
) = oldItem.id == newItem.id
}
| apache-2.0 | d4d82585bd4283b9d54fde9db2aa2263 | 38.067797 | 92 | 0.663991 | 4.93576 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/popup/CodeVisionListPopup.kt | 8 | 3125 | package com.intellij.codeInsight.codeVision.ui.popup
import com.intellij.codeInsight.codeVision.CodeVisionBundle
import com.intellij.codeInsight.codeVision.CodeVisionEntry
import com.intellij.codeInsight.codeVision.CodeVisionHost
import com.intellij.codeInsight.codeVision.ui.model.AdditionalCodeVisionEntry
import com.intellij.codeInsight.codeVision.ui.model.RangeCodeVisionModel
import com.intellij.codeInsight.codeVision.ui.model.contextAvailable
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.ListSeparator
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.ui.popup.list.ListPopupImpl
import javax.swing.Icon
class CodeVisionListPopup private constructor(project: Project, aStep: ListPopupStep<CodeVisionEntry>) : ListPopupImpl(project, aStep) {
companion object {
private val settingButton = AdditionalCodeVisionEntry(CodeVisionHost.settingsLensProviderId, "&Settings",
CodeVisionBundle.message("LensListPopup.tooltip.settings"))
fun createLensList(model: RangeCodeVisionModel, project: Project): CodeVisionListPopup {
val lst: ArrayList<CodeVisionEntry> = ArrayList(model.sortedLensesMorePopup())
lst.add(settingButton)
val hotkey = KeymapUtil.getShortcutsText(KeymapManager.getInstance()!!.activeKeymap.getShortcuts("CodeLens.ShowMore"))
val aStep = object : BaseListPopupStep<CodeVisionEntry>("${model.name}${if (hotkey.isEmpty()) "" else "($hotkey)"}", lst) {
override fun isAutoSelectionEnabled(): Boolean {
return true
}
override fun isSpeedSearchEnabled(): Boolean {
return true
}
override fun isMnemonicsNavigationEnabled(): Boolean {
return true
}
override fun getTextFor(value: CodeVisionEntry): String {
return value.longPresentation
}
override fun getIconFor(value: CodeVisionEntry): Icon? {
return value.icon
}
override fun onChosen(selectedValue: CodeVisionEntry, finalChoice: Boolean): PopupStep<*>? {
if (hasSubstep(selectedValue)) {
return SubCodeVisionMenu(selectedValue.extraActions,
{
model.handleLensExtraAction(selectedValue, it)
}
)
}
doFinalStep {
model.handleLensClick(selectedValue)
}
return PopupStep.FINAL_CHOICE
}
override fun hasSubstep(selectedValue: CodeVisionEntry): Boolean {
return selectedValue.contextAvailable()
}
override fun getSeparatorAbove(value: CodeVisionEntry): ListSeparator? {
return if (value == settingButton) ListSeparator() else null
}
}
return CodeVisionListPopup(project, aStep)
}
}
}
| apache-2.0 | c446463fae418a11f6d5e6e1a50d1edf | 37.580247 | 136 | 0.69056 | 5.314626 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ReassignmentActionFactory.kt | 2 | 2178 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory1
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsights.impl.base.quickFix.ChangeVariableMutabilityFix
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable.CreatePropertyDelegateAccessorsActionFactory
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtValVarKeywordOwner
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.util.OperatorNameConventions
class ReassignmentActionFactory(val factory: DiagnosticFactory1<*, DeclarationDescriptor>) : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val propertyDescriptor = factory.cast(diagnostic).a
val declaration =
DescriptorToSourceUtils.descriptorToDeclaration(propertyDescriptor) as? KtValVarKeywordOwner ?: return null
return ChangeVariableMutabilityFix(declaration, true)
}
}
object DelegatedPropertyValFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val element = Errors.DELEGATE_SPECIAL_FUNCTION_MISSING.cast(diagnostic).psiElement
val property = element.getStrictParentOfType<KtProperty>() ?: return null
val info = CreatePropertyDelegateAccessorsActionFactory.extractFixData(property, diagnostic).singleOrNull() ?: return null
if (info.name != OperatorNameConventions.SET_VALUE.asString()) return null
return ChangeVariableMutabilityFix(property, makeVar = false, actionText = KotlinBundle.message("change.to.val"))
}
} | apache-2.0 | 84dd7f02ff1d9c8f4df32c84dd6c7797 | 59.527778 | 158 | 0.816804 | 5.185714 | false | false | false | false |
GunoH/intellij-community | platform/feedback/src/com/intellij/feedback/npw/dialog/ProjectCreationFeedbackDialog.kt | 1 | 14412 | // 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.feedback.npw.dialog
import com.intellij.feedback.common.*
import com.intellij.feedback.common.dialog.COMMON_FEEDBACK_SYSTEM_INFO_VERSION
import com.intellij.feedback.common.dialog.CommonFeedbackSystemInfoData
import com.intellij.feedback.common.dialog.adjustBehaviourForFeedbackForm
import com.intellij.feedback.common.dialog.showFeedbackSystemInfoDialog
import com.intellij.feedback.npw.bundle.NPWFeedbackBundle
import com.intellij.feedback.npw.state.ProjectCreationInfoService
import com.intellij.ide.feedback.RatingComponent
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.LicensingFacade
import com.intellij.ui.PopupBorder
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.JBTextField
import com.intellij.ui.components.TextComponentEmptyText
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.gridLayout.JBGaps
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.*
import java.awt.event.ActionEvent
import java.util.function.Predicate
import javax.swing.Action
import javax.swing.JComponent
import javax.swing.SwingUtilities
class ProjectCreationFeedbackDialog(
private val project: Project?,
createdProjectTypeName: String,
private val forTest: Boolean
) : DialogWrapper(project) {
/** Increase the additional number when onboarding feedback format is changed */
private val FEEDBACK_JSON_VERSION = COMMON_FEEDBACK_SYSTEM_INFO_VERSION + 0
private val TICKET_TITLE_ZENDESK = "Project Creation Feedback"
private val FEEDBACK_TYPE_ZENDESK = "Project Creation Feedback"
private val NO_PROBLEM = "No problem"
private val EMPTY_PROJECT = "Empty project"
private val HARD_TO_FIND = "Hard to find"
private val LACK_OF_FRAMEWORK = "Lack of framework"
private val OTHER = "Other"
private val systemInfoData: ProjectCreationFeedbackSystemInfoData = createProjectCreationFeedbackSystemInfoData(createdProjectTypeName)
private val propertyGraph = PropertyGraph()
private val ratingProperty = propertyGraph.property(0)
private val checkBoxNoProblemProperty = propertyGraph.property(false)
private val checkBoxEmptyProjectDontWorkProperty = propertyGraph.property(false)
private val checkBoxHardFindDesireProjectProperty = propertyGraph.property(false)
private val checkBoxFrameworkProperty = propertyGraph.property(false)
private val checkBoxOtherProperty = propertyGraph.property(false)
private val textFieldOtherProblemProperty = propertyGraph.property("")
private val textAreaOverallFeedbackProperty = propertyGraph.property("")
private val checkBoxEmailProperty = propertyGraph.property(false)
private val textFieldEmailProperty = propertyGraph.lazyProperty { LicensingFacade.INSTANCE?.getLicenseeEmail().orEmpty() }
private var ratingComponent: RatingComponent? = null
private var missingRatingTooltip: JComponent? = null
private var checkBoxOther: JBCheckBox? = null
private var checkBoxEmail: JBCheckBox? = null
private val textAreaRowSize = 4
private val textFieldEmailColumnSize = 25
private val textFieldOtherColumnSize = 41
private val textAreaOverallFeedbackColumnSize = 42
private val jsonConverter = Json { prettyPrint = true }
init {
init()
title = NPWFeedbackBundle.message("dialog.creation.project.top.title")
isResizable = false
}
override fun doOKAction() {
super.doOKAction()
val projectCreationInfoState = ProjectCreationInfoService.getInstance().state
projectCreationInfoState.feedbackSent = true
val email = if (checkBoxEmailProperty.get()) textFieldEmailProperty.get() else DEFAULT_NO_EMAIL_ZENDESK_REQUESTER
submitGeneralFeedback(project,
TICKET_TITLE_ZENDESK,
createRequestDescription(),
FEEDBACK_TYPE_ZENDESK,
createCollectedDataJsonString(),
email,
{ },
{ },
if (forTest) FeedbackRequestType.TEST_REQUEST else FeedbackRequestType.PRODUCTION_REQUEST
)
}
private fun createRequestDescription(): String {
return buildString {
appendLine(NPWFeedbackBundle.message("dialog.creation.project.zendesk.title"))
appendLine(NPWFeedbackBundle.message("dialog.creation.project.zendesk.description"))
appendLine()
appendLine(NPWFeedbackBundle.message("dialog.created.project.zendesk.rating.label"))
appendLine(" ${ratingProperty.get()}")
appendLine()
appendLine(NPWFeedbackBundle.message("dialog.created.project.zendesk.problems.title"))
appendLine(createProblemsList())
appendLine()
appendLine(NPWFeedbackBundle.message("dialog.created.project.zendesk.overallExperience.label"))
appendLine(textAreaOverallFeedbackProperty.get())
}
}
private fun createProblemsList(): String {
val resultProblemsList = mutableListOf<String>()
if (checkBoxNoProblemProperty.get()) {
resultProblemsList.add(NPWFeedbackBundle.message("dialog.created.project.zendesk.problem.1.label"))
}
if (checkBoxEmptyProjectDontWorkProperty.get()) {
resultProblemsList.add(NPWFeedbackBundle.message("dialog.created.project.zendesk.problem.2.label"))
}
if (checkBoxHardFindDesireProjectProperty.get()) {
resultProblemsList.add(NPWFeedbackBundle.message("dialog.created.project.zendesk.problem.3.label"))
}
if (checkBoxFrameworkProperty.get()) {
resultProblemsList.add(NPWFeedbackBundle.message("dialog.created.project.zendesk.problem.4.label"))
}
if (checkBoxOtherProperty.get()) {
resultProblemsList.add(textFieldOtherProblemProperty.get())
}
return resultProblemsList.joinToString(prefix = "- ", separator = "\n- ")
}
private fun createCollectedDataJsonString(): String {
val collectedData = buildJsonObject {
put(FEEDBACK_REPORT_ID_KEY, "new_project_creation_dialog")
put("format_version", FEEDBACK_JSON_VERSION)
put("rating", ratingProperty.get())
put("project_type", systemInfoData.createdProjectTypeName)
putJsonArray("problems") {
if (checkBoxNoProblemProperty.get()) {
add(createProblemJsonObject(NO_PROBLEM))
}
if (checkBoxEmptyProjectDontWorkProperty.get()) {
add(createProblemJsonObject(EMPTY_PROJECT))
}
if (checkBoxHardFindDesireProjectProperty.get()) {
add(createProblemJsonObject(HARD_TO_FIND))
}
if (checkBoxFrameworkProperty.get()) {
add(createProblemJsonObject(LACK_OF_FRAMEWORK))
}
if (checkBoxOtherProperty.get()) {
add(createProblemJsonObject(OTHER, textFieldOtherProblemProperty.get()))
}
}
put("overall_exp", textAreaOverallFeedbackProperty.get())
put("system_info", jsonConverter.encodeToJsonElement(systemInfoData.commonSystemInfo))
}
return jsonConverter.encodeToString(collectedData)
}
private fun createProblemJsonObject(name: String, description: String? = null): JsonObject {
return buildJsonObject {
put("name", name)
if (description != null) {
put("description", description)
}
}
}
override fun createCenterPanel(): JComponent {
val mainPanel = panel {
row {
label(NPWFeedbackBundle.message("dialog.creation.project.title")).applyToComponent {
font = JBFont.h1()
}
}
row {
label(NPWFeedbackBundle.message("dialog.creation.project.description"))
}.bottomGap(BottomGap.MEDIUM)
row {
ratingComponent = RatingComponent().also {
it.addPropertyChangeListener(RatingComponent.RATING_PROPERTY) { _ ->
ratingProperty.set(it.myRating)
missingRatingTooltip?.isVisible = false
}
cell(it)
.label(NPWFeedbackBundle.message("dialog.created.project.rating.label"), LabelPosition.TOP)
}
missingRatingTooltip = label(NPWFeedbackBundle.message("dialog.created.project.rating.required")).applyToComponent {
border = JBUI.Borders.compound(PopupBorder.Factory.createColored(JBUI.CurrentTheme.Validator.errorBorderColor()),
JBUI.Borders.empty(JBUI.scale(4), JBUI.scale(8)))
background = JBUI.CurrentTheme.Validator.errorBackgroundColor()
isVisible = false
isOpaque = true
}.component
}.bottomGap(BottomGap.MEDIUM)
row {
checkBox(NPWFeedbackBundle.message("dialog.created.project.checkbox.1.label")).bindSelected(checkBoxNoProblemProperty)
.label(NPWFeedbackBundle.message("dialog.created.project.group.checkbox.title"), LabelPosition.TOP)
}.topGap(TopGap.MEDIUM)
row {
checkBox(NPWFeedbackBundle.message("dialog.created.project.checkbox.2.label")).bindSelected(checkBoxEmptyProjectDontWorkProperty)
}
row {
checkBox(NPWFeedbackBundle.message("dialog.created.project.checkbox.3.label")).bindSelected(checkBoxHardFindDesireProjectProperty)
}
row {
checkBox(NPWFeedbackBundle.message("dialog.created.project.checkbox.4.label")).bindSelected(checkBoxFrameworkProperty)
}
row {
checkBox("").bindSelected(checkBoxOtherProperty).applyToComponent {
checkBoxOther = this
}.customize(JBGaps(right = 4))
textField()
.bindText(textFieldOtherProblemProperty)
.columns(textFieldOtherColumnSize)
.errorOnApply(NPWFeedbackBundle.message("dialog.created.project.checkbox.5.required")) {
checkBoxOtherProperty.get() && it.text.isBlank()
}
.applyToComponent {
emptyText.text = NPWFeedbackBundle.message("dialog.created.project.checkbox.5.placeholder")
textFieldOtherProblemProperty.afterChange {
if (it.isNotBlank()) {
checkBoxOtherProperty.set(true)
}
else {
checkBoxOtherProperty.set(false)
}
}
putClientProperty(TextComponentEmptyText.STATUS_VISIBLE_FUNCTION, Predicate<JBTextField> { it.text.isEmpty() })
}
}.bottomGap(BottomGap.MEDIUM)
row {
textArea()
.bindText(textAreaOverallFeedbackProperty)
.rows(textAreaRowSize)
.columns(textAreaOverallFeedbackColumnSize)
.label(NPWFeedbackBundle.message("dialog.created.project.textarea.label"), LabelPosition.TOP)
.applyToComponent {
adjustBehaviourForFeedbackForm()
}
}.bottomGap(BottomGap.MEDIUM).topGap(TopGap.SMALL)
row {
checkBox(NPWFeedbackBundle.message("dialog.created.project.checkbox.email"))
.bindSelected(checkBoxEmailProperty).applyToComponent {
checkBoxEmail = this
}
}.topGap(TopGap.MEDIUM)
indent {
row {
textField().bindText(textFieldEmailProperty).columns(textFieldEmailColumnSize).applyToComponent {
emptyText.text = NPWFeedbackBundle.message("dialog.created.project.textfield.email.placeholder")
isEnabled = checkBoxEmailProperty.get()
checkBoxEmail?.addActionListener { _ ->
isEnabled = checkBoxEmailProperty.get()
}
putClientProperty(TextComponentEmptyText.STATUS_VISIBLE_FUNCTION, Predicate<JBTextField> { it.text.isEmpty() })
}.errorOnApply(NPWFeedbackBundle.message("dialog.created.project.textfield.email.required")) {
checkBoxEmailProperty.get() && it.text.isBlank()
}.errorOnApply(ApplicationBundle.message("feedback.form.email.invalid")) {
checkBoxEmailProperty.get() && it.text.isNotBlank() && !it.text.matches(Regex(".+@.+\\..+"))
}
}.bottomGap(BottomGap.MEDIUM)
}
row {
feedbackAgreement(project) {
showProjectCreationFeedbackSystemInfoDialog(project, systemInfoData)
}
}.bottomGap(BottomGap.SMALL).topGap(TopGap.MEDIUM)
}.also { dialog ->
dialog.border = JBEmptyBorder(JBUI.scale(15), JBUI.scale(10), JBUI.scale(0), JBUI.scale(10))
}
return JBScrollPane(mainPanel, JBScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JBScrollPane.HORIZONTAL_SCROLLBAR_NEVER).apply {
border = JBEmptyBorder(0)
}
}
override fun createActions(): Array<Action> {
return arrayOf(cancelAction, okAction)
}
override fun getOKAction(): Action {
return object : DialogWrapper.OkAction() {
init {
putValue(Action.NAME, NPWFeedbackBundle.message("dialog.created.project.ok"))
}
override fun doAction(e: ActionEvent) {
val ratingComponent = ratingComponent
missingRatingTooltip?.isVisible = ratingComponent?.myRating == 0
if (ratingComponent == null || ratingComponent.myRating != 0) {
super.doAction(e)
}
else {
enabled = false
SwingUtilities.invokeLater {
ratingComponent.requestFocusInWindow()
}
}
}
}
}
}
@Serializable
private data class ProjectCreationFeedbackSystemInfoData(
val createdProjectTypeName: String,
val commonSystemInfo: CommonFeedbackSystemInfoData
)
private fun showProjectCreationFeedbackSystemInfoDialog(project: Project?,
systemInfoData: ProjectCreationFeedbackSystemInfoData
) = showFeedbackSystemInfoDialog(project, systemInfoData.commonSystemInfo) {
row(NPWFeedbackBundle.message("dialog.created.project.system.info.panel.project.type")) {
label(systemInfoData.createdProjectTypeName) //NON-NLS
}
}
private fun createProjectCreationFeedbackSystemInfoData(createdProjectTypeName: String): ProjectCreationFeedbackSystemInfoData {
return ProjectCreationFeedbackSystemInfoData(createdProjectTypeName, CommonFeedbackSystemInfoData.getCurrentData())
}
| apache-2.0 | 6b539666723642cc53d691526018f64f | 41.765579 | 138 | 0.712115 | 4.883768 | false | false | false | false |
google/accompanist | navigation-animation/src/androidTest/java/com/google/accompanist/navigation/animation/AnimatedNavHostTest.kt | 1 | 8724 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.accompanist.navigation.animation
import android.app.Activity
import android.content.Intent
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.AnimationConstants
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.text.BasicText
import androidx.compose.material.TextField
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.navDeepLink
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@OptIn(ExperimentalAnimationApi::class)
@LargeTest
@RunWith(AndroidJUnit4::class)
class AnimatedNavHostTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun testAnimatedNavHost() {
lateinit var navController: NavHostController
composeTestRule.mainClock.autoAdvance = false
composeTestRule.setContent {
navController = rememberAnimatedNavController()
AnimatedNavHost(navController, startDestination = first) {
composable(first) { BasicText(first) }
composable(second) { BasicText(second) }
}
}
val firstEntry = navController.currentBackStackEntry
composeTestRule.mainClock.autoAdvance = true
composeTestRule.runOnIdle {
assertThat(firstEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.RESUMED)
}
composeTestRule.mainClock.autoAdvance = false
composeTestRule.runOnIdle {
navController.navigate(second)
}
assertThat(firstEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.CREATED)
assertThat(navController.currentBackStackEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.STARTED)
// advance half way between the crossfade
composeTestRule.mainClock.advanceTimeBy(AnimationConstants.DefaultDurationMillis.toLong() / 2)
assertThat(firstEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.CREATED)
assertThat(navController.currentBackStackEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.STARTED)
composeTestRule.onNodeWithText(first).assertExists()
composeTestRule.onNodeWithText(second).assertExists()
composeTestRule.mainClock.autoAdvance = true
composeTestRule.runOnIdle {
assertThat(firstEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.CREATED)
assertThat(navController.currentBackStackEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.RESUMED)
}
composeTestRule.mainClock.autoAdvance = false
val secondEntry = navController.currentBackStackEntry
composeTestRule.runOnIdle {
navController.popBackStack()
}
assertThat(navController.currentBackStackEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.STARTED)
assertThat(secondEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.CREATED)
// advance half way between the crossfade
composeTestRule.mainClock.advanceTimeBy(AnimationConstants.DefaultDurationMillis.toLong() / 2)
assertThat(navController.currentBackStackEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.STARTED)
assertThat(secondEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.CREATED)
composeTestRule.onNodeWithText(first).assertExists()
composeTestRule.onNodeWithText(second).assertExists()
composeTestRule.mainClock.autoAdvance = true
composeTestRule.runOnIdle {
assertThat(navController.currentBackStackEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.RESUMED)
assertThat(secondEntry?.lifecycle?.currentState)
.isEqualTo(Lifecycle.State.DESTROYED)
}
}
@Test
fun testNestedAnimatedNavHostNullLambda() {
lateinit var navController: NavHostController
composeTestRule.setContent {
navController = rememberAnimatedNavController()
AnimatedNavHost(navController, startDestination = first) {
composable(first) { BasicText(first) }
navigation(second, "subGraph", enterTransition = { null }) {
composable(second) { BasicText(second) }
}
}
}
composeTestRule.runOnIdle {
navController.navigate(second)
}
}
@Test
fun testAnimatedNavHostDeeplink() {
lateinit var navController: NavHostController
composeTestRule.mainClock.autoAdvance = false
composeTestRule.setContent {
// Add the flags to make NavController think this is a deep link
val activity = LocalContext.current as? Activity
activity?.intent?.run {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
navController = rememberAnimatedNavController()
AnimatedNavHost(navController, startDestination = first) {
composable(first) { BasicText(first) }
composable(
second,
deepLinks = listOf(navDeepLink { action = Intent.ACTION_MAIN })
) {
BasicText(second)
}
}
}
composeTestRule.waitForIdle()
val firstEntry = navController.getBackStackEntry(first)
val secondEntry = navController.getBackStackEntry(second)
composeTestRule.mainClock.autoAdvance = true
composeTestRule.runOnIdle {
assertThat(firstEntry.lifecycle.currentState)
.isEqualTo(Lifecycle.State.CREATED)
assertThat(secondEntry.lifecycle.currentState)
.isEqualTo(Lifecycle.State.RESUMED)
}
}
@Test
fun testStateSavedByCrossFade() {
lateinit var navController: NavHostController
lateinit var text: MutableState<String>
composeTestRule.setContent {
navController = rememberAnimatedNavController()
AnimatedNavHost(navController, "start") {
composable("start") {
text = rememberSaveable { mutableStateOf("") }
Column {
TextField(value = text.value, onValueChange = { text.value = it })
}
}
composable("second") { }
}
}
composeTestRule.onNodeWithText("test").assertDoesNotExist()
text.value = "test"
composeTestRule.onNodeWithText("test").assertExists()
composeTestRule.runOnIdle {
navController.navigate("second") {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
}
composeTestRule.runOnIdle {
navController.navigate("start") {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
}
composeTestRule.onNodeWithText("test").assertExists()
}
}
private const val first = "first"
private const val second = "second"
| apache-2.0 | 06b7e7afe7f2a8989e64d90413691017 | 34.319838 | 102 | 0.663457 | 5.701961 | false | true | false | false |
ktorio/ktor | ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/RequestResponseBuilderCommon.kt | 1 | 1272 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http.cio
import io.ktor.http.*
import io.ktor.utils.io.core.*
/**
* Builds an HTTP request or response
*/
public expect class RequestResponseBuilder() {
/**
* Append response status line
*/
public fun responseLine(version: CharSequence, status: Int, statusText: CharSequence)
/**
* Append request line
*/
public fun requestLine(method: HttpMethod, uri: CharSequence, version: CharSequence)
/**
* Append a line
*/
public fun line(line: CharSequence)
/**
* Append raw bytes
*/
public fun bytes(content: ByteArray, offset: Int = 0, length: Int = content.size)
/**
* Append header line
*/
public fun headerLine(name: CharSequence, value: CharSequence)
/**
* Append an empty line (CR + LF in fact)
*/
public fun emptyLine()
/**
* Build a packet of request/response
*/
public fun build(): ByteReadPacket
/**
* Release all resources hold by the builder
*/
public fun release()
}
private const val SP: Byte = 0x20
private const val CR: Byte = 0x0d
private const val LF: Byte = 0x0a
| apache-2.0 | 8eeeb24a9b5402d50ef9b19527840d5a | 21.315789 | 118 | 0.638365 | 4.103226 | false | false | false | false |
google/android-fhir | engine/src/main/java/com/google/android/fhir/db/impl/entities/NumberIndexEntity.kt | 1 | 1588 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.db.impl.entities
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.google.android.fhir.index.entities.NumberIndex
import java.util.UUID
import org.hl7.fhir.r4.model.ResourceType
@Entity(
indices =
[
Index(value = ["resourceType", "index_name", "index_value"]),
// keep this index for faster foreign lookup
Index(value = ["resourceUuid"])],
foreignKeys =
[
ForeignKey(
entity = ResourceEntity::class,
parentColumns = ["resourceUuid"],
childColumns = ["resourceUuid"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.NO_ACTION,
deferred = true
)]
)
internal data class NumberIndexEntity(
@PrimaryKey(autoGenerate = true) val id: Long,
val resourceUuid: UUID,
val resourceType: ResourceType,
@Embedded(prefix = "index_") val index: NumberIndex,
)
| apache-2.0 | 214085ea45f17c9618fd76ba587f324b | 30.76 | 75 | 0.713476 | 4.189974 | false | false | false | false |
android/project-replicator | model/src/main/kotlin/com/android/gradle/replicator/model/internal/DefaultAndroidInfo.kt | 1 | 2463 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gradle.replicator.model.internal
import com.android.gradle.replicator.model.AndroidInfo
import com.android.gradle.replicator.model.BuildFeaturesInfo
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
data class DefaultAndroidInfo(
override val compileSdkVersion: String,
override val minSdkVersion: Int,
override val targetSdkVersion: Int,
override val buildFeatures: BuildFeaturesInfo
) : AndroidInfo
class AndroidAdapter: TypeAdapter<AndroidInfo>() {
override fun write(output: JsonWriter, value: AndroidInfo) {
value.toJsonObject(output) {
name("compileSdkVersion").value(it.compileSdkVersion)
name("minSdkVersion").value(it.minSdkVersion)
name("targetSdkVersion").value(it.targetSdkVersion)
name("buildFeatures")
BuildFeaturesInfoAdapter().write(this, it.buildFeatures)
}
}
override fun read(input: JsonReader): AndroidInfo {
var compileSdkVersion: String? = null
var minSdkVersion: Int? = null
var targetSdkVersion: Int? = null
var buildFeaturesInfo: BuildFeaturesInfo? = null
input.readObjectProperties {
when (it) {
"compileSdkVersion" -> compileSdkVersion = nextString()
"minSdkVersion" -> minSdkVersion = nextInt()
"targetSdkVersion" -> targetSdkVersion = nextInt()
"buildFeatures" -> buildFeaturesInfo = BuildFeaturesInfoAdapter().read(input)
else -> skipValue()
}
}
return DefaultAndroidInfo(
compileSdkVersion ?: "",
minSdkVersion ?: 0,
targetSdkVersion ?: 0,
buildFeaturesInfo ?: DefaultBuildFeaturesInfo()
)
}
} | apache-2.0 | faafb1afd24398a5a23a2dc95e96006c | 35.776119 | 93 | 0.679659 | 4.916168 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/DeprecatedJavaAnnotationFix.kt | 2 | 4390 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.actions.OptimizeImportsProcessor
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
internal class DeprecatedJavaAnnotationFix(
element: KtAnnotationEntry,
private val annotationFqName: FqName
) : KotlinQuickFixAction<KtAnnotationEntry>(element) {
override fun getFamilyName() = KotlinBundle.message("replace.annotation")
override fun getText(): String = KotlinBundle.message("replace.annotation.with.0", annotationFqName.asString())
override fun startInWriteAction(): Boolean = false
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val psiFactory = KtPsiFactory(project)
val arguments = updateAnnotation(psiFactory)
val replacementAnnotation = psiFactory.createAnnotationEntry("@$annotationFqName")
val valueArgumentList = psiFactory.buildValueArgumentList {
appendFixedText("(")
arguments.forEach { argument ->
appendExpression(argument.getArgumentExpression())
}
appendFixedText(")")
}
if (arguments.isNotEmpty()) {
replacementAnnotation.add(valueArgumentList)
}
val replaced = runWriteAction {
element.replaced(replacementAnnotation)
}
OptimizeImportsProcessor(project, file).run()
runWriteAction {
ShortenReferences.DEFAULT.process(replaced)
}
}
private fun updateAnnotation(psiFactory: KtPsiFactory): List<KtValueArgument> {
val bindingContext = element?.analyze() ?: return emptyList()
val descriptor = bindingContext[BindingContext.ANNOTATION, element]
val name = descriptor?.fqName ?: return emptyList()
val argumentOutput = mutableListOf<KtValueArgument>()
if (name == RETENTION_FQ_NAME) {
for (arg in descriptor.allValueArguments.values) {
val typeAndValue = arg.value as? Pair<*, *>
val classId = typeAndValue?.first as? ClassId
val value = typeAndValue?.second
if (classId == RETENTION_POLICY_ID) {
val argument = when ((value as? Name)?.asString()) {
"SOURCE" -> psiFactory.createArgument("kotlin.annotation.AnnotationRetention.SOURCE")
"CLASS" -> psiFactory.createArgument("kotlin.annotation.AnnotationRetention.BINARY")
"RUNTIME" -> psiFactory.createArgument("kotlin.annotation.AnnotationRetention.RUNTIME")
else -> psiFactory.createArgument("${classId.shortClassName}.$value")
}
argumentOutput.add(argument)
}
}
}
return argumentOutput
}
companion object Factory : KotlinSingleIntentionActionFactory() {
private val RETENTION_FQ_NAME = FqName("java.lang.annotation.Retention")
private val RETENTION_POLICY_ID = ClassId(FqName("java.lang.annotation"), FqName("RetentionPolicy"), false)
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val castedDiagnostic = ErrorsJvm.DEPRECATED_JAVA_ANNOTATION.cast(diagnostic)
val updatedAnnotation = castedDiagnostic.a as? FqName ?: return null
val entry = diagnostic.psiElement as? KtAnnotationEntry ?: return null
return DeprecatedJavaAnnotationFix(entry, updatedAnnotation)
}
}
} | apache-2.0 | bae67e774df593de23a3cf21b9913e14 | 42.91 | 158 | 0.691344 | 5.32767 | false | false | false | false |
itohiro73/intellij-custom-language-support-kotlin | src/main/kotlin/jp/itohiro/intellij/simpleplugin/SimpleColorSettingsPage.kt | 1 | 2224 | package jp.itohiro.intellij.simpleplugin
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighter
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import org.jetbrains.annotations.Nullable
import javax.swing.Icon
public class SimpleColorSettingsPage: ColorSettingsPage {
private val DESCRIPTORS = arrayOf(
AttributesDescriptor("Key", SimpleSyntaxHighlighter.KEY),
AttributesDescriptor("Separator", SimpleSyntaxHighlighter.SEPARATOR),
AttributesDescriptor("Value", SimpleSyntaxHighlighter.VALUE)
)
@Nullable
override fun getAdditionalHighlightingTagToDescriptorMap(): MutableMap<String, TextAttributesKey>? {
return null;
}
@Nullable
override fun getIcon(): Icon? {
return SimpleIcons.ICON;
}
@Nullable
override fun getHighlighter(): SyntaxHighlighter {
return SimpleSyntaxHighlighter()
}
@Nullable
override fun getDemoText(): String {
return "# You are reading the \".properties\" entry.\n" +
"! The exclamation mark can also mark text as comments.\n" +
"website = http://en.wikipedia.org/\n" +
"language = English\n" +
"# The backslash below tells the application to continue reading\n" +
"# the value onto the next line.\n" +
"message = Welcome to \\\n" +
" Wikipedia!\n" +
"# Add spaces to the key\n" +
"key\\ with\\ spaces = This is the value that could be looked up with the key \"key with spaces\".\n" +
"# Unicode\n" +
"tab : \\u0009";
}
@Nullable
override fun getAttributeDescriptors(): Array<out AttributesDescriptor> {
return DESCRIPTORS
}
@Nullable
override fun getColorDescriptors(): Array<out ColorDescriptor> {
return ColorDescriptor.EMPTY_ARRAY
}
@Nullable
override fun getDisplayName(): String {
return "Simple"
}
} | apache-2.0 | 418386afa7a903a5be11911bc83d2dec | 33.765625 | 119 | 0.645234 | 5.220657 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/substring/ReplaceSubstringWithSubstringBeforeAfterIntentions.kt | 5 | 2636 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.substring
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtExpression
class ReplaceSubstringWithSubstringAfterInspection : ReplaceSubstringInspection() {
override fun inspectionText(element: KtDotQualifiedExpression): String =
KotlinBundle.message("inspection.replace.substring.with.substring.after.display.name")
override val defaultFixText: String get() = KotlinBundle.message("replace.substring.call.with.substringafter.call")
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
element.replaceWith(
"$0.substringAfter($1)",
(element.getArgumentExpression(0) as KtDotQualifiedExpression).getArgumentExpression(0)
)
}
override fun isApplicableInner(element: KtDotQualifiedExpression): Boolean {
val arguments = element.callExpression?.valueArguments ?: return false
return arguments.size == 1 && isIndexOfCall(arguments[0].getArgumentExpression(), element.receiverExpression)
}
}
class ReplaceSubstringWithSubstringBeforeInspection : ReplaceSubstringInspection() {
override fun inspectionText(element: KtDotQualifiedExpression): String =
KotlinBundle.message("inspection.replace.substring.with.substring.before.display.name")
override val defaultFixText: String get() = KotlinBundle.message("replace.substring.call.with.substringbefore.call")
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
element.replaceWith(
"$0.substringBefore($1)",
(element.getArgumentExpression(1) as KtDotQualifiedExpression).getArgumentExpression(0)
)
}
override fun isApplicableInner(element: KtDotQualifiedExpression): Boolean {
val arguments = element.callExpression?.valueArguments ?: return false
return arguments.size == 2
&& element.isFirstArgumentZero()
&& isIndexOfCall(arguments[1].getArgumentExpression(), element.receiverExpression)
}
}
private fun KtDotQualifiedExpression.getArgumentExpression(index: Int): KtExpression {
return callExpression!!.valueArguments[index].getArgumentExpression()!!
}
| apache-2.0 | ddd4a4678e66c59811a10ed3cd5c48a7 | 46.927273 | 158 | 0.759863 | 5.240557 | false | false | false | false |
fwcd/kotlin-language-server | server/src/main/kotlin/org/javacs/kt/index/Symbol.kt | 1 | 1002 | package org.javacs.kt.index
import org.jetbrains.kotlin.name.FqName
data class Symbol(
// TODO: Store location (e.g. using a URI)
val fqName: FqName,
val kind: Kind,
val visibility: Visibility,
val extensionReceiverType: FqName?
) {
enum class Kind(val rawValue: Int) {
CLASS(0),
INTERFACE(1),
FUNCTION(2),
VARIABLE(3),
MODULE(4),
ENUM(5),
ENUM_MEMBER(6),
CONSTRUCTOR(7),
FIELD(8),
UNKNOWN(9);
companion object {
fun fromRaw(rawValue: Int) = Kind.values().firstOrNull { it.rawValue == rawValue } ?: Kind.UNKNOWN
}
}
enum class Visibility(val rawValue: Int) {
PRIAVTE_TO_THIS(0),
PRIVATE(1),
INTERNAL(2),
PROTECTED(3),
PUBLIC(4),
UNKNOWN(5);
companion object {
fun fromRaw(rawValue: Int) = Visibility.values().firstOrNull { it.rawValue == rawValue } ?: Visibility.UNKNOWN
}
}
}
| mit | a071e2501267331a6ce4c0c1189fe364 | 23.439024 | 122 | 0.560878 | 4.05668 | false | false | false | false |
MarkusAmshove/Kluent | jvm/src/test/kotlin/org/amshove/kluent/tests/assertions/time/instant/ShouldBeBeforeShould.kt | 1 | 853 | package org.amshove.kluent.tests.assertions.time.instant
import org.amshove.kluent.shouldBeBefore
import java.time.Instant
import kotlin.test.Test
import kotlin.test.assertFails
class ShouldBeBeforeShould {
@Test
fun passWhenTestingAnEarlierInstant() {
val instantToTest = Instant.ofEpochSecond(5000)
val instantAfter = instantToTest.plusSeconds(10)
instantToTest shouldBeBefore instantAfter
}
@Test
fun failWhenTestingALaterInstant() {
val instantToTest = Instant.ofEpochSecond(5000)
val dateBefore = instantToTest.minusSeconds(10)
assertFails { instantToTest shouldBeBefore dateBefore }
}
@Test
fun failWhenTestingTheSameInstant() {
val instantToTest = Instant.ofEpochSecond(5000)
assertFails { instantToTest shouldBeBefore instantToTest }
}
}
| mit | 65aef6ab17ec48ca1682e380cd59ae5f | 26.516129 | 66 | 0.73388 | 4.959302 | false | true | false | false |
Leanplum/Leanplum-Android-SDK | AndroidSDKCore/src/main/java/com/leanplum/actions/internal/ActionManagerTriggering.kt | 1 | 1980 | /*
* Copyright 2022, Leanplum, Inc. All rights reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.leanplum.actions.internal
import com.leanplum.ActionContext
import com.leanplum.internal.ActionManager
import com.leanplum.internal.Log
fun ActionManager.trigger(
context: ActionContext,
priority: Priority = Priority.DEFAULT) {
trigger(listOf(context), priority)
}
fun ActionManager.trigger(
contexts: List<ActionContext>,
priority: Priority = Priority.DEFAULT,
trigger: ActionsTrigger? = null) {
if (contexts.isEmpty()) return
// By default, add only one message to queue if `prioritizeMessages` is not implemented
// This ensures backwards compatibility
val orderedContexts =
messageDisplayController?.prioritizeMessages(contexts, trigger) ?: listOf(contexts.first())
val actions: List<Action> = orderedContexts.map { context -> Action.create(context) }
Log.d("[ActionManager]: triggering with priority: ${priority.name} and actions: $orderedContexts")
when (priority) {
Priority.HIGH -> insertActions(actions)
Priority.DEFAULT -> appendActions(actions)
}
}
fun ActionManager.triggerDelayedMessages() {
appendActions(delayedQueue.popAll())
}
| apache-2.0 | 609233c187dba9210276273331bcdd00 | 32.559322 | 100 | 0.752525 | 4.276458 | false | false | false | false |
google/intellij-community | plugins/kotlin/util/test-generator-fe10/test/org/jetbrains/kotlin/fe10/testGenerator/Fe10GenerateTests.kt | 1 | 66269 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.fe10.testGenerator
import org.jetbrains.kotlin.AbstractDataFlowValueRenderingTest
import org.jetbrains.kotlin.addImport.AbstractAddImportTest
import org.jetbrains.kotlin.addImportAlias.AbstractAddImportAliasTest53
import org.jetbrains.kotlin.asJava.classes.AbstractUltraLightClassLoadingTest
import org.jetbrains.kotlin.asJava.classes.AbstractUltraLightClassSanityTest
import org.jetbrains.kotlin.asJava.classes.AbstractUltraLightFacadeClassTest15
import org.jetbrains.kotlin.asJava.classes.AbstractUltraLightScriptLoadingTest
import org.jetbrains.kotlin.checkers.*
import org.jetbrains.kotlin.copyright.AbstractUpdateKotlinCopyrightTest
import org.jetbrains.kotlin.findUsages.*
import org.jetbrains.kotlin.formatter.AbstractEnterHandlerTest
import org.jetbrains.kotlin.formatter.AbstractFormatterTest
import org.jetbrains.kotlin.idea.AbstractExpressionSelectionTest
import org.jetbrains.kotlin.idea.AbstractSmartSelectionTest
import org.jetbrains.kotlin.idea.AbstractWorkSelectionTest
import org.jetbrains.kotlin.idea.actions.AbstractGotoTestOrCodeActionTest
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.caches.resolve.*
import org.jetbrains.kotlin.idea.codeInsight.*
import org.jetbrains.kotlin.idea.codeInsight.codevision.AbstractKotlinCodeVisionProviderTest
import org.jetbrains.kotlin.idea.codeInsight.generate.AbstractCodeInsightActionTest
import org.jetbrains.kotlin.idea.codeInsight.generate.AbstractGenerateHashCodeAndEqualsActionTest
import org.jetbrains.kotlin.idea.codeInsight.generate.AbstractGenerateTestSupportMethodActionTest
import org.jetbrains.kotlin.idea.codeInsight.generate.AbstractGenerateToStringActionTest
import org.jetbrains.kotlin.idea.codeInsight.hints.AbstractKotlinArgumentsHintsProviderTest
import org.jetbrains.kotlin.idea.codeInsight.hints.AbstractKotlinLambdasHintsProvider
import org.jetbrains.kotlin.idea.codeInsight.hints.AbstractKotlinRangesHintsProviderTest
import org.jetbrains.kotlin.idea.codeInsight.hints.AbstractKotlinReferenceTypeHintsProviderTest
import org.jetbrains.kotlin.idea.codeInsight.intentions.shared.AbstractSharedK1InspectionTest
import org.jetbrains.kotlin.idea.codeInsight.intentions.shared.AbstractSharedK1IntentionTest
import org.jetbrains.kotlin.idea.codeInsight.intentions.shared.AbstractSharedK1LocalInspectionTest
import org.jetbrains.kotlin.idea.codeInsight.moveUpDown.AbstractMoveLeftRightTest
import org.jetbrains.kotlin.idea.codeInsight.moveUpDown.AbstractMoveStatementTest
import org.jetbrains.kotlin.idea.codeInsight.postfix.AbstractPostfixTemplateProviderTest
import org.jetbrains.kotlin.idea.codeInsight.surroundWith.AbstractSurroundWithTest
import org.jetbrains.kotlin.idea.codeInsight.unwrap.AbstractUnwrapRemoveTest
import org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization.AbstractSerializationPluginIdeDiagnosticTest
import org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization.AbstractSerializationQuickFixTest
import org.jetbrains.kotlin.idea.completion.test.*
import org.jetbrains.kotlin.idea.completion.test.handlers.AbstractBasicCompletionHandlerTest
import org.jetbrains.kotlin.idea.completion.test.handlers.AbstractCompletionCharFilterTest
import org.jetbrains.kotlin.idea.completion.test.handlers.AbstractKeywordCompletionHandlerTest
import org.jetbrains.kotlin.idea.completion.test.handlers.AbstractSmartCompletionHandlerTest
import org.jetbrains.kotlin.idea.completion.test.weighers.AbstractBasicCompletionWeigherTest
import org.jetbrains.kotlin.idea.completion.test.weighers.AbstractSmartCompletionWeigherTest
import org.jetbrains.kotlin.idea.configuration.AbstractGradleConfigureProjectByChangingFileTest
import org.jetbrains.kotlin.idea.conversion.copy.AbstractLiteralKotlinToKotlinCopyPasteTest
import org.jetbrains.kotlin.idea.conversion.copy.AbstractLiteralTextToKotlinCopyPasteTest
import org.jetbrains.kotlin.idea.coverage.AbstractKotlinCoverageOutputFilesTest
import org.jetbrains.kotlin.idea.debugger.evaluate.AbstractCodeFragmentAutoImportTest
import org.jetbrains.kotlin.idea.debugger.evaluate.AbstractCodeFragmentCompletionHandlerTest
import org.jetbrains.kotlin.idea.debugger.evaluate.AbstractCodeFragmentCompletionTest
import org.jetbrains.kotlin.idea.debugger.evaluate.AbstractCodeFragmentHighlightingTest
import org.jetbrains.kotlin.idea.debugger.test.*
import org.jetbrains.kotlin.idea.debugger.test.sequence.exec.AbstractSequenceTraceTestCase
import org.jetbrains.kotlin.idea.debugger.test.sequence.exec.AbstractSequenceTraceWithIREvaluatorTestCase
import org.jetbrains.kotlin.idea.decompiler.navigation.AbstractNavigateJavaToLibrarySourceTest
import org.jetbrains.kotlin.idea.decompiler.navigation.AbstractNavigateToDecompiledLibraryTest
import org.jetbrains.kotlin.idea.decompiler.navigation.AbstractNavigateToLibrarySourceTest
import org.jetbrains.kotlin.idea.decompiler.navigation.AbstractNavigateToLibrarySourceTestWithJS
import org.jetbrains.kotlin.idea.decompiler.stubBuilder.AbstractLoadJavaClsStubTest
import org.jetbrains.kotlin.idea.decompiler.textBuilder.AbstractCommonDecompiledTextFromJsMetadataTest
import org.jetbrains.kotlin.idea.decompiler.textBuilder.AbstractCommonDecompiledTextTest
import org.jetbrains.kotlin.idea.decompiler.textBuilder.AbstractJsDecompiledTextFromJsMetadataTest
import org.jetbrains.kotlin.idea.decompiler.textBuilder.AbstractJvmDecompiledTextTest
import org.jetbrains.kotlin.idea.editor.backspaceHandler.AbstractBackspaceHandlerTest
import org.jetbrains.kotlin.idea.editor.commenter.AbstractKotlinCommenterTest
import org.jetbrains.kotlin.idea.editor.quickDoc.AbstractQuickDocProviderTest
import org.jetbrains.kotlin.idea.externalAnnotations.AbstractExternalAnnotationTest
import org.jetbrains.kotlin.idea.folding.AbstractKotlinFoldingTest
import org.jetbrains.kotlin.idea.hierarchy.AbstractHierarchyTest
import org.jetbrains.kotlin.idea.hierarchy.AbstractHierarchyWithLibTest
import org.jetbrains.kotlin.idea.highlighter.*
import org.jetbrains.kotlin.idea.imports.AbstractAutoImportTest
import org.jetbrains.kotlin.idea.imports.AbstractFilteringAutoImportTest
import org.jetbrains.kotlin.idea.imports.AbstractJsOptimizeImportsTest
import org.jetbrains.kotlin.idea.imports.AbstractJvmOptimizeImportsTest
import org.jetbrains.kotlin.idea.index.AbstractKotlinTypeAliasByExpansionShortNameIndexTest
import org.jetbrains.kotlin.idea.inspections.AbstractLocalInspectionTest
import org.jetbrains.kotlin.idea.inspections.AbstractMultiFileLocalInspectionTest
import org.jetbrains.kotlin.idea.inspections.AbstractViewOfflineInspectionTest
import org.jetbrains.kotlin.idea.intentions.AbstractConcatenatedStringGeneratorTest
import org.jetbrains.kotlin.idea.intentions.AbstractIntentionTest
import org.jetbrains.kotlin.idea.intentions.AbstractIntentionTest2
import org.jetbrains.kotlin.idea.intentions.AbstractMultiFileIntentionTest
import org.jetbrains.kotlin.idea.intentions.declarations.AbstractJoinLinesTest
import org.jetbrains.kotlin.idea.internal.AbstractBytecodeToolWindowTest
import org.jetbrains.kotlin.idea.kdoc.AbstractKDocHighlightingTest
import org.jetbrains.kotlin.idea.kdoc.AbstractKDocTypingTest
import org.jetbrains.kotlin.idea.maven.AbstractKotlinMavenInspectionTest
import org.jetbrains.kotlin.idea.maven.configuration.AbstractMavenConfigureProjectByChangingFileTest
import org.jetbrains.kotlin.idea.navigation.*
import org.jetbrains.kotlin.idea.navigationToolbar.AbstractKotlinNavBarTest
import org.jetbrains.kotlin.idea.parameterInfo.AbstractParameterInfoTest
import org.jetbrains.kotlin.idea.perf.stats.AbstractPerformanceBasicCompletionHandlerStatNamesTest
import org.jetbrains.kotlin.idea.perf.stats.AbstractPerformanceHighlightingStatNamesTest
import org.jetbrains.kotlin.idea.perf.synthetic.*
import org.jetbrains.kotlin.idea.quickfix.AbstractQuickFixMultiFileTest
import org.jetbrains.kotlin.idea.quickfix.AbstractQuickFixMultiModuleTest
import org.jetbrains.kotlin.idea.quickfix.AbstractQuickFixTest
import org.jetbrains.kotlin.idea.refactoring.AbstractNameSuggestionProviderTest
import org.jetbrains.kotlin.idea.refactoring.copy.AbstractCopyTest
import org.jetbrains.kotlin.idea.refactoring.copy.AbstractMultiModuleCopyTest
import org.jetbrains.kotlin.idea.refactoring.inline.AbstractInlineMultiFileTest
import org.jetbrains.kotlin.idea.refactoring.inline.AbstractInlineTest
import org.jetbrains.kotlin.idea.refactoring.inline.AbstractInlineTestWithSomeDescriptors
import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractExtractionTest
import org.jetbrains.kotlin.idea.refactoring.move.AbstractMoveTest
import org.jetbrains.kotlin.idea.refactoring.move.AbstractMultiModuleMoveTest
import org.jetbrains.kotlin.idea.refactoring.pullUp.AbstractPullUpTest
import org.jetbrains.kotlin.idea.refactoring.pushDown.AbstractPushDownTest
import org.jetbrains.kotlin.idea.refactoring.rename.AbstractMultiModuleRenameTest
import org.jetbrains.kotlin.idea.refactoring.rename.AbstractRenameTest
import org.jetbrains.kotlin.idea.refactoring.safeDelete.AbstractMultiModuleSafeDeleteTest
import org.jetbrains.kotlin.idea.refactoring.safeDelete.AbstractSafeDeleteTest
import org.jetbrains.kotlin.idea.repl.AbstractIdeReplCompletionTest
import org.jetbrains.kotlin.idea.resolve.*
import org.jetbrains.kotlin.idea.scratch.AbstractScratchLineMarkersTest
import org.jetbrains.kotlin.idea.scratch.AbstractScratchRunActionTest
import org.jetbrains.kotlin.idea.script.*
import org.jetbrains.kotlin.idea.search.refIndex.AbstractFindUsagesWithCompilerReferenceIndexTest
import org.jetbrains.kotlin.idea.search.refIndex.AbstractKotlinCompilerReferenceTest
import org.jetbrains.kotlin.idea.slicer.AbstractSlicerLeafGroupingTest
import org.jetbrains.kotlin.idea.slicer.AbstractSlicerMultiplatformTest
import org.jetbrains.kotlin.idea.slicer.AbstractSlicerNullnessGroupingTest
import org.jetbrains.kotlin.idea.slicer.AbstractSlicerTreeTest
import org.jetbrains.kotlin.idea.structureView.AbstractKotlinFileStructureTest
import org.jetbrains.kotlin.idea.stubs.AbstractMultiFileHighlightingTest
import org.jetbrains.kotlin.idea.stubs.AbstractResolveByStubTest
import org.jetbrains.kotlin.idea.stubs.AbstractStubBuilderTest
import org.jetbrains.kotlin.nj2k.*
import org.jetbrains.kotlin.nj2k.inference.common.AbstractCommonConstraintCollectorTest
import org.jetbrains.kotlin.nj2k.inference.mutability.AbstractMutabilityInferenceTest
import org.jetbrains.kotlin.nj2k.inference.nullability.AbstractNullabilityInferenceTest
import org.jetbrains.kotlin.pacelize.ide.test.AbstractParcelizeCheckerTest
import org.jetbrains.kotlin.pacelize.ide.test.AbstractParcelizeQuickFixTest
import org.jetbrains.kotlin.psi.patternMatching.AbstractPsiUnifierTest
import org.jetbrains.kotlin.search.AbstractAnnotatedMembersSearchTest
import org.jetbrains.kotlin.search.AbstractInheritorsSearchTest
import org.jetbrains.kotlin.shortenRefs.AbstractShortenRefsTest
import org.jetbrains.kotlin.test.TargetBackend
import org.jetbrains.kotlin.testGenerator.generator.TestGenerator
import org.jetbrains.kotlin.testGenerator.model.*
import org.jetbrains.kotlin.testGenerator.model.Patterns.DIRECTORY
import org.jetbrains.kotlin.testGenerator.model.Patterns.JAVA
import org.jetbrains.kotlin.testGenerator.model.Patterns.KT
import org.jetbrains.kotlin.testGenerator.model.Patterns.KTS
import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_OR_KTS
import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_OR_KTS_WITHOUT_DOTS
import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_WITHOUT_DOTS
import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_WITHOUT_DOT_AND_FIR_PREFIX
import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_WITHOUT_FIR_PREFIX
import org.jetbrains.kotlin.testGenerator.model.Patterns.TEST
import org.jetbrains.kotlin.testGenerator.model.Patterns.WS_KTS
import org.jetbrains.kotlin.tools.projectWizard.cli.AbstractProjectTemplateBuildFileGenerationTest
import org.jetbrains.kotlin.tools.projectWizard.cli.AbstractYamlBuildFileGenerationTest
import org.jetbrains.kotlin.tools.projectWizard.wizard.AbstractProjectTemplateNewWizardProjectImportTest
import org.jetbrains.kotlin.tools.projectWizard.wizard.AbstractYamlNewWizardProjectImportTest
import org.jetbrains.uast.test.kotlin.comparison.*
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
generateK1Tests()
}
fun generateK1Tests(isUpToDateCheck: Boolean = false) {
System.setProperty("java.awt.headless", "true")
TestGenerator.write(assembleWorkspace(), isUpToDateCheck)
}
private fun assembleWorkspace(): TWorkspace = workspace {
val excludedFirPrecondition = fun(name: String) = !name.endsWith(".fir.kt") && !name.endsWith(".fir.kts")
testGroup("jvm-debugger/test") {
testClass<AbstractKotlinSteppingTest> {
model("stepping/stepIntoAndSmartStepInto", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepIntoTest", testClassName = "StepInto")
model("stepping/stepIntoAndSmartStepInto", pattern = KT_WITHOUT_DOTS, testMethodName = "doSmartStepIntoTest", testClassName = "SmartStepInto")
model("stepping/stepInto", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepIntoTest", testClassName = "StepIntoOnly")
model("stepping/stepOut", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepOutTest")
model("stepping/stepOver", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepOverTest")
model("stepping/filters", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepIntoTest")
model("stepping/custom", pattern = KT_WITHOUT_DOTS, testMethodName = "doCustomTest")
}
testClass<AbstractIrKotlinSteppingTest> {
model("stepping/stepIntoAndSmartStepInto", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepIntoTest", testClassName = "StepInto")
model("stepping/stepIntoAndSmartStepInto", pattern = KT_WITHOUT_DOTS, testMethodName = "doSmartStepIntoTest", testClassName = "SmartStepInto")
model("stepping/stepInto", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepIntoTest", testClassName = "StepIntoOnly")
model("stepping/stepOut", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepOutTest")
model("stepping/stepOver", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepOverTest")
model("stepping/filters", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepIntoTest")
model("stepping/custom", pattern = KT_WITHOUT_DOTS, testMethodName = "doCustomTest")
}
testClass<AbstractKotlinEvaluateExpressionTest> {
model("evaluation/singleBreakpoint", testMethodName = "doSingleBreakpointTest", targetBackend = TargetBackend.JVM_WITH_OLD_EVALUATOR)
model("evaluation/multipleBreakpoints", testMethodName = "doMultipleBreakpointsTest", targetBackend = TargetBackend.JVM_WITH_OLD_EVALUATOR)
}
testClass<AbstractIrKotlinEvaluateExpressionTest> {
model("evaluation/singleBreakpoint", testMethodName = "doSingleBreakpointTest", targetBackend = TargetBackend.JVM_IR_WITH_OLD_EVALUATOR)
model("evaluation/multipleBreakpoints", testMethodName = "doMultipleBreakpointsTest", targetBackend = TargetBackend.JVM_IR_WITH_OLD_EVALUATOR)
}
testClass<AbstractIrKotlinEvaluateExpressionWithIRFragmentCompilerTest> {
model("evaluation/singleBreakpoint", testMethodName = "doSingleBreakpointTest", targetBackend = TargetBackend.JVM_IR_WITH_IR_EVALUATOR)
model("evaluation/multipleBreakpoints", testMethodName = "doMultipleBreakpointsTest", targetBackend = TargetBackend.JVM_IR_WITH_IR_EVALUATOR)
}
testClass<AbstractKotlinEvaluateExpressionInMppTest> {
model("evaluation/singleBreakpoint", testMethodName = "doSingleBreakpointTest", targetBackend = TargetBackend.JVM_IR_WITH_OLD_EVALUATOR)
model("evaluation/multipleBreakpoints", testMethodName = "doMultipleBreakpointsTest", targetBackend = TargetBackend.JVM_IR_WITH_OLD_EVALUATOR)
model("evaluation/multiplatform", testMethodName = "doMultipleBreakpointsTest", targetBackend = TargetBackend.JVM_IR_WITH_IR_EVALUATOR)
}
testClass<AbstractSelectExpressionForDebuggerTestWithAnalysisApi> {
model("selectExpression")
}
testClass<AbstractSelectExpressionForDebuggerTestWithLegacyImplementation> {
model("selectExpression")
}
testClass<AbstractPositionManagerTest> {
model("positionManager", isRecursive = false, pattern = KT, testClassName = "SingleFile")
model("positionManager", isRecursive = false, pattern = DIRECTORY, testClassName = "MultiFile")
}
testClass<AbstractSmartStepIntoTest> {
model("smartStepInto")
}
testClass<AbstractBreakpointApplicabilityTest> {
model("breakpointApplicability")
}
testClass<AbstractFileRankingTest> {
model("fileRanking")
}
testClass<AbstractAsyncStackTraceTest> {
model("asyncStackTrace")
}
testClass<AbstractCoroutineDumpTest> {
model("coroutines")
}
testClass<AbstractSequenceTraceTestCase> { // TODO: implement mapping logic for terminal operations
model("sequence/streams/sequence", excludedDirectories = listOf("terminal"))
}
testClass<AbstractSequenceTraceWithIREvaluatorTestCase> { // TODO: implement mapping logic for terminal operations
model("sequence/streams/sequence", excludedDirectories = listOf("terminal"))
}
testClass<AbstractContinuationStackTraceTest> {
model("continuation")
}
testClass<AbstractKotlinVariablePrintingTest> {
model("variables")
}
testClass<AbstractXCoroutinesStackTraceTest> {
model("xcoroutines")
}
testClass<AbstractClassNameCalculatorTest> {
model("classNameCalculator")
}
testClass<AbstractKotlinExceptionFilterTest> {
model("exceptionFilter", pattern = Patterns.forRegex("""^([^.]+)$"""), isRecursive = false)
}
}
testGroup("copyright/tests") {
testClass<AbstractUpdateKotlinCopyrightTest> {
model("update", pattern = KT_OR_KTS, testMethodName = "doTest")
}
}
testGroup("coverage/tests") {
testClass<AbstractKotlinCoverageOutputFilesTest> {
model("outputFiles")
}
}
testGroup("idea/tests") {
testClass<AbstractAdditionalResolveDescriptorRendererTest> {
model("resolve/additionalLazyResolve")
}
testClass<AbstractPartialBodyResolveTest> {
model("resolve/partialBodyResolve")
}
testClass<AbstractResolveModeComparisonTest> {
model("resolve/resolveModeComparison")
}
testClass<AbstractKotlinHighlightVisitorTest> {
model("checker", isRecursive = false, pattern = KT.withPrecondition(excludedFirPrecondition))
model("checker/regression", pattern = KT.withPrecondition(excludedFirPrecondition))
model("checker/recovery", pattern = KT.withPrecondition(excludedFirPrecondition))
model("checker/rendering", pattern = KT.withPrecondition(excludedFirPrecondition))
model("checker/scripts", pattern = KTS.withPrecondition(excludedFirPrecondition))
model("checker/duplicateJvmSignature", pattern = KT.withPrecondition(excludedFirPrecondition))
model("checker/infos", testMethodName = "doTestWithInfos", pattern = KT.withPrecondition(excludedFirPrecondition))
model("checker/diagnosticsMessage", pattern = KT.withPrecondition(excludedFirPrecondition))
}
testClass<AbstractKotlinHighlightWolfPassTest> {
model("checker/wolf", isRecursive = false, pattern = KT.withPrecondition(excludedFirPrecondition))
}
testClass<AbstractJavaAgainstKotlinSourceCheckerTest> {
model("kotlinAndJavaChecker/javaAgainstKotlin")
model("kotlinAndJavaChecker/javaWithKotlin")
}
testClass<AbstractJavaAgainstKotlinBinariesCheckerTest> {
model("kotlinAndJavaChecker/javaAgainstKotlin")
}
testClass<AbstractPsiUnifierTest> {
model("unifier")
}
testClass<AbstractCodeFragmentHighlightingTest> {
model("checker/codeFragments", pattern = KT, isRecursive = false)
model("checker/codeFragments/imports", testMethodName = "doTestWithImport", pattern = KT)
}
testClass<AbstractCodeFragmentAutoImportTest> {
model("quickfix.special/codeFragmentAutoImport", pattern = KT, isRecursive = false)
}
testClass<AbstractJsCheckerTest> {
model("checker/js")
}
testClass<AbstractQuickFixTest> {
model("quickfix", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"))
}
testClass<AbstractGotoSuperTest> {
model("navigation/gotoSuper", pattern = TEST, isRecursive = false)
}
testClass<AbstractGotoTypeDeclarationTest> {
model("navigation/gotoTypeDeclaration", pattern = TEST)
}
testClass<AbstractGotoDeclarationTest> {
model("navigation/gotoDeclaration", pattern = TEST)
}
testClass<AbstractParameterInfoTest> {
model(
"parameterInfo",
pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"),
isRecursive = true,
excludedDirectories = listOf("withLib1/sharedLib", "withLib2/sharedLib", "withLib3/sharedLib"),
)
}
testClass<AbstractKotlinGotoTest> {
model("navigation/gotoClass", testMethodName = "doClassTest")
model("navigation/gotoSymbol", testMethodName = "doSymbolTest")
}
testClass<AbstractNavigateToLibrarySourceTest> {
model("decompiler/navigation/usercode")
}
testClass<AbstractNavigateJavaToLibrarySourceTest> {
model("decompiler/navigation/userJavaCode", pattern = Patterns.forRegex("^(.+)\\.java$"))
}
testClass<AbstractNavigateToLibrarySourceTestWithJS> {
model("decompiler/navigation/usercode", testClassName = "UsercodeWithJSModule")
}
testClass<AbstractNavigateToDecompiledLibraryTest> {
model("decompiler/navigation/usercode")
}
testClass<AbstractKotlinGotoImplementationTest> {
model("navigation/implementations", isRecursive = false)
}
testClass<AbstractGotoTestOrCodeActionTest> {
model("navigation/gotoTestOrCode", pattern = Patterns.forRegex("^(.+)\\.main\\..+\$"))
}
testClass<AbstractInheritorsSearchTest> {
model("search/inheritance")
}
testClass<AbstractAnnotatedMembersSearchTest> {
model("search/annotations")
}
testClass<AbstractExternalAnnotationTest> {
model("externalAnnotations")
}
testClass<AbstractQuickFixMultiFileTest> {
model("quickfix", pattern = Patterns.forRegex("""^(\w+)\.((before\.Main\.\w+)|(test))$"""), testMethodName = "doTestWithExtraFile")
}
testClass<AbstractKotlinTypeAliasByExpansionShortNameIndexTest> {
model("typealiasExpansionIndex")
}
testClass<AbstractHighlightingTest> {
model("highlighter")
}
testClass<AbstractHighlightingMetaInfoTest> {
model("highlighterMetaInfo")
}
testClass<AbstractDslHighlighterTest> {
model("dslHighlighter")
}
testClass<AbstractUsageHighlightingTest> {
model("usageHighlighter")
}
testClass<AbstractKotlinFoldingTest> {
model("folding/noCollapse")
model("folding/checkCollapse", testMethodName = "doSettingsFoldingTest")
}
testClass<AbstractSurroundWithTest> {
model("codeInsight/surroundWith/if", testMethodName = "doTestWithIfSurrounder")
model("codeInsight/surroundWith/ifElse", testMethodName = "doTestWithIfElseSurrounder")
model("codeInsight/surroundWith/ifElseExpression", testMethodName = "doTestWithIfElseExpressionSurrounder")
model("codeInsight/surroundWith/ifElseExpressionBraces", testMethodName = "doTestWithIfElseExpressionBracesSurrounder")
model("codeInsight/surroundWith/not", testMethodName = "doTestWithNotSurrounder")
model("codeInsight/surroundWith/parentheses", testMethodName = "doTestWithParenthesesSurrounder")
model("codeInsight/surroundWith/stringTemplate", testMethodName = "doTestWithStringTemplateSurrounder")
model("codeInsight/surroundWith/when", testMethodName = "doTestWithWhenSurrounder")
model("codeInsight/surroundWith/tryCatch", testMethodName = "doTestWithTryCatchSurrounder")
model("codeInsight/surroundWith/tryCatchExpression", testMethodName = "doTestWithTryCatchExpressionSurrounder")
model("codeInsight/surroundWith/tryCatchFinally", testMethodName = "doTestWithTryCatchFinallySurrounder")
model("codeInsight/surroundWith/tryCatchFinallyExpression", testMethodName = "doTestWithTryCatchFinallyExpressionSurrounder")
model("codeInsight/surroundWith/tryFinally", testMethodName = "doTestWithTryFinallySurrounder")
model("codeInsight/surroundWith/functionLiteral", testMethodName = "doTestWithFunctionLiteralSurrounder")
model("codeInsight/surroundWith/withIfExpression", testMethodName = "doTestWithSurroundWithIfExpression")
model("codeInsight/surroundWith/withIfElseExpression", testMethodName = "doTestWithSurroundWithIfElseExpression")
}
testClass<AbstractJoinLinesTest> {
model("joinLines")
}
testClass<AbstractBreadcrumbsTest> {
model("codeInsight/breadcrumbs")
}
testClass<AbstractIntentionTest> {
model("intentions", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.(kt|kts)$"))
}
testClass<AbstractIntentionTest2> {
model("intentions/loopToCallChain", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"))
}
testClass<AbstractConcatenatedStringGeneratorTest> {
model("concatenatedStringGenerator", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"))
}
testClass<AbstractInspectionTest> {
model("intentions", pattern = Patterns.forRegex("^(inspections\\.test)$"), flatten = true)
model("inspections", pattern = Patterns.forRegex("^(inspections\\.test)$"), flatten = true)
model("inspectionsLocal", pattern = Patterns.forRegex("^(inspections\\.test)$"), flatten = true)
}
testClass<AbstractLocalInspectionTest> {
model(
"inspectionsLocal", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.(kt|kts)$"),
// In FE1.0, this is a quickfix rather than a local inspection
excludedDirectories = listOf("unusedVariable")
)
}
testClass<AbstractViewOfflineInspectionTest> {
model("inspectionsLocal", pattern = Patterns.forRegex("^([\\w\\-_]+)_report\\.(xml)$"))
}
testClass<AbstractHierarchyTest> {
model("hierarchy/class/type", pattern = DIRECTORY, isRecursive = false, testMethodName = "doTypeClassHierarchyTest")
model("hierarchy/class/super", pattern = DIRECTORY, isRecursive = false, testMethodName = "doSuperClassHierarchyTest")
model("hierarchy/class/sub", pattern = DIRECTORY, isRecursive = false, testMethodName = "doSubClassHierarchyTest")
model("hierarchy/calls/callers", pattern = DIRECTORY, isRecursive = false, testMethodName = "doCallerHierarchyTest")
model("hierarchy/calls/callersJava", pattern = DIRECTORY, isRecursive = false, testMethodName = "doCallerJavaHierarchyTest")
model("hierarchy/calls/callees", pattern = DIRECTORY, isRecursive = false, testMethodName = "doCalleeHierarchyTest")
model("hierarchy/overrides", pattern = DIRECTORY, isRecursive = false, testMethodName = "doOverrideHierarchyTest")
}
testClass<AbstractHierarchyWithLibTest> {
model("hierarchy/withLib", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractMoveStatementTest> {
model("codeInsight/moveUpDown/classBodyDeclarations", pattern = KT_OR_KTS, testMethodName = "doTestClassBodyDeclaration")
model("codeInsight/moveUpDown/closingBraces", testMethodName = "doTestExpression")
model("codeInsight/moveUpDown/expressions", pattern = KT_OR_KTS, testMethodName = "doTestExpression")
model("codeInsight/moveUpDown/line", testMethodName = "doTestLine")
model("codeInsight/moveUpDown/parametersAndArguments", testMethodName = "doTestExpression")
model("codeInsight/moveUpDown/trailingComma", testMethodName = "doTestExpressionWithTrailingComma")
}
testClass<AbstractMoveLeftRightTest> {
model("codeInsight/moveLeftRight")
}
testClass<AbstractInlineTest> {
model("refactoring/inline", pattern = KT_WITHOUT_DOTS, excludedDirectories = listOf("withFullJdk"))
}
testClass<AbstractInlineTestWithSomeDescriptors> {
model("refactoring/inline/withFullJdk", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractInlineMultiFileTest> {
model("refactoring/inlineMultiFile", pattern = TEST, flatten = true)
}
testClass<AbstractUnwrapRemoveTest> {
model("codeInsight/unwrapAndRemove/removeExpression", testMethodName = "doTestExpressionRemover")
model("codeInsight/unwrapAndRemove/unwrapThen", testMethodName = "doTestThenUnwrapper")
model("codeInsight/unwrapAndRemove/unwrapElse", testMethodName = "doTestElseUnwrapper")
model("codeInsight/unwrapAndRemove/removeElse", testMethodName = "doTestElseRemover")
model("codeInsight/unwrapAndRemove/unwrapLoop", testMethodName = "doTestLoopUnwrapper")
model("codeInsight/unwrapAndRemove/unwrapTry", testMethodName = "doTestTryUnwrapper")
model("codeInsight/unwrapAndRemove/unwrapCatch", testMethodName = "doTestCatchUnwrapper")
model("codeInsight/unwrapAndRemove/removeCatch", testMethodName = "doTestCatchRemover")
model("codeInsight/unwrapAndRemove/unwrapFinally", testMethodName = "doTestFinallyUnwrapper")
model("codeInsight/unwrapAndRemove/removeFinally", testMethodName = "doTestFinallyRemover")
model("codeInsight/unwrapAndRemove/unwrapLambda", testMethodName = "doTestLambdaUnwrapper")
model("codeInsight/unwrapAndRemove/unwrapFunctionParameter", testMethodName = "doTestFunctionParameterUnwrapper")
}
testClass<AbstractExpressionTypeTest> {
model("codeInsight/expressionType")
}
testClass<AbstractRenderingKDocTest> {
model("codeInsight/renderingKDoc")
}
testClass<AbstractBackspaceHandlerTest> {
model("editor/backspaceHandler")
}
testClass<AbstractQuickDocProviderTest> {
model("editor/quickDoc", pattern = Patterns.forRegex("""^([^_]+)\.(kt|java)$"""))
}
testClass<AbstractSafeDeleteTest> {
model("refactoring/safeDelete/deleteClass/kotlinClass", testMethodName = "doClassTest")
model("refactoring/safeDelete/deleteClass/kotlinClassWithJava", testMethodName = "doClassTestWithJava")
model("refactoring/safeDelete/deleteClass/javaClassWithKotlin", pattern = JAVA, testMethodName = "doJavaClassTest")
model("refactoring/safeDelete/deleteObject/kotlinObject", testMethodName = "doObjectTest")
model("refactoring/safeDelete/deleteFunction/kotlinFunction", testMethodName = "doFunctionTest")
model("refactoring/safeDelete/deleteFunction/kotlinFunctionWithJava", testMethodName = "doFunctionTestWithJava")
model("refactoring/safeDelete/deleteFunction/javaFunctionWithKotlin", testMethodName = "doJavaMethodTest")
model("refactoring/safeDelete/deleteProperty/kotlinProperty", testMethodName = "doPropertyTest")
model("refactoring/safeDelete/deleteProperty/kotlinPropertyWithJava", testMethodName = "doPropertyTestWithJava")
model("refactoring/safeDelete/deleteProperty/javaPropertyWithKotlin", testMethodName = "doJavaPropertyTest")
model("refactoring/safeDelete/deleteTypeAlias/kotlinTypeAlias", testMethodName = "doTypeAliasTest")
model("refactoring/safeDelete/deleteTypeParameter/kotlinTypeParameter", testMethodName = "doTypeParameterTest")
model("refactoring/safeDelete/deleteTypeParameter/kotlinTypeParameterWithJava", testMethodName = "doTypeParameterTestWithJava")
model("refactoring/safeDelete/deleteValueParameter/kotlinValueParameter", testMethodName = "doValueParameterTest")
model("refactoring/safeDelete/deleteValueParameter/kotlinValueParameterWithJava", testMethodName = "doValueParameterTestWithJava")
model("refactoring/safeDelete/deleteValueParameter/javaParameterWithKotlin", pattern = JAVA, testMethodName = "doJavaParameterTest")
}
testClass<AbstractReferenceResolveTest> {
model("resolve/references", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractReferenceResolveInJavaTest> {
model("resolve/referenceInJava/binaryAndSource", pattern = JAVA)
model("resolve/referenceInJava/sourceOnly", pattern = JAVA)
}
testClass<AbstractReferenceToCompiledKotlinResolveInJavaTest> {
model("resolve/referenceInJava/binaryAndSource", pattern = JAVA)
}
testClass<AbstractReferenceResolveWithLibTest> {
model("resolve/referenceWithLib", isRecursive = false)
}
testClass<AbstractReferenceResolveInLibrarySourcesTest> {
model("resolve/referenceInLib", isRecursive = false)
}
testClass<AbstractReferenceToJavaWithWrongFileStructureTest> {
model("resolve/referenceToJavaWithWrongFileStructure", isRecursive = false)
}
testClass<AbstractFindUsagesTest> {
model("findUsages/kotlin", pattern = Patterns.forRegex("""^(.+)\.0\.kt$"""))
model("findUsages/java", pattern = Patterns.forRegex("""^(.+)\.0\.java$"""))
model("findUsages/propertyFiles", pattern = Patterns.forRegex("""^(.+)\.0\.properties$"""))
}
testClass<AbstractKotlinScriptFindUsagesTest> {
model("findUsages/kotlinScript", pattern = Patterns.forRegex("""^(.+)\.0\.kts$"""))
}
testClass<AbstractFindUsagesWithDisableComponentSearchTest> {
model("findUsages/kotlin/conventions/components", pattern = Patterns.forRegex("""^(.+)\.0\.(kt|kts)$"""))
}
testClass<AbstractKotlinFindUsagesWithLibraryTest> {
model("findUsages/libraryUsages", pattern = Patterns.forRegex("""^(.+)\.0\.kt$"""))
}
testClass<AbstractKotlinFindUsagesWithStdlibTest> {
model("findUsages/stdlibUsages", pattern = Patterns.forRegex("""^(.+)\.0\.kt$"""))
}
testClass<AbstractMoveTest> {
model("refactoring/move", pattern = TEST, flatten = true)
}
testClass<AbstractCopyTest> {
model("refactoring/copy", pattern = TEST, flatten = true)
}
testClass<AbstractMultiModuleMoveTest> {
model("refactoring/moveMultiModule", pattern = TEST, flatten = true)
}
testClass<AbstractMultiModuleCopyTest> {
model("refactoring/copyMultiModule", pattern = TEST, flatten = true)
}
testClass<AbstractMultiModuleSafeDeleteTest> {
model("refactoring/safeDeleteMultiModule", pattern = TEST, flatten = true)
}
testClass<AbstractMultiFileIntentionTest> {
model("multiFileIntentions", pattern = TEST, flatten = true)
}
testClass<AbstractMultiFileLocalInspectionTest> {
model("multiFileLocalInspections", pattern = TEST, flatten = true)
}
testClass<AbstractMultiFileInspectionTest> {
model("multiFileInspections", pattern = TEST, flatten = true)
}
testClass<AbstractFormatterTest> {
model("formatter", pattern = Patterns.forRegex("""^([^.]+)\.after\.kt.*$"""))
model("formatter/trailingComma", pattern = Patterns.forRegex("""^([^.]+)\.call\.after\.kt.*$"""), testMethodName = "doTestCallSite", testClassName = "FormatterCallSite")
model("formatter", pattern = Patterns.forRegex("""^([^.]+)\.after\.inv\.kt.*$"""), testMethodName = "doTestInverted", testClassName = "FormatterInverted")
model(
"formatter/trailingComma",
pattern = Patterns.forRegex("""^([^.]+)\.call\.after\.inv\.kt.*$"""),
testMethodName = "doTestInvertedCallSite",
testClassName = "FormatterInvertedCallSite",
)
}
testClass<AbstractDiagnosticMessageTest> {
model("diagnosticMessage", isRecursive = false)
}
testClass<AbstractDiagnosticMessageJsTest> {
model("diagnosticMessage/js", isRecursive = false, targetBackend = TargetBackend.JS)
}
testClass<AbstractRenameTest> {
model("refactoring/rename", pattern = TEST, flatten = true)
}
testClass<AbstractMultiModuleRenameTest> {
model("refactoring/renameMultiModule", pattern = TEST, flatten = true)
}
testClass<AbstractOutOfBlockModificationTest> {
model("codeInsight/outOfBlock", pattern = Patterns.forRegex("^(.+)\\.(kt|kts|java)$"))
}
testClass<AbstractChangeLocalityDetectorTest> {
model("codeInsight/changeLocality", pattern = KT_OR_KTS)
}
testClass<AbstractDataFlowValueRenderingTest> {
model("dataFlowValueRendering")
}
testClass<AbstractLiteralTextToKotlinCopyPasteTest> {
model("copyPaste/plainTextLiteral", pattern = Patterns.forRegex("""^([^.]+)\.txt$"""))
}
testClass<AbstractLiteralKotlinToKotlinCopyPasteTest> {
model("copyPaste/literal", pattern = Patterns.forRegex("""^([^.]+)\.kt$"""))
}
testClass<AbstractInsertImportOnPasteTest> {
model("copyPaste/imports", pattern = KT_WITHOUT_DOTS, testMethodName = "doTestCopy", testClassName = "Copy", isRecursive = false)
model("copyPaste/imports", pattern = KT_WITHOUT_DOTS, testMethodName = "doTestCut", testClassName = "Cut", isRecursive = false)
}
testClass<AbstractMoveOnCutPasteTest> {
model("copyPaste/moveDeclarations", pattern = KT_WITHOUT_DOTS, testMethodName = "doTest")
}
testClass<AbstractHighlightExitPointsTest> {
model("exitPoints")
}
testClass<AbstractLineMarkersTest> {
model("codeInsight/lineMarker", pattern = Patterns.forRegex("^(\\w+)\\.(kt|kts)$"))
}
testClass<AbstractLightTestRunLineMarkersTest> {
model("codeInsight/lineMarker/runMarkers", pattern = Patterns.forRegex("^((jUnit|test)\\w*)\\.kt$"), testMethodName = "doLightTest", testClassName = "WithLightTestFramework")
model("codeInsight/lineMarker/runMarkers", pattern = Patterns.forRegex("^((jUnit|test)\\w*)\\.kt$"), testMethodName = "doPureTest", testClassName = "WithoutLightTestFramework")
}
testClass<AbstractLineMarkersTestInLibrarySources> {
model("codeInsightInLibrary/lineMarker", testMethodName = "doTestWithLibrary")
}
testClass<AbstractMultiModuleLineMarkerTest> {
model("multiModuleLineMarker", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractShortenRefsTest> {
model("shortenRefs", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractAddImportTest> {
model("addImport", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractAddImportAliasTest53> {
model("addImportAlias", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractSmartSelectionTest> {
model("smartSelection", testMethodName = "doTestSmartSelection", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractWorkSelectionTest> {
model("wordSelection", pattern = DIRECTORY)
}
testClass<AbstractKotlinFileStructureTest> {
model("structureView/fileStructure", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractExpressionSelectionTest> {
model("expressionSelection", testMethodName = "doTestExpressionSelection", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractCommonDecompiledTextTest> {
model("decompiler/decompiledText", pattern = Patterns.forRegex("""^([^\.]+)$"""))
}
testClass<AbstractJvmDecompiledTextTest> {
model("decompiler/decompiledTextJvm", pattern = Patterns.forRegex("""^([^\.]+)$"""))
}
testClass<AbstractCommonDecompiledTextFromJsMetadataTest> {
model("decompiler/decompiledText", pattern = Patterns.forRegex("""^([^\.]+)$"""), targetBackend = TargetBackend.JS)
}
testClass<AbstractJsDecompiledTextFromJsMetadataTest> {
model("decompiler/decompiledTextJs", pattern = Patterns.forRegex("""^([^\.]+)$"""), targetBackend = TargetBackend.JS)
}
testClass<AbstractAutoImportTest> {
model("editor/autoImport", testMethodName = "doTest", testClassName = "WithAutoImport", pattern = DIRECTORY, isRecursive = false)
model("editor/autoImport", testMethodName = "doTestWithoutAutoImport", testClassName = "WithoutAutoImport", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractFilteringAutoImportTest> {
model("editor/autoImportExtension", testMethodName = "doTest", testClassName = "WithAutoImport", pattern = DIRECTORY, isRecursive = false)
model("editor/autoImportExtension", testMethodName = "doTestWithoutAutoImport", testClassName = "WithoutAutoImport", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractJvmOptimizeImportsTest> {
model("editor/optimizeImports/jvm", pattern = KT_OR_KTS_WITHOUT_DOTS)
model("editor/optimizeImports/common", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractJsOptimizeImportsTest> {
model("editor/optimizeImports/js", pattern = KT_WITHOUT_DOTS)
model("editor/optimizeImports/common", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractEnterHandlerTest> {
model("editor/enterHandler", pattern = Patterns.forRegex("""^([^.]+)\.after\.kt.*$"""), testMethodName = "doNewlineTest", testClassName = "DirectSettings")
model("editor/enterHandler", pattern = Patterns.forRegex("""^([^.]+)\.after\.inv\.kt.*$"""), testMethodName = "doNewlineTestWithInvert", testClassName = "InvertedSettings")
}
testClass<AbstractKotlinCommenterTest> {
model("editor/commenter", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractStubBuilderTest> {
model("stubs", pattern = KT)
}
testClass<AbstractMultiFileHighlightingTest> {
model("multiFileHighlighting", isRecursive = false)
}
testClass<AbstractMultiPlatformHighlightingTest> {
model("multiModuleHighlighting/multiplatform/", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractMultiplatformAnalysisTest> {
model("multiplatform", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractQuickFixMultiModuleTest> {
model("multiModuleQuickFix", pattern = DIRECTORY, depth = 1)
}
testClass<AbstractKotlinGotoImplementationMultiModuleTest> {
model("navigation/implementations/multiModule", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractKotlinGotoRelatedSymbolMultiModuleTest> {
model("navigation/relatedSymbols/multiModule", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractKotlinGotoSuperMultiModuleTest> {
model("navigation/gotoSuper/multiModule", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractExtractionTest> {
model("refactoring/introduceVariable", pattern = KT_OR_KTS, testMethodName = "doIntroduceVariableTest")
model("refactoring/extractFunction", pattern = KT_OR_KTS, testMethodName = "doExtractFunctionTest", excludedDirectories = listOf("inplace"))
model("refactoring/introduceProperty", pattern = KT_OR_KTS, testMethodName = "doIntroducePropertyTest")
model("refactoring/introduceParameter", pattern = KT_OR_KTS, testMethodName = "doIntroduceSimpleParameterTest")
model("refactoring/introduceLambdaParameter", pattern = KT_OR_KTS, testMethodName = "doIntroduceLambdaParameterTest")
model("refactoring/introduceJavaParameter", pattern = JAVA, testMethodName = "doIntroduceJavaParameterTest")
model("refactoring/introduceTypeParameter", pattern = KT_OR_KTS, testMethodName = "doIntroduceTypeParameterTest")
model("refactoring/introduceTypeAlias", pattern = KT_OR_KTS, testMethodName = "doIntroduceTypeAliasTest")
model("refactoring/introduceConstant", pattern = KT_OR_KTS, testMethodName = "doIntroduceConstantTest")
model("refactoring/extractSuperclass", pattern = KT_OR_KTS_WITHOUT_DOTS, testMethodName = "doExtractSuperclassTest")
model("refactoring/extractInterface", pattern = KT_OR_KTS_WITHOUT_DOTS, testMethodName = "doExtractInterfaceTest")
}
testClass<AbstractPullUpTest> {
model("refactoring/pullUp/k2k", pattern = KT, flatten = true, testClassName = "K2K", testMethodName = "doKotlinTest")
model("refactoring/pullUp/k2j", pattern = KT, flatten = true, testClassName = "K2J", testMethodName = "doKotlinTest")
model("refactoring/pullUp/j2k", pattern = JAVA, flatten = true, testClassName = "J2K", testMethodName = "doJavaTest")
}
testClass<AbstractPushDownTest> {
model("refactoring/pushDown/k2k", pattern = KT, flatten = true, testClassName = "K2K", testMethodName = "doKotlinTest")
model("refactoring/pushDown/k2j", pattern = KT, flatten = true, testClassName = "K2J", testMethodName = "doKotlinTest")
model("refactoring/pushDown/j2k", pattern = JAVA, flatten = true, testClassName = "J2K", testMethodName = "doJavaTest")
}
testClass<AbstractBytecodeToolWindowTest> {
model("internal/toolWindow", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractReferenceResolveTest>("org.jetbrains.kotlin.idea.kdoc.KdocResolveTestGenerated") {
model("kdoc/resolve")
}
testClass<AbstractKDocHighlightingTest> {
model("kdoc/highlighting")
}
testClass<AbstractKDocTypingTest> {
model("kdoc/typing")
}
testClass<AbstractGenerateTestSupportMethodActionTest> {
model("codeInsight/generate/testFrameworkSupport")
}
testClass<AbstractGenerateHashCodeAndEqualsActionTest> {
model("codeInsight/generate/equalsWithHashCode")
}
testClass<AbstractCodeInsightActionTest> {
model("codeInsight/generate/secondaryConstructors")
}
testClass<AbstractGenerateToStringActionTest> {
model("codeInsight/generate/toString")
}
testClass<AbstractIdeReplCompletionTest> {
model("repl/completion")
}
testClass<AbstractPostfixTemplateProviderTest> {
model("codeInsight/postfix")
}
testClass<AbstractKotlinArgumentsHintsProviderTest> {
model("codeInsight/hints/arguments")
}
testClass<AbstractKotlinReferenceTypeHintsProviderTest> {
model("codeInsight/hints/types")
}
testClass<AbstractKotlinLambdasHintsProvider> {
model("codeInsight/hints/lambda")
}
testClass<AbstractKotlinRangesHintsProviderTest> {
model("codeInsight/hints/ranges")
}
testClass<AbstractKotlinCodeVisionProviderTest> {
model("codeInsight/codeVision")
}
testClass<AbstractScriptConfigurationHighlightingTest> {
model("script/definition/highlighting", pattern = DIRECTORY, isRecursive = false)
model("script/definition/complex", pattern = DIRECTORY, isRecursive = false, testMethodName = "doComplexTest")
}
testClass<AbstractScriptConfigurationNavigationTest> {
model("script/definition/navigation", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractScriptConfigurationCompletionTest> {
model("script/definition/completion", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractScriptConfigurationInsertImportOnPasteTest> {
model("script/definition/imports", testMethodName = "doTestCopy", testClassName = "Copy", pattern = DIRECTORY, isRecursive = false)
model("script/definition/imports", testMethodName = "doTestCut", testClassName = "Cut", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractScriptDefinitionsOrderTest> {
model("script/definition/order", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractNameSuggestionProviderTest> {
model("refactoring/nameSuggestionProvider")
}
testClass<AbstractSlicerTreeTest> {
model("slicer", excludedDirectories = listOf("mpp"))
}
testClass<AbstractSlicerLeafGroupingTest> {
model("slicer/inflow", flatten = true)
}
testClass<AbstractSlicerNullnessGroupingTest> {
model("slicer/inflow", flatten = true)
}
testClass<AbstractSlicerMultiplatformTest> {
model("slicer/mpp", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractKotlinNavBarTest> {
model("navigationToolbar", isRecursive = false)
}
}
testGroup("scripting-support") {
testClass<AbstractScratchRunActionTest> {
model("scratch", pattern = KTS, testMethodName = "doScratchCompilingTest", testClassName = "ScratchCompiling", isRecursive = false)
model("scratch", pattern = KTS, testMethodName = "doScratchReplTest", testClassName = "ScratchRepl", isRecursive = false)
model("scratch/multiFile", pattern = DIRECTORY, testMethodName = "doScratchMultiFileTest", testClassName = "ScratchMultiFile", isRecursive = false)
model("worksheet", pattern = WS_KTS, testMethodName = "doWorksheetCompilingTest", testClassName = "WorksheetCompiling", isRecursive = false)
model("worksheet", pattern = WS_KTS, testMethodName = "doWorksheetReplTest", testClassName = "WorksheetRepl", isRecursive = false)
model("worksheet/multiFile", pattern = DIRECTORY, testMethodName = "doWorksheetMultiFileTest", testClassName = "WorksheetMultiFile", isRecursive = false)
model("scratch/rightPanelOutput", pattern = KTS, testMethodName = "doRightPreviewPanelOutputTest", testClassName = "ScratchRightPanelOutput", isRecursive = false)
}
testClass<AbstractScratchLineMarkersTest> {
model("scratch/lineMarker", testMethodName = "doScratchTest", pattern = KT_OR_KTS)
}
testClass<AbstractScriptTemplatesFromDependenciesTest> {
model("script/templatesFromDependencies", pattern = DIRECTORY, isRecursive = false)
}
}
testGroup("maven/tests") {
testClass<AbstractMavenConfigureProjectByChangingFileTest> {
model("configurator/jvm", pattern = DIRECTORY, isRecursive = false, testMethodName = "doTestWithMaven")
model("configurator/js", pattern = DIRECTORY, isRecursive = false, testMethodName = "doTestWithJSMaven")
}
testClass<AbstractKotlinMavenInspectionTest> {
val mavenInspections = "maven-inspections"
val pattern = Patterns.forRegex("^([\\w\\-]+).xml$")
testDataRoot.resolve(mavenInspections).listFiles()!!.onEach { check(it.isDirectory) }.sorted().forEach {
model("$mavenInspections/${it.name}", pattern = pattern, flatten = true)
}
}
}
testGroup("gradle/gradle-java/tests", testDataPath = "../../../idea/tests/testData") {
testClass<AbstractGradleConfigureProjectByChangingFileTest> {
model("configuration/gradle", pattern = DIRECTORY, isRecursive = false, testMethodName = "doTestGradle")
model("configuration/gsk", pattern = DIRECTORY, isRecursive = false, testMethodName = "doTestGradle")
}
}
testGroup("idea/tests", testDataPath = TestKotlinArtifacts.compilerTestData("compiler/testData")) {
testClass<AbstractResolveByStubTest> {
model("loadJava/compiledKotlin")
}
testClass<AbstractLoadJavaClsStubTest> {
model("loadJava/compiledKotlin", testMethodName = "doTestCompiledKotlin")
}
testClass<AbstractIdeLightClassTest> {
model("asJava/lightClasses", excludedDirectories = listOf("delegation", "script"), pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractIdeLightClassForScriptTest> {
model("asJava/script/ide", pattern = KT_OR_KTS_WITHOUT_DOTS)
}
testClass<AbstractUltraLightClassSanityTest> {
model("asJava/lightClasses", pattern = KT_OR_KTS)
}
testClass<AbstractUltraLightClassLoadingTest> {
model("asJava/ultraLightClasses", pattern = KT_OR_KTS)
}
testClass<AbstractUltraLightScriptLoadingTest> {
model("asJava/ultraLightScripts", pattern = KT_OR_KTS)
}
testClass<AbstractUltraLightFacadeClassTest15> {
model("asJava/ultraLightFacades", pattern = KT_OR_KTS)
}
testClass<AbstractIdeCompiledLightClassTest> {
model("asJava/lightClasses", excludedDirectories = listOf("local", "compilationErrors", "ideRegression", "script"), pattern = KT_OR_KTS_WITHOUT_DOTS)
}
}
testGroup("compiler-plugins/parcelize/tests") {
testClass<AbstractParcelizeQuickFixTest> {
model("quickfix", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"))
}
testClass<AbstractParcelizeCheckerTest> {
model("checker", pattern = KT)
}
}
testGroup("completion/tests-k1", testDataPath = "../testData") {
testClass<AbstractCompiledKotlinInJavaCompletionTest> {
model("injava", pattern = JAVA, isRecursive = false)
}
testClass<AbstractKotlinSourceInJavaCompletionTest> {
model("injava", pattern = JAVA, isRecursive = false)
}
testClass<AbstractKotlinStdLibInJavaCompletionTest> {
model("injava/stdlib", pattern = JAVA, isRecursive = false)
}
testClass<AbstractBasicCompletionWeigherTest> {
model("weighers/basic", pattern = KT_OR_KTS_WITHOUT_DOTS)
}
testClass<AbstractSmartCompletionWeigherTest> {
model("weighers/smart", pattern = KT_OR_KTS_WITHOUT_DOTS)
}
testClass<AbstractJSBasicCompletionTest> {
model("basic/common", pattern = KT_WITHOUT_FIR_PREFIX)
model("basic/js", pattern = KT_WITHOUT_FIR_PREFIX)
}
testClass<AbstractJvmBasicCompletionTest> {
model("basic/common", pattern = KT_WITHOUT_FIR_PREFIX)
model("basic/java", pattern = KT_WITHOUT_FIR_PREFIX)
}
testClass<AbstractJvmSmartCompletionTest> {
model("smart")
}
testClass<AbstractKeywordCompletionTest> {
model("keywords", isRecursive = false, pattern = KT.withPrecondition(excludedFirPrecondition))
}
testClass<AbstractJvmWithLibBasicCompletionTest> {
model("basic/withLib", isRecursive = false)
}
testClass<AbstractBasicCompletionHandlerTest> {
model("handlers/basic", pattern = KT_WITHOUT_DOT_AND_FIR_PREFIX)
}
testClass<AbstractSmartCompletionHandlerTest> {
model("handlers/smart", pattern = KT_WITHOUT_FIR_PREFIX)
}
testClass<AbstractKeywordCompletionHandlerTest> {
model("handlers/keywords", pattern = KT_WITHOUT_FIR_PREFIX)
}
testClass<AbstractCompletionCharFilterTest> {
model("handlers/charFilter", pattern = KT_WITHOUT_DOT_AND_FIR_PREFIX)
}
testClass<AbstractMultiFileJvmBasicCompletionTest> {
model("basic/multifile", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractMultiFileSmartCompletionTest> {
model("smartMultiFile", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractJvmBasicCompletionTest>("org.jetbrains.kotlin.idea.completion.test.KDocCompletionTestGenerated") {
model("kdoc")
}
testClass<AbstractJava8BasicCompletionTest> {
model("basic/java8")
}
testClass<AbstractCompletionIncrementalResolveTest31> {
model("incrementalResolve")
}
testClass<AbstractMultiPlatformCompletionTest> {
model("multiPlatform", isRecursive = false, pattern = DIRECTORY)
}
}
testGroup("project-wizard/tests") {
fun MutableTSuite.allBuildSystemTests(relativeRootPath: String) {
for (testClass in listOf("GradleKts", "GradleGroovy", "Maven")) {
model(
relativeRootPath,
isRecursive = false,
pattern = DIRECTORY,
testMethodName = "doTest${testClass}",
testClassName = testClass,
)
}
}
testClass<AbstractYamlBuildFileGenerationTest> {
model("buildFileGeneration", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractProjectTemplateBuildFileGenerationTest> {
model("projectTemplatesBuildFileGeneration", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractYamlNewWizardProjectImportTest> {
allBuildSystemTests("buildFileGeneration")
}
testClass<AbstractProjectTemplateNewWizardProjectImportTest> {
allBuildSystemTests("projectTemplatesBuildFileGeneration")
}
}
testGroup("idea/tests", testDataPath = "../../completion/testData") {
testClass<AbstractCodeFragmentCompletionHandlerTest> {
model("handlers/runtimeCast")
}
testClass<AbstractCodeFragmentCompletionTest> {
model("basic/codeFragments", pattern = KT)
}
}
testGroup("j2k/new/tests") {
testClass<AbstractNewJavaToKotlinConverterSingleFileTest> {
model("newJ2k", pattern = Patterns.forRegex("""^([^.]+)\.java$"""))
}
testClass<AbstractPartialConverterTest> {
model("partialConverter", pattern = Patterns.forRegex("""^([^.]+)\.java$"""))
}
testClass<AbstractCommonConstraintCollectorTest> {
model("inference/common")
}
testClass<AbstractNullabilityInferenceTest> {
model("inference/nullability")
}
testClass<AbstractMutabilityInferenceTest> {
model("inference/mutability")
}
testClass<AbstractNewJavaToKotlinCopyPasteConversionTest> {
model("copyPaste", pattern = Patterns.forRegex("""^([^.]+)\.java$"""))
}
testClass<AbstractTextNewJavaToKotlinCopyPasteConversionTest> {
model("copyPastePlainText", pattern = Patterns.forRegex("""^([^.]+)\.txt$"""))
}
testClass<AbstractNewJavaToKotlinConverterMultiFileTest> {
model("multiFile", pattern = DIRECTORY, isRecursive = false)
}
}
testGroup("compiler-reference-index/tests") {
testClass<AbstractKotlinCompilerReferenceTest> {
model("compilerIndex", pattern = DIRECTORY, classPerTest = true)
}
}
testGroup("compiler-reference-index/tests", testDataPath = "../../idea/tests/testData") {
testClass<AbstractFindUsagesWithCompilerReferenceIndexTest> {
model("findUsages/kotlin", pattern = Patterns.forRegex("""^(.+)\.0\.kt$"""), classPerTest = true)
model("findUsages/java", pattern = Patterns.forRegex("""^(.+)\.0\.java$"""), classPerTest = true)
model("findUsages/propertyFiles", pattern = Patterns.forRegex("""^(.+)\.0\.properties$"""), classPerTest = true)
}
}
testGroup("compiler-plugins/kotlinx-serialization/tests") {
testClass<AbstractSerializationPluginIdeDiagnosticTest> {
model("diagnostics")
}
testClass<AbstractSerializationQuickFixTest> {
model("quickfix", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"))
}
}
testGroup("uast/uast-kotlin/tests", testDataPath = "../../uast-kotlin-fir/testData") {
testClass<AbstractFE1UastDeclarationTest> {
model("declaration")
model("legacy")
}
testClass<AbstractFE1UastTypesTest> {
model("type")
}
}
testGroup("uast/uast-kotlin/tests") {
testClass<AbstractFE1LegacyUastDeclarationTest> {
model("")
}
testClass<AbstractFE1LegacyUastIdentifiersTest> {
model("")
}
testClass<AbstractFE1LegacyUastResolveEverythingTest> {
model("")
}
testClass<AbstractFE1LegacyUastTypesTest> {
model("")
}
testClass<AbstractFE1LegacyUastValuesTest> {
model("")
}
}
testGroup("performance-tests", testDataPath = "../idea/tests/testData") {
testClass<AbstractPerformanceJavaToKotlinCopyPasteConversionTest> {
model("copyPaste/conversion", testMethodName = "doPerfTest", pattern = Patterns.forRegex("""^([^.]+)\.java$"""))
}
testClass<AbstractPerformanceNewJavaToKotlinCopyPasteConversionTest> {
model("copyPaste/conversion", testMethodName = "doPerfTest", pattern = Patterns.forRegex("""^([^.]+)\.java$"""))
}
testClass<AbstractPerformanceLiteralKotlinToKotlinCopyPasteTest> {
model("copyPaste/literal", testMethodName = "doPerfTest", pattern = Patterns.forRegex("""^([^.]+)\.kt$"""))
}
testClass<AbstractPerformanceHighlightingTest> {
model("highlighter", testMethodName = "doPerfTest")
}
testClass<AbstractPerformanceHighlightingStatNamesTest> {
model("highlighter", testMethodName = "doPerfTest", pattern = Patterns.forRegex("""^(InvokeCall)\.kt$"""))
}
testClass<AbstractPerformanceAddImportTest> {
model("addImport", testMethodName = "doPerfTest", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractPerformanceTypingIndentationTest> {
model("editor/enterHandler", pattern = Patterns.forRegex("""^([^.]+)\.after\.kt.*$"""), testMethodName = "doNewlineTest", testClassName = "DirectSettings")
model("editor/enterHandler", pattern = Patterns.forRegex("""^([^.]+)\.after\.inv\.kt.*$"""), testMethodName = "doNewlineTestWithInvert", testClassName = "InvertedSettings")
}
}
testGroup("performance-tests", testDataPath = "../completion/testData") {
testClass<AbstractPerformanceCompletionIncrementalResolveTest> {
model("incrementalResolve", testMethodName = "doPerfTest")
}
testClass<AbstractPerformanceBasicCompletionHandlerTest> {
model("handlers/basic", testMethodName = "doPerfTest", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractPerformanceBasicCompletionHandlerStatNamesTest> {
model("handlers/basic", testMethodName = "doPerfTest", pattern = Patterns.forRegex("""^(GetOperator)\.kt$"""))
}
testClass<AbstractPerformanceSmartCompletionHandlerTest> {
model("handlers/smart", testMethodName = "doPerfTest")
}
testClass<AbstractPerformanceKeywordCompletionHandlerTest> {
model("handlers/keywords", testMethodName = "doPerfTest")
}
testClass<AbstractPerformanceCompletionCharFilterTest> {
model("handlers/charFilter", testMethodName = "doPerfTest", pattern = KT_WITHOUT_DOTS)
}
}
testGroup("code-insight/intentions-shared/tests/k1", testDataPath = "../testData") {
testClass<AbstractSharedK1IntentionTest> {
model("intentions", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.(kt|kts)$"))
}
}
testGroup("code-insight/inspections-shared/tests/k1", testDataPath = "../testData") {
testClass<AbstractSharedK1LocalInspectionTest> {
val pattern = Patterns.forRegex("^([\\w\\-_]+)\\.(kt|kts)$")
model("inspectionsLocal", pattern = pattern)
}
testClass<AbstractSharedK1InspectionTest> {
val pattern = Patterns.forRegex("^(inspections\\.test)$")
model("inspections", pattern = pattern)
model("inspectionsLocal", pattern = pattern)
}
}
}
| apache-2.0 | 146c2290e99e89cb759807d68c31b325 | 47.619956 | 188 | 0.702561 | 5.406184 | false | true | false | false |
google/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/ProjectExtensions.kt | 1 | 7635 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.packagesearch.intellij.plugin.util
import com.intellij.ProjectTopics
import com.intellij.facet.FacetManager
import com.intellij.ide.impl.TrustStateListener
import com.intellij.ide.impl.isTrusted
import com.intellij.ide.ui.LafManager
import com.intellij.ide.ui.LafManagerListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.ModuleListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.util.Function
import com.intellij.util.messages.Topic
import com.jetbrains.packagesearch.intellij.plugin.data.PackageSearchProjectService
import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineModuleTransformer
import com.jetbrains.packagesearch.intellij.plugin.extensibility.FlowModuleChangesSignalProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ModuleChangesSignalProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ModuleTransformer
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.lifecycle.PackageSearchLifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.ui.PkgsUiCommandsService
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiStateModifier
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiStateSource
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.PackageSearchCachesService
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.PackageSearchProjectCachesService
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.PackageVersionNormalizer
import kotlinx.coroutines.channels.ProducerScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.merge
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
internal val Project.packageSearchProjectService: PackageSearchProjectService
get() = service()
internal val packageSearchApplicationCaches: PackageSearchCachesService
get() = service()
internal val packageVersionNormalizer: PackageVersionNormalizer
get() = packageSearchApplicationCaches.normalizer
internal val Project.packageSearchProjectCachesService: PackageSearchProjectCachesService
get() = service()
internal val Project.toolWindowManagerFlow: Flow<ToolWindow>
get() = messageBusFlow(ToolWindowManagerListener.TOPIC) {
object : ToolWindowManagerListener {
override fun toolWindowShown(toolWindow: ToolWindow) {
trySend(toolWindow)
}
}
}
fun <L : Any, K> Project.messageBusFlow(
topic: Topic<L>,
initialValue: (suspend () -> K)? = null,
listener: suspend ProducerScope<K>.() -> L
): Flow<K> {
return callbackFlow {
initialValue?.let { send(it()) }
val connection = messageBus.simpleConnect()
connection.subscribe(topic, listener())
awaitClose { connection.disconnect() }
}
}
internal val Project.trustedProjectFlow: Flow<Boolean>
get() {
return ApplicationManager.getApplication().messageBusFlow(TrustStateListener.TOPIC, { isTrusted() }) {
object : TrustStateListener {
override fun onProjectTrusted(project: Project) {
if (project == this@trustedProjectFlow) trySend(isTrusted())
}
}
}.distinctUntilChanged()
}
internal val Project.nativeModulesFlow: Flow<List<Module>>
get() = messageBusFlow(ProjectTopics.MODULES, { getNativeModules() }) {
object : ModuleListener {
override fun modulesAdded(project: Project, modules: List<Module>) {
trySend(getNativeModules())
}
override fun moduleRemoved(project: Project, module: Module) {
trySend(getNativeModules())
}
override fun modulesRenamed(
project: Project,
modules: MutableList<out Module>,
oldNameProvider: Function<in Module, String>
) {
trySend(getNativeModules())
}
}
}
val Project.filesChangedEventFlow: Flow<MutableList<out VFileEvent>>
get() = messageBusFlow(VirtualFileManager.VFS_CHANGES) {
object : BulkFileListener {
override fun after(events: MutableList<out VFileEvent>) {
trySend(events)
}
}
}
internal fun Project.getNativeModules(): List<Module> = ModuleManager.getInstance(this).modules.toList()
internal val Project.moduleChangesSignalFlow: Flow<Unit>
get() = merge(
*ModuleChangesSignalProvider.extensions(this),
*FlowModuleChangesSignalProvider.extensions(this)
)
internal val Project.lifecycleScope: PackageSearchLifecycleScope
get() = service()
internal val ProjectModule.lifecycleScope: PackageSearchLifecycleScope
get() = nativeModule.project.lifecycleScope
internal val Project.pkgsUiStateModifier: UiStateModifier
get() = service<PkgsUiCommandsService>()
internal val Project.uiStateSource: UiStateSource
get() = service<PkgsUiCommandsService>()
val Project.dumbService: DumbService
get() = DumbService.getInstance(this)
suspend fun DumbService.awaitSmart() {
suspendCoroutine {
runWhenSmart { it.resume(Unit) }
}
}
internal val Project.moduleTransformers: List<CoroutineModuleTransformer>
get() = CoroutineModuleTransformer.extensions(this) + ModuleTransformer.extensions(this)
internal val Project.lookAndFeelFlow: Flow<LafManager>
get() = messageBusFlow(LafManagerListener.TOPIC, { LafManager.getInstance()!! }) {
LafManagerListener { trySend(it) }
}
val <T : Any> ExtensionPointName<T>.extensionsFlow: Flow<List<T>>
get() = callbackFlow {
val listener = object : ExtensionPointListener<T> {
override fun extensionAdded(extension: T, pluginDescriptor: PluginDescriptor) {
trySendBlocking(extensions.toList())
}
override fun extensionRemoved(extension: T, pluginDescriptor: PluginDescriptor) {
trySendBlocking(extensions.toList())
}
}
send(extensions.toList())
addExtensionPointListener(listener)
awaitClose { removeExtensionPointListener(listener) }
}
fun Project.hasKotlinModules(): Boolean = ModuleManager.getInstance(this).modules.any { it.hasKotlinFacet() }
internal fun Module.hasKotlinFacet(): Boolean {
val facetManager = FacetManager.getInstance(this)
return facetManager.allFacets.any { it.typeId.toString() == "kotlin-language" }
}
| apache-2.0 | 1708517dfb3e6bf8b9c7fbd819d9b5f2 | 40.721311 | 120 | 0.753766 | 4.928986 | false | false | false | false |
vanniktech/RxBinding | rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding2/widget/RxTextView.kt | 1 | 7019 | @file:Suppress("NOTHING_TO_INLINE")
package com.jakewharton.rxbinding2.widget
import android.support.annotation.CheckResult
import android.widget.TextView
import com.jakewharton.rxbinding2.InitialValueObservable
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import io.reactivex.functions.Predicate
import kotlin.Int
import kotlin.Suppress
/**
* Create an observable of editor actions on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [TextView.OnEditorActionListener] to
* observe actions. Only one observable can be used for a view at a time.
*/
@CheckResult
inline fun TextView.editorActions(): Observable<Int> = RxTextView.editorActions(this)
/**
* Create an observable of editor actions on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [TextView.OnEditorActionListener] to
* observe actions. Only one observable can be used for a view at a time.
*
* @param handled Predicate invoked each occurrence to determine the return value of the
* underlying [TextView.OnEditorActionListener].
*/
@CheckResult
inline fun TextView.editorActions(handled: Predicate<in Int>): Observable<Int> = RxTextView.editorActions(this, handled)
/**
* Create an observable of editor action events on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [TextView.OnEditorActionListener] to
* observe actions. Only one observable can be used for a view at a time.
*/
@CheckResult
inline fun TextView.editorActionEvents(): Observable<TextViewEditorActionEvent> = RxTextView.editorActionEvents(this)
/**
* Create an observable of editor action events on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [TextView.OnEditorActionListener] to
* observe actions. Only one observable can be used for a view at a time.
*
* @param handled Predicate invoked each occurrence to determine the return value of the
* underlying [TextView.OnEditorActionListener].
*/
@CheckResult
inline fun TextView.editorActionEvents(handled: Predicate<in TextViewEditorActionEvent>): Observable<TextViewEditorActionEvent> = RxTextView.editorActionEvents(this, handled)
/**
* Create an observable of character sequences for text changes on `view`.
*
* *Warning:* Values emitted by this observable are <b>mutable</b> and owned by the host
* `TextView` and thus are <b>not safe</b> to cache or delay reading (such as by observing
* on a different thread). If you want to cache or delay reading the items emitted then you must
* map values through a function which calls [String.valueOf] or
* {@link CharSequence#toString() .toString()} to create a copy.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
@CheckResult
inline fun TextView.textChanges(): InitialValueObservable<CharSequence> = RxTextView.textChanges(this)
/**
* Create an observable of text change events for `view`.
*
* *Warning:* Values emitted by this observable contain a <b>mutable</b>
* [CharSequence] owned by the host `TextView` and thus are <b>not safe</b> to cache
* or delay reading (such as by observing on a different thread). If you want to cache or delay
* reading the items emitted then you must map values through a function which calls
* [String.valueOf] or {@link CharSequence#toString() .toString()} to create a copy.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
@CheckResult
inline fun TextView.textChangeEvents(): InitialValueObservable<TextViewTextChangeEvent> = RxTextView.textChangeEvents(this)
/**
* Create an observable of before text change events for `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
@CheckResult
inline fun TextView.beforeTextChangeEvents(): InitialValueObservable<TextViewBeforeTextChangeEvent> = RxTextView.beforeTextChangeEvents(this)
/**
* Create an observable of after text change events for `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe using
* {@link TextView#getEditableText()}.
*/
@CheckResult
inline fun TextView.afterTextChangeEvents(): InitialValueObservable<TextViewAfterTextChangeEvent> = RxTextView.afterTextChangeEvents(this)
/**
* An action which sets the text property of `view` with character sequences.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun TextView.text(): Consumer<in CharSequence> = RxTextView.text(this)
/**
* An action which sets the text property of `view` string resource IDs.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun TextView.textRes(): Consumer<in Int> = RxTextView.textRes(this)
/**
* An action which sets the error property of `view` with character sequences.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun TextView.error(): Consumer<in CharSequence> = RxTextView.error(this)
/**
* An action which sets the error property of `view` string resource IDs.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun TextView.errorRes(): Consumer<in Int> = RxTextView.errorRes(this)
/**
* An action which sets the hint property of `view` with character sequences.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun TextView.hint(): Consumer<in CharSequence> = RxTextView.hint(this)
/**
* An action which sets the hint property of `view` string resource IDs.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun TextView.hintRes(): Consumer<in Int> = RxTextView.hintRes(this)
/**
* An action which sets the color property of `view` with color integer.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun TextView.color(): Consumer<in Int> = RxTextView.color(this)
| apache-2.0 | 5acac93cbcf611339310b28c62f7fa33 | 36.736559 | 174 | 0.756091 | 4.319385 | false | false | false | false |
JetBrains/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/testPanels.kt | 1 | 1407 | // 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.
@file:Suppress("HardCodedStringLiteral", "DialogTitleCapitalization")
package com.intellij.ui.layout
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.JBIntSpinner
import com.intellij.ui.components.CheckBox
import com.intellij.ui.components.textFieldWithHistoryWithBrowseButton
import java.awt.GridLayout
import javax.swing.*
fun createLafTestPanel(): JPanel {
val spacing = createIntelliJSpacingConfiguration()
val panel = JPanel(GridLayout(0, 1, spacing.horizontalGap, spacing.verticalGap))
panel.add(JTextField("text"))
panel.add(JPasswordField("secret"))
panel.add(ComboBox(arrayOf("one", "two")))
val field = ComboBox(arrayOf("one", "two"))
field.isEditable = true
panel.add(field)
panel.add(JButton("label"))
panel.add(CheckBox("enabled"))
panel.add(JRadioButton("label"))
panel.add(JBIntSpinner(0, 0, 7))
panel.add(textFieldWithHistoryWithBrowseButton(null, "File", FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor()))
return panel
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun separatorAndComment() : JPanel {
return panel {
row("Label", separated = true) {
textField({ "abc" }, {}).comment("comment")
}
}
}
| apache-2.0 | 645ccdd5dff7406d8d9753bae3229df8 | 34.175 | 140 | 0.759773 | 4.2 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/breakpoints/SelectBreakPropertiesPanel.kt | 1 | 4733 | package org.jetbrains.haskell.debugger.breakpoints
import com.intellij.xdebugger.breakpoints.ui.XBreakpointCustomPropertiesPanel
import com.intellij.xdebugger.breakpoints.XLineBreakpoint
import com.intellij.xdebugger.breakpoints.XBreakpointProperties
import javax.swing.JComponent
import com.intellij.openapi.ui.ComboBox
import javax.swing.DefaultComboBoxModel
import javax.swing.JPanel
import javax.swing.JLabel
import javax. swing.SpringLayout.Constraints
import java.awt.GridLayout
import com.intellij.openapi.util.Key
import org.jetbrains.haskell.debugger.HaskellDebugProcess
import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.Condition
import org.jetbrains.haskell.debugger.parser.HsFilePosition
import java.util.ArrayList
//import org.jetbrains.haskell.debugger.protocol.BreakListForLineCommand
import org.jetbrains.haskell.debugger.utils.SyncObject
import com.intellij.xdebugger.XDebuggerManager
import org.jetbrains.haskell.debugger.utils.HaskellUtils
import org.jetbrains.haskell.debugger.parser.BreakInfo
import org.jetbrains.haskell.debugger.utils.UIUtils
/**
* Panel with additional breakpoint settings (make right click on breakpoint to see it)
*
* @author Habibullin Marat
*/
class SelectBreakPropertiesPanel : XBreakpointCustomPropertiesPanel<XLineBreakpoint<XBreakpointProperties<out Any?>>>() {
private val PANEL_LABEL: String = "Select breakpoint:"
private val DEBUG_NOT_STARTED_ITEM: String = "start debug process to enable"
private val breaksComboBox: ComboBox<String> = ComboBox(DefaultComboBoxModel(arrayOf(DEBUG_NOT_STARTED_ITEM)))
private val mainPanel: JPanel = JPanel(GridLayout(1, 0))
init {
UIUtils.addLabeledControl(mainPanel, 0, PANEL_LABEL, breaksComboBox)
breaksComboBox.isEnabled = false
}
private var debugManager: XDebuggerManager? = null
private var debugProcess: HaskellDebugProcess? = null
private var breaksList: ArrayList<BreakInfo>? = ArrayList()
private var lastSelectedIndex: Int? = null
override fun getComponent(): JComponent = mainPanel
/**
* Called when one press 'Done' button in breakpoint's context menu. Saves user selection and resets breakpoint if needed
*/
override fun saveTo(breakpoint: XLineBreakpoint<XBreakpointProperties<out Any?>>) {
if(debuggingInProgress()) {
val selectedIndex = breaksComboBox.selectedIndex
if (selectedIndex != lastSelectedIndex && debugProcess != null) {
breakpoint.putUserData(HaskellLineBreakpointHandler.INDEX_IN_BREAKS_LIST_KEY, selectedIndex)
val moduleName = HaskellUtils.getModuleName(debugManager!!.currentSession!!.project, breakpoint.sourcePosition!!.file)
debugProcess?.removeBreakpoint(moduleName, HaskellUtils.zeroBasedToHaskellLineNumber(breakpoint.line))
debugProcess?.addBreakpointByIndex(moduleName, breaksList!!.get(selectedIndex).breakIndex, breakpoint)
}
}
}
/**
* Called on every right click on breakpoint. Fills combo box with available breaks info
*/
override fun loadFrom(breakpoint: XLineBreakpoint<XBreakpointProperties<out Any?>>) {
getUserData(breakpoint)
fillComboBox()
}
private fun getUserData(breakpoint: XLineBreakpoint<XBreakpointProperties<out Any?>>) {
val project = breakpoint.getUserData(HaskellLineBreakpointHandler.PROJECT_KEY)
if(project != null) {
debugManager = XDebuggerManager.getInstance(project)
val justDebugProcess = debugManager?.currentSession?.debugProcess
if(justDebugProcess != null) {
debugProcess = justDebugProcess as HaskellDebugProcess
} else {
debugProcess = null
}
}
breaksList = breakpoint.getUserData(HaskellLineBreakpointHandler.BREAKS_LIST_KEY)
lastSelectedIndex = breakpoint.getUserData(HaskellLineBreakpointHandler.INDEX_IN_BREAKS_LIST_KEY)
}
private fun fillComboBox() {
breaksComboBox.removeAllItems()
if(debuggingInProgress() && (breaksList as ArrayList<BreakInfo>).isNotEmpty()) {
for (breakEntry in breaksList as ArrayList<BreakInfo>) {
breaksComboBox.addItem(breakEntry.srcSpan.spanToString())
}
breaksComboBox.setSelectedIndex(lastSelectedIndex as Int)
breaksComboBox.setEnabled(true)
} else {
breaksComboBox.addItem(DEBUG_NOT_STARTED_ITEM)
breaksComboBox.setEnabled(false)
}
}
private fun debuggingInProgress(): Boolean {
return debugManager?.currentSession != null
}
} | apache-2.0 | 6351a14e28f22c8cd47d4f84ec0abae9 | 44.085714 | 134 | 0.735686 | 4.997888 | false | false | false | false |
Leifzhang/AndroidRouter | app/src/main/java/com/kronos/sample/viewbinding/viewbind/ViewGroupViewBinding.kt | 2 | 1572 | package com.kronos.sample.viewbinding.viewbind
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.kronos.sample.viewbinding.ext.inflateMethod
import com.kronos.sample.viewbinding.ext.inflateMethodWithViewGroup
import java.lang.reflect.Method
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* <pre>
* author: dhl
* date : 2020/12/17
* desc :
* </pre>
*/
class ViewGroupViewBinding<T : ViewBinding>(
classes: Class<T>,
val inflater: LayoutInflater,
val viewGroup: ViewGroup? = null
) : ReadOnlyProperty<ViewGroup, T> {
private var viewBinding: T? = null
private var layoutInflater: Method
init {
if (viewGroup != null) {
layoutInflater = classes.inflateMethodWithViewGroup()
} else {
layoutInflater = classes.inflateMethod()
}
}
override fun getValue(thisRef: ViewGroup, property: KProperty<*>): T {
return viewBinding?.run {
this
} ?: let {
val bind: T
if (viewGroup != null) {
bind = layoutInflater.invoke(null, inflater, viewGroup) as T
} else {
bind = layoutInflater.invoke(null, inflater) as T
}
bind.apply {
if (viewGroup == null) {
thisRef.addView(bind.root)
}
viewBinding = this
}
}
}
private fun destroyed() {
viewBinding = null
}
} | mit | 5894583e979d7daf4c2c54b0a8b86fb9 | 24.370968 | 76 | 0.599237 | 4.637168 | false | false | false | false |
getsenic/nuimo-emulator-android | app/src/main/java/com/senic/nuimo/emulator/DialView.kt | 1 | 3428 | /**
* Created by Lars Blumberg on 2/9/16.
* Copyright Β© 2015 Senic. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details. *
*/
package com.senic.nuimo.emulator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
open class DialView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
var ringSize = 40
set(value) {field = value; invalidate()}
var handleSize = 50
set(value) {field = value; invalidate()}
var value = 0.0f
set(value) {
if (field == value) return
val oldValue = field
field = value
invalidate()
dialListener?.onChangeValue(value, oldValue)
}
open var dialListener: DialListener? = null
private var isDragging = false
//TODO: Provide color properties as XML layout attributes
private val ringPaint = Paint().apply { color = Color.argb(255, 37, 37, 37); flags = Paint.ANTI_ALIAS_FLAG }
private val surfacePaint = Paint().apply { color = Color.argb(255, 55, 55, 55); flags = Paint.ANTI_ALIAS_FLAG }
private val handlePaint = Paint().apply { color = Color.argb(127, 127, 127, 127); flags = Paint.ANTI_ALIAS_FLAG }
private val size: Int get() = Math.min(width, height)
private val rotationSize: Int get() = size - Math.max(handleSize, ringSize)
override fun onTouchEvent(event: MotionEvent): Boolean {
val wasDragging = isDragging
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> if (isEnabled && (Math.abs(Math.sqrt(Math.pow(event.x - width / 2.0, 2.0) + Math.pow(height / 2.0 - event.y, 2.0)) - rotationSize / 2.0) < Math.max(handleSize, ringSize) / 2.0f)) {
isDragging = true
dialListener?.onStartDragging()
performDrag(event.x, event.y)
}
MotionEvent.ACTION_MOVE -> if (isDragging) {
performDrag(event.x, event.y)
}
MotionEvent.ACTION_UP -> if (isDragging) {
isDragging = false
dialListener?.onEndDragging()
}
}
return isDragging || wasDragging
}
private fun performDrag(x: Float, y: Float) {
val pos = (Math.atan2(x - width / 2.0, height / 2.0 - y) / 2.0 / Math.PI).toFloat()
value = pos + if (pos >= 0) 0.0f else 1.0f
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val centerX = width / 2.0f
val centerY = height / 2.0f
val deltaX = (Math.sin(value * 2.0f * Math.PI) * rotationSize / 2.0f).toFloat()
val deltaY = (Math.cos(value * 2.0f * Math.PI) * rotationSize / 2.0f).toFloat()
canvas.apply {
drawCircle(centerX, centerY, (rotationSize + ringSize) / 2.0f, ringPaint)
drawCircle(centerX, centerY, (rotationSize - ringSize) / 2.0f, surfacePaint)
if (!isEnabled) return
canvas.drawCircle(centerX + deltaX, centerY - deltaY, handleSize / 2.0f, handlePaint)
}
}
interface DialListener {
fun onChangeValue(value: Float, oldValue: Float)
fun onStartDragging()
fun onEndDragging()
}
}
| mit | 4d2fe5dc66df0c6beb12a626f5d904d7 | 35.457447 | 219 | 0.612489 | 3.765934 | false | false | false | false |
leafclick/intellij-community | plugins/filePrediction/src/com/intellij/filePrediction/vcs/FilePredictionVcsFeatures.kt | 1 | 2029 | // 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.filePrediction.vcs
import com.intellij.filePrediction.FilePredictionFeature
import com.intellij.filePrediction.FilePredictionFeatureProvider
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.actions.VcsContextFactory
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.impl.VcsProjectLog
import com.jetbrains.changeReminder.predict.FileProbabilityRequest
import java.util.*
import kotlin.collections.HashMap
class FilePredictionVcsFeatures : FilePredictionFeatureProvider {
override fun getName(): String = "vcs"
override fun calculateFileFeatures(project: Project, newFile: VirtualFile, prevFile: VirtualFile?): Map<String, FilePredictionFeature> {
if (!ProjectLevelVcsManager.getInstance(project).hasAnyMappings()) return emptyMap()
val result = HashMap<String, FilePredictionFeature>()
val changeListManager = ChangeListManager.getInstance(project)
if (prevFile != null) {
result["prev_in_changelist"] = FilePredictionFeature.binary(changeListManager.isFileAffected(prevFile))
}
result["in_changelist"] = FilePredictionFeature.binary(changeListManager.isFileAffected(newFile))
if (prevFile != null) {
val dataManager = VcsProjectLog.getInstance(project).dataManager
if (dataManager != null) {
val contextFactory = VcsContextFactory.SERVICE.getInstance()
val newPath = contextFactory.createFilePath(newFile.path, false)
val recentFile = contextFactory.createFilePath(prevFile.path, false)
val request = FileProbabilityRequest(project, dataManager, Collections.singletonList(recentFile))
result["related_prob"] = FilePredictionFeature.numerical(request.calculate(newPath))
}
}
return result
}
}
| apache-2.0 | 00af76ea66d66b7e467ffbbfe0a4b6ce | 47.309524 | 140 | 0.786594 | 4.842482 | false | false | false | false |
leafclick/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/ext/newify/NewifyMemberContributor.kt | 1 | 4157 | // 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.jetbrains.plugins.groovy.ext.newify
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightMethodBuilder
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.parentsWithSelf
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.GrAnnotationUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.GrAnnotationUtil.getClassArrayValue
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil
import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessMethods
internal const val newifyAnnotationFqn = "groovy.lang.Newify"
internal const val newifyOriginInfo = "by @Newify"
class NewifyMemberContributor : NonCodeMembersContributor() {
override fun processDynamicElements(qualifierType: PsiType,
aClass: PsiClass?,
processor: PsiScopeProcessor,
place: PsiElement,
state: ResolveState) {
if (!processor.shouldProcessMethods()) return
if (place !is GrReferenceExpression) return
val newifyAnnotations = place.listNewifyAnnotations()
if (newifyAnnotations.isEmpty()) return
val qualifier = place.qualifierExpression
val type = (qualifier as? GrReferenceExpression)?.resolve() as? PsiClass
for (annotation in newifyAnnotations) {
val newifiedClasses = getClassArrayValue(annotation, "value", true)
qualifier ?: newifiedClasses.flatMap { buildConstructors(it, it.name) }.forEach {
ResolveUtil.processElement(processor, it, state)
}
val createNewMethods = GrAnnotationUtil.inferBooleanAttributeNotNull(annotation, "auto")
if (type != null && createNewMethods) {
buildConstructors(type, "new").forEach {
ResolveUtil.processElement(processor, it, state)
}
}
}
}
private fun PsiElement.listNewifyAnnotations() = parentsWithSelf.flatMap {
val owner = it as? PsiModifierListOwner
val seq = owner?.modifierList?.annotations?.asSequence()?.filter { it.qualifiedName == newifyAnnotationFqn }
return@flatMap seq ?: emptySequence()
}.toList()
private fun buildConstructors(clazz: PsiClass, newName: String?): List<NewifiedConstructor> {
newName ?: return emptyList()
val constructors = clazz.constructors
if (constructors.isNotEmpty()) {
return constructors.mapNotNull { buildNewifiedConstructor(it, newName) }
}
else {
return listOf(buildNewifiedConstructor(clazz, newName))
}
}
private fun buildNewifiedConstructor(myPrototype: PsiMethod, newName: String): NewifiedConstructor? {
val builder = NewifiedConstructor(myPrototype.manager, newName)
val psiClass = myPrototype.containingClass ?: return null
builder.containingClass = psiClass
builder.setMethodReturnType(TypesUtil.createType(psiClass))
builder.navigationElement = myPrototype
myPrototype.parameterList.parameters.forEach {
builder.addParameter(it)
}
myPrototype.throwsList.referencedTypes.forEach {
builder.addException(it)
}
myPrototype.typeParameters.forEach {
builder.addTypeParameter(it)
}
return builder
}
private fun buildNewifiedConstructor(myPrototype: PsiClass, newName: String): NewifiedConstructor {
val builder = NewifiedConstructor(myPrototype.manager, newName)
builder.containingClass = myPrototype
builder.setMethodReturnType(TypesUtil.createType(myPrototype))
builder.navigationElement = myPrototype
return builder
}
class NewifiedConstructor(val myManager: PsiManager, val newName: String) : LightMethodBuilder(myManager, newName) {
init {
addModifier(PsiModifier.STATIC)
originInfo = newifyOriginInfo
}
}
} | apache-2.0 | ffbebc64c8639a2609db235d57c33699 | 41 | 140 | 0.735627 | 4.990396 | false | false | false | false |
grover-ws-1/http4k | http4k-core/src/main/kotlin/org/http4k/filter/CachingFilters.kt | 1 | 6061 | package org.http4k.filter
import org.http4k.core.Filter
import org.http4k.core.Headers
import org.http4k.core.HttpHandler
import org.http4k.core.Method.GET
import java.security.MessageDigest
import java.time.Clock
import java.time.Duration
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME
open class CacheControlHeaderPart(open val name: String, val value: Duration) {
fun toHeaderValue(): String = if (value.seconds > 0) "$name=${value.seconds}" else ""
}
data class StaleWhenRevalidateTtl(private val valueD: Duration) : CacheControlHeaderPart("stale-while-revalidate", valueD)
data class StaleIfErrorTtl(private val valueD: Duration) : CacheControlHeaderPart("stale-if-error", valueD)
data class MaxAgeTtl(private val valueD: Duration) : CacheControlHeaderPart("max-age", valueD)
data class DefaultCacheTimings(val maxAge: MaxAgeTtl,
val staleIfErrorTtl: StaleIfErrorTtl,
val staleWhenRevalidateTtl: StaleWhenRevalidateTtl)
/**
* Useful filters for applying Cache-Controls to request/responses
*/
object CachingFilters {
/**
* These filters operate on Requests (pre-flight)
*/
object Request {
fun AddIfModifiedSince(clock: Clock, maxAge: Duration) = Filter { next ->
{
next(it.header("If-Modified-Since", RFC_1123_DATE_TIME.format(ZonedDateTime.now(clock).minus(maxAge))))
}
}
}
/**
* These filters operate on Responses (post-flight)
*/
object Response {
private abstract class CacheFilter(private val predicate: (org.http4k.core.Response) -> Boolean) : Filter {
abstract fun headersFor(response: org.http4k.core.Response): Headers
override fun invoke(next: HttpHandler): HttpHandler =
{
val response = next(it)
val headers = if (it.method == GET && predicate(response)) headersFor(response) else emptyList()
headers.fold(response) { memo, (first, second) -> memo.header(first, second) }
}
}
/**
* By default, only applies when the status code of the response is < 400. This is overridable and useful -
* For example you could combine this with a MaxAge for everything >= 400
*/
fun NoCache(predicate: (org.http4k.core.Response) -> Boolean = { it.status.code < 400 }): Filter = object : CacheFilter(predicate) {
override fun headersFor(response: org.http4k.core.Response) = listOf("Cache-Control" to "private, must-revalidate", "Expires" to "0")
}
/**
* By default, only applies when the status code of the response is < 400. This is overridable.
*/
fun MaxAge(clock: Clock, maxAge: Duration, predicate: (org.http4k.core.Response) -> Boolean = { it.status.code < 400 }): Filter = object : CacheFilter(predicate) {
override fun headersFor(response: org.http4k.core.Response) = listOf(
"Cache-Control" to listOf("public", MaxAgeTtl(maxAge).toHeaderValue()).joinToString(", "),
"Expires" to RFC_1123_DATE_TIME.format(now(response).plusSeconds(maxAge.seconds))
)
private fun now(response: org.http4k.core.Response) =
try {
response.header("Date")?.let(RFC_1123_DATE_TIME::parse)?.let(ZonedDateTime::from) ?: ZonedDateTime.now(clock)
} catch (e: Exception) {
ZonedDateTime.now(clock)
}
}
/**
* Hash algo stolen from http://stackoverflow.com/questions/26423662/scalatra-response-hmac-calulation
* By default, only applies when the status code of the response is < 400. This is overridable.
*/
fun AddETag(predicate: (org.http4k.core.Response) -> Boolean = { it.status.code < 400 }): Filter = Filter { next ->
{
val response = next(it)
if (predicate(response)) {
val hashedBody = MessageDigest.getInstance("MD5")
.digest(response.body.payload.array())
.map { "%02x".format(it) }.joinToString("")
response.header("Etag", hashedBody)
} else
response
}
}
/**
* Applies the passed cache timings (Cache-Control, Expires, Vary) to responses, but only if they are not there already.
* Use this for adding default cache settings.
* By default, only applies when the status code of the response is < 400. This is overridable.
*/
fun FallbackCacheControl(clock: Clock, defaultCacheTimings: DefaultCacheTimings, predicate: (org.http4k.core.Response) -> Boolean = { it.status.code < 400 }): Filter = object : Filter {
override fun invoke(next: HttpHandler): HttpHandler =
{
val response = next(it)
if (it.method == GET && predicate(response)) addDefaultCacheHeadersIfAbsent(response) else response
}
private fun addDefaultHeaderIfAbsent(response: org.http4k.core.Response, header: String, defaultProducer: () -> String) =
response.header(header, response.header(header) ?: defaultProducer())
private fun addDefaultCacheHeadersIfAbsent(response: org.http4k.core.Response) =
addDefaultHeaderIfAbsent(response, "Cache-Control", {
listOf("public", defaultCacheTimings.maxAge.toHeaderValue(), defaultCacheTimings.staleWhenRevalidateTtl.toHeaderValue(), defaultCacheTimings.staleIfErrorTtl.toHeaderValue()).joinToString(", ")
})
.let { addDefaultHeaderIfAbsent(it, "Expires", { RFC_1123_DATE_TIME.format(ZonedDateTime.now(clock).plus(defaultCacheTimings.maxAge.value)) }) }
.let { addDefaultHeaderIfAbsent(it, "Vary", { "Accept-Encoding" }) }
}
}
}
| apache-2.0 | 44fbe48d6e63eff514c72bfcdfcf49d3 | 46.351563 | 212 | 0.624319 | 4.430556 | false | false | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/internal/inspector/ConfigureCustomSizeAction.kt | 3 | 1247 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.inspector
import com.intellij.ide.util.propComponentProperty
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import java.awt.GraphicsEnvironment
/**
* @author Konstantin Bulenkov
*/
class ConfigureCustomSizeAction: DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val centerPanel = panel {
row("Width:") { intTextField(CustomSizeModel::width, 20, 1..maxWidth()).focused() }
row("Height:") { intTextField(CustomSizeModel::height, 20, 1..maxHeight()) }
}
dialog("Default Size", centerPanel, project = e.project).show()
}
private fun maxWidth(): Int = maxWindowBounds().width
private fun maxHeight(): Int = maxWindowBounds().height
private fun maxWindowBounds() = GraphicsEnvironment.getLocalGraphicsEnvironment().maximumWindowBounds
object CustomSizeModel {
var width by propComponentProperty(defaultValue = 640)
var height by propComponentProperty(defaultValue = 300)
}
} | apache-2.0 | 65867499765bd098e2133e0584b8f3fe | 36.818182 | 140 | 0.761828 | 4.584559 | false | false | false | false |
MGaetan89/Kolumbus | kolumbus/src/main/kotlin/io/kolumbus/layout/TableLayoutManager.kt | 1 | 1870 | /*
* Copyright (C) 2016 MGaetan89
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.kolumbus.layout
import android.content.Context
import android.graphics.Point
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
class TableLayoutManager(context: Context) : LinearLayoutManager(context) {
override fun canScrollHorizontally() = true
override fun canScrollVertically() = true
override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
super.onLayoutChildren(recycler, state)
val size = Point(0, 0)
// Compute the biggest dimension from all the visible items
this.processChild(0, this.itemCount) {
it.measure(0, 0)
size.x = Math.max(size.x, it.measuredWidth)
size.y = Math.max(size.y, it.measuredHeight)
}
// Set the proper size on all the visible items
this.processChild(0, state?.itemCount ?: 0) {
it.layoutParams.height = size.y
it.layoutParams.width = size.x
it.post {
it.requestLayout()
}
}
}
private fun processChild(from: Int, to: Int, callback: (child: View) -> Unit) {
(from..to)
.mapNotNull { this.getChildAt(it) as ViewGroup? }
.forEach {
(0 until it.childCount)
.map(it::getChildAt)
.forEach(callback)
}
}
}
| apache-2.0 | 5b2a426b9d0f0da0a5fc8b71b9a76668 | 28.68254 | 94 | 0.722995 | 3.631068 | false | false | false | false |
nrkv/HypeAPI | src/main/kotlin/io/nrkv/HypeAPI/user/dao/implementation/UserDAOImpl.kt | 1 | 1001 | package io.nrkv.HypeAPI.user.dao.implementation
import io.nrkv.HypeAPI.user.dao.UserDAO
import io.nrkv.HypeAPI.user.model.UserCredentials
import io.nrkv.HypeAPI.user.model.UserDatabase
import io.nrkv.HypeAPI.user.model.implementation.UserDatabaseModel
import io.nrkv.HypeAPI.user.model.implementation.UserResponseModel
import org.springframework.stereotype.Repository
/**
* Created by Ivan Nyrkov on 08/06/17.
*/
@Repository
class UserDAOImpl : UserDAO {
val users = mutableListOf<UserDatabase>()
override fun register(credentials: UserCredentials): UserDatabase {
val newUser = UserDatabaseModel(response = UserResponseModel(), credentials = credentials)
users.add(newUser)
return newUser
}
override fun getById(userId: String): UserDatabase? {
return users.find { !it.isDeleted && it.id == userId }
}
override fun getByEmail(userEmail: String): UserDatabase? {
return users.find { !it.isDeleted && it.email == userEmail }
}
} | mit | 1419a557a7e29485cd86030c21f348c7 | 31.322581 | 98 | 0.738262 | 3.879845 | false | false | false | false |
codeka/wwmmo | common/src/main/kotlin/au/com/codeka/warworlds/common/sim/MutableStar.kt | 1 | 7337 | package au.com.codeka.warworlds.common.sim
import au.com.codeka.warworlds.common.proto.*
class MutableBuilding(private val building: Building) {
var id = building.id
val designType
get() = building.design_type
var level = building.level
fun build(): Building {
return building.copy(
id = id,
level = level)
}
}
class MutableFocus(focus: ColonyFocus) {
var construction = focus.construction
var farming = focus.farming
var mining = focus.mining
var energy = focus.energy
fun build(): ColonyFocus {
return ColonyFocus(
construction = construction,
farming = farming,
mining = mining,
energy = energy)
}
}
class MutableBuildRequest(private val buildRequest: BuildRequest) {
val id
get() = buildRequest.id
val startTime
get() = buildRequest.start_time!!
val designType
get() = buildRequest.design_type
val count
get() = buildRequest.count ?: 1
/** Non-null only if upgrading a building. */
val buildingId
get() = buildRequest.building_id
var progress = buildRequest.progress ?: 0f
var endTime = buildRequest.end_time ?: Long.MAX_VALUE
var mineralsDeltaPerHour = buildRequest.delta_minerals_per_hour ?: 0f
var mineralsEfficiency = buildRequest.minerals_efficiency ?: 0f
var populationEfficiency = buildRequest.population_efficiency ?: 0f
var progressPerStep = buildRequest.progress_per_step ?: 0f
fun build(): BuildRequest {
return buildRequest.copy(
progress = progress,
end_time = endTime,
delta_minerals_per_hour = mineralsDeltaPerHour,
minerals_efficiency = mineralsEfficiency,
population_efficiency = populationEfficiency,
progress_per_step = progressPerStep)
}
}
class MutableColony(private val colony: Colony) {
val id
get() = colony.id
val empireId
get() = colony.empire_id
var defenceBonus = colony.defence_bonus ?: 0f
var focus = MutableFocus(colony.focus)
/** Null if there is no cooldown. */
var cooldownEndTime = colony.cooldown_end_time
var buildings = ArrayList(colony.buildings.map { MutableBuilding(it) })
var buildRequests = ArrayList(colony.build_requests.map { MutableBuildRequest(it) })
var population = colony.population
var deltaGoods = colony.delta_goods ?: 0f
var deltaMinerals = colony.delta_minerals ?: 0f
var deltaPopulation = colony.delta_population ?: 0f
var deltaEnergy = colony.delta_energy ?: 0f
fun build(): Colony {
return colony.copy(
focus = focus.build(),
buildings = buildings.map { it.build() },
build_requests = buildRequests.map { it.build() },
defence_bonus = defenceBonus,
population = population,
delta_goods = deltaGoods,
delta_minerals = deltaMinerals,
delta_population = deltaPopulation,
delta_energy = deltaEnergy,
cooldown_end_time = cooldownEndTime)
}
}
class MutablePlanet(private val planet: Planet) {
/**
* Gets the immutable [Planet] we were constructed with. If you've made changes to this planet
* this will *not* include the changes.
*/
val proto
get() = planet
val index
get() = planet.index
val populationCongeniality
get() = planet.population_congeniality
var colony: MutableColony? = if (planet.colony == null) null else MutableColony(planet.colony)
fun build(): Planet {
return planet.copy(
colony = colony?.build())
}
}
class MutableFleet(private val fleet: Fleet) {
/**
* Gets the immutable [Fleet] we were constructed with. If you've made changes to this fleet
* this will *not* include the changes.
*/
val proto
get() = fleet
val empireId
get() = fleet.empire_id
val designType
get() = fleet.design_type
var id = fleet.id
var state = fleet.state
var stateStartTime = fleet.state_start_time
var stance = fleet.stance
var numShips = fleet.num_ships
var isDestroyed = fleet.is_destroyed ?: false
var fuelAmount = fleet.fuel_amount
var destinationStarId = fleet.destination_star_id
var eta = fleet.eta
fun build(): Fleet {
return fleet.copy(
id = id,
state = state,
state_start_time = stateStartTime,
stance = stance,
num_ships = numShips,
is_destroyed = isDestroyed,
fuel_amount = fuelAmount,
destination_star_id = destinationStarId,
eta = eta)
}
}
class MutableEmpireStorage(private val empireStore: EmpireStorage) {
val empireId
get() = empireStore.empire_id
var maxEnergy = empireStore.max_energy
var maxGoods = empireStore.max_goods
var maxMinerals = empireStore.max_minerals
var totalEnergy = empireStore.total_energy
var totalGoods = empireStore.total_goods
var totalMinerals = empireStore.total_minerals
var energyDeltaPerHour = empireStore.energy_delta_per_hour ?: 0f
var goodsDeltaPerHour = empireStore.goods_delta_per_hour ?: 0f
var mineralsDeltaPerHour = empireStore.minerals_delta_per_hour ?: 0f
/** Null if we don't hit zero. */
var goodsZeroTime = empireStore.goods_zero_time
fun build(): EmpireStorage {
return empireStore.copy(
max_energy = maxEnergy,
max_goods = maxGoods,
max_minerals = maxMinerals,
total_energy = totalEnergy,
total_goods = totalGoods,
total_minerals = totalMinerals,
energy_delta_per_hour = energyDeltaPerHour,
goods_delta_per_hour = goodsDeltaPerHour,
minerals_delta_per_hour = mineralsDeltaPerHour,
goods_zero_time = goodsZeroTime)
}
}
class MutableCombatReport(combatReport: CombatReport = CombatReport(time = 0)) {
var time = combatReport.time
// Note: we want to make sure our before/after are copies!
var fleetsBefore = combatReport.fleets_before.map { it.copy() }
var fleetsAfter = combatReport.fleets_after.map { it.copy() }
fun build(): CombatReport {
return CombatReport(
time = time,
fleets_before = fleetsBefore,
fleets_after = fleetsAfter)
}
}
/**
* The [Star] protocol buffer is kind of a pain to mutate. This is basically a mirror of [Star] that
* is fully mutable, for easier simulation, etc.
*/
class MutableStar private constructor(private val star: Star) {
companion object {
fun from(star: Star): MutableStar {
return MutableStar(star)
}
}
val id = star.id
val sectorX
get() = star.sector_x
val sectorY
get() = star.sector_y
val offsetX
get() = star.offset_x
val offsetY
get() = star.offset_y
var name = star.name
var lastSimulation = star.last_simulation
var planets = ArrayList(star.planets.map { MutablePlanet(it) })
var fleets = ArrayList(star.fleets.map { MutableFleet(it) })
var empireStores = ArrayList(star.empire_stores.map { MutableEmpireStorage(it) })
var combatReports = ArrayList(star.combat_reports.map { MutableCombatReport(it) })
var scoutReports = ArrayList(star.scout_reports)
var nextSimulation = star.next_simulation
// Re-build this [MutableStar] back into a [Star]
fun build(): Star {
return star.copy(
name = name,
last_simulation = lastSimulation,
planets = planets.map { it.build() },
fleets = fleets.map { it.build() },
empire_stores = empireStores.map { it.build() },
combat_reports = combatReports.map { it.build() },
scout_reports = scoutReports,
next_simulation = nextSimulation)
}
}
| mit | ee5c6b8b57922f2fd7d59ff68e1dfe6c | 27.660156 | 100 | 0.6902 | 3.789773 | false | false | false | false |
smmribeiro/intellij-community | spellchecker/src/com/intellij/spellchecker/grazie/dictionary/ExtendedWordListWithFrequency.kt | 9 | 915 | // 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 com.intellij.spellchecker.grazie.dictionary
import ai.grazie.spell.lists.WordListWithFrequency
internal class ExtendedWordListWithFrequency(private val base: WordListWithFrequency,
private val extension: WordListAdapter) : WordListWithFrequency {
override val defaultFrequency: Int
get() = base.defaultFrequency
override val maxFrequency: Int
get() = base.maxFrequency
override fun getFrequency(word: String) = base.getFrequency(word)
override fun contains(word: String, caseSensitive: Boolean) =
base.contains(word, caseSensitive) || extension.contains(word, caseSensitive)
override fun suggest(word: String) = base.suggest(word).apply { this += extension.suggest(word) }
}
| apache-2.0 | d6c430dcf81a66d60d0035e208aa5f13 | 44.75 | 158 | 0.744262 | 4.529703 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/jdk2k/ReplaceJavaStaticMethodWithKotlinAnalogInspection.kt | 1 | 11104 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.jdk2k
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.callExpressionVisitor
import org.jetbrains.kotlin.psi.psiUtil.getReceiverExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isChar
class ReplaceJavaStaticMethodWithKotlinAnalogInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(call) {
val callee = call.calleeExpression ?: return
val replacements = REPLACEMENTS[callee.text]
?.filter { it.filter(call) && it.transformation.isApplicable(call) }
?.takeIf { it.isNotEmpty() }
?.let { list ->
val context = call.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val callDescriptor = call.getResolvedCall(context) ?: return
list.filter {
callDescriptor.isCalling(FqName(it.javaMethodFqName)) && it.transformation.isApplicableInContext(
call,
context
)
}
}
?.takeIf { it.isNotEmpty() }
?.map(::ReplaceWithKotlinAnalogFunction)
?.toTypedArray() ?: return
holder.registerProblem(
call,
callee.textRangeIn(call),
KotlinBundle.message("should.be.replaced.with.kotlin.function"),
*replacements
)
})
private class ReplaceWithKotlinAnalogFunction(private val replacement: Replacement) : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.kotlin.analog.function.text", replacement.kotlinFunctionShortName)
override fun getFamilyName() = KotlinBundle.message("replace.with.kotlin.analog.function.family.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val callExpression = descriptor.psiElement as? KtCallExpression ?: return
replacement.transformation(callExpression, replacement)
}
}
companion object {
private val JAVA_PRIMITIVES = listOf(
"Integer" to "Int",
"Long" to "Long",
"Byte" to "Byte",
"Character" to "Char",
"Short" to "Short",
"Double" to "Double",
"Float" to "Float"
).flatMap { (javaPrimitive, kotlinPrimitive) ->
listOf(
Replacement("java.lang.$javaPrimitive.toString", "kotlin.text.toString", ToExtensionFunctionWithNonNullableReceiver) {
it.valueArguments.size == 2
},
Replacement(
"java.lang.$javaPrimitive.toString",
"kotlin.primitives.$kotlinPrimitive.toString",
ToExtensionFunctionWithNullableReceiver
) { call ->
val valueArguments = call.valueArguments
when {
valueArguments.size != 1 -> false
javaPrimitive != "Character" -> true
else -> {
val singleArgument = valueArguments.single().getArgumentExpression()
if (singleArgument != null) {
val context = call.analyze(BodyResolveMode.PARTIAL)
singleArgument.getType(context)?.isChar() == true
} else {
false
}
}
}
},
Replacement(
"java.lang.$javaPrimitive.compare",
"kotlin.primitives.$kotlinPrimitive.compareTo",
ToExtensionFunctionWithNonNullableReceiver
)
)
}
private val JAVA_IO = listOf(
Replacement("java.io.PrintStream.print", "kotlin.io.print", filter = ::isJavaSystemOut),
Replacement("java.io.PrintStream.println", "kotlin.io.println", filter = ::isJavaSystemOut)
)
// TODO: implement [java.lang.System.arraycopy]
private val JAVA_SYSTEM = listOf(
Replacement("java.lang.System.exit", "kotlin.system.exitProcess")
)
private val JAVA_MATH = listOf(
Replacement("java.lang.Math.abs", "kotlin.math.abs"),
Replacement("java.lang.Math.acos", "kotlin.math.acos"),
Replacement("java.lang.Math.asin", "kotlin.math.asin"),
Replacement("java.lang.Math.atan", "kotlin.math.atan"),
Replacement("java.lang.Math.atan2", "kotlin.math.atan2"),
Replacement("java.lang.Math.ceil", "kotlin.math.ceil"),
Replacement("java.lang.Math.cos", "kotlin.math.cos"),
Replacement("java.lang.Math.cosh", "kotlin.math.cosh"),
Replacement("java.lang.Math.exp", "kotlin.math.exp"),
Replacement("java.lang.Math.expm1", "kotlin.math.expm1"),
Replacement("java.lang.Math.floor", "kotlin.math.floor"),
Replacement("java.lang.Math.hypot", "kotlin.math.hypot"),
Replacement("java.lang.Math.IEEEremainder", "kotlin.math.IEEErem", ToExtensionFunctionWithNonNullableReceiver),
Replacement("java.lang.Math.log", "kotlin.math.ln"),
Replacement("java.lang.Math.log1p", "kotlin.math.ln1p"),
Replacement("java.lang.Math.log10", "kotlin.math.log10"),
Replacement("java.lang.Math.max", "kotlin.math.max"),
Replacement("java.lang.Math.max", "kotlin.ranges.coerceAtLeast", ToExtensionFunctionWithNonNullableReceiver),
Replacement("java.lang.Math.min", "kotlin.math.min"),
Replacement("java.lang.Math.min", "kotlin.ranges.coerceAtMost", ToExtensionFunctionWithNonNullableReceiver),
Replacement("java.lang.Math.nextDown", "kotlin.math.nextDown", ToExtensionFunctionWithNonNullableReceiver),
Replacement("java.lang.Math.nextAfter", "kotlin.math.nextTowards", ToExtensionFunctionWithNonNullableReceiver),
Replacement("java.lang.Math.nextUp", "kotlin.math.nextUp", ToExtensionFunctionWithNonNullableReceiver),
Replacement("java.lang.Math.pow", "kotlin.math.pow", ToExtensionFunctionWithNonNullableReceiver),
Replacement("java.lang.Math.rint", "kotlin.math.round"),
Replacement("java.lang.Math.round", "kotlin.math.roundToLong", ToExtensionFunctionWithNonNullableReceiver),
Replacement("java.lang.Math.round", "kotlin.math.roundToInt", ToExtensionFunctionWithNonNullableReceiver),
Replacement("java.lang.Math.signum", "kotlin.math.sign"),
Replacement("java.lang.Math.sin", "kotlin.math.sin"),
Replacement("java.lang.Math.sinh", "kotlin.math.sinh"),
Replacement("java.lang.Math.sqrt", "kotlin.math.sqrt"),
Replacement("java.lang.Math.tan", "kotlin.math.tan"),
Replacement("java.lang.Math.tanh", "kotlin.math.tanh"),
Replacement("java.lang.Math.copySign", "kotlin.math.withSign", ToExtensionFunctionWithNonNullableReceiver)
)
// TODO: implement [java.util.Arrays.binarySearch, java.util.Arrays.fill, java.util.Arrays.sort]
private val JAVA_COLLECTIONS = listOf(
Replacement("java.util.Arrays.copyOf", "kotlin.collections.copyOf", ToExtensionFunctionWithNonNullableReceiver) {
it.valueArguments.size == 2
},
Replacement("java.util.Arrays.copyOfRange", "kotlin.collections.copyOfRange", ToExtensionFunctionWithNonNullableReceiver),
Replacement("java.util.Arrays.equals", "kotlin.collections.contentEquals", ToExtensionFunctionWithNonNullableArguments) {
it.valueArguments.size == 2
},
Replacement("java.util.Arrays.deepEquals", "kotlin.collections.contentDeepEquals", ToExtensionFunctionWithNonNullableArguments),
Replacement(
"java.util.Arrays.deepHashCode",
"kotlin.collections.contentDeepHashCode",
ToExtensionFunctionWithNonNullableReceiver
),
Replacement("java.util.Arrays.hashCode", "kotlin.collections.contentHashCode", ToExtensionFunctionWithNonNullableReceiver),
Replacement(
"java.util.Arrays.deepToString",
"kotlin.collections.contentDeepToString",
ToExtensionFunctionWithNonNullableReceiver
),
Replacement("java.util.Arrays.toString", "kotlin.collections.contentToString", ToExtensionFunctionWithNonNullableReceiver),
Replacement("java.util.Arrays.asList", "kotlin.collections.listOf"),
Replacement("java.util.Arrays.asList", "kotlin.collections.mutableListOf"),
Replacement("java.util.Set.of", "kotlin.collections.setOf"),
Replacement("java.util.Set.of", "kotlin.collections.mutableSetOf"),
Replacement("java.util.List.of", "kotlin.collections.listOf"),
Replacement("java.util.List.of", "kotlin.collections.mutableListOf")
)
private val REPLACEMENTS = (JAVA_MATH + JAVA_SYSTEM + JAVA_IO + JAVA_PRIMITIVES + JAVA_COLLECTIONS)
.groupBy { it.javaMethodShortName }
}
}
data class Replacement(
val javaMethodFqName: String,
val kotlinFunctionFqName: String,
val transformation: Transformation = WithoutAdditionalTransformation,
val filter: (KtCallExpression) -> Boolean = { true }
) {
private fun String.shortName() = takeLastWhile { it != '.' }
val javaMethodShortName = javaMethodFqName.shortName()
val kotlinFunctionShortName = kotlinFunctionFqName.shortName()
}
private fun isJavaSystemOut(callExpression: KtCallExpression): Boolean =
(callExpression.calleeExpression as? KtSimpleNameExpression)
?.getReceiverExpression()
?.resolveToCall()
?.isCalling(FqName("java.lang.System.out")) ?: false | apache-2.0 | 14f23627d5e3e4dbdd333ac6c5af3e4d | 52.907767 | 158 | 0.649766 | 4.887324 | false | false | false | false |
smmribeiro/intellij-community | python/python-psi-impl/src/com/jetbrains/python/psi/types/PyCollectionTypeUtil.kt | 9 | 28195 | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.jetbrains.python.psi.types
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ArrayUtil
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyBuiltinCache
import com.jetbrains.python.psi.resolve.PyResolveContext
object PyCollectionTypeUtil {
const val DICT_CONSTRUCTOR: String = "dict.__init__"
private const val LIST_CONSTRUCTOR = "list.__init__"
private const val SET_CONSTRUCTOR = "set.__init__"
private const val RANGE_CONSTRUCTOR = "range"
private const val MAX_ANALYZED_ELEMENTS_OF_LITERALS = 10 /* performance */
fun getCollectionConstructors(languageLevel: LanguageLevel): Set<String> {
return if (languageLevel.isPython2) {
setOf(LIST_CONSTRUCTOR,
DICT_CONSTRUCTOR,
SET_CONSTRUCTOR,
RANGE_CONSTRUCTOR)
}
else {
setOf(LIST_CONSTRUCTOR,
DICT_CONSTRUCTOR,
SET_CONSTRUCTOR)
}
}
fun getTypedDictTypeWithModifications(sequence: PySequenceExpression, context: TypeEvalContext): PyTypedDictType? {
var allStrKeys = true
val keysToValueTypes = LinkedHashMap<String, Pair<PyExpression?, PyType?>>()
val typedDictType = getTypedDictTypeFromDictLiteral(sequence, context)
if (typedDictType != null) {
keysToValueTypes.putAll(typedDictType.getKeysToValuesWithTypes())
}
else {
allStrKeys = false
}
val (allStrKeysInModifications, typedDictTypeByModifications) = getTypedDictTypeByModificationsForDictConstructor(sequence, context)
if (allStrKeysInModifications && typedDictTypeByModifications != null) {
typedDictTypeByModifications.getKeysToValuesWithTypes().forEach {
if (keysToValueTypes.putIfAbsent(it.key, it.value) != null) {
keysToValueTypes[it.key] = Pair(it.value.first, PyUnionType.union(keysToValueTypes[it.key]?.second, it.value.second))
}
}
}
return if (allStrKeys && allStrKeysInModifications) return PyTypedDictType.createFromKeysToValueTypes(sequence, keysToValueTypes)
else null
}
fun getTypeByModifications(sequence: PySequenceExpression, context: TypeEvalContext): List<PyType?> {
return when (sequence) {
is PyListLiteralExpression -> listOf(getListOrSetIteratedValueType(sequence, context, true))
is PySetLiteralExpression -> listOf(getListOrSetIteratedValueType(sequence, context, true))
is PyDictLiteralExpression -> getDictElementTypesWithModifications(sequence, context)
else -> listOf<PyType?>(null)
}
}
private fun getListOrSetIteratedValueType(sequence: PySequenceExpression, context: TypeEvalContext, withModifications: Boolean): PyType? {
val elements = sequence.elements
val maxAnalyzedElements = MAX_ANALYZED_ELEMENTS_OF_LITERALS.coerceAtMost(elements.size)
var analyzedElementsType = PyUnionType.union(elements.take(maxAnalyzedElements).map { context.getType(it) })
if (withModifications) {
val typesByModifications = getCollectionTypeByModifications(sequence, context)
if (typesByModifications.isNotEmpty()) {
val typeByModifications = PyUnionType.union(typesByModifications)
analyzedElementsType = if (analyzedElementsType == null) typeByModifications
else PyUnionType.union(analyzedElementsType, typeByModifications)
}
}
return if (elements.size > maxAnalyzedElements) {
PyUnionType.createWeakType(analyzedElementsType)
}
else {
analyzedElementsType
}
}
private fun getDictElementTypes(sequence: PySequenceExpression, context: TypeEvalContext): Pair<PyType?, PyType?> {
val typedDictType = getTypedDictTypeFromDictLiteral(sequence, context)
if (typedDictType != null) {
return Pair(typedDictType.elementTypes.component1(), typedDictType.elementTypes.component2())
}
else {
return getDictLiteralElementTypes(sequence, context)
}
}
private fun getTypedDictTypeFromDictLiteral(sequence: PySequenceExpression,
context: TypeEvalContext): PyTypedDictType? {
val elements = sequence.elements
val maxAnalyzedElements = MAX_ANALYZED_ELEMENTS_OF_LITERALS.coerceAtMost(elements.size)
var allStrKeys = true
val strKeysToValueTypes = HashMap<String, Pair<PyExpression?, PyType?>>()
elements
.take(maxAnalyzedElements)
.map { element -> Pair(element, context.getType(element) as? PyTupleType) }
.forEach { (tuple, tupleType) ->
if (tupleType != null) {
val tupleElementTypes = tupleType.elementTypes
when {
tupleType.isHomogeneous -> {
val keyAndValueType = tupleType.iteratedItemType
val keysToValueTypes = assemblePotentialTypedDictFields(keyAndValueType, keyAndValueType, tuple)
if (keysToValueTypes != null) {
strKeysToValueTypes.putAll(keysToValueTypes)
}
else {
allStrKeys = false
}
}
tupleElementTypes.size == 2 -> {
val keysToValueTypes = assemblePotentialTypedDictFields(tupleElementTypes[0], tupleElementTypes[1], tuple)
if (keysToValueTypes != null) {
strKeysToValueTypes.putAll(keysToValueTypes)
}
else {
allStrKeys = false
}
}
else -> {
allStrKeys = false
}
}
}
else {
allStrKeys = false
}
}
if (elements.size > maxAnalyzedElements) {
allStrKeys = false
}
return if (allStrKeys) PyTypedDictType.createFromKeysToValueTypes(sequence, strKeysToValueTypes) else null
}
private fun getDictLiteralElementTypes(sequence: PySequenceExpression,
context: TypeEvalContext): Pair<PyType?, PyType?> {
val elements = sequence.elements
val maxAnalyzedElements = MAX_ANALYZED_ELEMENTS_OF_LITERALS.coerceAtMost(elements.size)
val keyTypes = ArrayList<PyType?>()
val valueTypes = ArrayList<PyType?>()
elements
.take(maxAnalyzedElements)
.map { element -> context.getType(element) as? PyTupleType }
.forEach { tupleType ->
if (tupleType != null) {
val tupleElementTypes = tupleType.elementTypes
when {
tupleType.isHomogeneous -> {
val keyAndValueType = tupleType.iteratedItemType
keyTypes.add(keyAndValueType)
valueTypes.add(keyAndValueType)
}
tupleElementTypes.size == 2 -> {
val keyType = tupleElementTypes[0]
val valueType = tupleElementTypes[1]
keyTypes.add(keyType)
valueTypes.add(valueType)
}
else -> {
keyTypes.add(null)
valueTypes.add(null)
}
}
}
else {
keyTypes.add(null)
valueTypes.add(null)
}
}
if (elements.size > maxAnalyzedElements) {
keyTypes.add(null)
valueTypes.add(null)
}
return Pair(PyUnionType.union(keyTypes), PyUnionType.union(valueTypes))
}
private fun assemblePotentialTypedDictFields(keyType: PyType?,
valueType: PyType?,
tuple: PyExpression): Map<String, Pair<PyExpression?, PyType?>>? {
val strKeysToValueTypes = LinkedHashMap<String, Pair<PyExpression?, PyType?>>()
var allStrKeys = true
if (keyType is PyClassType && "str" == keyType.name) {
when (tuple) {
is PyKeyValueExpression -> {
if (tuple.key is PyStringLiteralExpression) {
strKeysToValueTypes[(tuple.key as PyStringLiteralExpression).stringValue] = Pair(tuple.value, valueType)
}
}
is PyTupleExpression -> {
val tupleElements = tuple.elements
if (tupleElements.size > 1 && tupleElements[0] is PyStringLiteralExpression) {
strKeysToValueTypes[(tupleElements[0] as PyStringLiteralExpression).stringValue] = Pair(tupleElements[1], valueType)
}
}
}
}
else {
allStrKeys = false
}
return if (allStrKeys) strKeysToValueTypes else null
}
private fun getDictElementTypesWithModifications(sequence: PySequenceExpression, context: TypeEvalContext): List<PyType?> {
var keyType: PyType?
var valueType: PyType?
val elementTypes = getDictLiteralElementTypes(sequence, context)
keyType = elementTypes.first
valueType = elementTypes.second
val elements = sequence.elements
val typesByModifications = getCollectionTypeByModifications(sequence, context)
if (typesByModifications.size == 2) {
val keysByModifications = typesByModifications[0]
keyType = if (elements.isNotEmpty()) {
PyUnionType.union(keyType, keysByModifications)
}
else {
keysByModifications
}
val valuesByModifications = typesByModifications[1]
valueType = if (elements.isNotEmpty()) {
PyUnionType.union(valueType, valuesByModifications)
}
else {
valuesByModifications
}
}
return listOf(keyType, valueType)
}
private fun getTypedDictTypeByModificationsForDictConstructor(sequence: PySequenceExpression,
context: TypeEvalContext): Pair<Boolean, PyTypedDictType?> {
val target = getTargetForValueInAssignment(sequence) ?: return Pair(true, null)
val owner = ScopeUtil.getScopeOwner(target) ?: return Pair(true, null)
val visitor = PyTypedDictTypeVisitor(target, context)
owner.accept(visitor)
return Pair(visitor.hasAllStrKeys, visitor.typedDictType)
}
private fun getCollectionTypeByModifications(sequence: PySequenceExpression, context: TypeEvalContext): List<PyType?> {
val target = getTargetForValueInAssignment(sequence) ?: return emptyList()
val owner = ScopeUtil.getScopeOwner(target) ?: return emptyList()
val visitor = getVisitorForSequence(sequence, target, context) ?: return emptyList()
owner.accept(visitor)
return visitor.elementTypes
}
fun getTypedDictTypeByModificationsForDictConstructor(qualifiedName: String,
element: PsiElement,
context: TypeEvalContext): Pair<Boolean, PyTypedDictType?> {
if (qualifiedName == DICT_CONSTRUCTOR) {
val owner = ScopeUtil.getScopeOwner(element)
if (owner != null) {
val visitor = PyTypedDictTypeVisitor(element, context)
owner.accept(visitor)
return Pair(visitor.hasAllStrKeys, visitor.typedDictType)
}
}
return Pair(true, null)
}
fun getCollectionTypeByModifications(qualifiedName: String, element: PsiElement, context: TypeEvalContext): List<PyType?> {
val owner = ScopeUtil.getScopeOwner(element)
if (owner != null) {
val typeVisitor = getVisitorForQualifiedName(qualifiedName, element, context)
if (typeVisitor != null) {
owner.accept(typeVisitor)
return typeVisitor.elementTypes
}
}
return emptyList()
}
private fun getVisitorForSequence(sequence: PySequenceExpression,
element: PsiElement,
context: TypeEvalContext): PyCollectionTypeVisitor? {
return when (sequence) {
is PyListLiteralExpression -> PyListTypeVisitor(element, context)
is PyDictLiteralExpression -> PyDictTypeVisitor(element, context)
is PySetLiteralExpression -> PySetTypeVisitor(element, context)
else -> null
}
}
private fun getVisitorForQualifiedName(qualifiedName: String, element: PsiElement, context: TypeEvalContext): PyCollectionTypeVisitor? {
return when (qualifiedName) {
LIST_CONSTRUCTOR, RANGE_CONSTRUCTOR -> PyListTypeVisitor(element, context)
DICT_CONSTRUCTOR -> PyDictTypeVisitor(element, context)
SET_CONSTRUCTOR -> PySetTypeVisitor(element, context)
else -> null
}
}
fun getTargetForValueInAssignment(value: PyExpression): PyExpression? {
val assignmentStatement = PsiTreeUtil.getParentOfType(value, PyAssignmentStatement::class.java, true, ScopeOwner::class.java)
assignmentStatement?.targetsToValuesMapping?.filter { it.second === value }?.forEach { return it.first }
return null
}
private fun getTypeForArgument(arguments: Array<PyExpression>, argumentIndex: Int, typeEvalContext: TypeEvalContext): PyType? {
return if (argumentIndex < arguments.size)
typeEvalContext.getType(arguments[argumentIndex])
else
null
}
private fun getTypeByModifications(node: PyCallExpression,
modificationMethods: Map<String, (Array<PyExpression>) -> List<PyType?>>,
element: PsiElement,
typeEvalContext: TypeEvalContext): MutableList<PyType?>? {
val valueTypes = mutableListOf<PyType?>()
var isModificationExist = false
val qualifiedExpression = node.callee as? PyQualifiedExpression ?: return null
val funcName = qualifiedExpression.referencedName
if (modificationMethods.containsKey(funcName)) {
val referenceOwner = qualifiedExpression.qualifier as? PyReferenceOwner ?: return null
val resolveContext = PyResolveContext.defaultContext(typeEvalContext)
if (referenceOwner.getReference(resolveContext).isReferenceTo(element)) {
isModificationExist = true
val function = modificationMethods[funcName]
if (function != null) {
valueTypes.addAll(function(node.arguments))
}
}
}
return if (isModificationExist) valueTypes else null
}
private fun getRightValue(node: PySubscriptionExpression): PyExpression? {
var parent = node.parent
var tupleParent: PyTupleExpression? = null
if (parent is PyTupleExpression) {
tupleParent = parent
parent = tupleParent.parent
}
if (parent is PyAssignmentStatement) {
val assignment = parent
val leftExpression = assignment.leftHandSideExpression
if (tupleParent == null) {
if (leftExpression !== node) return null
}
else {
if (leftExpression !== tupleParent || !ArrayUtil.contains(node, *tupleParent.elements)) {
return null
}
}
var rightValue = assignment.assignedValue
if (tupleParent != null && rightValue is PyTupleExpression) {
val rightTuple = rightValue as PyTupleExpression?
val rightElements = rightTuple!!.elements
val indexInAssignment = tupleParent.elements.indexOf(node)
if (indexInAssignment < rightElements.size) {
rightValue = rightElements[indexInAssignment]
}
}
return rightValue
}
return null
}
private fun getTypedDictTypeByModificationsForDictConstructor(node: PySubscriptionExpression,
element: PsiElement,
typeEvalContext: TypeEvalContext): PyTypedDictType? {
var allStrKeys = true
val keysToValueTypes = LinkedHashMap<String, Pair<PyExpression?, PyType?>>()
val rightValue = getRightValue(node)
if (rightValue != null) {
val rightValueType = typeEvalContext.getType(rightValue)
val indexExpression = node.indexExpression
if (indexExpression is PyStringLiteralExpression) {
keysToValueTypes[indexExpression.stringValue] = Pair(rightValue, rightValueType)
}
else {
allStrKeys = false
}
}
return if (allStrKeys) PyTypedDictType.createFromKeysToValueTypes(element, keysToValueTypes) else null
}
private fun getTypeByModifications(node: PySubscriptionExpression,
element: PsiElement,
typeEvalContext: TypeEvalContext): Pair<List<PyType?>, List<PyType?>>? {
var parent = node.parent
val keyTypes = ArrayList<PyType?>()
val valueTypes = ArrayList<PyType?>()
var isModificationExist = false
var tupleParent: PyTupleExpression? = null
if (parent is PyTupleExpression) {
tupleParent = parent
parent = tupleParent.parent
}
if (parent is PyAssignmentStatement) {
val assignment = parent
val leftExpression = assignment.leftHandSideExpression
if (tupleParent == null) {
if (leftExpression !== node) return null
}
else {
if (leftExpression !== tupleParent || !ArrayUtil.contains(node, *tupleParent.elements)) {
return null
}
}
val resolveContext = PyResolveContext.defaultContext(typeEvalContext)
val referenceOwner = node.operand as? PyReferenceOwner ?: return null
val reference = referenceOwner.getReference(resolveContext)
isModificationExist = if (reference.isReferenceTo(element)) true else return null
val indexExpression = node.indexExpression
if (indexExpression != null) {
keyTypes.add(typeEvalContext.getType(indexExpression))
}
val rightValue = getRightValue(node)
if (rightValue != null) {
val rightValueType = typeEvalContext.getType(rightValue)
valueTypes.add(rightValueType)
}
}
return if (isModificationExist) Pair(keyTypes, valueTypes) else null
}
private abstract class PyCollectionTypeVisitor(protected val myElement: PsiElement,
protected val myTypeEvalContext: TypeEvalContext) : PyRecursiveElementVisitor() {
protected val scopeOwner: ScopeOwner? = ScopeUtil.getScopeOwner(myElement)
protected open var isModificationExist = false
open val typedDictType: PyTypedDictType? = null
abstract val elementTypes: List<PyType?>
abstract fun initMethods(): Map<String, (Array<PyExpression>) -> List<PyType?>>
override fun visitPyFunction(node: PyFunction) {
if (node === scopeOwner) {
super.visitPyFunction(node)
}
// ignore nested functions
}
override fun visitPyClass(node: PyClass) {
if (node === scopeOwner) {
super.visitPyClass(node)
}
// ignore nested classes
}
}
private class PyListTypeVisitor(element: PsiElement,
typeEvalContext: TypeEvalContext) : PyCollectionTypeVisitor(element, typeEvalContext) {
private val modificationMethods: Map<String, (Array<PyExpression>) -> List<PyType?>>
private val valueTypes: MutableList<PyType?>
override var isModificationExist = false
override val elementTypes: List<PyType?>
get() = if (isModificationExist) valueTypes else emptyList()
init {
modificationMethods = initMethods()
valueTypes = mutableListOf()
}
override fun initMethods(): Map<String, (Array<PyExpression>) -> List<PyType?>> {
val modificationMethods = HashMap<String, (Array<PyExpression>) -> List<PyType?>>()
modificationMethods["append"] = { listOf(getTypeForArgument(it, 0, myTypeEvalContext)) }
modificationMethods["index"] = { listOf(getTypeForArgument(it, 0, myTypeEvalContext)) }
modificationMethods["insert"] = { listOf(getTypeForArgument(it, 1, myTypeEvalContext)) }
modificationMethods["extend"] = {
val argType = getTypeForArgument(it, 0, myTypeEvalContext)
if (argType is PyCollectionType) {
argType.elementTypes
}
else {
emptyList()
}
}
return modificationMethods
}
override fun visitPyCallExpression(node: PyCallExpression) {
val types = getTypeByModifications(node, modificationMethods, myElement, myTypeEvalContext)
if (types != null) {
isModificationExist = true
valueTypes.addAll(types)
}
}
override fun visitPySubscriptionExpression(node: PySubscriptionExpression) {
val types = getTypeByModifications(node, myElement, myTypeEvalContext)
if (types != null) {
isModificationExist = true
valueTypes.addAll(types.second)
}
}
}
private class PyDictTypeVisitor(element: PsiElement,
typeEvalContext: TypeEvalContext) : PyCollectionTypeVisitor(element, typeEvalContext) {
private val modificationMethods: Map<String, (Array<PyExpression>) -> List<PyType?>>
private val keyTypes: MutableList<PyType?>
private val valueTypes: MutableList<PyType?>
override val elementTypes: List<PyType?>
get() = if (isModificationExist) {
listOf(PyUnionType.union(keyTypes), PyUnionType.union(valueTypes))
}
else emptyList()
init {
modificationMethods = initMethods()
keyTypes = mutableListOf()
valueTypes = mutableListOf()
}
override fun initMethods(): Map<String, (Array<PyExpression>) -> List<PyType?>> {
val modificationMethods = HashMap<String, (Array<PyExpression>) -> List<PyType?>>()
modificationMethods["update"] = { arguments ->
if (arguments.size == 1 && arguments[0] is PyDictLiteralExpression) {
val dict = arguments[0] as PyDictLiteralExpression
val dictTypes = getDictLiteralElementTypes(dict, myTypeEvalContext)
keyTypes.add(dictTypes.first)
valueTypes.add(dictTypes.second)
}
else if (arguments.isNotEmpty()) {
var keyStrAdded = false
for (arg in arguments) {
if (arg is PyKeywordArgument) {
if (!keyStrAdded) {
val strType = PyBuiltinCache.getInstance(myElement).strType
if (strType != null) {
keyTypes.add(strType)
}
keyStrAdded = true
}
val value = PyUtil.peelArgument(arg)
if (value != null) {
val valueType = myTypeEvalContext.getType(value)
valueTypes.add(valueType)
}
}
}
}
emptyList()
}
return modificationMethods
}
override fun visitPyCallExpression(node: PyCallExpression) {
val types = getTypeByModifications(node, modificationMethods, myElement, myTypeEvalContext)
if (types != null) {
isModificationExist = true
valueTypes.addAll(types)
}
}
override fun visitPySubscriptionExpression(node: PySubscriptionExpression) {
val types = getTypeByModifications(node, myElement, myTypeEvalContext)
if (types != null) {
isModificationExist = true
keyTypes.addAll(types.first)
valueTypes.addAll(types.second)
}
}
}
private class PyTypedDictTypeVisitor(element: PsiElement,
typeEvalContext: TypeEvalContext) : PyCollectionTypeVisitor(element, typeEvalContext) {
private val modificationMethods: Map<String, (Array<PyExpression>) -> List<PyType?>>
var hasAllStrKeys = true
private val strKeysToValueTypes = LinkedHashMap<String, Pair<PyExpression?, PyType?>>()
override val typedDictType: PyTypedDictType?
get() = if (isModificationExist && hasAllStrKeys) PyTypedDictType.createFromKeysToValueTypes(myElement, strKeysToValueTypes)
else null
override val elementTypes: List<PyType?>
get() = if (isModificationExist && hasAllStrKeys)
PyTypedDictType.createFromKeysToValueTypes(myElement, strKeysToValueTypes)?.elementTypes ?: emptyList()
else emptyList()
init {
modificationMethods = initMethods()
}
override fun initMethods(): Map<String, (Array<PyExpression>) -> List<PyType?>> {
val modificationMethods = HashMap<String, (Array<PyExpression>) -> List<PyType?>>()
modificationMethods["update"] = { arguments ->
if (arguments.size == 1 && arguments[0] is PyDictLiteralExpression) {
val dict = arguments[0] as PyDictLiteralExpression
val typedDictType = getTypedDictTypeFromDictLiteral(dict, myTypeEvalContext)
if (typedDictType != null) {
val dictTypeElementTypes = typedDictType.elementTypes
if (dictTypeElementTypes.size == 2) {
strKeysToValueTypes.putAll(typedDictType.getKeysToValuesWithTypes())
}
}
hasAllStrKeys = false
}
else if (arguments.isNotEmpty()) {
for (arg in arguments) {
if (arg is PyKeywordArgument) {
val value = PyUtil.peelArgument(arg)
if (value != null) {
val valueType = myTypeEvalContext.getType(value)
val keyword = arg.keyword
if (keyword != null) {
strKeysToValueTypes[keyword] = Pair(value, if (strKeysToValueTypes.containsKey(keyword))
PyUnionType.union(strKeysToValueTypes[keyword]?.second, valueType)
else valueType)
}
}
}
}
}
emptyList()
}
return modificationMethods
}
override fun visitPyCallExpression(node: PyCallExpression) {
val types = getTypeByModifications(node, modificationMethods, myElement, myTypeEvalContext)
if (types != null) {
isModificationExist = true
}
}
override fun visitPySubscriptionExpression(node: PySubscriptionExpression) {
val typedDictType = getTypedDictTypeByModificationsForDictConstructor(node, myElement, myTypeEvalContext)
if (typedDictType != null) {
isModificationExist = true
strKeysToValueTypes.putAll(typedDictType.getKeysToValuesWithTypes())
}
else {
hasAllStrKeys = false
}
}
}
private class PySetTypeVisitor(element: PsiElement,
typeEvalContext: TypeEvalContext) : PyCollectionTypeVisitor(element, typeEvalContext) {
private val modificationMethods: Map<String, (Array<PyExpression>) -> List<PyType?>>
private val valueTypes: MutableList<PyType?>
override val elementTypes: List<PyType?>
get() = if (isModificationExist) valueTypes else emptyList()
init {
modificationMethods = initMethods()
valueTypes = ArrayList()
}
override fun initMethods(): Map<String, (Array<PyExpression>) -> List<PyType?>> {
val modificationMethods = HashMap<String, (Array<PyExpression>) -> List<PyType?>>()
modificationMethods["add"] = { listOf(getTypeForArgument(it, 0, myTypeEvalContext)) }
modificationMethods["update"] = { arguments ->
val types = ArrayList<PyType?>()
for (argument in arguments) {
when (argument) {
is PySetLiteralExpression ->
types.add(getListOrSetIteratedValueType(argument as PySequenceExpression, myTypeEvalContext, false))
is PyListLiteralExpression ->
types.add(getListOrSetIteratedValueType(argument as PySequenceExpression, myTypeEvalContext, false))
is PyDictLiteralExpression ->
types.add(getDictElementTypes(argument as PySequenceExpression, myTypeEvalContext).first)
else -> {
val argType = myTypeEvalContext.getType(argument)
if (argType is PyCollectionType) {
types.addAll(argType.elementTypes)
}
else {
types.add(argType)
}
}
}
}
types
}
return modificationMethods
}
override fun visitPyCallExpression(node: PyCallExpression) {
val types = getTypeByModifications(node, modificationMethods, myElement, myTypeEvalContext)
if (types != null) {
isModificationExist = true
valueTypes.addAll(types)
}
}
}
}
| apache-2.0 | e6c5d641c6effa820214ddd71b7a217b | 37.465211 | 140 | 0.656358 | 5.024056 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/index/ui/GitStageUiSettings.kt | 4 | 1408 | // 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 git4idea.index.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.util.EventDispatcher
import java.util.*
interface GitStageUiSettings {
fun ignoredFilesShown(): Boolean
fun setIgnoredFilesShown(value: Boolean)
fun addListener(listener: GitStageUiSettingsListener, disposable: Disposable)
}
interface GitStageUiSettingsListener: EventListener {
fun settingsChanged()
}
@State(name = "Git.Stage.Ui.Settings", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)])
class GitStageUiSettingsImpl(val project: Project) : SimplePersistentStateComponent<GitStageUiSettingsImpl.State>(State()), GitStageUiSettings {
private val eventDispatcher = EventDispatcher.create(GitStageUiSettingsListener::class.java)
override fun ignoredFilesShown(): Boolean = state.ignoredFilesShown
override fun setIgnoredFilesShown(value: Boolean) {
state.ignoredFilesShown = value
eventDispatcher.multicaster.settingsChanged()
}
override fun addListener(listener: GitStageUiSettingsListener, disposable: Disposable) {
eventDispatcher.addListener(listener, disposable)
}
class State : BaseState() {
var ignoredFilesShown by property(false)
}
}
| apache-2.0 | cd075b810d46b4499b19ffc33e31080d | 37.054054 | 144 | 0.801136 | 4.586319 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/LetImplementInterfaceFix.kt | 5 | 3863 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.overrideImplement.ImplementMembersHandler
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.containsStarProjections
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.isObjectLiteral
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isInterface
class LetImplementInterfaceFix(
element: KtClassOrObject,
expectedType: KotlinType,
expressionType: KotlinType
) : KotlinQuickFixAction<KtClassOrObject>(element), LowPriorityAction {
private fun KotlinType.renderShort() = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(this)
private val expectedTypeName: String
private val expectedTypeNameSourceCode: String
private val prefix: String
private val validExpectedType = with(expectedType) {
isInterface() &&
!containsStarProjections() &&
constructor !in TypeUtils.getAllSupertypes(expressionType).map(KotlinType::constructor)
}
init {
val expectedTypeNotNullable = TypeUtils.makeNotNullable(expectedType)
expectedTypeName = expectedTypeNotNullable.renderShort()
expectedTypeNameSourceCode = IdeDescriptorRenderers.SOURCE_CODE.renderType(expectedTypeNotNullable)
val verb = if (expressionType.isInterface()) KotlinBundle.message("text.extend") else KotlinBundle.message("text.implement")
val typeDescription = if (element.isObjectLiteral())
KotlinBundle.message("the.anonymous.object")
else
"'${expressionType.renderShort()}'"
prefix = KotlinBundle.message("let.0.1", typeDescription, verb)
}
override fun getFamilyName() = KotlinBundle.message("let.type.implement.interface")
override fun getText() = KotlinBundle.message("0.interface.1", prefix, expectedTypeName)
override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = validExpectedType
override fun startInWriteAction() = false
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val point = element.createSmartPointer()
val superTypeEntry = KtPsiFactory(element).createSuperTypeEntry(expectedTypeNameSourceCode)
runWriteAction {
val entryElement = element.addSuperTypeListEntry(superTypeEntry)
ShortenReferences.DEFAULT.process(entryElement)
}
val newElement = point.element ?: return
val implementMembersHandler = ImplementMembersHandler()
if (implementMembersHandler.collectMembersToGenerate(newElement).isEmpty()) return
if (editor != null) {
editor.caretModel.moveToOffset(element.textRange.startOffset)
val containingFile = element.containingFile
FileEditorManager.getInstance(project).openFile(containingFile.virtualFile, true)
implementMembersHandler.invoke(project, editor, containingFile)
}
}
}
| apache-2.0 | 1d53859a78d6e3b12dec0ed857dad703 | 43.918605 | 158 | 0.762361 | 5.171352 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/multiModuleHighlighting/testRoot/m1/m1.kt | 13 | 1819 | package shared
import shared.<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: test">test</error>.*
private fun privateInM1() {
}
internal fun internalInM1() {
}
public fun publicInM1() {
}
fun access() {
privateInM1()
internalInM1()
publicInM1()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: privateInM1Test">privateInM1Test</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: internalInM1Test">internalInM1Test</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: publicInM1Test">publicInM1Test</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: privateInM2">privateInM2</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: internalInM2">internalInM2</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: publicInM2">publicInM2</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: privateInM2Test">privateInM2Test</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: internalInM2Test">internalInM2Test</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: publicInM2Test">publicInM2Test</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: privateInM3">privateInM3</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: internalInM3">internalInM3</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: publicInM3">publicInM3</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: privateInM3Test">privateInM3Test</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: internalInM3Test">internalInM3Test</error>()
<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: publicInM3Test">publicInM3Test</error>()
} | apache-2.0 | 081a84c9edffddf75c60b88ff36382d4 | 49.555556 | 107 | 0.763057 | 4.616751 | false | true | false | false |
kickstarter/android-oss | app/src/test/java/com/kickstarter/viewmodels/DiscoveryViewModelTest.kt | 1 | 28515 | package com.kickstarter.viewmodels
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import com.kickstarter.KSRobolectricTestCase
import com.kickstarter.R
import com.kickstarter.libs.CurrentUserType
import com.kickstarter.libs.Environment
import com.kickstarter.libs.MockCurrentUser
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.utils.EventName
import com.kickstarter.libs.utils.extensions.positionFromSort
import com.kickstarter.mock.factories.ApiExceptionFactory
import com.kickstarter.mock.factories.CategoryFactory.artCategory
import com.kickstarter.mock.factories.CategoryFactory.musicCategory
import com.kickstarter.mock.factories.InternalBuildEnvelopeFactory.newerBuildAvailable
import com.kickstarter.mock.factories.UserFactory.noRecommendations
import com.kickstarter.mock.factories.UserFactory.user
import com.kickstarter.mock.services.MockApiClient
import com.kickstarter.models.Category
import com.kickstarter.models.User
import com.kickstarter.services.DiscoveryParams
import com.kickstarter.services.apiresponses.EmailVerificationEnvelope
import com.kickstarter.services.apiresponses.ErrorEnvelope
import com.kickstarter.services.apiresponses.InternalBuildEnvelope
import com.kickstarter.ui.SharedPreferenceKey
import com.kickstarter.ui.adapters.DiscoveryPagerAdapter
import com.kickstarter.ui.adapters.data.NavigationDrawerData
import com.kickstarter.ui.viewholders.discoverydrawer.ChildFilterViewHolder
import com.kickstarter.ui.viewholders.discoverydrawer.LoggedInViewHolder
import com.kickstarter.ui.viewholders.discoverydrawer.LoggedOutViewHolder
import com.kickstarter.ui.viewholders.discoverydrawer.TopFilterViewHolder
import org.junit.Test
import org.mockito.Mockito
import rx.Observable
import rx.observers.TestSubscriber
class DiscoveryViewModelTest : KSRobolectricTestCase() {
private lateinit var vm: DiscoveryViewModel.ViewModel
private val clearPages = TestSubscriber<List<Int>>()
private val drawerIsOpen = TestSubscriber<Boolean>()
private val drawerMenuIcon = TestSubscriber<Int>()
private val expandSortTabLayout = TestSubscriber<Boolean>()
private val navigationDrawerDataEmitted = TestSubscriber<Void>()
private val position = TestSubscriber<Int>()
private val rootCategories = TestSubscriber<List<Category>>()
private val rotatedExpandSortTabLayout = TestSubscriber<Boolean>()
private val rotatedUpdatePage = TestSubscriber<Int>()
private val rotatedUpdateParams = TestSubscriber<DiscoveryParams>()
private val rotatedUpdateToolbarWithParams = TestSubscriber<DiscoveryParams>()
private val showActivityFeed = TestSubscriber<Void>()
private val showBuildCheckAlert = TestSubscriber<InternalBuildEnvelope>()
private val showCreatorDashboard = TestSubscriber<Void>()
private val showHelp = TestSubscriber<Void>()
private val showInternalTools = TestSubscriber<Void>()
private val showLoginTout = TestSubscriber<Void>()
private val showMessages = TestSubscriber<Void>()
private val showProfile = TestSubscriber<Void>()
private val showSettings = TestSubscriber<Void>()
private val updatePage = TestSubscriber<Int>()
private val updateParams = TestSubscriber<DiscoveryParams>()
private val updateToolbarWithParams = TestSubscriber<DiscoveryParams>()
private val showSuccessMessage = TestSubscriber<String>()
private val showErrorMessage = TestSubscriber<String>()
private val showNotifPermissionRequest = TestSubscriber<Void>()
private fun setUpEnvironment(environment: Environment) {
vm = DiscoveryViewModel.ViewModel(environment)
}
@Test
fun testBuildCheck() {
setUpEnvironment(environment())
val buildEnvelope = newerBuildAvailable()
vm.outputs.showBuildCheckAlert().subscribe(showBuildCheckAlert)
// Build check should not be shown.
showBuildCheckAlert.assertNoValues()
// Build check should be shown when newer build is available.
vm.inputs.newerBuildIsAvailable(buildEnvelope)
showBuildCheckAlert.assertValue(buildEnvelope)
}
@Test
fun testDrawerData() {
val currentUser = MockCurrentUser()
val env = environment().toBuilder().currentUser(currentUser).build()
setUpEnvironment(env)
vm.outputs.navigationDrawerData().compose(Transformers.ignoreValues()).subscribe(
navigationDrawerDataEmitted
)
vm.outputs.drawerIsOpen().subscribe(drawerIsOpen)
// Initialize activity.
val intent = Intent(Intent.ACTION_MAIN)
vm.intent(intent)
// Initial MAGIC page selected.
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
0
)
// Drawer data should emit. Drawer should be closed.
navigationDrawerDataEmitted.assertValueCount(1)
drawerIsOpen.assertNoValues()
segmentTrack.assertNoValues()
// Open drawer and click the top PWL filter.
vm.inputs.openDrawer(true)
vm.inputs.topFilterViewHolderRowClick(
Mockito.mock(
TopFilterViewHolder::class.java
),
NavigationDrawerData.Section.Row
.builder()
.params(DiscoveryParams.builder().staffPicks(true).build())
.build()
)
// Drawer data should emit. Drawer should open, then close upon selection.
navigationDrawerDataEmitted.assertValueCount(2)
drawerIsOpen.assertValues(true, false)
segmentTrack.assertValue(EventName.CTA_CLICKED.eventName)
// Open drawer and click a child filter.
vm.inputs.openDrawer(true)
vm.inputs.childFilterViewHolderRowClick(
Mockito.mock(
ChildFilterViewHolder::class.java
),
NavigationDrawerData.Section.Row
.builder()
.params(
DiscoveryParams
.builder()
.category(artCategory())
.build()
)
.build()
)
// Drawer data should emit. Drawer should open, then close upon selection.
navigationDrawerDataEmitted.assertValueCount(3)
drawerIsOpen.assertValues(true, false, true, false)
segmentTrack.assertValues(EventName.CTA_CLICKED.eventName, EventName.CTA_CLICKED.eventName)
}
@Test
fun testUpdateInterfaceElementsWithParams() {
setUpEnvironment(environment())
vm.outputs.updateToolbarWithParams().subscribe(updateToolbarWithParams)
vm.outputs.expandSortTabLayout().subscribe(expandSortTabLayout)
// Initialize activity.
val intent = Intent(Intent.ACTION_MAIN)
vm.intent(intent)
// Initial MAGIC page selected.
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
0
)
// Sort tab should be expanded.
expandSortTabLayout.assertValues(true, true)
// Toolbar params should be loaded with initial params.
updateToolbarWithParams.assertValues(
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build()
)
// Select POPULAR sort.
vm.inputs.sortClicked(1)
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
1
)
segmentTrack.assertValue(EventName.CTA_CLICKED.eventName)
// Sort tab should be expanded.
expandSortTabLayout.assertValues(true, true, true)
// Unchanged toolbar params should not emit.
updateToolbarWithParams.assertValues(
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build()
)
// Select ALL PROJECTS filter from drawer.
vm.inputs.topFilterViewHolderRowClick(
Mockito.mock(
TopFilterViewHolder::class.java
),
NavigationDrawerData.Section.Row.builder()
.params(DiscoveryParams.builder().sort(DiscoveryParams.Sort.POPULAR).build())
.build()
)
// Sort tab should be expanded.
expandSortTabLayout.assertValues(true, true, true, true, true)
segmentTrack.assertValues(EventName.CTA_CLICKED.eventName, EventName.CTA_CLICKED.eventName)
// Select ART category from drawer.
vm.inputs.childFilterViewHolderRowClick(
Mockito.mock(
ChildFilterViewHolder::class.java
),
NavigationDrawerData.Section.Row.builder()
.params(
DiscoveryParams.builder().category(artCategory())
.sort(DiscoveryParams.Sort.POPULAR).build()
)
.build()
)
// Sort tab should be expanded.
expandSortTabLayout.assertValues(true, true, true, true, true, true, true)
segmentTrack.assertValues(
EventName.CTA_CLICKED.eventName,
EventName.CTA_CLICKED.eventName,
EventName.CTA_CLICKED.eventName
)
// Simulate rotating the device and hitting initial getInputs() again.
vm.outputs.updateToolbarWithParams().subscribe(rotatedUpdateToolbarWithParams)
vm.outputs.expandSortTabLayout().subscribe(rotatedExpandSortTabLayout)
// Simulate recreating and setting POPULAR fragment, the previous position before rotation.
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
1
)
// Sort tab and toolbar params should emit again with same params.
rotatedExpandSortTabLayout.assertValues(true)
rotatedUpdateToolbarWithParams.assertValues(
DiscoveryParams.builder().category(artCategory()).sort(DiscoveryParams.Sort.POPULAR)
.build()
)
}
@Test
fun testClickingInterfaceElements() {
setUpEnvironment(environment())
vm.outputs.showActivityFeed().subscribe(showActivityFeed)
vm.outputs.showCreatorDashboard().subscribe(showCreatorDashboard)
vm.outputs.showHelp().subscribe(showHelp)
vm.outputs.showInternalTools().subscribe(showInternalTools)
vm.outputs.showLoginTout().subscribe(showLoginTout)
vm.outputs.showMessages().subscribe(showMessages)
vm.outputs.showProfile().subscribe(showProfile)
vm.outputs.showSettings().subscribe(showSettings)
showActivityFeed.assertNoValues()
showCreatorDashboard.assertNoValues()
showHelp.assertNoValues()
showInternalTools.assertNoValues()
showLoginTout.assertNoValues()
showMessages.assertNoValues()
showProfile.assertNoValues()
showSettings.assertNoValues()
vm.inputs.loggedInViewHolderActivityClick(
Mockito.mock(
LoggedInViewHolder::class.java
)
)
vm.inputs.loggedOutViewHolderActivityClick(
Mockito.mock(
LoggedOutViewHolder::class.java
)
)
vm.inputs.loggedInViewHolderDashboardClick(
Mockito.mock(
LoggedInViewHolder::class.java
)
)
vm.inputs.loggedOutViewHolderHelpClick(
Mockito.mock(
LoggedOutViewHolder::class.java
)
)
vm.inputs.loggedInViewHolderInternalToolsClick(
Mockito.mock(
LoggedInViewHolder::class.java
)
)
vm.inputs.loggedOutViewHolderLoginToutClick(
Mockito.mock(
LoggedOutViewHolder::class.java
)
)
vm.inputs.loggedInViewHolderMessagesClick(
Mockito.mock(
LoggedInViewHolder::class.java
)
)
vm.inputs.loggedInViewHolderProfileClick(
Mockito.mock(
LoggedInViewHolder::class.java
),
user()
)
vm.inputs.loggedInViewHolderSettingsClick(
Mockito.mock(
LoggedInViewHolder::class.java
),
user()
)
showActivityFeed.assertValueCount(2)
showCreatorDashboard.assertValueCount(1)
showHelp.assertValueCount(1)
showInternalTools.assertValueCount(1)
showLoginTout.assertValueCount(1)
showMessages.assertValueCount(1)
showProfile.assertValueCount(1)
showSettings.assertValueCount(1)
}
@Test
fun testInteractionBetweenParamsAndPageAdapter() {
setUpEnvironment(environment())
vm.outputs.updateParamsForPage().subscribe(updateParams)
vm.outputs.updateParamsForPage()
.map { params: DiscoveryParams -> params.sort().positionFromSort() }
.subscribe(updatePage)
// Start initial activity.
val intent = Intent(Intent.ACTION_MAIN)
vm.intent(intent)
// Initial MAGIC page selected.
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
0
)
// Initial params should emit. Page should not be updated yet.
updateParams.assertValues(
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build(),
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build()
)
updatePage.assertValues(0, 0)
// Select POPULAR sort position.
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
1
)
// Params and page should update with new POPULAR sort values.
updateParams.assertValues(
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build(),
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build(),
DiscoveryParams.builder().sort(DiscoveryParams.Sort.POPULAR).build()
)
updatePage.assertValues(0, 0, 1)
// Select ART category from the drawer.
vm.inputs.childFilterViewHolderRowClick(
Mockito.mock(
ChildFilterViewHolder::class.java
),
NavigationDrawerData.Section.Row.builder()
.params(DiscoveryParams.builder().category(artCategory()).build())
.build()
)
// Params should update with new category; page should remain the same.
updateParams.assertValues(
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build(),
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build(),
DiscoveryParams.builder().sort(DiscoveryParams.Sort.POPULAR).build(),
DiscoveryParams.builder().sort(DiscoveryParams.Sort.POPULAR).category(artCategory())
.build(),
DiscoveryParams.builder().category(artCategory()).sort(DiscoveryParams.Sort.POPULAR)
.build()
)
updatePage.assertValues(0, 0, 1, 1, 1)
// Select MAGIC sort position.
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
0
)
// Params and page should update with new MAGIC sort value.
updateParams.assertValues(
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build(),
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build(),
DiscoveryParams.builder().sort(DiscoveryParams.Sort.POPULAR).build(),
DiscoveryParams.builder().sort(DiscoveryParams.Sort.POPULAR).category(artCategory())
.build(),
DiscoveryParams.builder().category(artCategory()).sort(DiscoveryParams.Sort.POPULAR)
.build(),
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).category(artCategory())
.build()
)
updatePage.assertValues(0, 0, 1, 1, 1, 0)
// Simulate rotating the device and hitting initial getInputs() again.
vm.outputs.updateParamsForPage().subscribe(rotatedUpdateParams)
vm.outputs.updateParamsForPage()
.map { params: DiscoveryParams -> params.sort().positionFromSort() }
.subscribe(rotatedUpdatePage)
// Should emit again with same params.
rotatedUpdateParams.assertValues(
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).category(artCategory())
.build()
)
rotatedUpdatePage.assertValues(0)
}
@Test
fun testDefaultParams_withUserLoggedOut() {
setUpDefaultParamsTest(null)
updateParams.assertValues(
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build(),
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build()
)
}
@Test
fun testDefaultParams_withUserLoggedIn_optedIn() {
setUpDefaultParamsTest(user())
updateParams.assertValues(
DiscoveryParams.builder().recommended(true).backed(-1).sort(DiscoveryParams.Sort.MAGIC)
.build(),
DiscoveryParams.builder().recommended(true).backed(-1).sort(DiscoveryParams.Sort.MAGIC)
.build()
)
}
@Test
fun testDefaultParams_withUserLoggedIn_optedOut() {
setUpDefaultParamsTest(noRecommendations())
updateParams.assertValues(
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build(),
DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).build()
)
}
@Test
fun testClearingPages() {
setUpEnvironment(environment())
vm.outputs.clearPages().subscribe(clearPages)
// Start initial activity.
val intent = Intent(Intent.ACTION_MAIN)
vm.intent(intent)
clearPages.assertNoValues()
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
1
)
clearPages.assertNoValues()
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
3
)
clearPages.assertNoValues()
// Select ART category from the drawer.
vm.inputs.childFilterViewHolderRowClick(
Mockito.mock(
ChildFilterViewHolder::class.java
),
NavigationDrawerData.Section.Row.builder()
.params(DiscoveryParams.builder().category(artCategory()).build())
.build()
)
clearPages.assertValues(listOf(0, 1, 2))
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
1
)
// Select MUSIC category from the drawer.
vm.inputs.childFilterViewHolderRowClick(
Mockito.mock(
ChildFilterViewHolder::class.java
),
NavigationDrawerData.Section.Row.builder()
.params(DiscoveryParams.builder().category(musicCategory()).build())
.build()
)
clearPages.assertValues(listOf(0, 1, 2), listOf(0, 2, 3))
}
@Test
fun testRootCategoriesEmitWithPosition() {
setUpEnvironment(environment())
vm.outputs.rootCategoriesAndPosition()
.map { cp -> cp.first }
.subscribe(rootCategories)
vm.outputs.rootCategoriesAndPosition()
.map { cp -> cp.second }
.subscribe(position)
// Start initial activity.
vm.intent(Intent(Intent.ACTION_MAIN))
// Initial MAGIC page selected.
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
0
)
// Root categories should emit for the initial MAGIC sort this.position.
rootCategories.assertValueCount(1)
position.assertValues(0)
// Select POPULAR sort position.
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
1
)
// Root categories should emit for the POPULAR sort position.
rootCategories.assertValueCount(2)
position.assertValues(0, 1)
// Select ART category from the drawer.
vm.inputs.childFilterViewHolderRowClick(
Mockito.mock(
ChildFilterViewHolder::class.java
),
NavigationDrawerData.Section.Row.builder()
.params(DiscoveryParams.builder().category(artCategory()).build())
.build()
)
// Root categories should not emit again for the same position.
rootCategories.assertValueCount(2)
position.assertValues(0, 1)
}
@Test
fun testDrawerMenuIcon_whenLoggedOut() {
setUpEnvironment(environment())
vm.outputs.drawerMenuIcon().subscribe(drawerMenuIcon)
drawerMenuIcon.assertValue(R.drawable.ic_menu)
}
@Test
fun testDrawerMenuIcon_afterLogInRefreshAndLogOut() {
val currentUser = MockCurrentUser()
setUpEnvironment(environment().toBuilder().currentUser(currentUser).build())
vm.outputs.drawerMenuIcon().subscribe(drawerMenuIcon)
drawerMenuIcon.assertValue(R.drawable.ic_menu)
currentUser.refresh(user().toBuilder().unreadMessagesCount(4).build())
drawerMenuIcon.assertValues(R.drawable.ic_menu, R.drawable.ic_menu_indicator)
currentUser.refresh(user().toBuilder().erroredBackingsCount(2).build())
drawerMenuIcon.assertValues(
R.drawable.ic_menu,
R.drawable.ic_menu_indicator,
R.drawable.ic_menu_error_indicator
)
currentUser.refresh(
user().toBuilder().unreadMessagesCount(4).unseenActivityCount(3).erroredBackingsCount(2)
.build()
)
drawerMenuIcon.assertValues(
R.drawable.ic_menu,
R.drawable.ic_menu_indicator,
R.drawable.ic_menu_error_indicator
)
currentUser.logout()
drawerMenuIcon.assertValues(
R.drawable.ic_menu, R.drawable.ic_menu_indicator, R.drawable.ic_menu_error_indicator,
R.drawable.ic_menu
)
}
@Test
fun testDrawerMenuIcon_whenUserHasNoUnreadMessagesOrUnseenActivityOrErroredBackings() {
val currentUser = MockCurrentUser(user())
setUpEnvironment(
environment()
.toBuilder()
.currentUser(currentUser)
.build()
)
vm.outputs.drawerMenuIcon().subscribe(drawerMenuIcon)
drawerMenuIcon.assertValue(R.drawable.ic_menu)
}
@Test
fun testShowSnackBar_whenIntentFromDeepLinkSuccessResponse_showSuccessMessage() {
val url = "https://*.kickstarter.com/profile/verify_email"
val intentWithUrl = Intent().setData(Uri.parse(url))
val mockApiClient: MockApiClient = object : MockApiClient() {
override fun verifyEmail(token: String): Observable<EmailVerificationEnvelope> {
return Observable.just(
EmailVerificationEnvelope.builder()
.code(200)
.message("Success")
.build()
)
}
}
val mockedClientEnvironment = environment().toBuilder()
.apiClient(mockApiClient)
.build()
setUpEnvironment(mockedClientEnvironment)
vm.outputs.showSuccessMessage().subscribe(showSuccessMessage)
vm.outputs.showErrorMessage().subscribe(showErrorMessage)
vm.intent(intentWithUrl)
showSuccessMessage.assertValue("Success")
showErrorMessage.assertNoValues()
}
@Test
fun testShowSnackBar_whenIntentFromDeepLinkSuccessResponse_showErrorMessage() {
val url = "https://*.kickstarter.com/profile/verify_email"
val intentWithUrl = Intent().setData(Uri.parse(url))
val errorEnvelope = ErrorEnvelope.builder()
.httpCode(403).errorMessages(listOf("expired")).build()
val apiException = ApiExceptionFactory.apiError(errorEnvelope)
val mockApiClient: MockApiClient = object : MockApiClient() {
override fun verifyEmail(token: String): Observable<EmailVerificationEnvelope> {
return Observable.error(apiException)
}
}
val mockedClientEnvironment = environment().toBuilder()
.apiClient(mockApiClient)
.build()
setUpEnvironment(mockedClientEnvironment)
vm.outputs.showSuccessMessage().subscribe(showSuccessMessage)
vm.outputs.showErrorMessage().subscribe(showErrorMessage)
vm.intent(intentWithUrl)
showSuccessMessage.assertNoValues()
showErrorMessage.assertValue("expired")
}
@Test
fun testIntentWithUri_whenGivenSort_shouldEmitSort() {
val url = "https://www.kickstarter.com/discover/advanced?sort=end_date"
val intentWithUrl = Intent().setData(Uri.parse(url))
setUpEnvironment(environment())
vm.outputs.updateParamsForPage().subscribe(updateParams)
vm.intent(intentWithUrl)
updateParams.assertValue(
DiscoveryParams.builder().sort(DiscoveryParams.Sort.ENDING_SOON).build()
)
}
@Test
fun testNotificationPermissionRequest_whenUserNotLoggedIn_shouldNotEmit() {
setUpEnvironment(environment())
vm.outputs.showNotifPermissionsRequest().subscribe(showNotifPermissionRequest)
showNotifPermissionRequest.assertNoValues()
}
@Test
fun testNotificationPermissionRequest_whenUserHasSeenRequest_shouldNotEmit() {
var sharedPreferences: SharedPreferences = Mockito.mock(SharedPreferences::class.java)
var user: User = user()
val currentUser: CurrentUserType = MockCurrentUser(user)
Mockito.`when`(sharedPreferences.getBoolean(SharedPreferenceKey.HAS_SEEN_NOTIF_PERMISSIONS, false)).thenReturn(true)
setUpEnvironment(
environment()
.toBuilder()
.sharedPreferences(sharedPreferences)
.currentUser(currentUser)
.build()
)
vm.outputs.showNotifPermissionsRequest().subscribe(showNotifPermissionRequest)
showNotifPermissionRequest.assertNoValues()
}
@Test
fun testNotificationPermissionRequest_whenLoggedInAndHasNotSeeRequest_shouldEmit() {
var sharedPreferences: SharedPreferences = Mockito.mock(SharedPreferences::class.java)
var user: User = user()
val currentUser: CurrentUserType = MockCurrentUser(user)
Mockito.`when`(sharedPreferences.getBoolean(SharedPreferenceKey.HAS_SEEN_NOTIF_PERMISSIONS, false)).thenReturn(false)
setUpEnvironment(
environment()
.toBuilder()
.sharedPreferences(sharedPreferences)
.currentUser(currentUser)
.build()
)
vm.outputs.showNotifPermissionsRequest().subscribe(showNotifPermissionRequest)
showNotifPermissionRequest.assertValue(null)
}
private fun setUpDefaultParamsTest(user: User?) {
val environmentBuilder = environment().toBuilder()
if (user != null) {
val currentUser = MockCurrentUser(user)
environmentBuilder.currentUser(currentUser)
}
setUpEnvironment(environmentBuilder.build())
vm.outputs.updateParamsForPage().subscribe(updateParams)
// Start initial activity.
val intent = Intent(Intent.ACTION_MAIN)
vm.intent(intent)
// Initial MAGIC page selected.
vm.inputs.discoveryPagerAdapterSetPrimaryPage(
Mockito.mock(
DiscoveryPagerAdapter::class.java
),
0
)
}
}
| apache-2.0 | b14e29c8db95bfc4e84f1789c263eb60 | 37.223861 | 125 | 0.649518 | 5.263984 | false | true | false | false |
siosio/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/text/CommentProblemFilter.kt | 1 | 3319 | package com.intellij.grazie.text
import ai.grazie.nlp.tokenizer.sentence.SRXSentenceTokenizer
import com.intellij.grazie.text.TextContent.TextDomain.COMMENTS
import com.intellij.grazie.text.TextContent.TextDomain.DOCUMENTATION
import com.intellij.grazie.utils.Text
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import com.intellij.psi.search.PsiTodoSearchHelper
internal class CommentProblemFilter : ProblemFilter() {
override fun shouldIgnore(problem: TextProblem): Boolean {
val text = problem.text
val domain = text.domain
if (domain == COMMENTS || domain == DOCUMENTATION) {
if (isTodoComment(text.commonParent.containingFile, text)) {
return true
}
if (problem.rule.globalId.endsWith("DOUBLE_PUNCTUATION") && (isNumberRange(problem, text) || isPathPart(problem, text))) {
return true
}
if (problem.rule.globalId.startsWith("LanguageTool.") && isAboutIdentifierParts(problem, text)) {
return true
}
}
if (domain == DOCUMENTATION) {
return isInFirstSentence(problem) && problem.fitsGroup(RuleGroup(RuleGroup.INCOMPLETE_SENTENCE))
}
if (domain == COMMENTS) {
if (looksLikeCode(textAround(text, problem.highlightRange))) {
return true
}
if (problem.fitsGroup(RuleGroup(RuleGroup.UNDECORATED_SENTENCE_SEPARATION))) {
return true
}
if (Text.isSingleSentence(text) && problem.fitsGroup(RuleGroup.UNDECORATED_SINGLE_SENTENCE)) {
return true
}
}
return false
}
private fun textAround(text: CharSequence, range: TextRange): CharSequence {
return text.subSequence((range.startOffset - 20).coerceAtLeast(0), (range.endOffset + 20).coerceAtMost(text.length))
}
private fun looksLikeCode(text: CharSequence): Boolean {
var codeChars = 0
var textChars = 0
for (c in text) {
if ("(){}[]<>=+-*/%|&!;,.:\"'\\@$#^".contains(c)) {
codeChars++
} else if (c.isLetterOrDigit()) {
textChars++
}
}
return codeChars > 0 && textChars / codeChars < 4
}
private fun isInFirstSentence(problem: TextProblem) =
SRXSentenceTokenizer.tokenize(problem.text.substring(0, problem.highlightRange.startOffset)).size <= 1
private fun isNumberRange(problem: TextProblem, text: TextContent): Boolean {
val range = problem.highlightRange
return range.startOffset > 0 && range.endOffset < text.length &&
text[range.startOffset - 1].isDigit() && text[range.endOffset].isDigit()
}
private fun isPathPart(problem: TextProblem, text: TextContent): Boolean {
val range = problem.highlightRange
return text.subSequence(0, range.startOffset).endsWith('/') ||
text.subSequence(range.endOffset, text.length).startsWith('/')
}
private fun isAboutIdentifierParts(problem: TextProblem, text: TextContent): Boolean {
val range = problem.highlightRange
return text.subSequence(0, range.startOffset).endsWith('_') ||
text.subSequence(range.endOffset, text.length).startsWith('_')
}
// the _todo_ word spoils the grammar of what follows
private fun isTodoComment(file: PsiFile, text: TextContent) =
PsiTodoSearchHelper.SERVICE.getInstance(file.project).findTodoItems(file).any { text.intersectsRange(it.textRange) }
} | apache-2.0 | 9fb76d6cf5144fff2fc368b83a6538af | 36.727273 | 128 | 0.697198 | 4.112763 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/nameSuggester/KotlinNameSuggesterTest.kt | 1 | 3261 | // 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.nameSuggester
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.idea.refactoring.IntroduceRefactoringException
import org.jetbrains.kotlin.idea.refactoring.selectElement
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.test.TestMetadata
import org.jetbrains.kotlin.test.TestRoot
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
@TestRoot("idea/tests")
@TestMetadata("testData/refactoring/nameSuggester")
@RunWith(JUnit38ClassRunner::class)
class KotlinNameSuggesterTest : KotlinLightCodeInsightFixtureTestCase() {
fun testArrayList() = doTest()
fun testGetterSure() = doTest()
fun testNameArrayOfClasses() = doTest()
fun testNameArrayOfStrings() = doTest()
fun testNamePrimitiveArray() = doTest()
fun testNameCallExpression() = doTest()
fun testNameClassCamelHump() = doTest()
fun testNameLong() = doTest()
fun testNameReferenceExpression() = doTest()
fun testNameReferenceExpressionForConstants() = doTest()
fun testNameString() = doTest()
fun testAnonymousObject() = doTest()
fun testAnonymousObjectWithSuper() = doTest()
fun testArrayOfObjectsType() = doTest()
fun testURL() = doTest()
fun testParameterNameByArgumentExpression() = doTest()
fun testParameterNameByParenthesizedArgumentExpression() = doTest()
fun testIdWithDigits() = doTest()
fun testIdWithNonASCII() = doTest()
fun testFunction1() = doTest()
fun testFunction2() = doTest()
fun testExtensionFunction1() = doTest()
fun testExtensionFunction2() = doTest()
fun testNoCamelNamesForBacktickedNonId() = doTest()
private fun doTest() {
try {
myFixture.configureByFile(getTestName(false) + ".kt")
val file = myFixture.file as KtFile
val expectedResultText = KotlinTestUtils.getLastCommentInFile(file)
selectElement(myFixture.editor, file, listOf(CodeInsightUtils.ElementKind.EXPRESSION)) {
val names = KotlinNameSuggester
.suggestNamesByExpressionAndType(
it as KtExpression,
null,
it.analyze(BodyResolveMode.PARTIAL),
{ true },
"value"
)
.sorted()
val result = StringUtil.join(names, "\n").trim()
assertEquals(expectedResultText, result)
}
} catch (e: IntroduceRefactoringException) {
throw AssertionError("Failed to find expression: " + e.message)
}
}
}
| apache-2.0 | 77eb4c8440ae60a0f4562933c4121d9d | 32.96875 | 158 | 0.697945 | 4.940909 | false | true | false | false |
jwren/intellij-community | platform/util-ex/src/com/intellij/util/Futures.kt | 1 | 14130 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
// 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 com.intellij.util
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.util.concurrency.AppExecutorUtil
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.*
import java.util.function.BiConsumer
import java.util.function.BiFunction
import java.util.function.Consumer
import java.util.function.Function
/**
* Provides utilities for integration of [CompletableFuture]s
* with platform concurrency API, e.g. EDT, Read/Write actions, progress manager, etc.
*
* For each method there is an idiomatic overload for Java.
*
* @see "com.intellij.collaboration.async.CompletableFutureUtil"
*/
@ApiStatus.Experimental
object Futures {
/* ------------------------------------------------------------------------------------------- */
//region Executors
/**
* Is used to specify that the action should be executed on the EDT.
*
* ```
* calcSmthAsync(params) // executed on a pooled thread
* .thenAcceptAsync(it -> showInUI(it), Futures.inEdt()) // on EDT
* ```
*/
@JvmStatic
@JvmOverloads
fun inEdt(modalityState: ModalityState? = null) = Executor { runnable -> runInEdt(modalityState) { runnable.run() } }
/**
* Is used to specify that the action should be executed on the EDT inside write action.
*
* ```
* calcSmthAsync(params) // executed on a pooled thread
* .thenAcceptAsync( // executed inside write action
* it -> writeInDocument(it),
* Futures.inWriteAction())
* ```
*/
@JvmStatic
@JvmOverloads
fun inWriteAction(modalityState: ModalityState? = null) = Executor { runnable ->
runInEdt(modalityState) {
ApplicationManager.getApplication().runWriteAction(runnable)
}
}
//endregion
/* ------------------------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------------------------- */
//region Error handling utils
/**
* Check is the exception is a cancellation signal
*/
@JvmStatic
fun isCancellation(error: Throwable): Boolean {
return error is ProcessCanceledException
|| error is CancellationException
|| error is InterruptedException
|| error.cause?.let(::isCancellation) ?: false
}
/**
* Extract actual exception from the one returned by completable future
*/
@JvmStatic
fun extractError(error: Throwable): Throwable {
return when (error) {
is CompletionException -> extractError(error.cause!!)
is ExecutionException -> extractError(error.cause!!)
else -> error
}
}
/**
* If the given future failed with exception, and it wasn't a cancellation, logs the exception to the IDEA logger.
*
* @param transformException One may want to wrap the actual exception with
* [com.intellij.openapi.diagnostic.RuntimeExceptionWithAttachments] to additionally provide some diagnostic info
*/
inline fun <T> CompletableFuture<T>.logIfFailed(
loggingClass: Class<*>,
crossinline transformException: (Throwable) -> Throwable = { it }
): CompletableFuture<T> {
return whenComplete { _, cause ->
if (cause != null && !isCancellation(cause)) {
Logger.getInstance(loggingClass).error(transformException(cause))
}
}
}
/**
* Java-specific overload for [logIfFailed]
*
* ```java
* futuresChain
* .whenComplete(Futures.logIfFailed(SomeClass.class))
* ```
* or
* ```java
* futuresChain
* .whenComplete(Futures.logIfFailed(SomeClass.class,
* it -> addAttachments(it))
* ```
*/
@JvmStatic
@JvmOverloads
inline fun logIfFailed(
loggingClass: Class<*>,
crossinline transformException: (Throwable) -> Throwable = { it }
): BiConsumer<Any?, Throwable> {
return BiConsumer { _: Any?, cause: Throwable? ->
if (cause != null && !isCancellation(cause)) {
Logger.getInstance(loggingClass).error(transformException(cause))
}
}
}
//endregion
/* ------------------------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------------------------- */
//region CompletableFuture integration with platform progress
/**
* Runs given [action] inside the [Task.Modal] and returns its result as [CompletableFuture]
*/
@JvmStatic
@JvmOverloads
fun <T> runModalProgress(
project: Project,
@NlsContexts.DialogTitle title: String,
canBeCancelled: Boolean = true,
onCancel: Runnable? = null,
action: Function<ProgressIndicator, T>
): CompletableFuture<T> {
val future = CompletableFuture<T>()
ApplicationManager.getApplication().executeOnPooledThread {
ProgressManager.getInstance().run(object : Task.Modal(project, title, canBeCancelled) {
var value: Result<T>? = null
override fun run(indicator: ProgressIndicator) {
try {
value = Result.success(action.apply(indicator))
}
catch (t: Throwable) {
value = Result.failure(t)
}
}
override fun onCancel(): Unit = onCancel?.run() ?: Unit
override fun onSuccess() = future.waitForProgressBarCloseAndComplete(value!!.getOrThrow())
override fun onThrowable(error: Throwable) = future.waitForProgressBarCloseAndCompleteExceptionally(error)
})
}
return future
}
/**
* Runs given [action] inside the [Task.Backgroundable] and returns its result as [CompletableFuture]
*/
@JvmStatic
@JvmOverloads
fun <T> runProgressInBackground(
project: Project,
@NlsContexts.ProgressTitle title: String,
canBeCancelled: Boolean = true,
performInBackgroundOption: PerformInBackgroundOption? = null,
onCancel: Runnable? = null,
action: Function<ProgressIndicator, T>
): CompletableFuture<T> {
val future = CompletableFuture<T>()
ApplicationManager.getApplication().executeOnPooledThread {
ProgressManager.getInstance().run(object : Task.Backgroundable(project, title, canBeCancelled, performInBackgroundOption) {
var value: Result<T>? = null
override fun run(indicator: ProgressIndicator) {
try {
value = Result.success(action.apply(indicator))
}
catch (t: Throwable) {
value = Result.failure(t)
}
}
override fun onCancel(): Unit = onCancel?.run() ?: Unit
override fun onSuccess() = future.waitForProgressBarCloseAndComplete(value!!.getOrThrow())
override fun onThrowable(error: Throwable) = future.waitForProgressBarCloseAndCompleteExceptionally(error)
})
}
return future
}
/**
* Runs given asynchronous [action] and waits for its result inside the [Task.Backgroundable],
* then returns the result as [CompletableFuture]
*/
@JvmStatic
@JvmOverloads
fun <T> runAsyncProgressInBackground(
project: Project,
title: @NlsContexts.ProgressTitle String,
canBeCancelled: Boolean = true,
performInBackgroundOption: PerformInBackgroundOption? = null,
onCancel: Runnable? = null,
action: Function<ProgressIndicator, CompletableFuture<T>>
): CompletableFuture<T> {
val future = CompletableFuture<T>()
ApplicationManager.getApplication().executeOnPooledThread {
ProgressManager.getInstance().run(object : Task.Backgroundable(project, title, canBeCancelled, performInBackgroundOption) {
var value: Result<T>? = null
override fun run(indicator: ProgressIndicator) {
try {
val actionFuture = action.apply(indicator)
actionFuture.join()
value = Result.success(actionFuture.get())
}
catch (t: Throwable) {
value = Result.failure(t)
}
}
override fun onCancel(): Unit = onCancel?.run() ?: Unit
override fun onSuccess() = future.waitForProgressBarCloseAndComplete(value!!.getOrThrow())
override fun onThrowable(error: Throwable) = future.waitForProgressBarCloseAndCompleteExceptionally(error)
})
}
return future
}
/**
* We need to wait until progress bar will be hidden
* what is periodically done by InfoAndProgressPanel#myUpdateQueue every 50ms
*/
private fun <T> CompletableFuture<T>.waitForProgressBarCloseAndComplete(value: T) {
completeOnTimeout(value, 55, TimeUnit.MILLISECONDS)
}
private fun CompletableFuture<*>.waitForProgressBarCloseAndCompleteExceptionally(error: Throwable) {
ApplicationManager.getApplication().invokeLater {
completeExceptionally(error)
}
}
//endregion
/* ------------------------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------------------------- */
//region CompletableFuture common integrations with application actions
@JvmStatic
@JvmOverloads
inline fun <T> runInEdtAsync(modalityState: ModalityState? = null, crossinline action: () -> T): CompletableFuture<T> {
return CompletableFuture.supplyAsync({ action() }, inEdt(modalityState))
}
@JvmStatic
@JvmOverloads
fun runInEdtAsync(modalityState: ModalityState? = null, action: Runnable): CompletableFuture<Void> {
return CompletableFuture.runAsync(action, inEdt(modalityState))
}
@JvmStatic
@JvmOverloads
inline fun <T> runWriteActionAsync(modalityState: ModalityState? = null, crossinline action: () -> T): CompletableFuture<T> {
return CompletableFuture.supplyAsync({ action() }, inWriteAction(modalityState))
}
@JvmStatic
@JvmOverloads
fun runWriteActionAsync(modalityState: ModalityState? = null, action: Runnable): CompletableFuture<Void> {
return CompletableFuture.runAsync(action, inWriteAction(modalityState))
}
@JvmStatic
inline fun <T> runInBackgroundAsync(crossinline action: () -> T): CompletableFuture<T> {
return CompletableFuture.supplyAsync({ action() }, AppExecutorUtil.getAppExecutorService())
}
@JvmStatic
fun runInBackgroundAsync(action: Runnable): CompletableFuture<Void> {
return CompletableFuture.runAsync(action, AppExecutorUtil.getAppExecutorService())
}
//endregion
/* ------------------------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------------------------- */
//region Kotlin extension which for the Readability God Sake place executor param at the first and lambda at the last place
inline fun <T, U> CompletableFuture<T>.thenApplyAsync(executor: Executor, crossinline fn: (T) -> U): CompletableFuture<U> {
return thenApplyAsync(Function { fn(it) }, executor)
}
inline fun <T> CompletableFuture<T>.thenAcceptAsync(executor: Executor, crossinline action: (T) -> Unit): CompletableFuture<Void> {
return thenAcceptAsync(Consumer { action(it) }, executor)
}
inline fun <T> CompletableFuture<T>.thenRunAsync(executor: Executor, crossinline action: () -> Unit): CompletableFuture<Void> {
return thenRunAsync(Runnable { action() }, executor)
}
inline fun <T, U, V> CompletableFuture<T>.thenCombineAsync(
executor: Executor,
other: CompletionStage<out U>,
crossinline fn: (T, U) -> V
): CompletableFuture<V> {
return thenCombineAsync(other, BiFunction { a, b -> fn(a, b) }, executor)
}
inline fun <T, U> CompletableFuture<T>.thenAcceptBothAsync(
executor: Executor,
other: CompletionStage<out U>,
crossinline action: (T, U) -> U
): CompletableFuture<Void> {
return thenAcceptBothAsync(other, BiConsumer { a, b -> action(a, b) }, executor)
}
inline fun <T> CompletableFuture<T>.runAfterBothAsync(
executor: Executor,
other: CompletionStage<*>,
crossinline action: () -> Unit
): CompletableFuture<Void> {
return runAfterBothAsync(other, Runnable { action() }, executor)
}
inline fun <T, U> CompletableFuture<T>.applyToEitherAsync(
executor: Executor,
other: CompletionStage<out T>,
crossinline fn: (T) -> U
): CompletableFuture<U> {
return applyToEitherAsync(other, Function { fn(it) }, executor)
}
inline fun <T> CompletableFuture<T>.acceptEitherAsync(
executor: Executor,
other: CompletionStage<out T>,
crossinline action: (T) -> Unit
): CompletableFuture<Void> {
return acceptEitherAsync(other, Consumer { action(it) }, executor)
}
inline fun <T> CompletableFuture<T>.runAfterEitherAsync(
executor: Executor,
other: CompletionStage<*>,
crossinline action: () -> Unit
): CompletableFuture<Void> {
return runAfterEitherAsync(other, Runnable { action() }, executor)
}
inline fun <T, U> CompletableFuture<T>.thenComposeAsync(
executor: Executor,
crossinline fn: (T) -> CompletionStage<U>
): CompletableFuture<U> {
return thenComposeAsync(Function { fn(it) }, executor)
}
inline fun <T> CompletableFuture<T>.whenCompleteAsync(
executor: Executor,
crossinline action: (T?, Throwable?) -> Unit
): CompletableFuture<T> {
return whenCompleteAsync(BiConsumer { a, b -> action(a, b) }, executor)
}
inline fun <T, U> CompletableFuture<T>.handleAsync(
executor: Executor,
crossinline fn: (T?, Throwable?) -> U,
): CompletableFuture<U> {
return handleAsync(BiFunction { a, b -> fn(a, b) }, executor)
}
//endregion
/* ------------------------------------------------------------------------------------------- */
} | apache-2.0 | a45f223fa1f707e2ba1cfbffd48e02b0 | 34.41604 | 158 | 0.643454 | 4.827468 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Util.kt | 6 | 1861 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.j2k.ast
import org.jetbrains.kotlin.j2k.CodeBuilder
fun CodeBuilder.appendWithPrefix(element: Element, prefix: String): CodeBuilder = if (!element.isEmpty) this append prefix append element else this
fun CodeBuilder.appendWithSuffix(element: Element, suffix: String): CodeBuilder = if (!element.isEmpty) this append element append suffix else this
fun CodeBuilder.appendOperand(expression: Expression, operand: Expression, parenthesisForSamePrecedence: Boolean = false): CodeBuilder {
val parentPrecedence = expression.precedence() ?: throw IllegalArgumentException("Unknown precedence for $expression")
val operandPrecedence = operand.precedence()
val needParenthesis = operandPrecedence != null &&
(parentPrecedence < operandPrecedence || parentPrecedence == operandPrecedence && parenthesisForSamePrecedence)
if (needParenthesis) append("(")
append(operand)
if (needParenthesis) append(")")
return this
}
fun Element.wrapToBlockIfRequired(): Element = when (this) {
is AssignmentExpression -> if (isMultiAssignment()) Block.of(this).assignNoPrototype() else this
else -> this
}
private fun Expression.precedence(): Int? {
return when (this) {
is QualifiedExpression, is MethodCallExpression, is ArrayAccessExpression, is PostfixExpression, is BangBangExpression, is StarExpression -> 0
is PrefixExpression -> 1
is TypeCastExpression -> 2
is BinaryExpression -> op.precedence
is RangeExpression, is UntilExpression, is DownToExpression -> 5
is IsOperator -> 8
is IfStatement -> 13
is AssignmentExpression -> 14
else -> null
}
}
| apache-2.0 | 6b68d62457adf2fb8707ccc78f0f5191 | 38.595745 | 158 | 0.734551 | 4.975936 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/AmendHrefJSCodeBuilder.kt | 1 | 778 | package alraune
import pieces100.*
import vgrechka.*
class AmendHrefJSCodeBuilder(val replaceState: Boolean = true) {
private val buf = StringBuilder()
init {
// buf.ln("window.location = alraune.amendHref(alraune.AlFrontPile.state.initialLocation, [")
buf.ln("${TS.alraune.progressyNavigate}({replaceState: $replaceState, href: alraune.amendHref(alraune.AlFrontPile.state.initialLocation, [")
}
fun raw(param: String, js: String) = this.also {
buf.ln("{name: '" + param + "', value: " + js + "},")
}
fun string(param: String, value: String) = this.also {
buf.ln("{name: '" + param + "', value: " + jsonize(value) + "},")
}
fun build(): String {
buf.ln("])})")
return buf.toString()
}
}
| apache-2.0 | 5780499cb80103acabf2e237e1c37c1d | 26.785714 | 148 | 0.606684 | 3.618605 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/accessibility.kt | 13 | 3720 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.impl
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMember
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.psi.util.parentOfType
import com.intellij.util.containers.withPrevious
import org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocComment
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass
import org.jetbrains.plugins.groovy.lang.psi.util.contexts
fun isAccessible(member: PsiMember, place: PsiElement): Boolean {
if (isInGroovyDoc(place)) {
return true
}
val modifierList = member.modifierList
if (modifierList == null) {
return true
}
return when (PsiUtil.getAccessLevel(modifierList)) {
PsiUtil.ACCESS_LEVEL_PUBLIC -> true
PsiUtil.ACCESS_LEVEL_PROTECTED -> isProtectedMemberAccessibleFrom(place, member)
PsiUtil.ACCESS_LEVEL_PACKAGE_LOCAL -> isPackageLocalMemberAccessibleFrom(place, member)
PsiUtil.ACCESS_LEVEL_PRIVATE -> isPrivateMemberAccessibleFrom(member, place)
else -> error("unexpected access level")
}
}
private fun isProtectedMemberAccessibleFrom(place: PsiElement, member: PsiMember): Boolean {
if (JavaPsiFacade.getInstance(place.project).arePackagesTheSame(member, place)) {
return true
}
val memberClass = member.containingClass ?: return false
for (contextClass in place.contexts().filterIsInstance<GrTypeDefinition>()) {
if (InheritanceUtil.isInheritorOrSelf(contextClass, memberClass, true)) {
return true
}
}
return false
}
private fun isPackageLocalMemberAccessibleFrom(place: PsiElement, member: PsiMember): Boolean {
val facade = JavaPsiFacade.getInstance(place.project)
if (!facade.arePackagesTheSame(member, place)) {
return false
}
val memberClass: PsiClass = member.containingClass ?: return true
val placeClass: GrTypeDefinition = getContextClass(place) ?: return true
val placeSuperClass: PsiClass = placeClass.superClass ?: return true
if (!placeSuperClass.isInheritor(memberClass, true)) {
return true
}
for (superClass in generateSequence(placeSuperClass, PsiClass::getSuperClass)) {
if (superClass == memberClass) {
return true
}
if (!facade.arePackagesTheSame(superClass, memberClass)) {
return false
}
}
return false
}
private fun isPrivateMemberAccessibleFrom(member: PsiMember, place: PsiElement): Boolean {
val memberClass: GrTypeDefinition = member.containingClass as? GrTypeDefinition ?: return false
if (memberClass is GroovyScriptClass) {
for ((context, previousContext) in place.contexts().withPrevious()) {
if (context is GroovyFile && previousContext !is GrTypeDefinition) {
return context.scriptClass == memberClass
}
}
return false
}
else {
val memberTopLevelClass: GrTypeDefinition? = memberClass.contexts().filterIsInstance<GrTypeDefinition>().lastOrNull()
val placeTopLevelClass: GrTypeDefinition? = place.contexts().filterIsInstance<GrTypeDefinition>().lastOrNull()
return placeTopLevelClass == memberTopLevelClass
}
}
private fun isInGroovyDoc(place: PsiElement): Boolean = place.parentOfType<GrDocComment>() != null
private fun getContextClass(place: PsiElement): GrTypeDefinition? {
return place.contexts().filterIsInstance<GrTypeDefinition>().firstOrNull()
}
| apache-2.0 | cdea58e14e226812200ec2d2c269dfdc | 39.879121 | 140 | 0.769355 | 4.509091 | false | false | false | false |
androidx/androidx | development/importMaven/src/main/kotlin/androidx/build/importMaven/LocalMavenRepoDownloader.kt | 3 | 9279 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.build.importMaven
import okio.FileSystem
import okio.Path
import org.apache.logging.log4j.kotlin.logger
import org.jetbrains.kotlin.com.google.common.annotations.VisibleForTesting
import java.security.MessageDigest
import java.util.Locale
/**
* A [DownloadObserver] that will save all files into the given repository folders.
*/
class LocalMavenRepoDownloader(
val fileSystem: FileSystem,
/**
* Path to the internal repo (e.g. prebuilts/androidx/internal)
*/
val internalFolder: Path,
/**
* Path to the external repo (e.g. prebuilts/androidx/external)
*/
val externalFolder: Path,
) : DownloadObserver {
private val logger = logger("LocalMavenRepoDownloader")
private val licenseDownloader = LicenseDownloader(enableGithubApi = false)
private val writtenFiles = mutableSetOf<Path>()
/**
* Returns the list of files we've downloaded.
*/
fun getDownloadedFiles() = writtenFiles.sorted().distinct()
override fun onDownload(path: String, bytes: ByteArray) {
if (path.substringAfterLast('.') in checksumExtensions) {
// we sign files locally, don't download them
logger.trace {
"Skipping $path because we'll sign it locally"
}
return
}
val internal = isInternalArtifact(path)
val folder = if (internal) internalFolder else externalFolder
logger.trace {
"Downloading $path. internal? $internal"
}
folder.resolve(path).let { file ->
val targetFolder = file.parent ?: error("invalid parent for $file")
if (file.name.endsWith(".pom")) {
// Keep original MD5 and SHA1 hashes
copyWithDigest(targetFolder, fileName = file.name, bytes = bytes)
if (internal) {
val transformed = transformInternalPomFile(bytes)
copyWithoutDigest(targetFolder, fileName = file.name, bytes = transformed)
} else {
// download licenses only for external poms
licenseDownloader.fetchLicenseFromPom(bytes)?.let { licenseBytes ->
copyWithoutDigest(targetFolder, "LICENSE", licenseBytes)
}
}
} else {
copyWithDigest(
targetFolder = targetFolder,
fileName = file.name,
bytes = bytes
)
}
}
}
/**
* Creates the file in the given [targetFolder]/[fileName] pair.
*/
private fun copyWithoutDigest(
targetFolder: Path,
fileName: String,
bytes: ByteArray
) {
fileSystem.writeBytes(targetFolder / fileName, bytes)
}
/**
* Creates the file in the given [targetFolder]/[fileName] pair and also creates the md5 and
* sha1 checksums.
*/
private fun copyWithDigest(
targetFolder: Path,
fileName: String,
bytes: ByteArray
) {
copyWithoutDigest(targetFolder, fileName, bytes)
if (fileName.substringAfterLast('.') !in checksumExtensions) {
digest(bytes, fileName, "MD5").let { (name, contents) ->
fileSystem.writeBytes(targetFolder / name, contents)
}
digest(bytes, fileName, "SHA1").let { (name, contents) ->
fileSystem.writeBytes(targetFolder / name, contents)
}
}
}
private fun FileSystem.writeBytes(
file: Path,
contents: ByteArray
) {
writtenFiles.add(file.normalized())
file.parent?.let(fileSystem::createDirectories)
write(
file = file,
mustCreate = false
) {
write(contents)
}
logger.info {
"Saved ${file.normalized()} (${contents.size} bytes)"
}
}
/**
* Certain prebuilts might have improper downloads.
* This method traverses all folders into which we've fetched an artifact and deletes files
* that are not fetched by us.
*
* Note that, sometimes we might pull a pom file but not download its artifacts (if there is a
* newer version). So before cleaning any file, we make sure we fetched one of
* [EXTENSIONS_FOR_CLENAUP].
*
* This should be used only if the local repositories are disabled in resolution. Otherwise, it
* might delete files that were resolved from the local repository.
*/
fun cleanupLocalRepositories() {
val folders = writtenFiles.filter {
val isDirectory = fileSystem.metadata(it).isDirectory
!isDirectory && it.name.substringAfterLast(".") in EXTENSIONS_FOR_CLENAUP
}.mapNotNull {
it.parent
}.distinct()
logger.info {
"Cleaning up local repository. Folders to clean: ${folders.size}"
}
// traverse all folders and make sure they are in the written files list
folders.forEachIndexed { index, folder ->
logger.trace {
"Cleaning up $folder ($index of ${folders.size})"
}
fileSystem.list(folder).forEach { candidateToDelete ->
if (!writtenFiles.contains(candidateToDelete.normalized())) {
logger.trace {
"Deleting $candidateToDelete since it is not re-downloaded"
}
fileSystem.delete(candidateToDelete)
} else {
logger.trace {
"Keeping $candidateToDelete"
}
}
}
}
}
/**
* Transforms POM files so we automatically comment out nodes with <type>aar</type>.
*
* We are doing this for all internal libraries to account for -Pandroidx.useMaxDepVersions
* which swaps out the dependencies of all androidx libraries with their respective ToT
* versions. For more information look at b/127495641.
*
* Instead of parsing the dom and re-writing it, we use a simple string replace to keep the file
* contents intact.
*/
private fun transformInternalPomFile(bytes: ByteArray): ByteArray {
// using a simple line match rather than xml parsing because we want to keep file same as
// much as possible
return bytes.toString(Charsets.UTF_8).lineSequence().map {
it.replace("<type>aar</type>", "<!--<type>aar</type>-->")
}.joinToString("\n").toByteArray(Charsets.UTF_8)
}
companion object {
val checksumExtensions = listOf("md5", "sha1")
/**
* If we downloaded an artifact with one of these extensions, we can cleanup that folder
* for files that are not re-downloaded.
*/
private val EXTENSIONS_FOR_CLENAUP = listOf(
"jar",
"aar",
"klib"
)
private val INTERNAL_ARTIFACT_PREFIXES = listOf(
"android/arch",
"com/android/support",
"androidx"
)
// Need to exclude androidx.databinding
private val FORCE_EXTERNAL_PREFIXES = setOf(
"androidx/databinding"
)
/**
* Checks if an artifact is *internal*.
*/
fun isInternalArtifact(path: String): Boolean {
if (FORCE_EXTERNAL_PREFIXES.any {
path.startsWith(it)
}) {
return false
}
return INTERNAL_ARTIFACT_PREFIXES.any {
path.startsWith(it)
}
}
/**
* Creates digest for the given contents.
*
* @param contents file contents
* @param fileName original file name
* @param algorithm Algorithm to use
*
* @return a pair if <new file name> : <digest bytes>
*/
@VisibleForTesting
internal fun digest(
contents: ByteArray,
fileName: String,
algorithm: String
): Pair<String, ByteArray> {
val messageDigest = MessageDigest.getInstance(algorithm)
val digestBytes = messageDigest.digest(contents)
val builder = StringBuilder()
for (byte in digestBytes) {
builder.append(String.format("%02x", byte))
}
val signatureFileName = "$fileName.${algorithm.lowercase(Locale.US)}"
val resultBytes = builder.toString().toByteArray(Charsets.UTF_8)
return signatureFileName to resultBytes
}
}
} | apache-2.0 | 527f921a341246b05688cd4b6c76da73 | 34.968992 | 100 | 0.588318 | 4.9488 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/font/FontSynthesisTest.kt | 3 | 5799 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.font
import android.graphics.Typeface
import android.os.Build
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.text.FontTestData
import androidx.compose.ui.text.UncachedFontFamilyResolver
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.google.common.truth.Truth
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
@OptIn(ExperimentalTextApi::class)
class FontSynthesisTest {
private val context = InstrumentationRegistry.getInstrumentation().context
private val resolver = UncachedFontFamilyResolver(context)
private fun loadFont(font: Font): Pair<Font, Typeface> {
return font to resolver.resolve(
font.toFontFamily(),
font.weight,
font.style,
fontSynthesis = FontSynthesis.None
).value as Typeface
}
@Test
fun fontSynthesisDefault_synthesizeTheFontToItalicBold() {
val (font, typeface) = loadFont(FontTestData.FONT_100_REGULAR)
val synthesized = FontSynthesis.All.synthesizeTypeface(
typeface,
font,
FontWeight.Bold,
FontStyle.Italic
) as Typeface
// since 100 regular is not bold and not italic, passing FontWeight.bold and
// FontStyle.Italic should create a Typeface that is fake bold and fake Italic
Truth.assertThat(synthesized.isBold).isTrue()
Truth.assertThat(synthesized.isItalic).isTrue()
}
@Test
fun fontSynthesisStyle_synthesizeTheFontToItalic() {
val (font, typeface) = loadFont(FontTestData.FONT_100_REGULAR)
val synthesized = FontSynthesis.Style.synthesizeTypeface(
typeface,
font,
FontWeight.Bold,
FontStyle.Italic
) as Typeface
// since 100 regular is not bold and not italic, passing FontWeight.bold and
// FontStyle.Italic should create a Typeface that is only fake Italic
Truth.assertThat(synthesized.isBold).isFalse()
Truth.assertThat(synthesized.isItalic).isTrue()
}
@Test
fun fontSynthesisWeight_synthesizeTheFontToBold() {
val (font, typeface) = loadFont(FontTestData.FONT_100_REGULAR)
val synthesized = FontSynthesis.Weight.synthesizeTypeface(
typeface,
font,
FontWeight.Bold,
FontStyle.Italic
) as Typeface
// since 100 regular is not bold and not italic, passing FontWeight.bold and
// FontStyle.Italic should create a Typeface that is only fake bold
Truth.assertThat(synthesized.isBold).isTrue()
Truth.assertThat(synthesized.isItalic).isFalse()
}
@Test
fun fontSynthesisStyle_forMatchingItalicDoesNotSynthesize() {
val (font, typeface) = loadFont(FontTestData.FONT_100_ITALIC)
val synthesized = FontSynthesis.Style.synthesizeTypeface(
typeface,
font,
FontWeight.W700,
FontStyle.Italic
) as Typeface
Truth.assertThat(synthesized.isBold).isFalse()
Truth.assertThat(synthesized.isItalic).isFalse()
}
@Test
fun fontSynthesisAll_doesNotSynthesizeIfFontIsTheSame_beforeApi28() {
val (font, loaded) = loadFont(FontTestData.FONT_700_ITALIC)
val typeface = FontSynthesis.All.synthesizeTypeface(
loaded,
font,
FontWeight.W700,
FontStyle.Italic
) as Typeface
Truth.assertThat(typeface.isItalic).isFalse()
if (Build.VERSION.SDK_INT < 23) {
Truth.assertThat(typeface.isBold).isFalse()
} else if (Build.VERSION.SDK_INT < 28) {
Truth.assertThat(typeface.isBold).isTrue()
} else {
Truth.assertThat(typeface.isBold).isTrue()
Truth.assertThat(typeface.weight).isEqualTo(700)
}
}
@Test
fun fontSynthesisNone_doesNotSynthesize() {
val (font, loaded) = loadFont(FontTestData.FONT_100_REGULAR)
val typeface = FontSynthesis.None.synthesizeTypeface(
loaded,
font,
FontWeight.Bold,
FontStyle.Italic
) as Typeface
Truth.assertThat(typeface.isBold).isFalse()
Truth.assertThat(typeface.isItalic).isFalse()
}
@Test
fun fontSynthesisWeight_doesNotSynthesizeIfRequestedWeightIsLessThan600() {
val (font, loaded) = loadFont(FontTestData.FONT_100_REGULAR)
// Less than 600 is not synthesized
val typeface500 = FontSynthesis.Weight.synthesizeTypeface(
loaded,
font,
FontWeight.W500,
FontStyle.Normal
) as Typeface
// 600 or more is synthesized
val typeface600 = FontSynthesis.Weight.synthesizeTypeface(
loaded,
font,
FontWeight.W600,
FontStyle.Normal
) as Typeface
Truth.assertThat(typeface500.isBold).isFalse()
Truth.assertThat(typeface600.isBold).isTrue()
}
} | apache-2.0 | c85e15a2ad17609008b6e193c53f8bf6 | 32.333333 | 86 | 0.665632 | 4.606037 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.